✨ feat(backend): 补齐本地目录分页搜索与分享校验

This commit is contained in:
orion committed 2026-09-18 10:57:20 +08:00
1 parent 96e8eeac39
commit 3e32806b59
7 files changed
+137 -15

No files matched your search

+3 -3
View File
@@ -13,9 +13,9 @@ class IDsData(BaseModel):
class ShareItem(BaseModel):
expire_value: int
expire_style: str = "day"
filename: str
expire_value: int = Field(gt=0, le=1_000_000, strict=True)
expire_style: Literal["day", "hour", "minute", "count", "forever"] = "day"
filename: str = Field(min_length=1, max_length=255)
class DeleteItem(BaseModel):
+24 -7
View File
@@ -23,7 +23,7 @@ from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
from apps.base.utils import get_expire_info, get_random_code
from apps.base.utils import get_expire_info, get_random_code, validate_expire_style
from fastapi import HTTPException
from core.utils import get_now, hash_password, is_password_hashed, validate_background_url
@@ -1674,6 +1674,7 @@ class FileService(TrashManagementMixin):
}
async def share_local_file(self, item):
validate_expire_style(item.expire_style)
local_file = LocalFileClass(item.filename)
if not await local_file.exists():
raise HTTPException(status_code=404, detail="文件不存在")
@@ -1837,7 +1838,13 @@ class ConfigService:
).update(trash_expires_at=retention_expiry)
class LocalFileService:
async def list_files(self, path: str = "", *, legacy: bool = False):
async def list_files(self, path: str = "", *, legacy: bool = False, page: int | None = None, size: int = 20, keyword: str = ""):
# NAS metadata access may block; keep the request event loop responsive.
return await asyncio.to_thread(self._list_files, path, legacy=legacy, page=page, size=size, keyword=keyword)
def _list_files(self, path: str, *, legacy: bool, page: int | None, size: int, keyword: str):
if page is not None and (page < 1 or not 1 <= size <= 100):
raise HTTPException(status_code=400, detail="分页参数无效")
relpath = normalize_local_relpath(path, allow_empty=True)
directory = resolve_under_local(relpath)
if not directory.exists() or not directory.is_dir():
@@ -1850,16 +1857,15 @@ class LocalFileService:
except OSError as exc:
raise HTTPException(status_code=500, detail="无法读取目录") from exc
children.sort(key=lambda p: (not p.is_dir(), p.name.lower()))
keyword = keyword.strip().casefold()
truncated = False
for child in children:
if not legacy and len(items) >= MAX_LIST_ENTRIES:
truncated = True
break
try:
resolved = child.resolve()
resolved.relative_to(root)
except (OSError, ValueError):
except (OSError, ValueError, RuntimeError):
continue
if keyword and keyword not in child.name.casefold():
continue
if not resolved.is_file() and not resolved.is_dir():
continue
@@ -1878,6 +1884,14 @@ class LocalFileService:
}
)
items.sort(key=lambda item: (item["type"] != "dir", item["name"].casefold(), item["name"]))
total = len(items)
if page is not None:
page = min(page, max(1, (total + size - 1) // size))
items = items[(page - 1) * size:page * size]
elif not legacy:
truncated = total > MAX_LIST_ENTRIES
items = items[:MAX_LIST_ENTRIES]
parent = ""
if relpath:
parent_path = Path(relpath).parent.as_posix()
@@ -1887,6 +1901,9 @@ class LocalFileService:
"parent": parent,
"truncated": truncated,
"items": items,
"total": total,
"page": page,
"size": size,
}
async def delete_file(self, filename: str):
+5 -2
View File
@@ -6,7 +6,7 @@ import datetime
from collections import Counter
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Query
from apps.admin import services as admin_services
from apps.admin.services import FileService, ConfigService, LocalFileService
from apps.admin.dependencies import (
@@ -831,9 +831,12 @@ async def file_preview(
@admin_api.get("/local/lists")
async def get_local_lists(
path: Optional[str] = None,
page: Optional[int] = Query(default=None, ge=1),
size: int = Query(default=20, ge=1, le=100),
keyword: str = Query(default="", max_length=255),
local_file_service: LocalFileService = Depends(get_local_file_service),
):
listing = await local_file_service.list_files(path or "", legacy=path is None)
listing = await local_file_service.list_files(path or "", legacy=path is None, page=page, size=size, keyword=keyword)
# 无 path 参数保留旧主题的数组响应;显式 path 支持目录导航。
files = listing if path is not None else [item for item in listing["items"] if item["type"] == "file"]
return APIResponse(detail=files)