Skip to content

Commit 3672ab7

Browse files
committed
chore: 优化导入
1 parent ad8accf commit 3672ab7

File tree

10 files changed

+76
-38
lines changed

10 files changed

+76
-38
lines changed

assets/js/common.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,14 @@ class Element {
143143
this._render_i18n();
144144
return this;
145145
}
146+
aria_label(text) {
147+
if (Utils.isEmpty(text)) {
148+
this._base.removeAttribute("title")
149+
} else {
150+
this._base.setAttribute("title", text)
151+
}
152+
return this
153+
}
146154
_render_i18n() {
147155
if (this._i18n_key == null) {
148156
return;

assets/js/index.js

Lines changed: 59 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,17 @@ $style.addAll({
992992
}
993993
})
994994
class Tools {
995+
static _NUMBER_UNITS = {
996+
"": 1,
997+
"K": 1e3,
998+
"M": 1e3,
999+
"B": 1e3,
1000+
"T": 1e3,
1001+
"P": 1e3,
1002+
"E": 1e3,
1003+
"Z": 1e3,
1004+
"Y": 1e3,
1005+
}
9951006
static formatTime(seconds) {
9961007
if (seconds < 0 || seconds == null) return $i18n.t("format.count_time.days", {
9971008
day: "--",
@@ -1027,6 +1038,8 @@ class Tools {
10271038
value_i18n: "",
10281039
title_variable: () => { },
10291040
value_variable: () => { },
1041+
aria_label_value: () => { },
1042+
aria_label_title: () => { },
10301043
i18n: {}
10311044
}) {
10321045
var i18n = params.i18n || {};
@@ -1039,17 +1052,28 @@ class Tools {
10391052
"value"
10401053
]) {
10411054
label[key].i18n(params[key + "_i18n"])
1055+
var title = ref({}, {
1056+
handler: (args) => {
1057+
console.log(args)
1058+
label[key].aria_label(args.object.value)
1059+
}
1060+
})
10421061
var obj = ref({}, {
10431062
handler: (args) => {
10441063
label[key].t18n(args.object)
10451064
}
10461065
})
1047-
var handler = params[key + "_variable"]
1048-
if (!handler) continue;
1049-
try {
1050-
handler(obj)
1051-
} catch (e) {
1052-
console.error(e)
1066+
var handlers = [
1067+
[params[key + "_variable"], obj],
1068+
[params["aria_label_" + key], title],
1069+
]
1070+
for (let [handler, o] of handlers) {
1071+
if (!handler) continue;
1072+
try {
1073+
handler(o)
1074+
} catch (e) {
1075+
console.error(e)
1076+
}
10531077
}
10541078
}
10551079
})
@@ -1100,6 +1124,18 @@ class Tools {
11001124
// convert number to belike: 100,000, if 100000.0, we are 100,000.0
11011125
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ", ")
11021126
}
1127+
static formatUnitNumber(number) {
1128+
var i = 0
1129+
for (const [u, un] of Object.entries(Tools._NUMBER_UNITS).slice(1)) {
1130+
if (number / un < 1) {
1131+
break
1132+
}
1133+
number /= un
1134+
i += 1
1135+
}
1136+
let unit = Object.keys(Tools._NUMBER_UNITS)[i]
1137+
return `${number.toFixed(unit.length != 0 ? (number % 1 == 0 ? 0 : 1) : 2)}${unit}`
1138+
}
11031139
static _BYTES = {
11041140
"iB": 1,
11051141
"KiB": 1024,
@@ -1141,7 +1177,6 @@ class UserAuth {
11411177
})
11421178
}
11431179
}
1144-
11451180
const $userAuth = new UserAuth();
11461181

