diff --git a/apps/admin/services.py b/apps/admin/services.py index ab7a97e..be9ae42 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -1,28 +1,32 @@ import asyncio import hashlib -import io from pathlib import Path -import os -import time -import uuid from datetime import datetime, timedelta from typing import Any, Optional from core.response import APIResponse -from core.storage import FileStorageInterface, StoredFile, storages +from core.storage import FileStorageInterface, storages from core.settings import ( ADMIN_SESSION_EXPIRE_MAX, ADMIN_SESSION_EXPIRE_MIN, settings, ) from apps.base.config import refresh_settings -from apps.base.services import response_from_download, stored_file_of +from apps.base.services import get_stored_download, response_from_download, stored_file_of from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret from apps.base.models import FileCodes, KeyValue -from apps.base.utils import get_expire_info, get_file_path_name -from apps.base.quota import release_storage, reserve_storage +from apps.base.utils import get_expire_info +from apps.base.local_share import ( + LOCAL_REF_MARKER, + MAX_LIST_ENTRIES, + format_local_ctime, + get_local_root, + is_local_ref, + normalize_local_relpath, + resolve_under_local, + should_skip_storage_delete, +) from fastapi import HTTPException -from core.settings import data_root from core.utils import get_now, hash_password, is_password_hashed, validate_background_url # KeyValue 里的 settings/activities/presets 都是整块 JSON 读-改-写; @@ -98,7 +102,7 @@ class FileService: return f"{self.FILE_METADATA_KEY_PREFIX}{file_id}" async def _delete_file_code(self, file_code: FileCodes): - if file_code.text is None: + if not should_skip_storage_delete(file_code): await self.file_storage.delete_file(stored_file_of(file_code)) await KeyValue.filter(key=self._file_metadata_key(file_code.id)).delete() await file_code.delete() @@ -498,7 +502,7 @@ class FileService: "file_count": 0, "chunked_count": 0, **self._empty_health_summary(), - "storage_used": sum(file_code.size for file_code in all_files), + "storage_used": sum(file_code.size for file_code in all_files if not is_local_ref(file_code)), "used_count": sum(file_code.used_count for file_code in all_files), } @@ -603,6 +607,7 @@ class FileService: "file_hash": file_code.file_hash, "is_chunked": file_code.is_chunked, "upload_id": file_code.upload_id, + "is_local_ref": is_local_ref(file_code), } data.update( { @@ -1412,7 +1417,7 @@ class FileService: if file_code.text: return APIResponse(detail=file_code.text) else: - return response_from_download(await self.file_storage.get_file_response(stored_file_of(file_code))) + return response_from_download(await get_stored_download(file_code, self.file_storage)) async def preview_file(self, file_id: int, max_chars: int = 4000): max_chars = min(max(max_chars, 1), 20000) @@ -1443,40 +1448,28 @@ class FileService: if not await local_file.exists(): raise HTTPException(status_code=404, detail="文件不存在") - reservation_token = f"local:{uuid.uuid4().hex}" - await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600) - try: - data = await local_file.read() # bytes(read 内部用 with 关闭句柄) - expired_at, expired_count, used_count, code = await get_expire_info( - item.expire_value, item.expire_style - ) - path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name( - item - ) - await self.file_storage.save_file(io.BytesIO(data), save_path) - try: - await FileCodes.create( - code=code, - prefix=prefix, - suffix=suffix, - uuid_file_name=uuid_file_name, - file_path=path, - size=local_file.size, - expired_at=expired_at, - expired_count=expired_count, - used_count=used_count, - ) - except Exception: - await self.file_storage.delete_file( - StoredFile(file_path=path, uuid_file_name=uuid_file_name) - ) - raise - finally: - await release_storage(reservation_token) - + expired_at, expired_count, used_count, code = await get_expire_info( + item.expire_value, item.expire_style + ) + name = local_file.name + suffix = Path(name).suffix + prefix = name[: len(name) - len(suffix)] if suffix else name + record = await FileCodes.create( + code=code, + prefix=prefix, + suffix=suffix, + uuid_file_name=local_file.file, + file_path=LOCAL_REF_MARKER, + size=local_file.size or 0, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + ) return { "code": code, - "name": local_file.file, + "name": name, + "path": local_file.file, + "id": record.id, } @@ -1587,18 +1580,55 @@ class ConfigService: class LocalFileService: - async def list_files(self): - files = [] - if not os.path.exists(data_root / "local"): - os.makedirs(data_root / "local") - for file in os.listdir(data_root / "local"): - local_file = LocalFileClass(file) - files.append({ - "file": local_file.file, - "ctime": local_file.ctime, - "size": local_file.size, - }) - return files + async def list_files(self, path: str = ""): + relpath = normalize_local_relpath(path, allow_empty=True) + directory = resolve_under_local(relpath) + if not directory.exists() or not directory.is_dir(): + raise HTTPException(status_code=404, detail="目录不存在") + + root = get_local_root() + items = [] + try: + children = list(directory.iterdir()) + except OSError as exc: + raise HTTPException(status_code=500, detail="无法读取目录") from exc + + children.sort(key=lambda p: (not p.is_dir(), p.name.lower())) + truncated = False + for child in children: + if len(items) >= MAX_LIST_ENTRIES: + truncated = True + break + try: + resolved = child.resolve() + resolved.relative_to(root) + except (OSError, ValueError): + continue + if not resolved.is_file() and not resolved.is_dir(): + continue + child_rel = child.name if not relpath else f"{relpath}/{child.name}" + is_dir = resolved.is_dir() + items.append( + { + "file": child.name, + "name": child.name, + "path": child_rel, + "type": "dir" if is_dir else "file", + "ctime": format_local_ctime(resolved), + "size": None if is_dir else resolved.stat().st_size, + } + ) + + parent = "" + if relpath: + parent_path = Path(relpath).parent.as_posix() + parent = "" if parent_path == "." else parent_path + return { + "path": relpath, + "parent": parent, + "truncated": truncated, + "items": items, + } async def delete_file(self, filename: str): file = LocalFileClass(filename) @@ -1610,39 +1640,13 @@ class LocalFileService: class LocalFileClass: def __init__(self, file): - # 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。 - raw_name = str(file or "") - normalized = Path(raw_name).as_posix() - # 输入本身不得包含路径分隔符或绝对路径形态。 - if ( - not raw_name - or raw_name in {".", ".."} - or normalized in {".", ".."} - or "/" in normalized - or normalized.startswith("~") - or Path(raw_name).is_absolute() - or Path(raw_name).name != raw_name - ): - raise HTTPException(status_code=400, detail="非法文件名") - - safe_name = Path(raw_name).name - if not safe_name or safe_name in {".", ".."}: - raise HTTPException(status_code=400, detail="非法文件名") - - local_root = (data_root / "local").resolve() - candidate = (local_root / safe_name).resolve() - try: - candidate.relative_to(local_root) - except ValueError: - raise HTTPException(status_code=400, detail="非法文件路径") - - self.file = safe_name - self.path = candidate + relpath = normalize_local_relpath(file) + self.file = relpath + self.name = Path(relpath).name + self.path = resolve_under_local(relpath) if self.path.is_file(): - self.ctime = time.strftime( - "%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path)) - ) - self.size = os.path.getsize(self.path) + self.ctime = format_local_ctime(self.path) + self.size = self.path.stat().st_size else: self.ctime = None self.size = None @@ -1652,11 +1656,13 @@ class LocalFileClass: return fh.read() async def write(self, data): - with open(self.path, "w") as f: + with open(self.path, "wb") as f: f.write(data) async def delete(self): - os.remove(self.path) + if not self.path.is_file(): + raise HTTPException(status_code=404, detail="文件不存在") + self.path.unlink() async def exists(self): return self.path.is_file() diff --git a/apps/admin/views.py b/apps/admin/views.py index dcbd61a..aa665ff 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -31,6 +31,7 @@ from apps.admin.schemas import ( ) from core.response import APIResponse from apps.base.models import FileCodes, KeyValue +from apps.base.quota import owned_storage_queryset from tortoise.expressions import Q from tortoise.functions import Count, Sum from apps.admin.dependencies import ( @@ -144,7 +145,7 @@ async def dashboard(file_service: FileService = Depends(get_file_service)): # 健康摘要依赖逐行 rules engine(_build_file_status_insights),保留一次遍历。 total_files = await FileCodes.all().count() expired_count = await FileCodes.filter(_expired_predicate(now)).count() - all_size = await _sum_size(FileCodes.all()) + all_size = await _sum_size(owned_storage_queryset()) used_count = ( await FileCodes.all().annotate(total=Sum("used_count")).values("total") )[0]["total"] or 0 @@ -154,10 +155,14 @@ async def dashboard(file_service: FileService = Depends(get_file_service)): created_at__gte=yesterday_start, created_at__lte=yesterday_end ).count() yesterday_size = await _sum_size( - FileCodes.filter(created_at__gte=yesterday_start, created_at__lte=yesterday_end) + owned_storage_queryset( + FileCodes.filter(created_at__gte=yesterday_start, created_at__lte=yesterday_end) + ) ) today_count = await FileCodes.filter(created_at__gte=today_start).count() - today_size = await _sum_size(FileCodes.filter(created_at__gte=today_start)) + today_size = await _sum_size( + owned_storage_queryset(FileCodes.filter(created_at__gte=today_start)) + ) suffix_rows = ( await FileCodes.filter(text__isnull=True) @@ -567,9 +572,10 @@ async def file_preview( @admin_api.get("/local/lists") async def get_local_lists( + path: str = "", local_file_service: LocalFileService = Depends(get_local_file_service), ): - files = await local_file_service.list_files() + files = await local_file_service.list_files(path) return APIResponse(detail=files) diff --git a/apps/base/local_share.py b/apps/base/local_share.py new file mode 100644 index 0000000..ad85dbf --- /dev/null +++ b/apps/base/local_share.py @@ -0,0 +1,106 @@ +"""Local NAS-style share helpers. + +Files under ``data/local`` can be browsed by admin and turned into extract +codes without copying them into ``data/share``. The original file is never +deleted when a share expires or is removed from the file list. + +``FileCodes.file_path`` is the sentinel ``local-ref``; ``uuid_file_name`` +stores the posix relative path under ``data/local``. Accidental storage +deletes therefore look at ``data/local-ref/...`` and cannot touch the +original NAS file. +""" +from __future__ import annotations + +import time +from pathlib import Path +from urllib.parse import quote + +from fastapi import HTTPException + +from core.errors import StorageError +from core.storage import StoredDownload + +LOCAL_REF_MARKER = "local-ref" +MAX_RELPATH_LEN = 255 +MAX_LIST_ENTRIES = 500 + + +def is_local_ref(file_code) -> bool: + return (getattr(file_code, "file_path", None) or "") == LOCAL_REF_MARKER + + +def should_skip_storage_delete(file_code) -> bool: + return is_local_ref(file_code) or getattr(file_code, "text", None) is not None + + +def get_local_root() -> Path: + from core.settings import data_root + + root = (Path(data_root) / "local").resolve() + root.mkdir(parents=True, exist_ok=True) + return root + + +def normalize_local_relpath(raw: str, *, allow_empty: bool = False) -> str: + text = str(raw or "").replace("\\", "/").strip() + if not text: + if allow_empty: + return "" + raise HTTPException(status_code=400, detail="非法文件名") + if ( + text in {".", ".."} + or text.startswith("/") + or text.startswith("~") + or "\x00" in text + or ":" in text.split("/", 1)[0] + ): + raise HTTPException(status_code=400, detail="非法文件名") + + parts = [part for part in text.split("/") if part not in {"", "."}] + if not parts or any(part == ".." for part in parts): + raise HTTPException(status_code=400, detail="非法文件名") + + relpath = "/".join(parts) + if len(relpath) > MAX_RELPATH_LEN: + raise HTTPException(status_code=400, detail="路径过长") + return relpath + + +def resolve_under_local(relpath: str) -> Path: + root = get_local_root() + if not relpath: + return root + candidate = (root / relpath).resolve() + try: + candidate.relative_to(root) + except ValueError as exc: + raise HTTPException(status_code=400, detail="非法文件路径") from exc + return candidate + + +def format_local_ctime(path: Path) -> str | None: + try: + return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(path.stat().st_ctime)) + except OSError: + return None + + +def build_local_ref_download(file_code) -> StoredDownload: + try: + relpath = normalize_local_relpath(getattr(file_code, "uuid_file_name", None) or "") + path = resolve_under_local(relpath) + except HTTPException as exc: + raise StorageError(status_code=404, detail="文件已过期删除") from exc + if not path.is_file(): + raise StorageError(status_code=404, detail="文件已过期删除") + + filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}" + if not filename: + filename = path.name + encoded_filename = quote(filename, safe="") + headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"} + try: + headers["Content-Length"] = str(path.stat().st_size) + except OSError: + pass + return StoredDownload(filename=filename, headers=headers, path=path) diff --git a/apps/base/quota.py b/apps/base/quota.py index 988ffc7..e17d2fe 100644 --- a/apps/base/quota.py +++ b/apps/base/quota.py @@ -2,13 +2,24 @@ import datetime from fastapi import HTTPException from tortoise import connections +from tortoise.expressions import Q from tortoise.functions import Sum from apps.base.models import FileCodes, StorageReservation +from apps.base.local_share import LOCAL_REF_MARKER from core.settings import settings from core.utils import get_now +def owned_storage_queryset(queryset=None): + """FileCodes that occupy FileCodeBox storage (exclude NAS local-ref rows). + + SQL ``file_path != 'local-ref'`` drops NULLs, so keep null paths explicitly. + """ + qs = FileCodes.all() if queryset is None else queryset + return qs.filter(Q(file_path__isnull=True) | ~Q(file_path=LOCAL_REF_MARKER)) + + def _detect_sql_dialect() -> str: """识别当前默认连接的 SQL 方言。 @@ -56,7 +67,7 @@ def get_storage_limit() -> int: async def get_storage_usage() -> dict[str, int | None]: now = await get_now() # SQL 聚合:此函数在每次上传配额检查时调用,禁止全表拉取(D3) - used_rows = await FileCodes.all().annotate(total=Sum("size")).values("total") + used_rows = await owned_storage_queryset().annotate(total=Sum("size")).values("total") reserved_rows = await StorageReservation.filter(expires_at__gt=now).annotate( total=Sum("size") ).values("total") @@ -94,7 +105,7 @@ async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None: INSERT INTO storagereservation (token, size, expires_at) SELECT {ph[0]}, {ph[1]}, {ph[2]} WHERE ( - COALESCE((SELECT SUM(size) FROM filecodes), 0) + COALESCE((SELECT SUM(size) FROM filecodes WHERE file_path IS NULL OR file_path != '{LOCAL_REF_MARKER}'), 0) + COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0) + {ph[4]} ) <= {ph[5]} diff --git a/apps/base/services.py b/apps/base/services.py index 095c469..39115e3 100644 --- a/apps/base/services.py +++ b/apps/base/services.py @@ -15,6 +15,7 @@ from core.settings import settings from core.storage import FileStorageInterface, StoredDownload, StoredFile, storages from apps.base.file_validation import validate_upload_file +from apps.base.local_share import build_local_ref_download, is_local_ref from apps.base.models import FileCodes, PresignUploadSession, UploadChunk from apps.base.quota import release_storage, reserve_storage from apps.base.utils import build_file_path, get_expire_info @@ -37,6 +38,13 @@ def stored_file_of(code: FileCodes) -> StoredFile: ) +async def get_stored_download(file_code, file_storage: FileStorageInterface | None = None) -> StoredDownload: + if is_local_ref(file_code): + return build_local_ref_download(file_code) + storage = file_storage or storages[settings.file_storage]() + return await storage.get_file_response(stored_file_of(file_code)) + + async def rollback_saved_file( storage: FileStorageInterface, file_path: str, diff --git a/apps/base/tasks.py b/apps/base/tasks.py index 4a68287..c45505c 100644 --- a/apps/base/tasks.py +++ b/apps/base/tasks.py @@ -20,9 +20,9 @@ from core.logger import logger from core.settings import settings, data_root from core.storage import FileStorageInterface, StoredFile, storages from apps.base.services import stored_file_of +from apps.base.local_share import is_local_ref from core.utils import get_now - async def delete_expire_files(): while True: try: @@ -42,7 +42,8 @@ async def delete_expire_files(): ).all() for exp in expire_data: try: - await file_storage.delete_file(stored_file_of(exp)) + if not is_local_ref(exp): + await file_storage.delete_file(stored_file_of(exp)) except Exception as e: logger.error(f"删除过期文件失败 code={exp.code}: {e}") try: diff --git a/apps/base/views.py b/apps/base/views.py index ef54a84..85746bf 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -18,6 +18,7 @@ from apps.base.quota import release_storage, reserve_storage from apps.base.services import ( PRESIGN_SESSION_EXPIRES, FileUploadService, + get_stored_download, response_from_download, stored_file_of, validate_file_size, @@ -36,6 +37,7 @@ from apps.base.utils import ( get_chunk_file_path_name, validate_expire_style, ) +from apps.base.local_share import is_local_ref from core.response import APIResponse from core.settings import settings from core.storage import storages, FileStorageInterface @@ -151,8 +153,8 @@ async def build_select_detail( metadata = build_file_metadata(file_code) if file_code.text is not None: download_url = None - elif file_code.expired_count >= 0: - # 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。 + elif file_code.expired_count >= 0 or is_local_ref(file_code): + # 次数限制与 NAS 引用都必须走下载接口,避免直链绕过次数或打到错误存储。 download_url = await get_proxy_file_url(file_code.code) else: download_url = await file_storage.get_file_url(stored_file_of(file_code)) @@ -213,7 +215,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])): ) }, ) - return response_from_download(await file_storage.get_file_response(stored_file_of(file_code))) + return response_from_download(await get_stored_download(file_code, file_storage)) @share_api.post("/select/") @@ -258,7 +260,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"] return ( APIResponse(detail=file_code.text) if file_code.text - else response_from_download(await file_storage.get_file_response(stored_file_of(file_code))) + else response_from_download(await get_stored_download(file_code, file_storage)) ) diff --git a/docker-compose.yml b/docker-compose.yml index 8729256..80ddc0d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,6 +4,8 @@ services: image: lanol/filecodebox:2.6.1 # x-release-please-version volumes: - fcb-data:/app/data:rw + # NAS 已有文件:把共享目录挂到 /app/data/local,即可在后台「本地分享」里生成提取码,无需再上传 + # - /volume1/share:/app/data/local:ro restart: unless-stopped ports: - "12345:12345" diff --git a/docs/en/guide/management.md b/docs/en/guide/management.md index 04a85ae..d6a6574 100644 --- a/docs/en/guide/management.md +++ b/docs/en/guide/management.md @@ -166,50 +166,51 @@ When modifying extraction codes, the system checks if the new code is already in ## Local File Management -In addition to managing shared files, the admin panel also provides local file management functionality for managing files in the `data/local` directory. +In addition to managing shared files, the admin panel has a Local Share page for browsing `data/local` (including subfolders) and minting extract codes. + +Mount a NAS share at `/app/data/local` to generate extract codes for files already on disk, without downloading and re-uploading them. + +```yaml +volumes: + - fcb-data:/app/data:rw + # Read-only NAS share for admin browsing and extract-code generation + - /volume1/share:/app/data/local:ro +``` ### View Local Files -The local file list displays all files in the `data/local` directory: +The Local Share page supports nested folders. List API: -| Information | Description | -|-------------|-------------| -| Filename | Complete filename | -| Creation Time | File creation time | -| File Size | File size (bytes) | +``` +GET /admin/local/lists?path=movies +``` + +`path` is relative to `data/local`; leave it empty for the root. Response: + +| Field | Description | +|------|------| +| `path` | Current directory | +| `parent` | Parent directory | +| `truncated` | Whether the listing was truncated | +| `items[].type` | `dir` or `file` | +| `items[].path` | Path relative to `data/local`, used as `filename` when sharing | ### Share Local Files -You can quickly share local files: - -1. Select the file to share in the local file list +1. Open the target subfolder and pick a file 2. Set expiration method and value -3. Click the share button -4. System generates extraction code +3. Create an extract code + +Sharing is a **zero-copy reference**: the file is not copied into `data/share` and does not count against storage quota. Expiring or deleting the share record **does not delete the original NAS file**. **Share parameters:** | Parameter | Description | |-----------|-------------| -| `filename` | Filename to share | +| `filename` | Path relative to `data/local`, e.g. `movies/a.mp4` | | `expire_style` | Expiration method (day/hour/minute/forever/count) | | `expire_value` | Expiration value (days/hours/minutes/download count) | -### Delete Local Files - -You can delete files in the `data/local` directory: - -1. Find the file to delete in the local file list -2. Click the delete button -3. Confirm deletion - -::: tip Use Cases -Local file management is useful for: -- Sharing files after batch uploading to the server -- Managing files uploaded to the server through other means -- Cleaning up unnecessary local files -::: - ## System Settings
@@ -338,7 +339,7 @@ Content-Type: application/json
**Get Local File List**
```
-GET /admin/local/lists
+GET /admin/local/lists?path=movies
Authorization: Bearer
@@ -337,7 +338,7 @@ Content-Type: application/json
**获取本地文件列表**
```
-GET /admin/local/lists
+GET /admin/local/lists?path=movies
Authorization: Bearer