Skip to content

Commit 61acf28

Browse files
committed
🎨 格式化文档
1 parent ea630ab commit 61acf28

File tree

6 files changed

+127
-64
lines changed

6 files changed

+127
-64
lines changed

core/api.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ def __init__(self, name, width: int) -> None:
8181
self.name = name
8282
self.disabled = False
8383
self.width = width
84+
8485
def get_name(self):
8586
return self.name
8687

core/cluster.py

Lines changed: 102 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ async def fetchToken(self):
7878
Timer.delay(
7979
self.fetchToken, delay=float(content["ttl"]) / 1000.0 - 600
8080
)
81-
self.token_expires = content['ttl'] / 1000.0 - 600 + time.time()
81+
self.token_expires = content["ttl"] / 1000.0 - 600 + time.time()
8282
tll = utils.format_time(content["ttl"] / 1000.0)
8383
logger.success(locale.t("cluster.success.token.fetched", tll=tll))
8484

@@ -425,7 +425,11 @@ async def __call__(
425425
file_size = unit.format_bytes(
426426
sum(file.size for file in files) * len(storages.get_storages())
427427
)
428-
logger.success(locale.t("cluster.success.check.finished", count=file_count, size=file_size))
428+
logger.success(
429+
locale.t(
430+
"cluster.success.check.finished", count=file_count, size=file_size
431+
)
432+
)
429433
else:
430434
logger.info(
431435
locale.t(
@@ -577,9 +581,13 @@ async def clear_cache(self):
577581
return
578582
for key in old_keys:
579583
self.cache.pop(key)
580-
logger.info(locale.t("cluster.info.clear_cache.count",
581-
count=unit.format_number(len(old_keys)),
582-
size=unit.format_bytes(old_size)))
584+
logger.info(
585+
locale.t(
586+
"cluster.info.clear_cache.count",
587+
count=unit.format_number(len(old_keys)),
588+
size=unit.format_bytes(old_size),
589+
)
590+
)
583591

584592
async def get_files(self, dir: str) -> list[str]:
585593
files = []
@@ -616,13 +624,13 @@ async def get_cache_stats(self) -> StatsCache:
616624

617625
class WebDav(Storage):
618626
def __init__(
619-
self,
627+
self,
620628
name: str,
621629
width: int,
622630
username: str,
623631
password: str,
624632
hostname: str,
625-
endpoint: str
633+
endpoint: str,
626634
) -> None:
627635
super().__init__(name, width)
628636
self.username = username
@@ -645,34 +653,62 @@ def __init__(
645653
)
646654
Timer.delay(self._list_all)
647655
Timer.repeat(self._keepalive, interval=60)
656+
648657
async def _keepalive(self):
649658
try:
650-
info = await asyncio.wait_for(self.session.info(self.endpoint), timeout=5)
651659
hostname = self.hostname
652660
endpoint = self.endpoint
653661
if not self.disabled:
654-
logger.success(locale.t("cluster.success.webdav.keepalive", hostname=hostname, endpoint=endpoint))
662+
logger.success(
663+
locale.t(
664+
"cluster.success.webdav.keepalive",
665+
hostname=hostname,
666+
endpoint=endpoint,
667+
)
668+
)
655669
else:
656670
storages.enable(self)
657-
logger.success(locale.t("cluster.success.webdav.enabled", hostname=hostname, endpoint=endpoint))
671+
logger.success(
672+
locale.t(
673+
"cluster.success.webdav.enabled",
674+
hostname=hostname,
675+
endpoint=endpoint,
676+
)
677+
)
658678
await self._list_all()
659679
except webdav3_exceptions.NoConnection:
660680
if not self.disabled:
661-
logger.warn(locale.t("cluster.warn.webdav.no_connection", hostname=hostname, endpoint=endpoint))
681+
logger.warn(
682+
locale.t(
683+
"cluster.warn.webdav.no_connection",
684+
hostname=hostname,
685+
endpoint=endpoint,
686+
)
687+
)
662688
storages.disable(self)
663689
self.fetch = False
664690
except:
665691
logger.error(traceback.format_exc())
692+
666693
async def _execute(self, target):
667694
try:
668695
return await target
669696
except webdav3_exceptions.NoConnection as e:
670-
logger.warn(locale.t("cluster.warn.webdav.no_connection", hostname=hostname, endpoint=endpoint))
697+
hostname = self.hostname
698+
endpoint = self.endpoint
699+
logger.warn(
700+
locale.t(
701+
"cluster.warn.webdav.no_connection",
702+
hostname=hostname,
703+
endpoint=endpoint,
704+
)
705+
)
671706
storages.disable(self)
672707
self.fetch = False
673708
raise e
674709
except Exception as e:
675710
raise e
711+
676712
def _endpoint(self, file: str):
677713
return f"{self.endpoint}/{file.removeprefix('/')}"
678714

@@ -694,18 +730,23 @@ async def _list_all(self, force=False):
694730
try:
695731
await self._mkdir(self.endpoint)
696732
dirs = (await self._execute(self.session.list(self.endpoint)))[1:]
697-
with tqdm(total=len(dirs), desc=f"[WebDav List Files <endpoint: '{self.endpoint}'>]") as pbar:
733+
with tqdm(
734+
total=len(dirs),
735+
desc=f"[WebDav List Files <endpoint: '{self.endpoint}'>]",
736+
) as pbar:
698737
await dashboard.set_status_by_tqdm("正在获取 WebDav 文件列表中", pbar)
699738
for dir in (await self._execute(self.session.list(self.endpoint)))[1:]:
700739
pbar.update(1)
701740
files: dict[str, File] = {}
702741
for file in (
703-
await self._execute(self.session.list(
704-
self._endpoint(
705-
dir,
706-
),
707-
get_info=True,
708-
))
742+
await self._execute(
743+
self.session.list(
744+
self._endpoint(
745+
dir,
746+
),
747+
get_info=True,
748+
)
749+
)
709750
)[1:]:
710751
files[file["name"]] = File(
711752
file["path"].removeprefix(f"/dav/{self.endpoint}/"),
@@ -744,7 +785,8 @@ async def get(self, file: str, offset: int = 0) -> File:
744785
auth=aiohttp.BasicAuth(self.username, self.password)
745786
) as session:
746787
async with session.get(
747-
self.hostname + self._endpoint(file[:2] + "/" + file), allow_redirects=False
788+
self.hostname + self._endpoint(file[:2] + "/" + file),
789+
allow_redirects=False,
748790
) as resp:
749791
logger.debug(resp.status, resp.closed)
750792
f = File(
@@ -754,10 +796,10 @@ async def get(self, file: str, offset: int = 0) -> File:
754796
)
755797
f.headers = {}
756798
for field in (
757-
"ETag",
799+
"ETag",
758800
"Last-Modified",
759801
"Content-Length",
760-
"Content-Range"
802+
"Content-Range",
761803
):
762804
if field not in resp.headers:
763805
continue
@@ -767,11 +809,14 @@ async def get(self, file: str, offset: int = 0) -> File:
767809
f.expiry = time.time() + CACHE_TIME
768810
elif resp.status // 100 == 3:
769811
f.path = resp.headers.get("Location")
770-
f.expiry = time.time() + utils.parse_cache_control(resp.headers.get("Cache-Control", ""))
812+
f.expiry = time.time() + utils.parse_cache_control(
813+
resp.headers.get("Cache-Control", "")
814+
)
771815
self.cache[file] = f
772816
return self.cache[file]
773817
except Exception as e:
774818
storages.disable(self)
819+
775820
async def exists(self, hash: str) -> bool:
776821
await self._wait_lock()
777822
if not self.fetch:
@@ -796,9 +841,9 @@ async def get_files(self, dir: str) -> list[str]:
796841

797842
async def get_hash(self, hash: str) -> str:
798843
h = get_hash(hash)
799-
async for data in await self._execute(self.session.download_iter(
800-
self._endpoint(f"{hash[:2]}/{hash}")
801-
)):
844+
async for data in await self._execute(
845+
self.session.download_iter(self._endpoint(f"{hash[:2]}/{hash}"))
846+
):
802847
h.update(data)
803848
return h.hexdigest()
804849

@@ -811,7 +856,9 @@ async def get_files_size(self, dir: str) -> int:
811856
async def removes(self, hashs: list[str]) -> int:
812857
success = 0
813858
for hash in hashs:
814-
await self._execute(self.session.clean(self._endpoint(f"{hash[:2]}/{hash}")))
859+
await self._execute(
860+
self.session.clean(self._endpoint(f"{hash[:2]}/{hash}"))
861+
)
815862
success += 1
816863
return success
817864

@@ -880,9 +927,13 @@ def get_all_storages(self):
880927

881928
def get_storages(self):
882929
return [storage for storage in self._storages if not storage.disabled]
883-
930+
884931
def get_available_storages(self):
885-
return [storage for storage in self._storages if not storage.disabled and storage.width != -1]
932+
return [
933+
storage
934+
for storage in self._storages
935+
if not storage.disabled and storage.width != -1
936+
]
886937

887938
def get_storage_stats(self):
888939
return self._storage_stats
@@ -961,6 +1012,7 @@ async def connect(self):
9611012
logger.warn(locale.t("cluster.warn.cluster.failed_to_connect"))
9621013
return False
9631014
return True
1015+
9641016
async def init(self):
9651017
if not await self.connect():
9661018
return
@@ -1231,18 +1283,31 @@ async def init():
12311283
await plugin.enable()
12321284
for storage in STORAGES:
12331285
if storage.type == "file":
1234-
storages.add_storage(FileStorage(storage.name, Path(storage.path), storage.width))
1286+
storages.add_storage(
1287+
FileStorage(storage.name, Path(storage.path), storage.width)
1288+
)
12351289
elif storage.type == "webdav":
1236-
storages.add_storage(WebDav(storage.name, storage.width, storage.kwargs['username'], storage.kwargs['password'], storage.kwargs['endpoint'], storage.path))
1290+
storages.add_storage(
1291+
WebDav(
1292+
storage.name,
1293+
storage.width,
1294+
storage.kwargs["username"],
1295+
storage.kwargs["password"],
1296+
storage.kwargs["endpoint"],
1297+
storage.path,
1298+
)
1299+
)
12371300
Timer.delay(cluster.init)
12381301
app = web.app
12391302
if DEBUG:
12401303
logger.debug("Currently in developer mode")
1304+
12411305
@app.get("/files")
12421306
async def _():
1243-
files = sorted(cluster.downloader.files, key = lambda x: x.hash)
1307+
files = sorted(cluster.downloader.files, key=lambda x: x.hash)
12441308
for file in files:
12451309
yield f'<a href="/dev_download/{file.hash}" target="_blank">{file}</a></br>'.encode()
1310+
12461311
@app.get("/dev_download/{hash}")
12471312
async def _(hash: str):
12481313
cur_time = int(time.time() * 1000.0) + 600
@@ -1251,7 +1316,9 @@ async def _(hash: str):
12511316
s.update(CLUSTER_SECERT.encode("utf-8"))
12521317
s.update(hash.encode("utf-8"))
12531318
s.update(e.encode("utf-8"))
1254-
return web.RedirectResponse(f"/download/{hash}?s={base64.urlsafe_b64encode(s.digest()).decode().strip('=')}&e={e}")
1319+
return web.RedirectResponse(
1320+
f"/download/{hash}?s={base64.urlsafe_b64encode(s.digest()).decode().strip('=')}&e={e}"
1321+
)
12551322

12561323
@app.get("/measure/{size}")
12571324
async def _(request: web.Request, size: int, config: web.ResponseConfiguration):
@@ -1326,7 +1393,7 @@ async def _(request: web.Request):
13261393
@app.get("/sync_download/{hash}")
13271394
async def _(request: web.Request, hash: str):
13281395
return Path(f"./bmclapi/{hash[:2]}/{hash}")
1329-
1396+
13301397
dir = Path("./bmclapi_dashboard/")
13311398
dir.mkdir(exist_ok=True, parents=True)
13321399
app.mount_resource(web.Resource("/", dir, show_dir=False))
@@ -1376,7 +1443,6 @@ async def _(request: web.Request):
13761443
cookies=[web.Cookie("auth", token.value, expires=int(time.time() + 86400))],
13771444
)
13781445

1379-
13801446
@app.post("/api/{name}")
13811447
async def _(request: web.Request, name: str):
13821448
if name == "auth":
@@ -1397,6 +1463,7 @@ async def _(request: web.Request, name: str):
13971463

13981464
app.redirect("/", "/dashboard/")
13991465

1466+
14001467
async def close():
14011468
global cluster
14021469
for plugin in plugins.get_enable_plugins():

core/config.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,7 @@
3535
"advanced.language": "zh_cn",
3636
"dashboard.username": "admin",
3737
"dashboard.password": "",
38-
"storages": {
39-
"bmclapi": {
40-
"type": "file",
41-
"path": "./bmclapi",
42-
"width": 0
43-
}
44-
}
38+
"storages": {"bmclapi": {"type": "file", "path": "./bmclapi", "width": 0}},
4539
}
4640

4741

core/const.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,14 @@
103103
}
104104
REQUEST_TIME_UNITS = ["ns", "ms", "s", "m", "h"]
105105
FILECHECK = Config.get("file.check")
106-
STORAGES: list['StorageParse'] = []
106+
STORAGES: list["StorageParse"] = []
107107
COMPRESSOR: dict[str, Any] = {
108108
"zstd": pyzstd.compress,
109109
"gzip": gzip.compress,
110-
"deflate": zlib.compress
110+
"deflate": zlib.compress,
111111
}
112112

113+
113114
@dataclass
114115
class StorageParse:
115116
name: str
@@ -124,10 +125,6 @@ class StorageParse:
124125
storage = Config.get(f"storages.{name}")
125126
STORAGES.append(
126127
StorageParse(
127-
name,
128-
storage['type'],
129-
storage['path'],
130-
storage.get("width", 0),
131-
storage
128+
name, storage["type"], storage["path"], storage.get("width", 0), storage
132129
)
133130
)

0 commit comments

Comments
 (0)