Skip to content

Commit bd6f646

Browse files
committed
fix: some error
1 parent 5f82650 commit bd6f646

File tree

7 files changed

+39
-25
lines changed

7 files changed

+39
-25
lines changed

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,4 +156,7 @@ data/.env
156156
/cloc-1.64.exe
157157

158158
# Ignore node_modules
159-
node_modules/
159+
node_modules/
160+
161+
162+
AGENTS.md

apps/admin/services.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,10 +123,14 @@ class LocalFileClass:
123123
def __init__(self, file):
124124
self.file = file
125125
self.path = data_root / "local" / file
126-
self.ctime = time.strftime(
127-
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
128-
)
129-
self.size = os.path.getsize(self.path)
126+
if os.path.exists(self.path):
127+
self.ctime = time.strftime(
128+
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
129+
)
130+
self.size = os.path.getsize(self.path)
131+
else:
132+
self.ctime = None
133+
self.size = None
130134

131135
async def read(self):
132136
return open(self.path, "rb")

apps/base/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,6 @@ async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
109109

110110

111111
ip_limit = {
112-
"error": IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute),
113-
"upload": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
112+
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
113+
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
114114
}

apps/base/views.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,19 @@
1616
share_api = APIRouter(prefix="/share", tags=["分享"])
1717

1818

19-
async def validate_file_size(file: UploadFile, max_size: int):
20-
if file.size > max_size:
19+
async def validate_file_size(file: UploadFile, max_size: int) -> int:
20+
size = file.size
21+
if size is None:
22+
# 读取流计算大小,保持指针复位
23+
await file.seek(0, 2)
24+
size = file.file.tell()
25+
await file.seek(0)
26+
if size > max_size:
2127
max_size_mb = max_size / (1024 * 1024)
2228
raise HTTPException(
2329
status_code=403, detail=f"大小超过限制,最大为{max_size_mb:.2f} MB"
2430
)
31+
return size
2532

2633

2734
async def create_file_code(code, **kwargs):
@@ -63,7 +70,7 @@ async def share_file(
6370
file: UploadFile = File(...),
6471
ip: str = Depends(ip_limit["upload"]),
6572
):
66-
await validate_file_size(file, settings.uploadSize)
73+
file_size = await validate_file_size(file, settings.uploadSize)
6774
if expire_style not in settings.expireStyle:
6875
raise HTTPException(status_code=400, detail="过期时间类型错误")
6976
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
@@ -76,7 +83,7 @@ async def share_file(
7683
suffix=suffix,
7784
uuid_file_name=uuid_file_name,
7885
file_path=path,
79-
size=file.size,
86+
size=file_size,
8087
expired_at=expired_at,
8188
expired_count=expired_count,
8289
used_count=used_count,
@@ -141,6 +148,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
141148
file_storage: FileStorageInterface = storages[settings.file_storage]()
142149
if await get_select_token(code) != key:
143150
ip_limit["error"].add_ip(ip)
151+
raise HTTPException(status_code=403, detail="下载鉴权失败")
144152
has, file_code = await get_code_file_by_code(code, False)
145153
if not has:
146154
return APIResponse(code=404, detail="文件不存在")

core/storage.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,6 @@
2727

2828

2929
class FileStorageInterface:
30-
_instance: Optional["FileStorageInterface"] = None
31-
32-
def __new__(cls, *args, **kwargs):
33-
if cls._instance is None:
34-
cls._instance = super(FileStorageInterface, cls).__new__(
35-
cls, *args, **kwargs
36-
)
37-
return cls._instance
3830

3931
async def save_file(self, file: UploadFile, save_path: str):
4032
"""
@@ -191,7 +183,10 @@ async def clean_chunks(self, upload_id: str, save_path: str):
191183
"""
192184
chunk_dir = (self.root_path / save_path).parent / 'chunks'
193185
if chunk_dir.exists():
194-
shutil.rmtree(chunk_dir)
186+
try:
187+
shutil.rmtree(chunk_dir)
188+
except Exception as e:
189+
logger.info(f"清理本地分片目录失败: {e}")
195190

196191

197192
class S3FileStorage(FileStorageInterface):

core/tasks.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,14 @@ async def delete_expire_files():
3030
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
3131
).all()
3232
for exp in expire_data:
33-
await file_storage.delete_file(exp)
34-
await exp.delete()
33+
try:
34+
await file_storage.delete_file(exp)
35+
except Exception as e:
36+
logging.error(f"删除过期文件失败 code={exp.code}: {e}")
37+
try:
38+
await exp.delete()
39+
except Exception as e:
40+
logging.error(f"删除记录失败 code={exp.code}: {e}")
3541
except Exception as e:
3642
logging.error(e)
3743
finally:

core/utils.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,7 @@ async def get_select_token(code: str):
4646
:return:
4747
"""
4848
token = settings.admin_token
49-
return hashlib.sha256(
50-
f"{code}{int(time.time() / 1000)}000{token}".encode()
51-
).hexdigest()
49+
return hashlib.sha256(f"{code}{int(time.time() / 1000)}000{token}".encode()).hexdigest()
5250

5351

5452
async def get_file_url(code: str):

0 commit comments

Comments
 (0)