style: code format

This commit is contained in:
Lan
2025-02-15 22:00:53 +08:00
parent 802d2551ff
commit 1ff1d6c695
14 changed files with 404 additions and 311 deletions
+2 -2
View File
@@ -6,10 +6,10 @@ from typing import Generic, TypeVar
from pydantic.v1.generics import GenericModel
T = TypeVar('T')
T = TypeVar("T")
class APIResponse(GenericModel, Generic[T]):
code: int = 200
message: str = 'ok'
message: str = "ok"
detail: T
+59 -57
View File
@@ -5,70 +5,70 @@
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
data_root = BASE_DIR / 'data'
data_root = BASE_DIR / "data"
if not data_root.exists():
data_root.mkdir(parents=True, exist_ok=True)
DEFAULT_CONFIG = {
'file_storage': 'local',
'storage_path': '',
'name': '文件快递柜 - FileCodeBox',
'description': '开箱即用的文件快传系统',
'notify_title': '系统通知',
'notify_content': '欢迎使用 FileCodeBox,本程序开源于 <a href="https://github.com/vastsa/FileCodeBox" target="_blank">Github</a> ,欢迎Star和Fork。',
'page_explain': '请勿上传或分享违法内容。根据《中华人民共和国网络安全法》、《中华人民共和国刑法》、《中华人民共和国治安管理处罚法》等相关规定。 传播或存储违法、违规内容,会受到相关处罚,严重者将承担刑事责任。本站坚决配合相关部门,确保网络内容的安全,和谐,打造绿色网络环境。',
'keywords': 'FileCodeBox, 文件快递柜, 口令传送箱, 匿名口令分享文本, 文件',
's3_access_key_id': '',
's3_secret_access_key': '',
's3_bucket_name': '',
's3_endpoint_url': '',
's3_region_name': 'auto',
's3_signature_version': 's3v2',
's3_hostname': '',
's3_proxy': 0,
'max_save_seconds': 0,
'aws_session_token': '',
'onedrive_domain': '',
'onedrive_client_id': '',
'onedrive_username': '',
'onedrive_password': '',
'onedrive_root_path': 'filebox_storage',
'onedrive_proxy': 0,
'webdav_hostname': '',
'webdav_root_path': 'filebox_storage',
'webdav_proxy': 0,
'admin_token': 'FileCodeBox2023',
'openUpload': 1,
'uploadSize': 1024 * 1024 * 10,
'expireStyle': ['day', 'hour', 'minute', 'forever', 'count'],
'uploadMinute': 1,
'webdav_url': '',
'webdav_password': '',
'webdav_username': '',
'opacity': 0.9,
'background': '',
'uploadCount': 10,
'themesChoices': [
"file_storage": "local",
"storage_path": "",
"name": "文件快递柜 - FileCodeBox",
"description": "开箱即用的文件快传系统",
"notify_title": "系统通知",
"notify_content": '欢迎使用 FileCodeBox,本程序开源于 <a href="https://github.com/vastsa/FileCodeBox" target="_blank">Github</a> ,欢迎Star和Fork。',
"page_explain": "请勿上传或分享违法内容。根据《中华人民共和国网络安全法》、《中华人民共和国刑法》、《中华人民共和国治安管理处罚法》等相关规定。 传播或存储违法、违规内容,会受到相关处罚,严重者将承担刑事责任。本站坚决配合相关部门,确保网络内容的安全,和谐,打造绿色网络环境。",
"keywords": "FileCodeBox, 文件快递柜, 口令传送箱, 匿名口令分享文本, 文件",
"s3_access_key_id": "",
"s3_secret_access_key": "",
"s3_bucket_name": "",
"s3_endpoint_url": "",
"s3_region_name": "auto",
"s3_signature_version": "s3v2",
"s3_hostname": "",
"s3_proxy": 0,
"max_save_seconds": 0,
"aws_session_token": "",
"onedrive_domain": "",
"onedrive_client_id": "",
"onedrive_username": "",
"onedrive_password": "",
"onedrive_root_path": "filebox_storage",
"onedrive_proxy": 0,
"webdav_hostname": "",
"webdav_root_path": "filebox_storage",
"webdav_proxy": 0,
"admin_token": "FileCodeBox2023",
"openUpload": 1,
"uploadSize": 1024 * 1024 * 10,
"expireStyle": ["day", "hour", "minute", "forever", "count"],
"uploadMinute": 1,
"webdav_url": "",
"webdav_password": "",
"webdav_username": "",
"opacity": 0.9,
"background": "",
"uploadCount": 10,
"themesChoices": [
{
'name': '2023',
'key': 'themes/2023',
'author': 'Lan',
'version': '1.0',
"name": "2023",
"key": "themes/2023",
"author": "Lan",
"version": "1.0",
},
{
'name': '2024',
'key': 'themes/2024',
'author': 'Lan',
'version': '1.0',
}
"name": "2024",
"key": "themes/2024",
"author": "Lan",
"version": "1.0",
},
],
'themesSelect': 'themes/2024',
'errorMinute': 1,
'errorCount': 1,
'port': 12345,
'showAdminAddr': 0,
'robotsText': 'User-agent: *\nDisallow: /',
"themesSelect": "themes/2024",
"errorMinute": 1,
"errorCount": 1,
"port": 12345,
"showAdminAddr": 0,
"robotsText": "User-agent: *\nDisallow: /",
}
@@ -82,10 +82,12 @@ class Settings:
return self.user_config[attr]
if attr in self.default_config:
return self.default_config[attr]
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attr}'")
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{attr}'"
)
def __setattr__(self, key, value):
if key in ['default_config', 'user_config']:
if key in ["default_config", "user_config"]:
super().__setattr__(key, value)
else:
self.user_config[key] = value
+6 -6
View File
@@ -412,7 +412,7 @@ class WebDAVFileStorage(FileStorageInterface):
async def _is_dir_empty(self, dir_path: str) -> bool:
"""检查目录是否为空"""
url = self._build_url(dir_path)
async with aiohttp.ClientSession(auth=self.auth) as session:
async with session.request("PROPFIND", url, headers={"Depth": "1"}) as resp:
if resp.status != 207: # 207 是 Multi-Status 响应
@@ -425,16 +425,16 @@ class WebDAVFileStorage(FileStorageInterface):
"""递归删除空目录"""
path_obj = Path(file_path)
current_path = path_obj.parent
while str(current_path) != ".":
if not await self._is_dir_empty(str(current_path)):
break
url = self._build_url(str(current_path))
async with session.delete(url) as resp:
if resp.status not in (200, 204, 404):
break
current_path = current_path.parent
async def save_file(self, file: UploadFile, save_path: str):
@@ -478,10 +478,10 @@ class WebDAVFileStorage(FileStorageInterface):
status_code=resp.status,
detail=f"WebDAV删除失败: {content[:200]}",
)
# 使用同一个 session 删除空目录
await self._delete_empty_dirs(file_path, session)
except aiohttp.ClientError as e:
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
+6 -4
View File
@@ -19,13 +19,15 @@ async def delete_expire_files():
while True:
try:
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
if settings.file_storage == 'local':
if settings.file_storage == "local":
for root, dirs, files in os.walk(f"{data_root}/share/data"):
if not dirs and not files:
os.rmdir(root)
await ip_limit['error'].remove_expired_ip()
await ip_limit['upload'].remove_expired_ip()
expire_data = await FileCodes.filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
await ip_limit["error"].remove_expired_ip()
await ip_limit["upload"].remove_expired_ip()
expire_data = await FileCodes.filter(
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
).all()
for exp in expire_data:
await file_storage.delete_file(exp)
await exp.delete()
+22 -21
View File
@@ -9,6 +9,7 @@ import string
import time
from core.settings import settings
async def get_random_num():
"""
获取随机数
@@ -25,7 +26,7 @@ async def get_random_string():
获取随机字符串
:return:
"""
return ''.join(random.choice(r_s) for _ in range(5))
return "".join(random.choice(r_s) for _ in range(5))
async def get_now():
@@ -33,9 +34,7 @@ async def get_now():
获取当前时间
:return:
"""
return datetime.datetime.now(
datetime.timezone(datetime.timedelta(hours=8))
)
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
async def get_select_token(code: str):
@@ -45,7 +44,9 @@ async def get_select_token(code: str):
:return:
"""
token = settings.admin_token
return hashlib.sha256(f"{code}{int(time.time() / 1000)}000{token}".encode()).hexdigest()
return hashlib.sha256(
f"{code}{int(time.time() / 1000)}000{token}".encode()
).hexdigest()
async def get_file_url(code: str):
@@ -54,7 +55,7 @@ async def get_file_url(code: str):
:param code:
:return:
"""
return f'/share/download?key={await get_select_token(code)}&code={code}'
return f"/share/download?key={await get_select_token(code)}&code={code}"
async def max_save_times_desc(max_save_seconds: int):
@@ -66,28 +67,28 @@ async def max_save_times_desc(max_save_seconds: int):
def gen_desc_zh(value: int, desc: str):
if value > 0:
return f'{value}{desc}'
return f"{value}{desc}"
else:
return ''
return ""
def gen_desc_en(value: int, desc: str):
if value > 0:
ret = f'{value} {desc}'
ret = f"{value} {desc}"
if value > 1:
ret += 's'
ret += ' '
ret += "s"
ret += " "
return ret
else:
return ''
return ""
max_timedelta = datetime.timedelta(seconds=max_save_seconds)
desc_zh, desc_en = '最长保存时间:', 'Max save time: '
desc_zh += gen_desc_zh(max_timedelta.days, '')
desc_en += gen_desc_en(max_timedelta.days, 'day')
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, '小时')
desc_en += gen_desc_en(max_timedelta.seconds // 3600, 'hour')
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, '分钟')
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, 'minute')
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, '')
desc_en += gen_desc_en(max_timedelta.seconds % 60, 'second')
desc_zh, desc_en = "最长保存时间:", "Max save time: "
desc_zh += gen_desc_zh(max_timedelta.days, "")
desc_en += gen_desc_en(max_timedelta.days, "day")
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时")
desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour")
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟")
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute")
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "")
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
return desc_zh, desc_en