Skip to content

Commit 98389ba

Browse files
committed
✨ 格式化文档
1 parent 705cf4c commit 98389ba

File tree

8 files changed

+248
-146
lines changed

8 files changed

+248
-146
lines changed

core/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,12 +241,15 @@ async def main():
241241
os.environ["ASYNCIO_STARTUP"] = str(0)
242242
os.kill(os.getpid(), signal.SIGINT)
243243

244+
244245
def init():
245246
asyncio.run(main())
246247

248+
247249
async def close():
248250
await web.close()
249251

252+
250253
def kill(_, __):
251254
if int(os.environ["ASYNCIO_STARTUP"]) and server:
252255
server.close()
@@ -256,4 +259,4 @@ def kill(_, __):
256259

257260

258261
for sig in (signal.SIGINT, signal.SIGTERM):
259-
signal.signal(sig, kill)
262+
signal.signal(sig, kill)

core/cluster.py

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@
3333
get_hash,
3434
)
3535

36-
VERSION = ''
36+
VERSION = ""
3737
version_path = Path("VERSION")
3838
if version_path.exists():
39-
with open(Path("VERSION"), 'r', encoding='utf-8') as f:
39+
with open(Path("VERSION"), "r", encoding="utf-8") as f:
4040
VERSION = f.read()
4141
f.close()
4242
else:
@@ -512,9 +512,7 @@ async def check_files(self):
512512
if not miss:
513513
logger.success(f"Checked all files: {len(files) * len(self.storages)}!")
514514
else:
515-
logger.info(
516-
f"File missing: {unit.format_number(len(miss))}."
517-
)
515+
logger.info(f"File missing: {unit.format_number(len(miss))}.")
518516
await downloader.download(self.storages, list(miss))
519517
if os.path.exists("./cache/download"):
520518
paths = []
@@ -565,6 +563,7 @@ async def start(
565563
await self.check_files()
566564
await dashboard.set_status("启动服务")
567565
await self.enable()
566+
568567
async def get(self, hash, offset: int = 0) -> File:
569568
storage = self.storages[0]
570569
stat = self.storage_stats[storage]
@@ -606,6 +605,7 @@ async def enable(self) -> None:
606605
},
607606
)
608607
await dashboard.set_status("巡检中")
608+
609609
async def message(self, type, data: list[Any]):
610610
if len(data) == 1:
611611
data.append(None)
@@ -629,7 +629,9 @@ async def message(self, type, data: list[Any]):
629629
f"Hosting on {CLUSTER_ID}.openbmclapi.933.moe:{PUBLIC_PORT or PORT}."
630630
)
631631
await self.start_keepalive()
632-
await dashboard.set_status("正常工作" + ("" if self.trusted else "(节点信任度过低)"))
632+
await dashboard.set_status(
633+
"正常工作" + ("" if self.trusted else "(节点信任度过低)")
634+
)
633635
elif type == "keep-alive":
634636
if err:
635637
logger.error(f"Unable to keep alive! Reconnecting...")
@@ -718,21 +720,22 @@ async def disable(self):
718720
cluster: Optional[Cluster] = None
719721
last_status: str = "-"
720722
github_api = "https://api.github.com"
723+
724+
721725
async def check_update():
722-
async with aiohttp.ClientSession(
723-
base_url=github_api
724-
) as session:
725-
logger.info("Checking update...")
726-
try:
727-
async with session.get("/repos/TTB-Network/python-openbmclapi/tags") as req:
728-
req.raise_for_status()
729-
fetched_version: str = (await req.json())[0]["name"]
730-
if fetched_version != VERSION:
731-
logger.success(f"New version found: {fetched_version}!")
732-
else:
733-
logger.info(f"Already up to date.")
734-
except aiohttp.ClientError as e:
735-
logger.error(f"An error occured whilst checking update: {e}.")
726+
async with aiohttp.ClientSession(base_url=github_api) as session:
727+
logger.info("Checking update...")
728+
try:
729+
async with session.get("/repos/TTB-Network/python-openbmclapi/tags") as req:
730+
req.raise_for_status()
731+
fetched_version: str = (await req.json())[0]["name"]
732+
if fetched_version != VERSION:
733+
logger.success(f"New version found: {fetched_version}!")
734+
else:
735+
logger.info(f"Already up to date.")
736+
except aiohttp.ClientError as e:
737+
logger.error(f"An error occured whilst checking update: {e}.")
738+
736739

