🐛 永久封存恢复前的旧取件码
This commit is contained in:
1 parent
56a86c59cf
commit
d75044e884
7 files changed
+92
-10
No files matched your search
@@ -17,7 +17,7 @@ from core.settings import (
|
||||
)
|
||||
from core.config import refresh_settings
|
||||
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
|
||||
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, get_random_code
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
@@ -178,6 +178,11 @@ class FileService:
|
||||
original_path,
|
||||
)
|
||||
file_code.file_path = destination_dir
|
||||
original_code = file_code.code
|
||||
await ShareCodeReservations.get_or_create(
|
||||
code=original_code,
|
||||
defaults={"file_code_id": file_code.id, "reason": "restored"},
|
||||
)
|
||||
file_code.code = await get_random_code()
|
||||
file_code.is_trashed = False
|
||||
file_code.trashed_at = None
|
||||
|
||||
+6
-4
@@ -31,7 +31,7 @@ from apps.admin.schemas import (
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
|
||||
from apps.admin.dependencies import (
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
@@ -859,9 +859,11 @@ async def update_file(
|
||||
update_data = {}
|
||||
|
||||
if data.code is not None and data.code != file_code.code:
|
||||
# 判断code是否存在
|
||||
if await FileCodes.filter(code=data.code).first():
|
||||
raise HTTPException(status_code=400, detail="code已存在")
|
||||
# 当前记录和全部退役取件码都不可重复使用。
|
||||
if await FileCodes.filter(code=data.code).first() or await ShareCodeReservations.filter(
|
||||
code=data.code
|
||||
).first():
|
||||
raise HTTPException(status_code=400, detail="取件码已被占用")
|
||||
update_data["code"] = data.code
|
||||
if data.prefix is not None and data.prefix != file_code.prefix:
|
||||
update_data["prefix"] = data.prefix
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS share_code_reservations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
code VARCHAR(255) NOT NULL UNIQUE,
|
||||
file_code_id INT NULL,
|
||||
reason VARCHAR(32) NOT NULL DEFAULT 'retired',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_code
|
||||
ON share_code_reservations(code);
|
||||
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_file_code_id
|
||||
ON share_code_reservations(file_code_id);
|
||||
"""
|
||||
)
|
||||
@@ -46,6 +46,19 @@ class FileCodes(models.Model):
|
||||
return f"{self.file_path}/{self.uuid_file_name}"
|
||||
|
||||
|
||||
class ShareCodeReservations(models.Model):
|
||||
"""已退役取件码的永久封存登记,防止恢复文件后旧码被重新分配。"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
code = fields.CharField(max_length=255, unique=True, index=True)
|
||||
file_code_id = fields.IntField(null=True, index=True)
|
||||
reason = fields.CharField(max_length=32, default="retired")
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
table = "share_code_reservations"
|
||||
|
||||
|
||||
class UploadChunk(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, index=True)
|
||||
|
||||
+4
-2
@@ -8,7 +8,7 @@ from fastapi import UploadFile, HTTPException
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.models import FileCodes, ShareCodeReservations
|
||||
from core.settings import settings
|
||||
from core.utils import (
|
||||
get_random_num,
|
||||
@@ -122,7 +122,9 @@ async def get_random_code(style: str | None = None) -> str:
|
||||
if code_style == "number"
|
||||
else await get_random_string(CODE_LENGTH)
|
||||
)
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
if not await FileCodes.filter(code=code).exists() and not await ShareCodeReservations.filter(
|
||||
code=code
|
||||
).exists():
|
||||
return str(code)
|
||||
raise HTTPException(status_code=503, detail="取件码生成暂时繁忙,请重试")
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, patch
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.models import FileCodes, ShareCodeReservations
|
||||
from apps.base.utils import CODE_LENGTH, get_random_code
|
||||
from apps.admin.services import FileService
|
||||
from core.settings import settings
|
||||
@@ -55,8 +55,8 @@ class RecycleBinTests(unittest.TestCase):
|
||||
with self.assertRaises(Exception):
|
||||
await service.restore_from_trash(item.id)
|
||||
|
||||
await FileCodes.create(code="RETIRED1", is_trashed=True, trash_purged_at=datetime.datetime.now())
|
||||
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRED1", "FRESH002"])):
|
||||
await ShareCodeReservations.create(code="RETIRE02", file_code_id=item.id)
|
||||
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRE02", "FRESH002"])):
|
||||
self.assertEqual(await get_random_code(), "FRESH002")
|
||||
|
||||
generated_code = await get_random_code()
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.admin.services import FileService
|
||||
from apps.base.models import FileCodes, ShareCodeReservations
|
||||
|
||||
|
||||
class ShareCodeReservationTests(unittest.TestCase):
|
||||
def test_restore_reserves_old_code_before_assigning_new_code(self):
|
||||
asyncio.run(self.scenario())
|
||||
|
||||
async def scenario(self):
|
||||
await Tortoise.init(
|
||||
config={
|
||||
"connections": {"default": {"engine": "tortoise.backends.sqlite", "credentials": {"file_path": ":memory:"}}},
|
||||
"apps": {"models": {"models": ["apps.base.models"], "default_connection": "default"}},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
)
|
||||
await Tortoise.generate_schemas()
|
||||
try:
|
||||
item = await FileCodes.create(code="OLD_CODE", is_trashed=True, text="text")
|
||||
service = FileService()
|
||||
with patch("apps.admin.services.get_random_code", AsyncMock(return_value="NEWCODE8")):
|
||||
restored = await service.restore_from_trash(item.id)
|
||||
|
||||
self.assertEqual(restored.code, "NEWCODE8")
|
||||
reservation = await ShareCodeReservations.get(code="OLD_CODE")
|
||||
self.assertEqual(reservation.file_code_id, item.id)
|
||||
self.assertEqual(reservation.reason, "restored")
|
||||
finally:
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user