def display_user_info(user_info: PcsUser): user_id, user_name, auth, age, sex, quota, products, level = user_info bduss = auth and auth.bduss quota_str = "" if quota: quota_str = human_size(quota.used) + "/" + human_size(quota.quota) products_str = "" for p in products or []: name = p.name start_date = format_date(p.start_time) end_date = format_date(p.end_time) avail = str(datetime.timedelta(seconds=(int(p.end_time - time.time())))) value = f"From {start_date} to {end_date}, left {avail}" products_str += f"\n {name}: {value}" _tempt = ( f"user id: {user_id}\n" f"user name: {user_name}\n" f"bduss: {bduss}\n" f"age: {age}\n" f"sex: {sex}\n" f"quota: {quota_str}\n" f"level: {level}\n" f"products:{products_str}\n" ) console = Console() console.print(_tempt, highlight=True)
async def handle_request( request: Request, remotepath: str, order: str = "asc", # desc , asc sort: str = "name", # name, time, size ): desc = order == "desc" name = sort == "name" time = sort == "time" size = sort == "size" global _root_dir global _api assert _api remotepath = remotepath.strip("/") _rp = join_path(_root_dir, remotepath) # Anti path traversal attack if not _rp.startswith(_root_dir): raise HTTPException(status_code=404, detail="Item not found") _range = request.headers.get("range") if not _api.exists(_rp): raise HTTPException(status_code=404, detail="Item not found") is_dir = _api.is_dir(_rp) if is_dir: chunks = ["/"] + (remotepath.split("/") if remotepath != "" else []) navigation = [ (i - 1, "../" * (len(chunks) - i), name) for i, name in enumerate(chunks, 1) ] pcs_files = _api.list(_rp, desc=desc, name=name, time=time, size=size) entries = [] for f in pcs_files: p = Path(f.path) entries.append((f.is_dir, p.name, f.size, format_date(f.local_mtime or 0))) cn = _html_tempt.render( root_dir=remotepath, navigation=navigation, entries=entries ) return HTMLResponse(cn) else: try: fs = _api.file_stream(_rp, encrypt_password=_encrypt_password) except Exception as err: print("Error:", err) raise HTTPException( status_code=500, detail=f"Error: {err}, remotepath: {_rp}" ) if not fs: raise HTTPException(status_code=404, detail=f"No download link: {_rp}") length = len(fs) headers: Dict[str, str] = { "accept-ranges": "bytes", "connection": "Keep-Alive", "access-control-allow-origin": "*", } ext = os.path.splitext(remotepath)[-1] content_type = mimetypes.types_map.get(ext) if content_type: headers["content-type"] = content_type if _range and fs.seekable(): assert _range.startswith("bytes=") status_code = 206 start, end = _range[6:].split("-") _s, _e = int(start or 0), int(end or length - 1) + 1 _iter_io = fake_io(fs, _s, _e) headers["content-range"] = f"bytes {_s}-{_e-1}/{length}" headers["content-length"] = str(_e - _s) else: status_code = 200 _iter_io = fake_io(fs) headers["content-length"] = str(length) return StreamingResponse(_iter_io, status_code=status_code, headers=headers)
def display_files( pcs_files: List[PcsFile], remotepath: Optional[str], sifters: List[Sifter] = [], highlight: bool = False, show_size: bool = False, show_date: bool = False, show_md5: bool = False, show_absolute_path: bool = False, ): pcs_files = sift(pcs_files, sifters) if not pcs_files: return table = Table(box=SIMPLE, padding=0, show_edge=False) table.add_column() if show_size: table.add_column("Size", justify="right") if show_date: table.add_column("Modified Time", justify="center") if show_md5: table.add_column("md5", justify="left") table.add_column("Path", justify="left", overflow="fold") max_size_str_len = max([len(str(pcs_file.size)) for pcs_file in pcs_files]) for pcs_file in pcs_files: row: List[Union[str, Text]] = [] tp = Text("-", style="bold red") row.append(tp) if show_size: size = human_size(pcs_file.size) if pcs_file.size else "" row.append(f"{size} {pcs_file.size: >{max_size_str_len}}") if show_date: date = format_date(pcs_file.mtime) if pcs_file.mtime else "" row.append(date) if show_md5: md5 = pcs_file.md5 or "" row.append(md5) path = pcs_file.path if show_absolute_path else Path(pcs_file.path).name background = Text() if pcs_file.is_dir: tp._text = ["d"] background.style = "blue" if highlight and sifters: pats: List[Union[Pattern, str]] = list( filter( None, [sifter.pattern() for sifter in sifters if sifter.include()] ) ) highlighter = Highlighter(pats, "yellow") _path = highlighter(path) else: _path = Text(path) row.append(background + _path) table.add_row(*row) console = Console() if remotepath: title = Text(remotepath, style="italic green") console.print(title) console.print(table)
def display_files( pcs_files: List[PcsFile], remotepath: Optional[str], sifters: List[Sifter] = [], highlight: bool = False, show_size: bool = False, show_date: bool = False, show_md5: bool = False, show_absolute_path: bool = False, show_dl_link: bool = False, show_hash_link: bool = False, hash_link_protocol: str = PcsRapidUploadInfo.default_hash_link_protocol(), csv: bool = False, ): if not pcs_files: return table = Table(box=SIMPLE, padding=0, show_edge=False) table.add_column() headers = [] # for csv headers.append("\t") if show_size: header = "Size" table.add_column(header, justify="right") headers.append(header) if show_date: header = "Modified Time" table.add_column(header, justify="center") headers.append(header) if show_md5: header = "md5" table.add_column(header, justify="left") headers.append(header) header = "Path" table.add_column(header, justify="left", overflow="fold") headers.append(header) if show_dl_link: header = "Download Link" table.add_column(header, justify="left", overflow="fold") headers.append(header) if show_hash_link: header = "Hash Link" table.add_column(header, justify="left", overflow="fold") headers.append(header) rows = [] # for csv max_size_str_len = max([len(str(pcs_file.size)) for pcs_file in pcs_files]) for pcs_file in pcs_files: row: List[Union[str, Text]] = [] if csv: row.append("-") else: tp = Text("-", style="bold red") row.append(tp) if show_size: size = human_size(pcs_file.size) if pcs_file.size else "" if csv: row.append(f"{size} {pcs_file.size}") else: row.append(f"{size} {pcs_file.size: >{max_size_str_len}}") if show_date: date = format_date( pcs_file.local_mtime) if pcs_file.local_mtime else "" row.append(date) if show_md5: md5 = pcs_file.md5 or "" row.append(md5) path = pcs_file.path if show_absolute_path else Path( pcs_file.path).name background = Text() if pcs_file.is_dir: if csv: row[0] = "d" else: tp._text = ["d"] background.style = "blue" if highlight and sifters: pats: List[Union[Pattern, str]] = list( filter(None, [ sifter.pattern() for sifter in sifters if sifter.include() ])) highlighter = Highlighter(pats, "yellow") _path = highlighter(path) else: _path = Text(path) if csv: row.append(path) else: row.append(background + _path) if show_dl_link: row.append(pcs_file.dl_link or "") rpinfo = pcs_file.rapid_upload_info if show_hash_link: link = "" if rpinfo: link = rpinfo.cs3l() row.append(link) if csv: rows.append(row) else: table.add_row(*row) if csv: _print(remotepath) _print("\t".join(headers)) for row in rows: _print("\t".join(row)) # type: ignore else: console = Console() if remotepath: title = Text(remotepath, style="italic green") console.print(title) console.print(table)
async def http_server( request: Request, remotepath: str, order: str = "asc", # desc , asc sort: str = "name", # name, time, size ): desc = order == "desc" name = sort == "name" time = sort == "time" size = sort == "size" global _root_dir global _api assert _api remotepath = remotepath.strip("/") _rp = Path(_root_dir) / remotepath _rp_str = _rp.as_posix() _range = request.headers.get("range") if not _api.exists(_rp_str): raise HTTPException(status_code=404, detail="Item not found") is_dir = _api.is_dir(_rp_str) if is_dir: chunks = ["/"] + (remotepath.split("/") if remotepath != "" else []) navigation = [(i - 1, "../" * (len(chunks) - i), name) for i, name in enumerate(chunks, 1)] pcs_files = _api.list(_rp_str, desc=desc, name=name, time=time, size=size) entries = [] for f in pcs_files: p = Path(f.path) entries.append((f.is_dir, p.name, f.size, format_date(f.mtime or 0))) cn = _html_tempt.render(root_dir=remotepath, navigation=navigation, entries=entries) return HTMLResponse(cn) else: range_request_io = _api.file_stream(_rp_str) length = len(range_request_io) headers: Dict[str, str] = { "accept-ranges": "bytes", "connection": "Keep-Alive", } if _range: assert _range.startswith("bytes=") status_code = 206 start, end = _range[6:].split("-") _s, _e = int(start or 0), int(end or length - 1) _io = fake_io(range_request_io, _s, _e) headers["content-range"] = f"bytes {_s}-{_e}/{length}" headers["content-length"] = str(_e - _s + 1) else: status_code = 200 _io = fake_io(range_request_io) headers["content-length"] = str(length) return StreamingResponse(_io, status_code=status_code, headers=headers)