737740
async def init():
738741
await check_update()
@@ -778,8 +781,10 @@ async def _(request: web.Request, hash: str):
778781
if not await cluster.exists(hash):
779782
return web.Response(status_code=404)
780783
start_bytes = 0
781-
range_str = await request.get_headers('range', '')
782-
range_match = re.search(r'bytes=(\d+)-(\d+)', range_str, re.S) or re.search(r'bytes=(\d+)-', range_str, re.S)
784+
range_str = await request.get_headers("range", "")
785+
range_match = re.search(r"bytes=(\d+)-(\d+)", range_str, re.S) or re.search(
786+
r"bytes=(\d+)-", range_str, re.S
787+
)
783788
if range_match:
784789
start_bytes = int(range_match.group(1)) if range_match else 0
785790
data = await cluster.get(hash, start_bytes)
@@ -797,7 +802,9 @@ async def _(request: web.Request, ws: web.WebSocket):
797802
auth = False
798803
for cookie in await request.get_cookies():
799804
if cookie.name == "auth" and dashboard.token_isvaild(cookie.value):
800-
await ws.send(dashboard.to_bytes("auth", DASHBOARD_USERNAME).io.getbuffer())
805+
await ws.send(
806+
dashboard.to_bytes("auth", DASHBOARD_USERNAME).io.getbuffer()
807+
)
801808
auth = True
802809
break
803810
if not auth:
@@ -810,18 +817,29 @@ async def _(request: web.Request, ws: web.WebSocket):
810817
input = utils.DataInputStream(raw_data)
811818
type = input.readString()
812819
data = dashboard.deserialize(input)
813-
await ws.send(dashboard.to_bytes(type, await dashboard.process(type, data)).io.getbuffer())
820+
await ws.send(
821+
dashboard.to_bytes(
822+
type, await dashboard.process(type, data)
823+
).io.getbuffer()
824+
)
825+
814826
@router.get("/auth")
815827
async def _(request: web.Request):
816828
auth = (await request.get_headers("Authorization")).split(" ", 1)[1]
817829
try:
818830
info = json.loads(base64.b64decode(auth))
819831
except:
820832
return web.Response(status_code=401)
821-
if info["username"] != DASHBOARD_USERNAME or info["password"] != DASHBOARD_PASSWORD:
833+
if (
834+
info["username"] != DASHBOARD_USERNAME
835+
or info["password"] != DASHBOARD_PASSWORD
836+
):
822837
return web.Response(status_code=401)
823838
token = dashboard.generate_token(request)
824-
return web.Response(DASHBOARD_USERNAME, cookies=[web.Cookie("auth", token.value, expires=int(time.time() + 86400))])
839+
return web.Response(
840+
DASHBOARD_USERNAME,
841+
cookies=[web.Cookie("auth", token.value, expires=int(time.time() + 86400))],
842+
)
825843

826844
app.mount(router)
827845
app.redirect("/bmcl", "/bmcl/")

core/dashboard.py

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,20 @@
1212
from core.api import StatsCache
1313
from core.config import Config
1414

15+
1516
@dataclass
1617
class Token:
1718
value: str
1819
create_at: float
1920

21+
2022
BASE_URL = "https://openbmclapi.bangbang93.com/"
2123
CLUSTER_ID: str = Config.get("cluster.id")
2224
CLUSTER_SECERT: str = Config.get("cluster.secret")
2325
last_status = ""
2426
tokens: list[Token] = []
27+
28+
2529
def deserialize(data: utils.DataInputStream):
2630
match (data.readVarInt()):
2731
case 0:
@@ -35,9 +39,13 @@ def deserialize(data: utils.DataInputStream):
3539
case 4:
3640
return [deserialize(data) for _ in range(data.readVarInt())]
3741
case 5:
38-
return {deserialize(data): deserialize(data) for _ in range(data.readVarInt())}
42+
return {
43+
deserialize(data): deserialize(data) for _ in range(data.readVarInt())
44+
}
3945
case 6:
4046
return None
47+
48+
4149
def serialize(data: Any):
4250
buf = utils.DataOutputStream()
4351
if isinstance(data, str):
@@ -55,14 +63,23 @@ def serialize(data: Any):
5563
elif isinstance(data, list):
5664
buf.writeVarInt(4)
5765
buf.writeVarInt(len(data))
58-
buf.write(b''.join((serialize(v).io.getvalue() for v in data)))
66+
buf.write(b"".join((serialize(v).io.getvalue() for v in data)))
5967
elif isinstance(data, dict):
6068
buf.writeVarInt(5)
6169
buf.writeVarInt(len(data.keys()))
62-
buf.write(b''.join((serialize(k).io.getvalue() + serialize(v).io.getvalue() for k, v in data.items())))
70+
buf.write(
71+
b"".join(
72+
(
73+
serialize(k).io.getvalue() + serialize(v).io.getvalue()
74+
for k, v in data.items()
75+
)
76+
)
77+
)
6378
elif data == None:
6479
buf.writeVarInt(6)
6580
return buf
81+
82+
6683
async def process(type: str, data: Any):
6784
if type == "runtime":
6885
return float(os.getenv("STARTUP") or 0)
@@ -83,31 +100,56 @@ async def process(type: str, data: Any):
83100
"memory": system.get_used_memory(),
84101
"connections": system.get_connections(),
85102
"cpu": system.get_cpus(),
86-
"cache": asdict(await cluster.cluster.get_cache_stats()) if cluster.cluster else StatsCache()
103+
"cache": (
104+
asdict(await cluster.cluster.get_cache_stats())
105+
if cluster.cluster
106+
else StatsCache()
107+
),
87108
}
109+
110+
88111
async def set_status(text):
89-
global last_status
112+
global last_status
90113
if last_status != text:
91114
app = web.app
92115
output = to_bytes("status", text)
93116
for ws in app.get_websockets("/bmcl/"):
94117
await ws.send(output.io.getvalue())
95118
last_status = text
96119

