✨ feat(backend): 补齐本地目录分页搜索与分享校验
This commit is contained in:
1 parent
96e8eeac39
commit
3e32806b59
7 files changed
+137
-15
No files matched your search
@@ -1 +1 @@
|
|||||||
7f9aaf8a4d8045a807b97c87ed54954fea062e43
|
e8c12af8348076125f6f0748c0c42bbfa63aae9f
|
||||||
+15
-1
@@ -21,7 +21,9 @@
|
|||||||
仪表盘仍使用定制健康规则;没有照搬上游整套统计重构。
|
仪表盘仍使用定制健康规则;没有照搬上游整套统计重构。
|
||||||
|
|
||||||
`GET /admin/local/lists` 保留旧数组响应;显式 `?path=` 返回目录对象,
|
`GET /admin/local/lists` 保留旧数组响应;显式 `?path=` 返回目录对象,
|
||||||
含 `items/path/parent/truncated`,目录浏览最多返回 500 项。
|
含 `items/path/parent/truncated`。旧目录请求最多返回 500 项;新增 `page`、`size`(1–100)
|
||||||
|
和 `keyword` 后返回完整目录的分页结果(含 `total/page/size`),搜索先于分页。
|
||||||
|
目录扫描在工作线程执行,慢 NAS 不阻塞 API 事件循环。
|
||||||
`POST /admin/local/share` 的 `filename` 可传相对路径。
|
`POST /admin/local/share` 的 `filename` 可传相对路径。
|
||||||
管理端“删除本地文件”接口仍会删除指定原件;这与删除分享记录不同。
|
管理端“删除本地文件”接口仍会删除指定原件;这与删除分享记录不同。
|
||||||
|
|
||||||
@@ -75,3 +77,15 @@ docker build -f Dockerfile.upgrade \
|
|||||||
官方发布更高版本后仍应提示,再重复本流程。
|
官方发布更高版本后仍应提示,再重复本流程。
|
||||||
|
|
||||||
生产按单 worker 运行。配置/审计写锁为进程内锁;多 worker 需要跨进程并发控制后再启用。
|
生产按单 worker 运行。配置/审计写锁为进程内锁;多 worker 需要跨进程并发控制后再启用。
|
||||||
|
|
||||||
|
## 本地文件分享入口
|
||||||
|
|
||||||
|
管理后台 → 本地文件(`/#/admin/local`):浏览子目录、搜索、分页,选择文件后设置
|
||||||
|
有效期并生成取件码,支持复制取件码和分享链接。分享记录统一出现在文件管理。
|
||||||
|
生成失败在弹窗内提示,支持重试;成功后不会因重复点击再生成一条记录。
|
||||||
|
|
||||||
|
正式站本地原件目录:`/opt/1panel/apps/filecodebox/filecodebox/data/local/`;
|
||||||
|
测试站对应 `filecodebox-test/data/local/`。它们与 WebDAV 独立,普通上传仍走 WebDAV。
|
||||||
|
用户可先把服务器已有文件放入该目录,或自行将 NAS 挂载到容器 `/app/data/local`。
|
||||||
|
本次不迁移 WebDAV 文件、不新增宿主机目录挂载。分享期间应保持原文件路径可读;
|
||||||
|
移动、删除或修改原件会影响下载。此页面没有删除原件操作,删除分享不会删除原件。
|
||||||
@@ -13,9 +13,9 @@ class IDsData(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ShareItem(BaseModel):
|
class ShareItem(BaseModel):
|
||||||
expire_value: int
|
expire_value: int = Field(gt=0, le=1_000_000, strict=True)
|
||||||
expire_style: str = "day"
|
expire_style: Literal["day", "hour", "minute", "count", "forever"] = "day"
|
||||||
filename: str
|
filename: str = Field(min_length=1, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
class DeleteItem(BaseModel):
|
class DeleteItem(BaseModel):
|
||||||
|
|||||||
+24
-7
@@ -23,7 +23,7 @@ from core.config import refresh_settings
|
|||||||
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
|
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.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 fastapi import HTTPException
|
||||||
from core.utils import get_now, hash_password, is_password_hashed, validate_background_url
|
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):
|
async def share_local_file(self, item):
|
||||||
|
validate_expire_style(item.expire_style)
|
||||||
local_file = LocalFileClass(item.filename)
|
local_file = LocalFileClass(item.filename)
|
||||||
if not await local_file.exists():
|
if not await local_file.exists():
|
||||||
raise HTTPException(status_code=404, detail="文件不存在")
|
raise HTTPException(status_code=404, detail="文件不存在")
|
||||||
@@ -1837,7 +1838,13 @@ class ConfigService:
|
|||||||
).update(trash_expires_at=retention_expiry)
|
).update(trash_expires_at=retention_expiry)
|
||||||
|
|
||||||
class LocalFileService:
|
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)
|
relpath = normalize_local_relpath(path, allow_empty=True)
|
||||||
directory = resolve_under_local(relpath)
|
directory = resolve_under_local(relpath)
|
||||||
if not directory.exists() or not directory.is_dir():
|
if not directory.exists() or not directory.is_dir():
|
||||||
@@ -1850,16 +1857,15 @@ class LocalFileService:
|
|||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
raise HTTPException(status_code=500, detail="无法读取目录") from 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
|
truncated = False
|
||||||
for child in children:
|
for child in children:
|
||||||
if not legacy and len(items) >= MAX_LIST_ENTRIES:
|
|
||||||
truncated = True
|
|
||||||
break
|
|
||||||
try:
|
try:
|
||||||
resolved = child.resolve()
|
resolved = child.resolve()
|
||||||
resolved.relative_to(root)
|
resolved.relative_to(root)
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError, RuntimeError):
|
||||||
|
continue
|
||||||
|
if keyword and keyword not in child.name.casefold():
|
||||||
continue
|
continue
|
||||||
if not resolved.is_file() and not resolved.is_dir():
|
if not resolved.is_file() and not resolved.is_dir():
|
||||||
continue
|
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 = ""
|
parent = ""
|
||||||
if relpath:
|
if relpath:
|
||||||
parent_path = Path(relpath).parent.as_posix()
|
parent_path = Path(relpath).parent.as_posix()
|
||||||
@@ -1887,6 +1901,9 @@ class LocalFileService:
|
|||||||
"parent": parent,
|
"parent": parent,
|
||||||
"truncated": truncated,
|
"truncated": truncated,
|
||||||
"items": items,
|
"items": items,
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"size": size,
|
||||||
}
|
}
|
||||||
|
|
||||||
async def delete_file(self, filename: str):
|
async def delete_file(self, filename: str):
|
||||||
|
|||||||
+5
-2
@@ -6,7 +6,7 @@ import datetime
|
|||||||
from collections import Counter
|
from collections import Counter
|
||||||
from typing import Optional
|
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 import services as admin_services
|
||||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||||
from apps.admin.dependencies import (
|
from apps.admin.dependencies import (
|
||||||
@@ -831,9 +831,12 @@ async def file_preview(
|
|||||||
@admin_api.get("/local/lists")
|
@admin_api.get("/local/lists")
|
||||||
async def get_local_lists(
|
async def get_local_lists(
|
||||||
path: Optional[str] = None,
|
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),
|
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 支持目录导航。
|
# 无 path 参数保留旧主题的数组响应;显式 path 支持目录导航。
|
||||||
files = listing if path is not None else [item for item in listing["items"] if item["type"] == "file"]
|
files = listing if path is not None else [item for item in listing["items"] if item["type"] == "file"]
|
||||||
return APIResponse(detail=files)
|
return APIResponse(detail=files)
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from apps.admin.services import LocalFileService
|
||||||
|
from apps.admin.views import admin_api
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
from apps.base.models import FileCodes
|
||||||
|
from core.settings import settings
|
||||||
|
from tests.helpers import init_memory_db, close_db
|
||||||
|
|
||||||
|
|
||||||
|
class LocalBrowserTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.original = dict(settings.user_config)
|
||||||
|
await init_memory_db()
|
||||||
|
self.tmp = TemporaryDirectory()
|
||||||
|
self.root = Path(self.tmp.name)
|
||||||
|
self.patch = patch('core.settings.data_root', self.root)
|
||||||
|
self.patch.start()
|
||||||
|
(self.root/'local').mkdir()
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
self.patch.stop()
|
||||||
|
self.tmp.cleanup()
|
||||||
|
settings.user_config = self.original
|
||||||
|
await close_db()
|
||||||
|
|
||||||
|
async def test_pagination_and_search_reach_beyond_500_entries(self):
|
||||||
|
root = self.root/'local'
|
||||||
|
for n in range(505): (root/f'{n:04d}.txt').write_text('data')
|
||||||
|
(root/'folder').mkdir()
|
||||||
|
service = LocalFileService()
|
||||||
|
first = await service.list_files('', page=1, size=20)
|
||||||
|
self.assertEqual((first['total'], first['page'], first['size']), (506,1,20))
|
||||||
|
self.assertEqual(first['items'][0]['type'], 'dir')
|
||||||
|
last = await service.list_files('', page=26, size=20)
|
||||||
|
self.assertEqual(last['items'][-1]['name'], '0504.txt')
|
||||||
|
self.assertEqual(len(last['items']), 6)
|
||||||
|
search = await service.list_files('', page=1, size=20, keyword='0504')
|
||||||
|
self.assertEqual(search['total'],1)
|
||||||
|
self.assertEqual(search['items'][0]['path'],'0504.txt')
|
||||||
|
self.assertEqual(len((await service.list_files('', legacy=True))['items']),505)
|
||||||
|
empty = await service.list_files('', page=999, size=20, keyword='missing')
|
||||||
|
self.assertEqual((empty['page'],empty['items']), (1,[]))
|
||||||
|
|
||||||
|
async def test_http_pagination_auth_and_share_validation(self):
|
||||||
|
(self.root/'local'/'safe.txt').write_text('safe')
|
||||||
|
app = FastAPI(); app.include_router(admin_api)
|
||||||
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test') as client:
|
||||||
|
self.assertIn((await client.get('/admin/local/lists?path=&page=1')).status_code,(401,403))
|
||||||
|
app.dependency_overrides[admin_required] = lambda: None
|
||||||
|
response=await client.get('/admin/local/lists?path=&page=1&size=20&keyword=safe')
|
||||||
|
self.assertEqual(response.status_code,200)
|
||||||
|
self.assertEqual(response.json()['detail']['total'],1)
|
||||||
|
for params in [{'page':0},{'size':0},{'size':101}]:
|
||||||
|
self.assertEqual((await client.get('/admin/local/lists',params={'path':'',**params})).status_code,422)
|
||||||
|
settings.expireStyle=['day','count']
|
||||||
|
for style,value in [('wrong',1),('forever',1),('day',0),('day',-1),('count',0)]:
|
||||||
|
r=await client.post('/admin/local/share',json={'filename':'safe.txt','expire_style':style,'expire_value':value})
|
||||||
|
self.assertIn(r.status_code,(400,422),r.text)
|
||||||
|
self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
r=await client.post('/admin/local/share',json={'filename':'safe.txt','expire_style':'count','expire_value':2})
|
||||||
|
self.assertEqual(r.status_code,200,r.text)
|
||||||
|
self.assertEqual((await FileCodes.get(code=r.json()['detail']['code'])).expired_count,2)
|
||||||
|
self.assertEqual((self.root/'local'/'safe.txt').read_text(),'safe')
|
||||||
|
|
||||||
|
async def test_slow_directory_scan_does_not_block_other_requests(self):
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
original = Path.iterdir
|
||||||
|
events = []
|
||||||
|
def slow_scan(directory):
|
||||||
|
time.sleep(0.08)
|
||||||
|
return original(directory)
|
||||||
|
async def browse():
|
||||||
|
await LocalFileService().list_files('', page=1)
|
||||||
|
events.append('listed')
|
||||||
|
async def other_request():
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
events.append('other')
|
||||||
|
with patch.object(Path, 'iterdir', slow_scan):
|
||||||
|
await asyncio.gather(browse(), other_request())
|
||||||
|
self.assertEqual(events, ['other', 'listed'])
|
||||||
@@ -40,7 +40,7 @@ class UpgradeIntegrationTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
for n in range(501):
|
for n in range(501):
|
||||||
(root / f"dir-{n}").mkdir()
|
(root / f"dir-{n}").mkdir()
|
||||||
(root / "visible.txt").write_text("visible")
|
(root / "visible.txt").write_text("visible")
|
||||||
result = await get_local_lists(path=None, local_file_service=LocalFileService())
|
result = await get_local_lists(path=None, page=None, size=20, keyword="", local_file_service=LocalFileService())
|
||||||
self.assertEqual([item["file"] for item in result.detail], ["visible.txt"])
|
self.assertEqual([item["file"] for item in result.detail], ["visible.txt"])
|
||||||
|
|
||||||
async def test_local_paths_preserve_spaces_and_reject_external_symlinks(self):
|
async def test_local_paths_preserve_spaces_and_reject_external_symlinks(self):
|
||||||
|
|||||||
Reference in new issue
Block a user