11471182
async function load() {
@@ -1334,6 +1369,9 @@ async function load() {
13341369
value_variable: (obj) => {
13351370
$dashboard_locals.files_info_today_hits = obj;
13361371
},
1372+
aria_label_value: (obj) => {
1373+
$dashboard_locals.files_info_today_hits_label = obj;
1374+
},
13371375
i18n: {
13381376
"zh_CN": {
13391377
"dashboard.title.today.hits": "今日下载数",
@@ -1360,6 +1398,9 @@ async function load() {
13601398
value_variable: (obj) => {
13611399
$dashboard_locals.files_info_30days_hits = obj;
13621400
},
1401+
aria_label_value: (obj) => {
1402+
$dashboard_locals.files_info_30days_hits_label = obj;
1403+
},
13631404
i18n: {
13641405
"zh_CN": {
13651406
"dashboard.title.30days.hits": "30 天下载数",
@@ -1920,28 +1961,32 @@ async function load() {
19201961
handler, obj, data
19211962
} of [
19221963
{
1923-
handler: Tools.formatSimpleNumber,
1924-
obj: $dashboard_locals.files_info_today_hits,
1964+
handler: Tools.formatUnitNumber,
1965+
obj: 'today_hits',
19251966
data: rdata.hourly_hits
19261967
},
19271968
{
1928-
handler: Tools.formatSimpleNumber,
1929-
obj: $dashboard_locals.files_info_30days_hits,
1969+
handler: Tools.formatUnitNumber,
1970+
obj: '30days_hits',
19301971
data: rdata.daily_hits
19311972
},
19321973
{
19331974
handler: Tools.formatBytes,
1934-
obj: $dashboard_locals.files_info_today_bytes,
1975+
obj: 'today_bytes',
19351976
data: rdata.hourly_bytes
19361977
},
19371978
{
19381979
handler: Tools.formatBytes,
1939-
obj: $dashboard_locals.files_info_30days_bytes,
1980+
obj: '30days_bytes',
19401981
data: rdata.daily_bytes
19411982
}
19421983
]) {
19431984
var formatted = handler(data)
1944-
obj.value = formatted
1985+
var o = $dashboard_locals[`files_info_${obj}`]
1986+
var label = $dashboard_locals[`files_info_${obj}_label`]
1987+
o.value = formatted
1988+
if (label == undefined) continue
1989+
label.value = data
19451990
}
19461991
})();
19471992
for (const [statistics_type, data] of Object.entries(temp_response)) {

core/cache.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import abc
21
import collections
3-
from dataclasses import dataclass
42
import inspect
53
import time
64
from typing import Any, Iterator, MutableMapping, Optional, TypeVar

core/cluster.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@
1616
import aiohttp
1717
from tqdm import tqdm
1818

19-
from . import web
20-
from . import utils, logger, config, scheduler, units, storages, i18n, dashboard
19+
from . import web, utils, logger, config, scheduler, units, storages, i18n, dashboard
2120
from .storages import File as SFile, MeasureFile
2221
import socketio
2322
import urllib.parse as urlparse

core/dashboard.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,30 @@
11
import asyncio
22
import base64
33
from collections import defaultdict, deque
4-
from dataclasses import asdict, dataclass, field, fields, is_dataclass
4+
from dataclasses import asdict, dataclass, is_dataclass
55
import datetime
66
import enum
77
import io
88
import json
99
import os
1010
from pathlib import Path
1111
import socket
12-
import sys
1312
import threading
1413
import time
1514
from typing import Any, Optional
1615

1716
import aiohttp
1817
import psutil
1918

20-
from core import cache, cluster, config, logger, units
19+
from . import cache, cluster, config, logger, units, utils, scheduler, database as db
2120
import ipdb
22-
from . import utils
2321

24-
from . import scheduler
2522
from .web import (
2623
routes as route,
2724
time_qps
2825
)
2926
from aiohttp import web
3027

31-
from . import database as db
32-
3328
@dataclass
3429
class CollectionUsage:
3530
total: int

core/database.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,6 @@ def decompress(data: bytes) -> defaultdict[str, int]:
215215
logger.ttraceback("database.error.unable.to.decompress", data=data)
216216
return defaultdict(lambda: 0)
217217

218-
219218
def commit():
220219
try:
221220
global FILE_CACHE
@@ -299,7 +298,6 @@ def init_storages_key(*storage: storages.iStorage):
299298
q.update({"data": content})
300299
session.commit()
301300

302-
303301
async def init():
304302
Base.metadata.create_all(engine)
305303
scheduler.run_repeat_later(commit, 5, 10)

core/logger.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import sys
22
import traceback
3-
from typing import Optional
43
from loguru import logger as Logger
54
from .config import const
65

core/units.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ def format_bytes(n: float) -> str:
4242
i += 1
4343
return f'{n:.2f}{BYTES_UNITS[i][0]}'
4444

45-
4645
def format_number(n: float) -> str:
4746
i = 0
4847
for u, un in NUMBER_UNITS[1:]:
@@ -52,7 +51,6 @@ def format_number(n: float) -> str:
5251
i += 1
5352
return f'{n:.2f}{NUMBER_UNITS[i][0]}'
5453

55-
5654
def format_count_time(n: float, round: int = 2) -> str:
5755
i = 0
5856
for u, un in TIME_UNITS[1:]:
@@ -75,7 +73,6 @@ def format_count_datetime(secs: float) -> str:
7573
else:
7674
return f'{m:02d}:{s:02d}'
7775

78-
7976
def format_datetime_from_timestamp(seconds: float):
8077
return datetime.fromtimestamp(seconds).strftime('%Y-%m-%d %H:%M:%S')
8178

core/utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -407,24 +407,20 @@ def parse_time(time_str: str):
407407
setattr(obj, maps[unit], value)
408408
return obj
409409

410-
411410
async def run_sync(func, *args, **kwargs):
412411
loop = asyncio.get_running_loop()
413412
return await loop.run_in_executor(None, func, *args, **kwargs)
414413

415-
416414
@dataclass
417415
class ServiceError:
418416
code: str
419417
httpCode: int
420418
message: str
421419
name: str
422420

423-
424421
wrapper_tqdms: deque[WrapperTQDM] = deque()
425422
status_manager: StatusManager = StatusManager()
426423

427-
428424
def retry(max_retries: int = 3, delay: float = 1.0):
429425
def decorator(func):
430426
@functools.wraps(func)
@@ -463,9 +459,11 @@ def _raise_invalid_id(oid: str):
463459
"%r is not a valid ObjectId, it must be a 12-byte input"
464460
" or a 24-character hex string" % oid
465461
)
462+
466463
def _random_bytes() -> bytes:
467464
"""Get the 5-byte random field of an ObjectId."""
468465
return os.urandom(5)
466+
469467
class ObjectId:
470468
_pid = os.getpid()
471469
_inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE)
@@ -571,6 +569,7 @@ def __hash__(self) -> int:
571569
return hash(self.__id)
572570

573571
ZERO: timedelta = timedelta(0)
572+
574573
class FixedOffset(tzinfo):
575574
def __init__(self, offset: Union[float, timedelta], name: str) -> None:
576575
if isinstance(offset, timedelta):
@@ -588,4 +587,5 @@ def tzname(self, dt: Optional[datetime]) -> str:
588587
return self.__name
589588
def dst(self, dt: Optional[datetime]) -> timedelta:
590589
return ZERO
590+
591591
utc: FixedOffset = FixedOffset(0, "UTC")

core/web.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ async def special_response():
114114
await asyncio.sleep(random.randint(30, 180))
115115
status = random.choice(DISALLOW_PUBLIC_DASHBOARD)
116116
return web.Response(status=status)
117+
117118
REQUEST_BUFFER = 4096
118119
IO_BUFFER = 16384
119120
FINDING_FILTER = "127.0.0.1"
@@ -166,6 +167,7 @@ async def special_response():
166167
431,
167168
451,
168169
]
170+
169171
ip_tables: dict[tuple[str, int], tuple[str, int]] = {}
170172
ip_count: defaultdict[tuple[str, int], int] = defaultdict(int)
171173
app = web.Application(
@@ -174,12 +176,10 @@ async def special_response():
174176
]
175177
)
176178
routes = web.RouteTableDef()
177-
178179
runner: Optional[web.AppRunner] = None
179180
site: Optional[web.TCPSite] = None
180181
public_servers: deque[asyncio.Server] = deque()
181182
privates: dict[tuple[str, str], PrivateSSLServer] = {}
182-
183183
time_qps: defaultdict[int, int] = defaultdict(int)
184184
xff: int = config.const.xff
185185

@@ -368,7 +368,6 @@ def start():
368368
await start()
369369
logger.tsuccess("web.success.public_port", port=port, current=len(public_servers), total=count)
370370

371-
372371
def get_public_port():
373372
port = int(config.const.port)
374373
if port < 0:

0 commit comments

Comments
 (0)