120+
97121
def to_bytes(type: str, data: Any):
98122
output = utils.DataOutputStream()
99123
output.writeString(type)
100124
output.write(serialize(data).io.getvalue())
101125
return output
102126

103-
def generate_token(request: 'web.Request') -> Token:
127+
128+
def generate_token(request: "web.Request") -> Token:
104129
global tokens
105-
token = Token(hashlib.sha256(zlib.compress(hashlib.sha512((request.get_ip() + request.get_user_agent() + request.get_url() + CLUSTER_ID + CLUSTER_SECERT + str(time.time())).encode("utf-8")).digest())).hexdigest(), time.time())
130+
token = Token(
131+
hashlib.sha256(
132+
zlib.compress(
133+
hashlib.sha512(
134+
(
135+
request.get_ip()
136+
+ request.get_user_agent()
137+
+ request.get_url()
138+
+ CLUSTER_ID
139+
+ CLUSTER_SECERT
140+
+ str(time.time())
141+
).encode("utf-8")
142+
).digest()
143+
)
144+
).hexdigest(),
145+
time.time(),
146+
)
106147
tokens.append(token)
107148
return token
108149

150+
109151
def token_isvaild(value) -> bool:
110152
for token in tokens:
111153
if token.value == value and token.create_at + 86400 > time.time():
112154
return True
113-
return False
155+
return False

core/logger.py

Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -5,54 +5,54 @@
55
basic_logger_format = "<green>[{time:YYYY-MM-DD HH:mm:ss}]</green> <level>[{level}] <yellow>[{name}:{function}:{line}]</yellow>: {message}</level>"
66

77

8-
def log(*values):
9-
data = []
10-
for v in values:
11-
try:
12-
data.append(str(v))
13-
except:
14-
data.append(repr(v))
15-
return " ".join(data)
16-
17-
18-
class LoggingLogger:
19-
def __init__(self):
8+
def log(*values):
9+
data = []
10+
for v in values:
11+
try:
12+
data.append(str(v))
13+
except:
14+
data.append(repr(v))
15+
return " ".join(data)
16+
17+
18+
class LoggingLogger:
19+
def __init__(self):
2020
self.log = Logger.opt(depth=2)
21-
self.log.remove()
22-
self.log.add(
23-
sys.stderr,
24-
format=basic_logger_format,
25-
level="DEBUG",
26-
colorize=True,
27-
)
28-
self.log.add(
29-
Path("./logs/{time:YYYY-MM-DD}.log"),
30-
format=basic_logger_format,
31-
retention="10 days",
32-
encoding="utf-8",
33-
)
34-
35-
def _log_with_args(self, level, *args, **kwargs):
36-
message = log(*args) if args else ""
37-
self.log.log(level, message, **kwargs)
38-
39-
def info(self, *args, **kwargs):
40-
self._log_with_args("INFO", *args, **kwargs)
41-
42-
def error(self, *args, **kwargs):
43-
self._log_with_args("ERROR", *args, **kwargs)
44-
45-
def debug(self, *args, **kwargs):
46-
self._log_with_args("DEBUG", *args, **kwargs)
47-
48-
def warn(self, *args, **kwargs):
49-
self._log_with_args("WARNING", *args, **kwargs)
50-
51-
def exception(self, *args, **kwargs):
52-
self._log_with_args("EXCEPTION", *args, **kwargs)
53-
54-
def success(self, *args, **kwargs):
55-
self._log_with_args("SUCCESS", *args, **kwargs)
21+
self.log.remove()
22+
self.log.add(
23+
sys.stderr,
24+
format=basic_logger_format,
25+
level="DEBUG",
26+
colorize=True,
27+
)
28+
self.log.add(
29+
Path("./logs/{time:YYYY-MM-DD}.log"),
30+
format=basic_logger_format,
31+
retention="10 days",
32+
encoding="utf-8",
33+
)
34+
35+
def _log_with_args(self, level, *args, **kwargs):
36+
message = log(*args) if args else ""
37+
self.log.log(level, message, **kwargs)
38+
39+
def info(self, *args, **kwargs):
40+
self._log_with_args("INFO", *args, **kwargs)
41+
42+
def error(self, *args, **kwargs):
43+
self._log_with_args("ERROR", *args, **kwargs)
44+
45+
def debug(self, *args, **kwargs):
46+
self._log_with_args("DEBUG", *args, **kwargs)
47+
48+
def warn(self, *args, **kwargs):
49+
self._log_with_args("WARNING", *args, **kwargs)
50+
51+
def exception(self, *args, **kwargs):
52+
self._log_with_args("EXCEPTION", *args, **kwargs)
53+
54+
def success(self, *args, **kwargs):
55+
self._log_with_args("SUCCESS", *args, **kwargs)
5656

5757

5858
logger = LoggingLogger()

0 commit comments

Comments
 (0)