diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..20c0fa3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,98 @@ +# 第一阶段:构建前端主题 +# 前端产物与 CPU 架构无关,使用原生构建平台避免在 QEMU 中运行 Node/pnpm。 +FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder + +ARG FRONTEND_2024_REF=main +ARG FRONTEND_2023_REF=main + +RUN apk add --no-cache git python3 make g++ + +RUN corepack enable && \ + corepack prepare pnpm@9.15.9 --activate + +WORKDIR /build + +# 克隆并构建 2024 主题 +ARG FRONTEND_2024_REPO=https://git.orionc.me/orion/FileCodeBoxFronted.git +ARG FRONTEND_2024_BRANCH=main +ARG FRONTEND_CACHE_BUST=1 +RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \ + git clone --filter=blob:none --no-checkout "$FRONTEND_2024_REPO" /build/fronted-2024 && \ + cd /build/fronted-2024 && \ + git fetch --depth 1 origin "${FRONTEND_2024_REF}" && \ + git checkout --detach FETCH_HEAD && \ + pnpm install --frozen-lockfile --prod=false && \ + VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build + +# 克隆并构建定制 2026 主题 +ARG FRONTEND_2026_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2026.git +ARG FRONTEND_2026_BRANCH=test/custom-admin-ui +RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-2026-cache-bust && \ + git clone --depth 1 --branch "$FRONTEND_2026_BRANCH" "$FRONTEND_2026_REPO" /build/fronted-2026 && \ + cd /build/fronted-2026 && \ + pnpm install --frozen-lockfile --prod=false && \ + VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build + +# 克隆并构建 2023 主题 +ARG FRONTEND_2023_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2023.git +ARG FRONTEND_2023_BRANCH=main +RUN git clone --filter=blob:none --no-checkout "$FRONTEND_2023_REPO" /build/fronted-2023 && \ + cd /build/fronted-2023 && \ + git fetch --depth 1 origin "${FRONTEND_2023_REF}" && \ + git checkout --detach FETCH_HEAD && \ + npm install --legacy-peer-deps && \ + npm run build + +# 第二阶段:构建最终镜像 +FROM python:3.12-slim-bookworm +ARG APP_VERSION +ARG VCS_REF=unknown +ARG FRONTEND_2024_REF=main +ARG FRONTEND_2023_REF=main +LABEL author="Lan" +LABEL email="xzu@live.com" +LABEL org.opencontainers.image.version="${APP_VERSION}" +LABEL org.opencontainers.image.revision="${VCS_REF}" +LABEL org.opencontainers.image.filecodebox.frontend-2024-revision="${FRONTEND_2024_REF}" +LABEL org.opencontainers.image.filecodebox.frontend-2023-revision="${FRONTEND_2023_REF}" + +WORKDIR /app + +# 复制项目文件(通过 .dockerignore 排除不必要的文件) +COPY . . + +# 分支镜像使用带提交号的开发版本;正式镜像使用 VERSION 中的版本。 +ENV APP_VERSION="${APP_VERSION}" + +# 设置时区 +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \ + echo 'Asia/Shanghai' > /etc/timezone + +# 从构建阶段复制编译好的前端主题 +COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024 +COPY --from=frontend-builder /build/fronted-2026/dist ./themes/2026 +COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023 + +# 应用管理后台详情页取件记录展开/收起、复制回退与悬停边框补丁 +RUN python scripts/patch_admin_timeline_ui.py + +# 安装系统安全更新 + Python 依赖 +RUN apt-get update \ + && apt-get upgrade -y --no-install-recommends \ + && rm -rf /var/lib/apt/lists/* \ + && pip install --no-cache-dir -r requirements.txt \ + && pip cache purge || true + + +# 环境变量配置 +ENV HOST="0.0.0.0" \ + PORT=12345 \ + WORKERS=1 \ + LOG_LEVEL="info" \ + FORWARDED_ALLOW_IPS="" + +EXPOSE 12345 + +# 生产环境启动命令 +# FORWARDED_ALLOW_IPS 由部署环境显式指定,避免任意客户端伪造 X-Forwarded-*。 +CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""] diff --git a/apps/admin/schemas.py b/apps/admin/schemas.py new file mode 100644 index 0000000..48dc89c --- /dev/null +++ b/apps/admin/schemas.py @@ -0,0 +1,79 @@ +import datetime +from typing import Any, Optional, Union + +from pydantic import BaseModel + + +class IDData(BaseModel): + id: int + + +class IDsData(BaseModel): + ids: list[int] + + +class ShareItem(BaseModel): + expire_value: int + expire_style: str = "day" + filename: str + + +class DeleteItem(BaseModel): + filename: str + + +class LoginData(BaseModel): + password: str + + +class UpdateFileData(BaseModel): + id: int + code: Optional[str] = None + prefix: Optional[str] = None + suffix: Optional[str] = None + expired_at: Optional[Union[datetime.datetime, str]] = None + expired_count: Optional[int] = None + + +class BatchUpdateFileData(BaseModel): + ids: list[int] + expired_at: Optional[Union[datetime.datetime, str]] = None + expired_count: Optional[int] = None + clearExpiredAt: Optional[bool] = None + clear_expired_at: Optional[bool] = None + + +class FilePolicyActionData(BaseModel): + id: int + action: str + downloadLimit: Optional[int] = None + download_limit: Optional[int] = None + + +class BatchFilePolicyActionData(BaseModel): + ids: list[int] + action: str + downloadLimit: Optional[int] = None + download_limit: Optional[int] = None + + +class TrashRetentionData(BaseModel): + id: int + retentionDays: int + + +class FileMetadataData(BaseModel): + id: int + note: Optional[str] = None + tags: Optional[list[str]] = None + + +class FileViewPresetData(BaseModel): + id: Optional[str] = None + name: str + filters: Optional[dict[str, Any]] = None + params: Optional[dict[str, Any]] = None + + +class FileViewPresetDeleteData(BaseModel): + id: str diff --git a/apps/admin/services.py b/apps/admin/services.py new file mode 100644 index 0000000..9e861d6 --- /dev/null +++ b/apps/admin/services.py @@ -0,0 +1,1887 @@ +import hashlib +import json +from pathlib import Path + +import os +import time +import uuid +from datetime import datetime, timedelta +from typing import Any, Dict, List, Optional, Tuple + +from core.response import APIResponse +from core.storage import FileStorageInterface, storages +from core.settings import ( + ADMIN_SESSION_EXPIRE_MAX, + ADMIN_SESSION_EXPIRE_MIN, + settings, +) +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.utils import get_expire_info, get_file_path_name, get_random_code +from apps.base.quota import release_storage, reserve_storage +from fastapi import HTTPException +from core.settings import data_root +from core.utils import get_now, hash_password, is_password_hashed + + +class FileService: + FILE_METADATA_KEY_PREFIX = "admin_file_metadata:" + FILE_VIEW_PRESETS_KEY = "admin_file_view_presets" + ADMIN_ACTIVITY_KEY = "admin_activity_events" + MAX_METADATA_NOTE_LENGTH = 2000 + MAX_METADATA_TAGS = 12 + MAX_METADATA_TAG_LENGTH = 24 + MAX_VIEW_PRESETS = 24 + MAX_VIEW_PRESET_NAME_LENGTH = 32 + MAX_VIEW_PRESET_KEYWORD_LENGTH = 80 + MAX_ADMIN_ACTIVITIES = 5000 + MAX_ADMIN_ACTIVITY_TEXT_LENGTH = 120 + + POLICY_ACTIONS = { + "extend_24h", + "extend_7d", + "make_permanent", + "reset_download_limit", + } + + SORT_FIELDS = { + "created_at", + "createdat", + "expired_at", + "expiredat", + "name", + "size", + "used_count", + "usedcount", + "code", + } + VIEW_PRESET_STATUS_VALUES = {"all", "active", "expired"} + VIEW_PRESET_TYPE_VALUES = {"all", "file", "text", "chunked"} + VIEW_PRESET_HEALTH_VALUES = { + "all", + "attention", + "danger", + "warning", + "healthy", + "expired", + "expiring_soon", + "storage_issue", + "never_retrieved", + "permanent", + } + VIEW_PRESET_SORT_FIELDS = { + "created_at", + "expired_at", + "name", + "size", + "used_count", + "code", + } + + TRASH_DEFAULT_RETENTION_DAYS = 7 + TRASH_MAX_RETENTION_DAYS = 365 + + def __init__(self): + self._file_storage: Optional[FileStorageInterface] = None + + @property + def file_storage(self) -> FileStorageInterface: + if self._file_storage is None: + self._file_storage = storages[settings.file_storage]() + return self._file_storage + + def _file_metadata_key(self, file_id: int) -> str: + return f"{self.FILE_METADATA_KEY_PREFIX}{file_id}" + + def _dedupe_download_stats(self, stats: List[TransferStats]) -> List[TransferStats]: + deduped: List[TransferStats] = [] + recent_downloads: Dict[Tuple[Optional[int], str, int], datetime] = {} + for stat in stats: + key = (stat.file_code_id, stat.ip or "", int(stat.size or 0)) + previous = recent_downloads.get(key) + if previous and (stat.created_at - previous).total_seconds() <= 5: + continue + recent_downloads[key] = stat.created_at + deduped.append(stat) + return deduped + + async def _delete_file_code(self, file_code: FileCodes): + await self.move_to_trash(file_code, reason="manual") + + @staticmethod + def _trash_path(file_code: FileCodes) -> str: + filename = file_code.uuid_file_name or f"{file_code.prefix}{file_code.suffix}" + return f"trash/{file_code.id}/{filename}" + + @classmethod + def _trash_expiry(cls, now: datetime, retention_days: Optional[int]): + if retention_days is None: + retention_days = cls.TRASH_DEFAULT_RETENTION_DAYS + if retention_days == 0: + return None + if not 1 <= retention_days <= cls.TRASH_MAX_RETENTION_DAYS: + raise HTTPException(status_code=400, detail="回收站保留期限必须为 1 到 365 天,或设为永久") + return now + timedelta(days=retention_days) + + async def move_to_trash( + self, + file_code: FileCodes, + reason: str, + retention_days: Optional[int] = None, + ) -> FileCodes: + if file_code.is_trashed: + return file_code + now = await get_now() + original_path = await file_code.get_file_path() if file_code.text is None else "" + if file_code.text is None: + await self.file_storage.move_file(file_code, self._trash_path(file_code)) + await file_code.update_from_dict( + { + "is_trashed": True, + "trashed_at": now, + "trash_expires_at": self._trash_expiry(now, retention_days), + "trash_reason": reason, + "trash_original_path": original_path, + } + ).save() + await TransferStats.create( + action="trash", + file_code_id=file_code.id, + code=file_code.code, + name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code, + size=int(file_code.size or 0), + ip=f"system-{reason}", + file_path=original_path, + expired_at=file_code.expired_at, + deleted_at=now, + meta=json.dumps({"reason": reason, "trash_path": self._trash_path(file_code)}, ensure_ascii=False), + ) + return file_code + + async def restore_from_trash(self, file_id: int) -> FileCodes: + file_code = await FileCodes.filter(id=file_id, is_trashed=True).first() + if not file_code: + raise HTTPException(status_code=404, detail="回收站文件不存在") + if file_code.trash_purged_at is not None: + raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录") + original_path = file_code.trash_original_path or "" + if file_code.text is None: + if not original_path: + raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复") + destination_dir, filename = os.path.split(original_path) + if filename != (file_code.uuid_file_name or filename): + raise HTTPException(status_code=409, detail="回收站文件名不一致,无法恢复") + await self.file_storage.move_file( + FileCodes(file_path=os.path.dirname(self._trash_path(file_code)), uuid_file_name=os.path.basename(self._trash_path(file_code))), + original_path, + ) + file_code.file_path = destination_dir + file_code.code = await get_random_code() + file_code.is_trashed = False + file_code.trashed_at = None + file_code.trash_expires_at = None + file_code.trash_reason = None + file_code.trash_original_path = None + file_code.trash_purged_at = None + await file_code.save() + await TransferStats.create( + action="restore", + file_code_id=file_code.id, + code=file_code.code, + name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code, + size=int(file_code.size or 0), + ip="admin-restore", + file_path=file_code.file_path or "", + expired_at=file_code.expired_at, + meta=json.dumps({"new_code": file_code.code}, ensure_ascii=False), + ) + await self.record_admin_activity( + action="trash.restore", + target_type="file", + target_id=file_code.id, + target_name=self._build_file_activity_name(file_code), + meta={"newCode": file_code.code}, + ) + return file_code + + async def purge_trashed_file(self, file_code: FileCodes) -> None: + if file_code.trash_purged_at is not None: + return + if file_code.text is None: + trash_path = self._trash_path(file_code) + await self.file_storage.delete_file( + FileCodes( + file_path=os.path.dirname(trash_path), + uuid_file_name=os.path.basename(trash_path), + ) + ) + purged_at = await get_now() + file_code.trash_purged_at = purged_at + file_code.trash_expires_at = None + await file_code.save(update_fields=["trash_purged_at", "trash_expires_at"]) + await TransferStats.create( + action="purge", + file_code_id=file_code.id, + code=file_code.code, + name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code, + size=int(file_code.size or 0), + ip="system-purge", + file_path=file_code.trash_original_path or "", + expired_at=file_code.expired_at, + deleted_at=purged_at, + meta=json.dumps({"reason": "trash_purge"}, ensure_ascii=False), + ) + await self.record_admin_activity( + action="trash.purge", + target_type="file", + target_id=file_code.id, + target_name=self._build_file_activity_name(file_code), + meta={"auditOnly": True}, + ) + + async def list_trash(self, page: int, size: int) -> dict[str, Any]: + page = max(page, 1) + size = min(max(size, 1), 100) + query = FileCodes.filter(is_trashed=True).order_by("-trashed_at", "-id") + total = await query.count() + files = await query.offset((page - 1) * size).limit(size) + now = await get_now() + items = [] + for file_code in files: + item = await self._build_admin_file_item(file_code, now=now) + item.update( + { + "trashedAt": file_code.trashed_at, + "trashExpiresAt": file_code.trash_expires_at, + "trashReason": file_code.trash_reason, + "trashPurgedAt": file_code.trash_purged_at, + "isTrashPermanent": file_code.trash_expires_at is None and file_code.trash_purged_at is None, + "isTrashPurged": file_code.trash_purged_at is not None, + } + ) + items.append(item) + return {"page": page, "size": size, "total": total, "data": items} + + async def set_trash_retention(self, file_id: int, retention_days: int) -> FileCodes: + file_code = await FileCodes.filter(id=file_id, is_trashed=True).first() + if not file_code: + raise HTTPException(status_code=404, detail="回收站文件不存在") + file_code.trash_expires_at = self._trash_expiry(await get_now(), retention_days) + await file_code.save(update_fields=["trash_expires_at"]) + return file_code + + async def delete_file(self, file_id: int): + file_code = await FileCodes.get(id=file_id) + target_name = self._build_file_activity_name(file_code) + await self._delete_file_code(file_code) + await self.record_admin_activity( + action="file.delete", + target_type="file", + target_id=file_id, + target_name=target_name, + count=1, + ) + + async def delete_files(self, file_ids: list[int]): + unique_ids = list(dict.fromkeys(file_ids)) + deleted = [] + failed = [] + missing = [] + + for file_id in unique_ids: + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + missing.append(file_id) + continue + + try: + await self._delete_file_code(file_code) + deleted.append(file_id) + except Exception as exc: + failed.append({"id": file_id, "reason": str(exc)}) + + if deleted: + await self.record_admin_activity( + action="files.batch_delete", + target_type="file", + count=len(deleted), + meta={ + "requestedCount": len(file_ids), + "uniqueCount": len(unique_ids), + "deleted": deleted, + "missing": missing, + "failedCount": len(failed), + }, + ) + + return { + "requestedCount": len(file_ids), + "requested_count": len(file_ids), + "uniqueCount": len(unique_ids), + "unique_count": len(unique_ids), + "deletedCount": len(deleted), + "deleted_count": len(deleted), + "missingCount": len(missing), + "missing_count": len(missing), + "failedCount": len(failed), + "failed_count": len(failed), + "deleted": deleted, + "missing": missing, + "failed": failed, + } + + async def update_files(self, file_ids: list[int], update_data: dict[str, Any]): + unique_ids = list(dict.fromkeys(file_ids)) + updated = [] + failed = [] + missing = [] + + for file_id in unique_ids: + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + missing.append(file_id) + continue + + try: + await file_code.update_from_dict(update_data).save() + updated.append(file_id) + except Exception as exc: + failed.append({"id": file_id, "reason": str(exc)}) + + if updated: + await self.record_admin_activity( + action="files.batch_update", + target_type="file", + count=len(updated), + meta={ + "fields": sorted(update_data.keys()), + "requestedCount": len(file_ids), + "uniqueCount": len(unique_ids), + "updated": updated, + "missing": missing, + "failedCount": len(failed), + }, + ) + + return { + "requestedCount": len(file_ids), + "requested_count": len(file_ids), + "uniqueCount": len(unique_ids), + "unique_count": len(unique_ids), + "updatedCount": len(updated), + "updated_count": len(updated), + "missingCount": len(missing), + "missing_count": len(missing), + "failedCount": len(failed), + "failed_count": len(failed), + "updated": updated, + "missing": missing, + "failed": failed, + } + + async def apply_file_policy_action( + self, + file_id: int, + action: str, + download_limit: Optional[int] = None, + ) -> dict[str, Any]: + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + + action = action.strip().lower() + now = await get_now() + update_data = self._build_policy_action_update( + file_code=file_code, + action=action, + now=now, + download_limit=download_limit, + ) + + await file_code.update_from_dict(update_data).save() + await self.record_admin_activity( + action="file.policy_action", + target_type="file", + target_id=file_id, + target_name=self._build_file_activity_name(file_code), + count=1, + meta={"policyAction": action}, + ) + return await self.get_file_detail(file_id) + + async def get_file_metadata(self, file_id: int) -> dict[str, Any]: + record = await KeyValue.filter(key=self._file_metadata_key(file_id)).first() + return self._normalize_file_metadata(record.value if record else None) + + async def update_file_metadata( + self, + file_id: int, + note: Optional[str], + tags: Optional[list[str]], + update_note: bool, + update_tags: bool, + ) -> dict[str, Any]: + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + + current_metadata = await self.get_file_metadata(file_id) + next_metadata = dict(current_metadata) + if update_note: + next_metadata["note"] = self._normalize_metadata_note(note) + if update_tags: + next_metadata["tags"] = self._normalize_metadata_tags(tags) + + now = await get_now() + updated_at = now.isoformat() + next_metadata["updatedAt"] = updated_at + next_metadata["updated_at"] = updated_at + await KeyValue.update_or_create( + key=self._file_metadata_key(file_id), + defaults={"value": next_metadata}, + ) + await self.record_admin_activity( + action="file.metadata_update", + target_type="file", + target_id=file_id, + target_name=self._build_file_activity_name(file_code), + count=1, + meta={ + "updateNote": update_note, + "updateTags": update_tags, + "tagCount": len(next_metadata["tags"]), + }, + ) + return await self.get_file_detail(file_id) + + async def list_file_view_presets(self) -> dict[str, Any]: + presets = await self._get_file_view_presets() + return { + "presets": presets, + "items": presets, + "total": len(presets), + } + + async def save_file_view_preset( + self, + preset_id: Optional[str], + name: str, + filters: dict[str, Any], + ) -> dict[str, Any]: + presets = await self._get_file_view_presets() + normalized_name = self._normalize_file_view_preset_name(name) + normalized_filters = self._normalize_file_view_preset_filters(filters) + now = await get_now() + updated_at = now.isoformat() + + target_index = next( + (index for index, preset in enumerate(presets) if preset["id"] == preset_id), + -1, + ) + is_update = target_index >= 0 + if is_update: + preset = presets[target_index] + next_preset = { + **preset, + "name": normalized_name, + "filters": normalized_filters, + "params": normalized_filters, + "updatedAt": updated_at, + "updated_at": updated_at, + } + presets[target_index] = next_preset + else: + if len(presets) >= self.MAX_VIEW_PRESETS: + raise HTTPException(status_code=400, detail="视图预设数量已达上限") + next_preset = { + "id": preset_id or self._build_file_view_preset_id(normalized_name, now), + "name": normalized_name, + "filters": normalized_filters, + "params": normalized_filters, + "createdAt": updated_at, + "created_at": updated_at, + "updatedAt": updated_at, + "updated_at": updated_at, + } + presets.append(next_preset) + + await self._save_file_view_presets(presets) + await self.record_admin_activity( + action="file.view_preset_update" if is_update else "file.view_preset_create", + target_type="view_preset", + target_id=next_preset["id"], + target_name=next_preset["name"], + count=1, + meta={"filters": normalized_filters}, + ) + return next_preset + + async def delete_file_view_preset(self, preset_id: str) -> dict[str, Any]: + preset_id = str(preset_id).strip() + if not preset_id: + raise HTTPException(status_code=400, detail="请选择要删除的视图预设") + + presets = await self._get_file_view_presets() + deleted_preset = next( + (preset for preset in presets if preset["id"] == preset_id), + None, + ) + next_presets = [preset for preset in presets if preset["id"] != preset_id] + if len(next_presets) == len(presets): + raise HTTPException(status_code=404, detail="视图预设不存在") + + await self._save_file_view_presets(next_presets) + await self.record_admin_activity( + action="file.view_preset_delete", + target_type="view_preset", + target_id=preset_id, + target_name=(deleted_preset or {}).get("name", ""), + count=1, + ) + return { + "deleted": preset_id, + "deletedPresetId": preset_id, + "deleted_preset_id": preset_id, + "total": len(next_presets), + } + + async def apply_files_policy_action( + self, + file_ids: list[int], + action: str, + download_limit: Optional[int] = None, + ) -> dict[str, Any]: + unique_ids = list(dict.fromkeys(file_ids)) + updated = [] + failed = [] + missing = [] + action = action.strip().lower() + + if action not in self.POLICY_ACTIONS: + raise HTTPException(status_code=400, detail="不支持的策略动作") + + if action == "reset_download_limit": + next_limit = download_limit if download_limit is not None else 5 + if next_limit < 1: + raise HTTPException(status_code=400, detail="取件次数必须大于 0") + + now = await get_now() + for file_id in unique_ids: + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + missing.append(file_id) + continue + + try: + update_data = self._build_policy_action_update( + file_code=file_code, + action=action, + now=now, + download_limit=download_limit, + ) + await file_code.update_from_dict(update_data).save() + updated.append(file_id) + except Exception as exc: + failed.append({"id": file_id, "reason": str(exc)}) + + if updated: + await self.record_admin_activity( + action="files.batch_policy_action", + target_type="file", + count=len(updated), + meta={ + "policyAction": action, + "requestedCount": len(file_ids), + "uniqueCount": len(unique_ids), + "updated": updated, + "missing": missing, + "failedCount": len(failed), + }, + ) + + return { + "requestedCount": len(file_ids), + "requested_count": len(file_ids), + "uniqueCount": len(unique_ids), + "unique_count": len(unique_ids), + "updatedCount": len(updated), + "updated_count": len(updated), + "missingCount": len(missing), + "missing_count": len(missing), + "failedCount": len(failed), + "failed_count": len(failed), + "action": action, + "updated": updated, + "missing": missing, + "failed": failed, + } + + async def list_files( + self, + page: int, + size: int, + keyword: str = "", + status: str = "", + file_type: str = "", + health: str = "", + sort_by: str = "created_at", + sort_order: str = "desc", + ): + page = max(page, 1) + size = min(max(size, 1), 100) + keyword = keyword.strip().lower() + status = status.strip().lower() + file_type = file_type.strip().lower() + health = health.strip().lower() + sort_by = self._normalize_sort_by(sort_by) + reverse = sort_order.strip().lower() != "asc" + + all_files = await FileCodes.filter(is_trashed=False).all() + now = await get_now() + enriched_files = [] + summary = { + "totalFiles": len(all_files), + "activeCount": 0, + "expiredCount": 0, + "textCount": 0, + "fileCount": 0, + "chunkedCount": 0, + **self._empty_health_summary(), + "storageUsed": sum(file_code.size for file_code in all_files), + "usedCount": sum(file_code.used_count for file_code in all_files), + } + + for file_code in all_files: + item = await self._build_admin_file_item(file_code, now=now) + if item["isExpired"]: + summary["expiredCount"] += 1 + else: + summary["activeCount"] += 1 + if item["isText"]: + summary["textCount"] += 1 + else: + summary["fileCount"] += 1 + if item["isChunked"]: + summary["chunkedCount"] += 1 + self._accumulate_health_summary(summary, item) + + if not self._match_admin_file(item, keyword, status, file_type, health): + continue + enriched_files.append(item) + + enriched_files.sort( + key=lambda item: self._get_sort_value(item, sort_by), + reverse=reverse, + ) + offset = (page - 1) * size + return enriched_files[offset : offset + size], len(enriched_files), summary + + def _empty_health_summary(self) -> dict[str, int]: + return { + "healthAttentionCount": 0, + "healthDangerCount": 0, + "healthWarningCount": 0, + "expiringSoonCount": 0, + "storageIssueCount": 0, + "neverRetrievedCount": 0, + "healthyCount": 0, + "permanentCount": 0, + } + + def _accumulate_health_summary(self, summary: dict[str, Any], item: dict[str, Any]) -> None: + status_insights = item.get("statusInsights") or {} + reasons = status_insights.get("reasons") or [] + severity = status_insights.get("severity") + state = status_insights.get("state") + + if severity in {"danger", "warning"}: + summary["healthAttentionCount"] += 1 + if severity == "danger": + summary["healthDangerCount"] += 1 + if severity == "warning": + summary["healthWarningCount"] += 1 + if severity == "success": + summary["healthyCount"] += 1 + if state == "permanent": + summary["permanentCount"] += 1 + if "expires_soon" in reasons: + summary["expiringSoonCount"] += 1 + if "storage_metadata_incomplete" in reasons: + summary["storageIssueCount"] += 1 + if "never_retrieved" in reasons: + summary["neverRetrievedCount"] += 1 + + async def build_file_health_summary( + self, file_codes: list[FileCodes], now: Optional[datetime] = None + ) -> dict[str, int]: + if now is None: + now = await get_now() + summary = self._empty_health_summary() + for file_code in file_codes: + item = await self._build_admin_file_item(file_code, now=now) + self._accumulate_health_summary(summary, item) + return summary + + async def _build_admin_file_item( + self, file_code: FileCodes, now: Optional[datetime] = None + ) -> dict[str, Any]: + if now is None: + now = await get_now() + is_text = file_code.text is not None + is_expired = await file_code.is_expired() + name = f"{file_code.prefix}{file_code.suffix}" + has_download_limit = file_code.expired_count >= 0 + is_permanent = file_code.expired_at is None and file_code.expired_count < 0 + can_download = is_text or bool(file_code.file_path or file_code.uuid_file_name) + remaining_downloads = ( + max(file_code.expired_count, 0) if file_code.expired_count >= 0 else None + ) + data = { + "id": file_code.id, + "code": file_code.code, + "prefix": file_code.prefix, + "suffix": file_code.suffix, + "uuid_file_name": file_code.uuid_file_name, + "file_path": file_code.file_path, + "size": file_code.size or 0, + "text": file_code.text, + "expired_at": file_code.expired_at, + "expired_count": file_code.expired_count, + "used_count": file_code.used_count, + "created_at": file_code.created_at, + "file_hash": file_code.file_hash, + "is_chunked": file_code.is_chunked, + "upload_id": file_code.upload_id, + } + data.update( + { + "name": name, + "type": "text" if is_text else "file", + "status": "expired" if is_expired else "active", + "isText": is_text, + "is_text": is_text, + "isExpired": is_expired, + "is_expired": is_expired, + "isChunked": file_code.is_chunked, + "is_chunked": file_code.is_chunked, + "remainingDownloads": remaining_downloads, + "remaining_downloads": remaining_downloads, + "usedCount": file_code.used_count, + "used_count": file_code.used_count, + "createdAt": file_code.created_at, + "created_at": file_code.created_at, + "expiredAt": file_code.expired_at, + "expired_at": file_code.expired_at, + "fileHash": file_code.file_hash, + "file_hash": file_code.file_hash, + } + ) + status_insights = self._build_file_status_insights( + file_code=file_code, + detail=data, + now=now, + has_download_limit=has_download_limit, + is_permanent=is_permanent, + can_download=can_download, + ) + data.update( + { + "statusInsights": status_insights, + "status_insights": status_insights, + } + ) + return data + + async def get_file_detail(self, file_id: int): + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + + now = await get_now() + detail = await self._build_admin_file_item(file_code, now=now) + is_text = file_code.text is not None + has_download_limit = file_code.expired_count >= 0 + is_permanent = file_code.expired_at is None and file_code.expired_count < 0 + text_length = len(file_code.text) if file_code.text else 0 + can_download = is_text or bool(file_code.file_path or file_code.uuid_file_name) + status_insights = self._build_file_status_insights( + file_code=file_code, + detail=detail, + now=now, + has_download_limit=has_download_limit, + is_permanent=is_permanent, + can_download=can_download, + ) + timeline = await self._build_file_timeline( + file_code=file_code, + detail=detail, + now=now, + has_download_limit=has_download_limit, + is_permanent=is_permanent, + is_text=is_text, + ) + + detail.update( + { + "filename": detail["name"], + "displayName": detail["name"], + "display_name": detail["name"], + "isPermanent": is_permanent, + "is_permanent": is_permanent, + "hasDownloadLimit": has_download_limit, + "has_download_limit": has_download_limit, + "hasExpirationTime": file_code.expired_at is not None, + "has_expiration_time": file_code.expired_at is not None, + "textLength": text_length, + "text_length": text_length, + "canPreviewText": is_text, + "can_preview_text": is_text, + "canDownload": can_download, + "can_download": can_download, + "storageBackend": settings.file_storage, + "storage_backend": settings.file_storage, + "filePath": file_code.file_path, + "file_path": file_code.file_path, + "uuidFileName": file_code.uuid_file_name, + "uuid_file_name": file_code.uuid_file_name, + "uploadId": file_code.upload_id, + "upload_id": file_code.upload_id, + "policy": { + "expiredAt": file_code.expired_at, + "expired_at": file_code.expired_at, + "expiredCount": file_code.expired_count, + "expired_count": file_code.expired_count, + "remainingDownloads": detail["remainingDownloads"], + "remaining_downloads": detail["remaining_downloads"], + "isExpired": detail["isExpired"], + "is_expired": detail["is_expired"], + "isPermanent": is_permanent, + "is_permanent": is_permanent, + }, + "storage": { + "backend": settings.file_storage, + "filePath": file_code.file_path, + "file_path": file_code.file_path, + "uuidFileName": file_code.uuid_file_name, + "uuid_file_name": file_code.uuid_file_name, + "fileHash": file_code.file_hash, + "file_hash": file_code.file_hash, + "isChunked": file_code.is_chunked, + "is_chunked": file_code.is_chunked, + "uploadId": file_code.upload_id, + "upload_id": file_code.upload_id, + }, + "statusInsights": status_insights, + "status_insights": status_insights, + "timeline": timeline, + } + ) + metadata = await self.get_file_metadata(file_id) + detail.update( + { + "metadata": metadata, + "meta": metadata, + "note": metadata["note"], + "tags": metadata["tags"], + "metadataUpdatedAt": metadata["updatedAt"], + "metadata_updated_at": metadata["updated_at"], + } + ) + return detail + + def _normalize_metadata_note(self, note: Optional[str]) -> str: + if note is None: + return "" + return str(note).strip()[: self.MAX_METADATA_NOTE_LENGTH] + + def _normalize_metadata_tags(self, tags: Any) -> list[str]: + if not tags: + return [] + if isinstance(tags, str): + tags = [tags] + elif not isinstance(tags, list): + return [] + + normalized_tags = [] + seen_tags = set() + for raw_tag in tags: + tag = str(raw_tag).strip() + if not tag: + continue + tag = tag[: self.MAX_METADATA_TAG_LENGTH] + dedupe_key = tag.lower() + if dedupe_key in seen_tags: + continue + seen_tags.add(dedupe_key) + normalized_tags.append(tag) + if len(normalized_tags) >= self.MAX_METADATA_TAGS: + break + return normalized_tags + + def _normalize_file_metadata(self, metadata: Any) -> dict[str, Any]: + if not isinstance(metadata, dict): + metadata = {} + + updated_at = metadata.get("updatedAt") or metadata.get("updated_at") + return { + "note": self._normalize_metadata_note(metadata.get("note")), + "tags": self._normalize_metadata_tags(metadata.get("tags")), + "updatedAt": updated_at, + "updated_at": updated_at, + } + + async def list_admin_activities( + self, + page: int = 1, + size: int = 20, + limit: Optional[int] = None, + action: Optional[str] = None, + target_type: Optional[str] = None, + keyword: Optional[str] = None, + ) -> dict[str, Any]: + if limit is not None: + size = limit + try: + page = max(int(page or 1), 1) + except (TypeError, ValueError): + page = 1 + try: + size = int(size or 20) + except (TypeError, ValueError): + size = 20 + size = min(max(size, 1), 100) + activities = await self._get_admin_activities() + normalized_action = self._normalize_admin_activity_text(action).lower() + normalized_target_type = self._normalize_admin_activity_text(target_type).lower() + normalized_keyword = self._normalize_admin_activity_text(keyword).lower() + filtered_activities = self._filter_admin_activities( + activities, + action=normalized_action, + target_type=normalized_target_type, + keyword=normalized_keyword, + ) + offset = (page - 1) * size + visible_activities = filtered_activities[offset : offset + size] + action_options = self._build_admin_activity_options(activities, "action") + target_type_options = self._build_admin_activity_options(activities, "targetType") + return { + "activities": visible_activities, + "items": visible_activities, + "page": page, + "size": size, + "total": len(filtered_activities), + "storedTotal": len(activities), + "stored_total": len(activities), + "filters": { + "action": normalized_action, + "targetType": normalized_target_type, + "target_type": normalized_target_type, + "keyword": normalized_keyword, + }, + "actionOptions": action_options, + "action_options": action_options, + "targetTypeOptions": target_type_options, + "target_type_options": target_type_options, + } + + async def record_admin_activity( + self, + action: str, + target_type: str, + target_id: Optional[Any] = None, + target_name: str = "", + count: int = 1, + meta: Optional[dict[str, Any]] = None, + ) -> Optional[dict[str, Any]]: + try: + now = await get_now() + created_at = now.isoformat() + activity = self._normalize_admin_activity( + { + "id": self._build_admin_activity_id( + action=action, + target_type=target_type, + target_id=target_id, + target_name=target_name, + timestamp=now, + ), + "action": action, + "targetType": target_type, + "target_type": target_type, + "targetId": target_id, + "target_id": target_id, + "targetName": target_name, + "target_name": target_name, + "count": count, + "meta": meta or {}, + "createdAt": created_at, + "created_at": created_at, + } + ) + if not activity: + return None + + activities = await self._get_admin_activities() + next_activities = [ + activity, + *[item for item in activities if item["id"] != activity["id"]], + ][: self.MAX_ADMIN_ACTIVITIES] + await self._save_admin_activities(next_activities) + return activity + except Exception: + return None + + async def _get_admin_activities(self) -> list[dict[str, Any]]: + record = await KeyValue.filter(key=self.ADMIN_ACTIVITY_KEY).first() + raw_activities = record.value if record else [] + if isinstance(raw_activities, dict): + raw_activities = ( + raw_activities.get("activities") or raw_activities.get("items") or [] + ) + if not isinstance(raw_activities, list): + return [] + + activities = [] + seen_ids = set() + for raw_activity in raw_activities: + activity = self._normalize_admin_activity(raw_activity) + if not activity or activity["id"] in seen_ids: + continue + seen_ids.add(activity["id"]) + activities.append(activity) + if len(activities) >= self.MAX_ADMIN_ACTIVITIES: + break + + activities.sort(key=lambda item: item.get("createdAt") or "", reverse=True) + return activities + + async def _save_admin_activities(self, activities: list[dict[str, Any]]) -> None: + await KeyValue.update_or_create( + key=self.ADMIN_ACTIVITY_KEY, + defaults={"value": {"activities": activities}}, + ) + + def _normalize_admin_activity(self, activity: Any) -> Optional[dict[str, Any]]: + if not isinstance(activity, dict): + return None + + action = self._normalize_admin_activity_text(activity.get("action")) + target_type = self._normalize_admin_activity_text( + activity.get("targetType") or activity.get("target_type") or "system" + ) + if not action: + return None + + target_name = self._normalize_admin_activity_text( + activity.get("targetName") or activity.get("target_name") + ) + created_at = activity.get("createdAt") or activity.get("created_at") + if isinstance(created_at, datetime): + created_at = created_at.isoformat() + created_at = str(created_at or "") + if not created_at: + return None + + target_id = activity.get("targetId") + if target_id is None: + target_id = activity.get("target_id") + + count = activity.get("count", 1) + try: + count = max(int(count), 1) + except (TypeError, ValueError): + count = 1 + + meta = activity.get("meta") + if not isinstance(meta, dict): + meta = {} + + activity_id = self._normalize_admin_activity_text(activity.get("id")) + if not activity_id: + activity_id = self._build_admin_activity_id( + action=action, + target_type=target_type, + target_id=target_id, + target_name=target_name, + timestamp=None, + seed=created_at, + ) + + return { + "id": activity_id, + "action": action, + "targetType": target_type, + "target_type": target_type, + "targetId": target_id, + "target_id": target_id, + "targetName": target_name, + "target_name": target_name, + "count": count, + "meta": meta, + "createdAt": created_at, + "created_at": created_at, + } + + def _normalize_admin_activity_text(self, value: Any) -> str: + return str(value or "").strip()[: self.MAX_ADMIN_ACTIVITY_TEXT_LENGTH] + + def _filter_admin_activities( + self, + activities: list[dict[str, Any]], + action: str, + target_type: str, + keyword: str, + ) -> list[dict[str, Any]]: + filtered_activities = [] + for activity in activities: + if action and str(activity.get("action") or "").lower() != action: + continue + if target_type and str(activity.get("targetType") or "").lower() != target_type: + continue + if keyword and not self._activity_matches_keyword(activity, keyword): + continue + filtered_activities.append(activity) + return filtered_activities + + def _activity_matches_keyword(self, activity: dict[str, Any], keyword: str) -> bool: + searchable_values = [ + activity.get("action"), + activity.get("targetType"), + activity.get("target_type"), + activity.get("targetId"), + activity.get("target_id"), + activity.get("targetName"), + activity.get("target_name"), + ] + meta = activity.get("meta") + if isinstance(meta, dict): + searchable_values.extend(meta.values()) + + return any(keyword in str(value or "").lower() for value in searchable_values) + + def _build_admin_activity_options( + self, + activities: list[dict[str, Any]], + field: str, + ) -> list[dict[str, Any]]: + counters: dict[str, dict[str, Any]] = {} + for activity in activities: + raw_value = self._normalize_admin_activity_text(activity.get(field)) + if not raw_value: + continue + value = raw_value.lower() + if value not in counters: + counters[value] = {"label": raw_value, "count": 0} + counters[value]["count"] += 1 + + return [ + { + "value": value, + "label": option["label"], + "count": option["count"], + } + for value, option in sorted( + counters.items(), + key=lambda item: (-item[1]["count"], item[0]), + ) + ] + + def _build_admin_activity_id( + self, + action: str, + target_type: str, + target_id: Optional[Any], + target_name: str, + timestamp: Optional[datetime], + seed: Optional[str] = None, + ) -> str: + timestamp_seed = ( + str(int(timestamp.timestamp() * 1000)) if timestamp else str(seed or "activity") + ) + digest = hashlib.sha1( + f"{timestamp_seed}:{action}:{target_type}:{target_id}:{target_name}".encode("utf-8") + ).hexdigest()[:10] + return f"act_{timestamp_seed}_{digest}" + + def _build_file_activity_name(self, file_code: FileCodes) -> str: + return (file_code.prefix + file_code.suffix) or file_code.code + + async def _get_file_view_presets(self) -> list[dict[str, Any]]: + record = await KeyValue.filter(key=self.FILE_VIEW_PRESETS_KEY).first() + raw_presets = record.value if record else [] + if isinstance(raw_presets, dict): + raw_presets = raw_presets.get("presets") or raw_presets.get("items") or [] + if not isinstance(raw_presets, list): + return [] + + presets = [] + seen_ids = set() + for raw_preset in raw_presets: + try: + preset = self._normalize_file_view_preset(raw_preset) + except HTTPException: + continue + if not preset or preset["id"] in seen_ids: + continue + seen_ids.add(preset["id"]) + presets.append(preset) + if len(presets) >= self.MAX_VIEW_PRESETS: + break + return presets + + async def _save_file_view_presets(self, presets: list[dict[str, Any]]) -> None: + await KeyValue.update_or_create( + key=self.FILE_VIEW_PRESETS_KEY, + defaults={"value": {"presets": presets}}, + ) + + def _normalize_file_view_preset(self, preset: Any) -> Optional[dict[str, Any]]: + if not isinstance(preset, dict): + return None + + preset_id = str(preset.get("id") or "").strip() + raw_name = str(preset.get("name") or "").strip() + if not raw_name: + return None + name = self._normalize_file_view_preset_name(raw_name) + if not preset_id: + preset_id = self._build_file_view_preset_id(name) + + filters = preset.get("filters") or preset.get("params") or {} + normalized_filters = self._normalize_file_view_preset_filters(filters) + created_at = preset.get("createdAt") or preset.get("created_at") + updated_at = preset.get("updatedAt") or preset.get("updated_at") + + return { + "id": preset_id, + "name": name, + "filters": normalized_filters, + "params": normalized_filters, + "createdAt": created_at, + "created_at": created_at, + "updatedAt": updated_at, + "updated_at": updated_at, + } + + def _normalize_file_view_preset_name(self, name: Any) -> str: + normalized_name = str(name or "").strip() + if not normalized_name: + raise HTTPException(status_code=400, detail="请输入视图名称") + return normalized_name[: self.MAX_VIEW_PRESET_NAME_LENGTH] + + def _normalize_file_view_preset_filters(self, filters: Any) -> dict[str, Any]: + if not isinstance(filters, dict): + filters = {} + + sort_by = str(filters.get("sortBy") or filters.get("sort_by") or "created_at") + sort_by = sort_by.replace("-", "_").strip().lower() + if sort_by not in self.VIEW_PRESET_SORT_FIELDS: + sort_by = "created_at" + + sort_order = str(filters.get("sortOrder") or filters.get("sort_order") or "desc") + sort_order = sort_order.strip().lower() + if sort_order not in {"asc", "desc"}: + sort_order = "desc" + + size = filters.get("size", 10) + try: + size = int(size) + except (TypeError, ValueError): + size = 10 + + return { + "keyword": str(filters.get("keyword") or "").strip()[ + : self.MAX_VIEW_PRESET_KEYWORD_LENGTH + ], + "status": self._normalize_file_view_preset_choice( + filters.get("status"), self.VIEW_PRESET_STATUS_VALUES + ), + "type": self._normalize_file_view_preset_choice( + filters.get("type"), self.VIEW_PRESET_TYPE_VALUES + ), + "health": self._normalize_file_view_preset_choice( + filters.get("health"), self.VIEW_PRESET_HEALTH_VALUES + ), + "sortBy": sort_by, + "sortOrder": sort_order, + "size": min(max(size, 1), 100), + } + + def _normalize_file_view_preset_choice(self, value: Any, allowed_values: set[str]) -> str: + normalized_value = str(value or "all").strip().lower() + if normalized_value not in allowed_values: + return "all" + return normalized_value + + def _build_file_view_preset_id( + self, name: str, timestamp: Optional[datetime] = None + ) -> str: + seed = int(timestamp.timestamp() * 1000) if timestamp else "saved" + digest = hashlib.sha1(name.encode("utf-8")).hexdigest()[:8] + return f"view_{seed}_{digest}" + + def _build_file_status_insights( + self, + file_code: FileCodes, + detail: dict[str, Any], + now: datetime, + has_download_limit: bool, + is_permanent: bool, + can_download: bool, + ) -> dict[str, Any]: + remaining_downloads = detail["remainingDownloads"] + seconds_until_expiration = self._seconds_between(now, file_code.expired_at) + age_seconds = self._seconds_between(file_code.created_at, now) + reasons = [] + + if detail["isExpired"]: + reasons.append("expired") + if has_download_limit and remaining_downloads == 0: + reasons.append("download_limit_exhausted") + if seconds_until_expiration is not None and 0 < seconds_until_expiration <= 86400: + reasons.append("expires_soon") + if file_code.used_count == 0: + reasons.append("never_retrieved") + if not can_download: + reasons.append("storage_metadata_incomplete") + if file_code.is_chunked: + reasons.append("chunked_upload") + + severity = "success" + state = "available" + next_action = "monitor" + if detail["isExpired"] or (has_download_limit and remaining_downloads == 0): + severity = "danger" + state = "expired" + next_action = "extend_or_delete" + elif not can_download: + severity = "danger" + state = "storage_incomplete" + next_action = "inspect_storage" + elif "expires_soon" in reasons: + severity = "warning" + state = "expiring_soon" + next_action = "extend_expiration" + elif is_permanent: + state = "permanent" + next_action = "monitor" + + return { + "severity": severity, + "state": state, + "nextAction": next_action, + "next_action": next_action, + "reasons": reasons, + "metrics": { + "ageSeconds": max(age_seconds or 0, 0), + "age_seconds": max(age_seconds or 0, 0), + "secondsUntilExpiration": seconds_until_expiration, + "seconds_until_expiration": seconds_until_expiration, + "remainingDownloads": remaining_downloads, + "remaining_downloads": remaining_downloads, + "usedCount": file_code.used_count, + "used_count": file_code.used_count, + }, + } + + async def _build_file_timeline( + self, + file_code: FileCodes, + detail: dict[str, Any], + now: datetime, + has_download_limit: bool, + is_permanent: bool, + is_text: bool, + ) -> list[dict[str, Any]]: + remaining_downloads = detail["remainingDownloads"] + seconds_until_expiration = self._seconds_between(now, file_code.expired_at) + timeline = [ + { + "key": "created", + "status": "done", + "severity": "success", + "timestamp": file_code.created_at, + }, + { + "key": "content_ready", + "status": "done", + "severity": "success", + "timestamp": file_code.created_at, + "detail": "text" if is_text else "file", + }, + ] + + if file_code.upload_id: + timeline.append( + { + "key": "upload_session", + "status": "done", + "severity": "info", + "timestamp": file_code.created_at, + "detail": file_code.upload_id, + } + ) + + if is_permanent: + timeline.append( + { + "key": "expiration_policy", + "status": "unlimited", + "severity": "success", + "timestamp": file_code.created_at, + } + ) + elif file_code.expired_at is not None: + expired = seconds_until_expiration is not None and seconds_until_expiration <= 0 + timeline.append( + { + "key": "expiration_policy", + "status": "expired" if expired else "pending", + "severity": "danger" if expired else "warning", + "timestamp": file_code.expired_at, + "value": seconds_until_expiration, + } + ) + + if has_download_limit: + exhausted = remaining_downloads == 0 + timeline.append( + { + "key": "download_limit", + "status": "exhausted" if exhausted else "active", + "severity": "danger" if exhausted else "info", + "timestamp": file_code.created_at, + "value": remaining_downloads, + } + ) + else: + timeline.append( + { + "key": "download_limit", + "status": "unlimited", + "severity": "success", + "timestamp": file_code.created_at, + "value": None, + } + ) + + download_stats = await TransferStats.filter( + action="download", file_code_id=file_code.id + ).order_by("created_at") + download_event_count = len(download_stats) + display_download_count = max(int(file_code.used_count or 0), download_event_count) + timeline.append( + { + "key": "retrieved", + "status": "done" if display_download_count > 0 else "pending", + "severity": "success" if display_download_count > 0 else "neutral", + "timestamp": ( + download_stats[-1].created_at if download_stats else file_code.created_at + ), + "value": display_download_count, + "event_count": download_event_count, + } + ) + for index, stat in enumerate(download_stats, start=1): + timeline.append( + { + "key": "retrieved_event", + "status": "done", + "severity": "success", + "timestamp": stat.created_at, + "value": index, + "detail": stat.ip or "", + } + ) + return timeline + + def _seconds_between( + self, start: Optional[datetime], end: Optional[datetime] + ) -> Optional[int]: + if start is None or end is None: + return None + if start.tzinfo is None and end.tzinfo is not None: + end = end.replace(tzinfo=None) + elif start.tzinfo is not None and end.tzinfo is None: + start = start.replace(tzinfo=None) + return int((end - start).total_seconds()) + + def _build_policy_action_update( + self, + file_code: FileCodes, + action: str, + now: datetime, + download_limit: Optional[int], + ) -> dict[str, Any]: + if action == "extend_24h": + return {"expired_at": self._extended_expiration(file_code.expired_at, now, hours=24)} + if action == "extend_7d": + return {"expired_at": self._extended_expiration(file_code.expired_at, now, days=7)} + if action == "make_permanent": + return {"expired_at": None, "expired_count": -1} + if action == "reset_download_limit": + next_limit = download_limit if download_limit is not None else 5 + if next_limit < 1: + raise HTTPException(status_code=400, detail="取件次数必须大于 0") + return {"expired_count": next_limit} + + raise HTTPException(status_code=400, detail="不支持的策略动作") + + def _extended_expiration( + self, + expired_at: Optional[datetime], + now: datetime, + **duration: int, + ) -> datetime: + base_time = now + if expired_at is not None: + comparable_expired_at = self._align_datetime(expired_at, now) + if comparable_expired_at > now: + base_time = comparable_expired_at + return base_time + timedelta(**duration) + + def _align_datetime(self, value: datetime, reference: datetime) -> datetime: + if value.tzinfo is None and reference.tzinfo is not None: + return value.replace(tzinfo=reference.tzinfo) + if value.tzinfo is not None and reference.tzinfo is None: + return value.replace(tzinfo=None) + return value + + def _match_admin_file( + self, + item: dict[str, Any], + keyword: str, + status: str, + file_type: str, + health: str, + ) -> bool: + if status == "active" and item["isExpired"]: + return False + if status == "expired" and not item["isExpired"]: + return False + if file_type == "text" and not item["isText"]: + return False + if file_type == "file" and item["isText"]: + return False + if file_type == "chunked" and not item["isChunked"]: + return False + if not self._match_admin_file_health(item, health): + return False + if not keyword: + return True + + search_values = [ + item.get("code"), + item.get("name"), + item.get("prefix"), + item.get("suffix"), + item.get("fileHash"), + item.get("text"), + ] + return any(keyword in str(value).lower() for value in search_values if value) + + def _match_admin_file_health(self, item: dict[str, Any], health: str) -> bool: + if not health or health == "all": + return True + + status_insights = item.get("statusInsights") or {} + severity = status_insights.get("severity") + state = status_insights.get("state") + reasons = set(status_insights.get("reasons") or []) + + if health == "attention": + return severity in {"danger", "warning"} + if health == "danger": + return severity == "danger" + if health == "warning": + return severity == "warning" + if health == "expired": + return state == "expired" or item.get("isExpired") is True + if health == "expiring_soon": + return "expires_soon" in reasons + if health == "storage_issue": + return state == "storage_incomplete" or "storage_metadata_incomplete" in reasons + if health == "never_retrieved": + return "never_retrieved" in reasons + if health == "healthy": + return severity == "success" + if health == "permanent": + return state == "permanent" + + return True + + def _normalize_sort_by(self, sort_by: str) -> str: + normalized = sort_by.replace("-", "_").strip().lower() + if normalized not in self.SORT_FIELDS: + return "created_at" + return normalized + + def _get_sort_value(self, item: dict[str, Any], sort_by: str): + def date_value(value: Any) -> float: + if value is None: + return 0 + if isinstance(value, datetime): + return value.timestamp() + return 0 + + sort_map = { + "created_at": date_value(item.get("createdAt")), + "createdat": date_value(item.get("createdAt")), + "expired_at": date_value(item.get("expiredAt")), + "expiredat": date_value(item.get("expiredAt")), + "name": item.get("name") or "", + "size": item.get("size") or 0, + "used_count": item.get("usedCount") or 0, + "usedcount": item.get("usedCount") or 0, + "code": item.get("code") or "", + } + return sort_map.get(sort_by) + + async def download_file(self, file_id: int): + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + if file_code.text: + return APIResponse(detail=file_code.text) + else: + return await self.file_storage.get_file_response(file_code) + + async def preview_file(self, file_id: int, max_chars: int = 4000): + max_chars = min(max(max_chars, 1), 20000) + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + if file_code.text is None: + raise HTTPException(status_code=400, detail="仅文本分享支持预览") + + content = file_code.text + preview = content[:max_chars] + return { + "id": file_code.id, + "code": file_code.code, + "name": f"{file_code.prefix}{file_code.suffix}", + "type": "text", + "content": preview, + "length": len(content), + "previewLength": len(preview), + "preview_length": len(preview), + "truncated": len(content) > max_chars, + "maxChars": max_chars, + "max_chars": max_chars, + "createdAt": file_code.created_at, + "created_at": file_code.created_at, + "expiredAt": file_code.expired_at, + "expired_at": file_code.expired_at, + } + + async def share_local_file(self, item): + local_file = LocalFileClass(item.filename) + 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: + text = await local_file.read() + 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(text, 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( + FileCodes(file_path=path, uuid_file_name=uuid_file_name) + ) + raise + finally: + await release_storage(reservation_token) + + return { + "code": code, + "name": local_file.file, + } + + +class ConfigService: + INT_FIELDS = { + "adminSessionExpire", + "enableChunk", + "errorCount", + "errorMinute", + "loginCount", + "loginMinute", + "max_save_seconds", + "onedrive_proxy", + "openUpload", + "port", + "s3_proxy", + "serverPort", + "serverWorkers", + "showAdminAddr", + "storageLimit", + "uploadCount", + "uploadMinute", + "uploadSize", + "webdav_proxy", + } + FLOAT_FIELDS = {"opacity"} + + def get_config(self): + config = dict(settings.items()) + config["admin_token"] = "" + for key in INTERNAL_CONFIG_KEYS: + config.pop(key, None) + return config + + async def update_config(self, data: dict): + current_config = dict(settings.items()) + next_config = dict(current_config) + update_data = { + key: value + for key, value in data.items() + if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS + } + + admin_token = update_data.get("admin_token") + admin_password_changed = False + if admin_token is None or admin_token == "": + update_data.pop("admin_token", None) + elif not is_password_hashed(admin_token): + update_data["admin_token"] = hash_password(admin_token) + admin_password_changed = True + else: + admin_password_changed = True + + for key, value in update_data.items(): + if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS: + continue + + try: + if key in self.INT_FIELDS: + next_config[key] = int(value) + elif key in self.FLOAT_FIELDS: + next_config[key] = float(value) + else: + next_config[key] = value + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误") + + try: + session_expire = int(next_config.get("adminSessionExpire")) + except (TypeError, ValueError): + raise HTTPException( + status_code=400, + detail="adminSessionExpire 配置值格式错误", + ) + if ( + not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX + or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0 + ): + raise HTTPException( + status_code=400, + detail="adminSessionExpire 必须是 1 到 365 个整天", + ) + next_config["adminSessionExpire"] = session_expire + + if int(next_config.get("storageLimit", 0)) < 0: + raise HTTPException( + status_code=400, + detail="storageLimit 不能小于 0", + ) + + if admin_password_changed: + next_config["jwt_secret"] = generate_jwt_secret() + + await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) + await refresh_settings() + + +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 delete_file(self, filename: str): + file = LocalFileClass(filename) + if await file.exists(): + await file.delete() + return "删除成功" + raise HTTPException(status_code=404, detail="文件不存在") + + +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 + 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) + else: + self.ctime = None + self.size = None + + async def read(self): + return open(self.path, "rb") + + async def write(self, data): + with open(self.path, "w") as f: + f.write(data) + + async def delete(self): + os.remove(self.path) + + async def exists(self): + return self.path.is_file() diff --git a/apps/admin/views.py b/apps/admin/views.py new file mode 100644 index 0000000..0128c4a --- /dev/null +++ b/apps/admin/views.py @@ -0,0 +1,889 @@ +# @Time : 2023/8/14 14:38 +# @Author : Lan +# @File : views.py +# @Software: PyCharm +import datetime +from collections import Counter +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException +from apps.admin.services import FileService, ConfigService, LocalFileService +from apps.admin.dependencies import ( + admin_required, + get_admin_session, + get_file_service, + get_config_service, + get_local_file_service, +) +from apps.admin.schemas import ( + IDData, + IDsData, + BatchUpdateFileData, + BatchFilePolicyActionData, + FilePolicyActionData, + TrashRetentionData, + FileMetadataData, + FileViewPresetData, + FileViewPresetDeleteData, + ShareItem, + DeleteItem, + LoginData, + UpdateFileData, +) +from core.response import APIResponse +from apps.base.models import FileCodes, KeyValue, TransferStats +from apps.admin.dependencies import ( + create_token, + get_admin_session_expire_seconds, + verify_token, +) + +from core.settings import settings +from core.utils import get_now, verify_password +from apps.base.utils import ip_limit + +admin_api = APIRouter( + prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)] +) + + +def _pick_query_text(*values: Optional[str]) -> Optional[str]: + for value in values: + normalized_value = str(value or "").strip() + if normalized_value: + return normalized_value + return None + + +@admin_api.post("/login") +async def login(data: LoginData, ip: str = Depends(ip_limit["login"])): + # 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定 + if not verify_password(data.password, settings.admin_token): + ip_limit["login"].add_ip(ip) + raise HTTPException(status_code=401, detail="密码错误") + + expires_in = get_admin_session_expire_seconds() + token = create_token({"is_admin": True}, expires_in=expires_in) + return APIResponse( + detail={ + "id": "admin", + "username": "admin", + "token": token, + "token_type": "Bearer", + "expires_at": verify_token(token)["exp"], + "expires_in": expires_in, + } + ) + + +@admin_api.get("/verify") +async def verify_admin(session: dict = Depends(get_admin_session)): + return APIResponse(detail=session) + + +@admin_api.post("/logout") +async def logout_admin(): + return APIResponse(detail={"ok": True}) + + +async def build_dashboard_recent_file(file_code: FileCodes) -> dict: + is_expired = await file_code.is_expired() + return { + "id": file_code.id, + "code": file_code.code, + "name": file_code.prefix + file_code.suffix, + "suffix": file_code.suffix, + "size": file_code.size, + "text": file_code.text is not None, + "expiredAt": file_code.expired_at, + "expiredCount": file_code.expired_count, + "usedCount": file_code.used_count, + "createdAt": file_code.created_at, + "isExpired": is_expired, + } + + +@admin_api.get("/dashboard") +async def dashboard(file_service: FileService = Depends(get_file_service)): + all_codes = await FileCodes.filter(is_trashed=False).all() + all_size = sum([code.size for code in all_codes]) + sys_start = await KeyValue.filter(key="sys_start").first() + now = await get_now() + today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) + yesterday_start = today_start - datetime.timedelta(days=1) + yesterday_end = today_start - datetime.timedelta(microseconds=1) + yesterday_codes = FileCodes.filter( + created_at__gte=yesterday_start, created_at__lte=yesterday_end + ) + today_codes = FileCodes.filter(created_at__gte=today_start) + yesterday_file_codes = await yesterday_codes + today_file_codes = await today_codes + expired_count = 0 + for file_code in all_codes: + if await file_code.is_expired(): + expired_count += 1 + health_summary = await file_service.build_file_health_summary(all_codes, now=now) + + text_count = sum(1 for file_code in all_codes if file_code.text is not None) + chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked) + used_count = sum([file_code.used_count for file_code in all_codes]) + suffix_counter = Counter( + "Text" if file_code.text is not None else (file_code.suffix or "file") + for file_code in all_codes + ) + recent_file_codes = sorted( + all_codes, + key=lambda file_code: file_code.created_at.timestamp() + if file_code.created_at + else 0, + reverse=True, + )[:8] + recent_activities = await file_service.list_admin_activities(limit=8) + return APIResponse( + detail={ + "totalFiles": len(all_codes), + "storageUsed": str(all_size), + "sysUptime": sys_start.value if sys_start else None, + "yesterdayCount": len(yesterday_file_codes), + "yesterdaySize": str(sum([code.size for code in yesterday_file_codes])), + "todayCount": len(today_file_codes), + "todaySize": str(sum([code.size for code in today_file_codes])), + "activeCount": len(all_codes) - expired_count, + "expiredCount": expired_count, + "textCount": text_count, + "fileCount": len(all_codes) - text_count, + "chunkedCount": chunked_count, + "usedCount": used_count, + "storageBackend": settings.file_storage, + "uploadSizeLimit": settings.uploadSize, + "openUpload": settings.openUpload, + "enableChunk": settings.enableChunk, + "maxSaveSeconds": settings.max_save_seconds, + **health_summary, + "healthSummary": health_summary, + "topSuffixes": [ + {"suffix": suffix, "count": count} + for suffix, count in suffix_counter.most_common(8) + ], + "recentFiles": [ + await build_dashboard_recent_file(file_code) + for file_code in recent_file_codes + ], + "recentActivities": recent_activities["activities"], + "recent_activities": recent_activities["activities"], + } + ) + + +@admin_api.get("/activities") +async def admin_activities( + page: int = 1, + size: int = 20, + limit: Optional[int] = None, + action: Optional[str] = None, + targetType: Optional[str] = None, + target_type: Optional[str] = None, + keyword: Optional[str] = None, + file_service: FileService = Depends(get_file_service), +): + result = await file_service.list_admin_activities( + page=page, + size=size, + limit=limit, + action=action, + target_type=_pick_query_text(targetType, target_type), + keyword=keyword, + ) + return APIResponse(detail=result) + + +@admin_api.get("/analytics") +async def analytics(start: str = "", end: str = ""): + now = await get_now() + + def parse_day(value: str, fallback: datetime.datetime) -> datetime.datetime: + if not value: + return fallback + try: + return datetime.datetime.strptime(value[:10], "%Y-%m-%d") + except Exception: + return fallback + + end_day = parse_day(end, now.replace(hour=0, minute=0, second=0, microsecond=0)) + start_day = parse_day(start, end_day - datetime.timedelta(days=29)) + end_exclusive = end_day + datetime.timedelta(days=1) + raw_stats = await TransferStats.filter( + created_at__gte=start_day, + created_at__lt=end_exclusive, + ).order_by("created_at", "id") + stats = [] + recent_downloads = {} + for item in raw_stats: + if item.action == "download": + dedupe_key = ( + item.file_code_id or item.code or "", + item.ip or "", + int(item.size or 0), + ) + previous = recent_downloads.get(dedupe_key) + if previous and (item.created_at - previous).total_seconds() <= 5: + continue + recent_downloads[dedupe_key] = item.created_at + stats.append(item) + + files = await FileCodes.all() + file_map = {item.code: item for item in files} + + day_map = {} + cursor = start_day + while cursor < end_exclusive: + key = cursor.strftime("%Y-%m-%d") + day_map[key] = { + "date": key, + "downloads": 0, + "uploads": 0, + "downloadTraffic": 0, + "uploadTraffic": 0, + } + cursor += datetime.timedelta(days=1) + + file_stats = {} + for item in stats: + key = item.created_at.strftime("%Y-%m-%d") + row = day_map.get(key) + if row and item.action == "download": + row["downloads"] += 1 + row["downloadTraffic"] += item.size or 0 + elif row and item.action == "upload": + row["uploads"] += 1 + row["uploadTraffic"] += item.size or 0 + if not item.code: + continue + bucket = file_stats.setdefault( + item.code, + { + "downloads": 0, + "downloadTraffic": 0, + "uploads": 0, + "uploadTraffic": 0, + "name": item.name or item.code, + "size": int(item.size or 0), + "uploaded_at": None, + "expired_at": item.expired_at, + "deleted_at": None, + "deleted": False, + }, + ) + bucket["name"] = bucket["name"] or item.name or item.code + bucket["size"] = bucket["size"] or int(item.size or 0) + bucket["expired_at"] = bucket["expired_at"] or item.expired_at + if item.action == "upload": + bucket["uploads"] += 1 + bucket["uploadTraffic"] += item.size or 0 + bucket["uploaded_at"] = bucket["uploaded_at"] or item.created_at + elif item.action == "download": + bucket["downloads"] += 1 + bucket["downloadTraffic"] += item.size or 0 + elif item.action == "delete": + bucket["deleted"] = True + bucket["deleted_at"] = item.deleted_at or item.created_at + + for file_item in files: + current_name = ( + f"{file_item.prefix or ''}{file_item.suffix or ''}" + or file_item.uuid_file_name + or file_item.code + ) + bucket = file_stats.setdefault( + file_item.code, + { + "downloads": 0, + "downloadTraffic": 0, + "uploads": 0, + "uploadTraffic": 0, + "name": current_name, + "size": int(file_item.size or 0), + "uploaded_at": file_item.created_at, + "expired_at": file_item.expired_at, + "deleted_at": None, + "deleted": False, + }, + ) + bucket["name"] = current_name + bucket["size"] = int(file_item.size or 0) + bucket["uploaded_at"] = file_item.created_at or bucket["uploaded_at"] + bucket["expired_at"] = file_item.expired_at + bucket["deleted"] = False + bucket["deleted_at"] = None + created_key = ( + file_item.created_at.strftime("%Y-%m-%d") if file_item.created_at else "" + ) + created_row = day_map.get(created_key) + if bucket["uploads"] <= 0: + bucket["uploads"] = 1 + bucket["uploadTraffic"] = int(file_item.size or 0) + if created_row: + created_row["uploads"] += 1 + created_row["uploadTraffic"] += int(file_item.size or 0) + missing_downloads = max(0, int(file_item.used_count or 0) - bucket["downloads"]) + if missing_downloads: + traffic = missing_downloads * int(file_item.size or 0) + bucket["downloads"] += missing_downloads + bucket["downloadTraffic"] += traffic + if created_row: + created_row["downloads"] += missing_downloads + created_row["downloadTraffic"] += traffic + + def iso(value): + return value.isoformat() if value else "" + + def current_file_expired(file_item) -> bool: + if not file_item: + return False + if file_item.expired_at and file_item.expired_at < now: + return True + return file_item.expired_count == 0 + + def history_row(code: str, data: dict) -> dict: + file_item = file_map.get(code) + current_name = "" + if file_item: + current_name = ( + f"{file_item.prefix or ''}{file_item.suffix or ''}" + or file_item.uuid_file_name + or file_item.code + ) + uploaded_at = file_item.created_at if file_item else data.get("uploaded_at") + expired_at = file_item.expired_at if file_item else data.get("expired_at") + size = int(file_item.size or 0) if file_item else data.get("size") or 0 + return { + "code": code, + "name": current_name or data.get("name") or code, + "size": str(size), + "download_count": data.get("downloads") or 0, + "download_traffic": str(data.get("downloadTraffic") or 0), + "upload_count": data.get("uploads") or 0, + "upload_traffic": str(data.get("uploadTraffic") or 0), + "current": bool(file_item), + "expired": current_file_expired(file_item), + "deleted": bool(data.get("deleted")) and not bool(file_item), + "created_at": iso(uploaded_at), + "uploaded_at": iso(uploaded_at), + "expired_at": iso(expired_at), + "deleted_at": iso(data.get("deleted_at")), + } + + def sort_time(value) -> float: + return value.timestamp() if value else 0 + + history = sorted( + file_stats.items(), + key=lambda kv: ( + sort_time(kv[1].get("deleted_at") or kv[1].get("uploaded_at")), + kv[1].get("downloads") or 0, + kv[1].get("downloadTraffic") or 0, + ), + reverse=True, + ) + top_files = sorted( + [item for item in history if (item[1].get("downloads") or 0) > 0], + key=lambda kv: (kv[1].get("downloads") or 0, kv[1].get("downloadTraffic") or 0), + reverse=True, + )[:5] + daily_rows = list(day_map.values()) + + return APIResponse( + detail={ + "range": { + "start": start_day.strftime("%Y-%m-%d"), + "end": end_day.strftime("%Y-%m-%d"), + }, + "totals": { + "totalDownloads": sum(row["downloads"] for row in daily_rows), + "downloadedFiles": len( + [item for item in file_stats.values() if (item.get("downloads") or 0) > 0] + ), + "downloadTraffic": str( + sum(row["downloadTraffic"] for row in daily_rows) + ), + "historicalFiles": len(file_stats), + "currentFiles": len(files), + "totalUploads": sum(row["uploads"] for row in daily_rows), + "uploadTraffic": str( + sum(row["uploadTraffic"] for row in daily_rows) + ), + }, + "daily": daily_rows, + "topFiles": [history_row(code, data) for code, data in top_files], + "historyFiles": [history_row(code, data) for code, data in history], + } + ) + + +@admin_api.delete("/file/delete") +async def file_delete( + data: IDData, + file_service: FileService = Depends(get_file_service), +): + await file_service.delete_file(data.id) + return APIResponse() + + +async def batch_delete_files( + data: IDsData, + file_service: FileService, +): + if not data.ids: + raise HTTPException(status_code=400, detail="请选择要删除的文件") + result = await file_service.delete_files(data.ids) + return APIResponse(detail=result) + + +@admin_api.delete("/file/batch-delete") +async def file_batch_delete( + data: IDsData, + file_service: FileService = Depends(get_file_service), +): + return await batch_delete_files(data, file_service) + + +@admin_api.post("/file/batch-delete") +async def file_batch_delete_post( + data: IDsData, + file_service: FileService = Depends(get_file_service), +): + return await batch_delete_files(data, file_service) + + +@admin_api.get("/trash/list") +async def trash_list( + page: int = 1, + size: int = 20, + file_service: FileService = Depends(get_file_service), +): + return APIResponse(detail=await file_service.list_trash(page, size)) + + +@admin_api.post("/trash/restore") +async def trash_restore( + data: IDData, + file_service: FileService = Depends(get_file_service), +): + file_code = await file_service.restore_from_trash(data.id) + return APIResponse(detail=await file_service.get_file_detail(file_code.id)) + + +@admin_api.post("/trash/retention") +async def trash_retention( + data: TrashRetentionData, + file_service: FileService = Depends(get_file_service), +): + file_code = await file_service.set_trash_retention(data.id, data.retentionDays) + return APIResponse(detail={"id": file_code.id, "trashExpiresAt": file_code.trash_expires_at}) + + +@admin_api.delete("/trash/purge") +async def trash_purge( + data: IDData, + file_service: FileService = Depends(get_file_service), +): + file_code = await FileCodes.filter(id=data.id, is_trashed=True).first() + if not file_code: + raise HTTPException(status_code=404, detail="回收站文件不存在") + await file_service.purge_trashed_file(file_code) + return APIResponse() + + +async def batch_update_files( + data: BatchUpdateFileData, + file_service: FileService, +): + if not data.ids: + raise HTTPException(status_code=400, detail="请选择要更新的文件") + + update_data = {} + fields_set = data.model_fields_set + should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at) + + if should_clear_expired_at: + update_data["expired_at"] = None + update_data["expired_count"] = -1 + elif "expired_at" in fields_set and data.expired_at != "": + update_data["expired_at"] = data.expired_at + + if ( + not should_clear_expired_at + and "expired_count" in fields_set + and data.expired_count is not None + ): + update_data["expired_count"] = data.expired_count + + if not update_data: + raise HTTPException(status_code=400, detail="请选择要更新的字段") + + result = await file_service.update_files(data.ids, update_data) + return APIResponse(detail=result) + + +@admin_api.patch("/file/batch-update") +async def file_batch_update( + data: BatchUpdateFileData, + file_service: FileService = Depends(get_file_service), +): + return await batch_update_files(data, file_service) + + +@admin_api.post("/file/batch-update") +async def file_batch_update_post( + data: BatchUpdateFileData, + file_service: FileService = Depends(get_file_service), +): + return await batch_update_files(data, file_service) + + +async def apply_file_policy_action( + data: FilePolicyActionData, + file_service: FileService, +): + download_limit = data.downloadLimit + if download_limit is None: + download_limit = data.download_limit + + detail = await file_service.apply_file_policy_action( + file_id=data.id, + action=data.action, + download_limit=download_limit, + ) + return APIResponse(detail=detail) + + +@admin_api.patch("/file/policy-action") +async def file_policy_action( + data: FilePolicyActionData, + file_service: FileService = Depends(get_file_service), +): + return await apply_file_policy_action(data, file_service) + + +@admin_api.post("/file/policy-action") +async def file_policy_action_post( + data: FilePolicyActionData, + file_service: FileService = Depends(get_file_service), +): + return await apply_file_policy_action(data, file_service) + + +async def apply_batch_file_policy_action( + data: BatchFilePolicyActionData, + file_service: FileService, +): + if not data.ids: + raise HTTPException(status_code=400, detail="请选择要更新的文件") + + download_limit = data.downloadLimit + if download_limit is None: + download_limit = data.download_limit + + result = await file_service.apply_files_policy_action( + file_ids=data.ids, + action=data.action, + download_limit=download_limit, + ) + return APIResponse(detail=result) + + +@admin_api.patch("/file/batch-policy-action") +async def file_batch_policy_action( + data: BatchFilePolicyActionData, + file_service: FileService = Depends(get_file_service), +): + return await apply_batch_file_policy_action(data, file_service) + + +@admin_api.post("/file/batch-policy-action") +async def file_batch_policy_action_post( + data: BatchFilePolicyActionData, + file_service: FileService = Depends(get_file_service), +): + return await apply_batch_file_policy_action(data, file_service) + + +@admin_api.get("/file/list") +async def file_list( + page: int = 1, + size: int = 10, + keyword: str = "", + status: str = "", + type: str = "", + health: str = "", + sortBy: str = "created_at", + sortOrder: str = "desc", + file_service: FileService = Depends(get_file_service), +): + page = max(page, 1) + size = min(max(size, 1), 100) + files, total, summary = await file_service.list_files( + page, + size, + keyword, + status=status, + file_type=type, + health=health, + sort_by=sortBy, + sort_order=sortOrder, + ) + return APIResponse( + detail={ + "page": page, + "size": size, + "data": files, + "total": total, + "summary": summary, + } + ) + + +@admin_api.get("/file/detail") +async def file_detail( + id: int, + file_service: FileService = Depends(get_file_service), +): + detail = await file_service.get_file_detail(id) + return APIResponse(detail=detail) + + +@admin_api.post("/file/detail") +async def file_detail_post( + data: IDData, + file_service: FileService = Depends(get_file_service), +): + detail = await file_service.get_file_detail(data.id) + return APIResponse(detail=detail) + + +async def update_file_metadata( + data: FileMetadataData, + file_service: FileService, +): + fields_set = data.model_fields_set + update_note = "note" in fields_set + update_tags = "tags" in fields_set + if not update_note and not update_tags: + raise HTTPException(status_code=400, detail="请选择要更新的元数据") + + detail = await file_service.update_file_metadata( + file_id=data.id, + note=data.note, + tags=data.tags, + update_note=update_note, + update_tags=update_tags, + ) + return APIResponse(detail=detail) + + +@admin_api.patch("/file/metadata") +async def file_metadata( + data: FileMetadataData, + file_service: FileService = Depends(get_file_service), +): + return await update_file_metadata(data, file_service) + + +@admin_api.post("/file/metadata") +async def file_metadata_post( + data: FileMetadataData, + file_service: FileService = Depends(get_file_service), +): + return await update_file_metadata(data, file_service) + + +@admin_api.get("/file/view-presets") +async def file_view_presets( + file_service: FileService = Depends(get_file_service), +): + result = await file_service.list_file_view_presets() + return APIResponse(detail=result) + + +async def save_file_view_preset( + data: FileViewPresetData, + file_service: FileService, +): + filters = data.filters if data.filters is not None else data.params + preset = await file_service.save_file_view_preset( + preset_id=data.id, + name=data.name, + filters=filters or {}, + ) + return APIResponse(detail=preset) + + +@admin_api.post("/file/view-presets") +async def file_view_presets_save( + data: FileViewPresetData, + file_service: FileService = Depends(get_file_service), +): + return await save_file_view_preset(data, file_service) + + +@admin_api.patch("/file/view-presets") +async def file_view_presets_patch( + data: FileViewPresetData, + file_service: FileService = Depends(get_file_service), +): + return await save_file_view_preset(data, file_service) + + +async def delete_file_view_preset( + data: FileViewPresetDeleteData, + file_service: FileService, +): + result = await file_service.delete_file_view_preset(data.id) + return APIResponse(detail=result) + + +@admin_api.delete("/file/view-presets") +async def file_view_presets_delete( + data: FileViewPresetDeleteData, + file_service: FileService = Depends(get_file_service), +): + return await delete_file_view_preset(data, file_service) + + +@admin_api.post("/file/view-presets/delete") +async def file_view_presets_delete_post( + data: FileViewPresetDeleteData, + file_service: FileService = Depends(get_file_service), +): + return await delete_file_view_preset(data, file_service) + + +@admin_api.get("/config/get") +async def get_config( + config_service: ConfigService = Depends(get_config_service), +): + return APIResponse(detail=config_service.get_config()) + + +@admin_api.patch("/config/update") +async def update_config( + data: dict, + config_service: ConfigService = Depends(get_config_service), + file_service: FileService = Depends(get_file_service), +): + data.pop("themesChoices", None) + await config_service.update_config(data) + await file_service.record_admin_activity( + action="config.update", + target_type="config", + target_name="system", + count=1, + meta={"fields": sorted(data.keys())}, + ) + return APIResponse() + + +@admin_api.get("/file/download") +async def file_download( + id: int, + file_service: FileService = Depends(get_file_service), +): + file_content = await file_service.download_file(id) + return file_content + + +@admin_api.get("/file/preview") +async def file_preview( + id: int, + maxChars: int = 4000, + file_service: FileService = Depends(get_file_service), +): + preview = await file_service.preview_file(id, maxChars) + return APIResponse(detail=preview) + + +@admin_api.get("/local/lists") +async def get_local_lists( + local_file_service: LocalFileService = Depends(get_local_file_service), +): + files = await local_file_service.list_files() + return APIResponse(detail=files) + + +@admin_api.delete("/local/delete") +async def delete_local_file( + item: DeleteItem, + local_file_service: LocalFileService = Depends(get_local_file_service), + file_service: FileService = Depends(get_file_service), +): + result = await local_file_service.delete_file(item.filename) + await file_service.record_admin_activity( + action="local_file.delete", + target_type="local_file", + target_name=item.filename, + count=1, + meta={"success": bool(result)}, + ) + return APIResponse(detail=result) + + +@admin_api.post("/local/share") +async def share_local_file( + item: ShareItem, + file_service: FileService = Depends(get_file_service), +): + share_info = await file_service.share_local_file(item) + await file_service.record_admin_activity( + action="local_file.share", + target_type="file", + target_id=share_info.get("id") if isinstance(share_info, dict) else None, + target_name=item.filename, + count=1, + meta={ + "expireValue": item.expire_value, + "expireStyle": item.expire_style, + }, + ) + return APIResponse(detail=share_info) + + +@admin_api.patch("/file/update") +async def update_file( + data: UpdateFileData, + file_service: FileService = Depends(get_file_service), +): + file_code = await FileCodes.filter(id=data.id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + target_name = file_service._build_file_activity_name(file_code) + 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已存在") + update_data["code"] = data.code + if data.prefix is not None and data.prefix != file_code.prefix: + update_data["prefix"] = data.prefix + if data.suffix is not None and data.suffix != file_code.suffix: + update_data["suffix"] = data.suffix + if ( + data.expired_at is not None + and data.expired_at != "" + and data.expired_at != file_code.expired_at + ): + update_data["expired_at"] = data.expired_at + if data.expired_count is not None and data.expired_count != file_code.expired_count: + update_data["expired_count"] = data.expired_count + + await file_code.update_from_dict(update_data).save() + if update_data: + await file_service.record_admin_activity( + action="file.update", + target_type="file", + target_id=data.id, + target_name=target_name, + count=1, + meta={"fields": sorted(update_data.keys())}, + ) + return APIResponse(detail="更新成功") \ No newline at end of file diff --git a/apps/base/migrations/migrations_007_recycle_bin.py b/apps/base/migrations/migrations_007_recycle_bin.py new file mode 100644 index 0000000..324a4df --- /dev/null +++ b/apps/base/migrations/migrations_007_recycle_bin.py @@ -0,0 +1,24 @@ +from tortoise import connections + + +async def migrate(): + conn = connections.get("default") + result = await conn.execute_query("PRAGMA table_info(filecodes)") + columns = {row[1] for row in (result[1] if result and len(result) > 1 else [])} + additions = [ + ("is_trashed", "BOOLEAN NOT NULL DEFAULT 0"), + ("trashed_at", "TIMESTAMP NULL"), + ("trash_expires_at", "TIMESTAMP NULL"), + ("trash_reason", "VARCHAR(32) NULL"), + ("trash_original_path", "VARCHAR(1024) NULL"), + ("trash_purged_at", "TIMESTAMP NULL"), + ] + for name, definition in additions: + if name not in columns: + await conn.execute_query(f"ALTER TABLE filecodes ADD COLUMN {name} {definition}") + await conn.execute_script( + """ + CREATE INDEX IF NOT EXISTS idx_filecodes_is_trashed ON filecodes(is_trashed); + CREATE INDEX IF NOT EXISTS idx_filecodes_trash_expires_at ON filecodes(trash_expires_at); + """ + ) diff --git a/apps/base/models.py b/apps/base/models.py new file mode 100644 index 0000000..ecdef43 --- /dev/null +++ b/apps/base/models.py @@ -0,0 +1,125 @@ +# @Time : 2023/8/13 20:43 +# @Author : Lan +# @File : models.py +# @Software: PyCharm +from typing import Optional + +from tortoise.models import Model +from tortoise.contrib.pydantic import pydantic_model_creator + +from tortoise import fields, models +from datetime import datetime +from core.utils import get_now + + +class FileCodes(models.Model): + id = fields.IntField(pk=True) + code = fields.CharField(max_length=255, unique=True, index=True) + prefix = fields.CharField(max_length=255, default="") + suffix = fields.CharField(max_length=255, default="") + uuid_file_name = fields.CharField(max_length=255, null=True) + file_path = fields.CharField(max_length=255, null=True) + size = fields.BigIntField(default=0) + text = fields.TextField(null=True) + expired_at = fields.DatetimeField(null=True) + expired_count = fields.IntField(default=0) + used_count = fields.IntField(default=0) + created_at = fields.DatetimeField(auto_now_add=True) + file_hash = fields.CharField(max_length=64, null=True) + is_chunked = fields.BooleanField(default=False) + upload_id = fields.CharField(max_length=36, null=True) + is_trashed = fields.BooleanField(default=False, index=True) + trashed_at = fields.DatetimeField(null=True, index=True) + trash_expires_at = fields.DatetimeField(null=True, index=True) + trash_reason = fields.CharField(max_length=32, null=True) + trash_original_path = fields.CharField(max_length=1024, null=True) + trash_purged_at = fields.DatetimeField(null=True, index=True) + + async def is_expired(self): + if self.expired_at is None: + return False + if self.expired_at and self.expired_count < 0: + return self.expired_at < await get_now() + return self.expired_count <= 0 + + async def get_file_path(self): + return f"{self.file_path}/{self.uuid_file_name}" + + +class UploadChunk(models.Model): + id = fields.IntField(pk=True) + upload_id = fields.CharField(max_length=36, index=True) + chunk_index = fields.IntField() + chunk_hash = fields.CharField(max_length=64) + total_chunks = fields.IntField() + file_size = fields.BigIntField() + chunk_size = fields.IntField() + file_name = fields.CharField(max_length=255) + save_path = fields.CharField(max_length=512, null=True) + created_at = fields.DatetimeField(auto_now_add=True) + completed = fields.BooleanField(default=False) + + +class TransferStats(models.Model): + id = fields.IntField(pk=True) + action = fields.CharField(max_length=16, index=True) + file_code_id = fields.IntField(null=True, index=True) + code = fields.CharField(max_length=255, null=True, index=True) + name = fields.CharField(max_length=512, default="") + size = fields.BigIntField(default=0) + ip = fields.CharField(max_length=64, default="") + file_path = fields.CharField(max_length=1024, default="") + expired_at = fields.DatetimeField(null=True) + deleted_at = fields.DatetimeField(null=True, index=True) + meta = fields.TextField(null=True) + created_at = fields.DatetimeField(auto_now_add=True, index=True) + + class Meta: + table = "transfer_stats" + + +class KeyValue(Model): + id: Optional[int] = fields.IntField(pk=True) + key: Optional[str] = fields.CharField( + max_length=255, description="键", index=True, unique=True + ) + value: Optional[str] = fields.JSONField(description="值", null=True) + created_at: Optional[datetime] = fields.DatetimeField( + auto_now_add=True, description="创建时间" + ) + + +class PresignUploadSession(models.Model): + """预签名上传会话模型""" + + id = fields.IntField(pk=True) + upload_id = fields.CharField(max_length=36, unique=True, index=True) + file_name = fields.CharField(max_length=255) + file_size = fields.BigIntField() + save_path = fields.CharField(max_length=512) + mode = fields.CharField(max_length=10) # "direct" 或 "proxy" + expire_value = fields.IntField(default=1) + expire_style = fields.CharField(max_length=20, default="day") + created_at = fields.DatetimeField(auto_now_add=True) + expires_at = fields.DatetimeField() # 会话过期时间 + + async def is_expired(self): + """检查会话是否已过期""" + return self.expires_at < await get_now() + + +class StorageReservation(models.Model): + """尚未写入 FileCodes 的上传容量预留。""" + + id = fields.IntField(pk=True) + token = fields.CharField(max_length=64, unique=True, index=True) + size = fields.BigIntField() + expires_at = fields.DatetimeField(index=True) + + +file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes") +upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk") +key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue") +presign_upload_session_pydantic = pydantic_model_creator( + PresignUploadSession, name="PresignUploadSession" +) \ No newline at end of file diff --git a/apps/base/utils.py b/apps/base/utils.py new file mode 100644 index 0000000..1aab8dc --- /dev/null +++ b/apps/base/utils.py @@ -0,0 +1,147 @@ +import datetime +import hashlib +import os +import uuid +from urllib.parse import unquote + +from fastapi import UploadFile, HTTPException +from typing import Optional, Tuple + +from apps.base.dependencies import IPRateLimit +from apps.base.models import FileCodes +from core.settings import settings +from core.utils import ( + get_random_num, + get_random_string, + max_save_times_desc, + sanitize_filename, + get_now, +) + + +def validate_expire_style(expire_style: str) -> str: + """校验过期方式是否在管理员配置的白名单内。""" + if expire_style not in settings.expireStyle: + raise HTTPException(status_code=400, detail="过期时间类型错误") + return expire_style + + +async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]: + today = await get_now() + storage_path = settings.storage_path.strip("/") + file_uuid = uuid.uuid4().hex + filename = await sanitize_filename(unquote(file.filename or "")) + base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}" + path = f"{storage_path}/{base_path}" if storage_path else base_path + prefix, suffix = os.path.splitext(filename) + save_path = f"{path}/{filename}" + return path, suffix, prefix, filename, save_path + + +async def get_chunk_file_path_name( + file_name: str, upload_id: str +) -> Tuple[str, str, str, str, str]: + today = await get_now() + storage_path = settings.storage_path.strip("/") + base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}" + path = f"{storage_path}/{base_path}" if storage_path else base_path + prefix, suffix = os.path.splitext(file_name) + save_path = f"{path}/{prefix}{suffix}" + return path, suffix, prefix, file_name, save_path + + +async def get_expire_info( + expire_value: int, expire_style: str +) -> Tuple[Optional[datetime.datetime], int, int, str]: + expired_count, used_count = -1, 0 + now = await get_now() + code = None + + max_timedelta = ( + datetime.timedelta(seconds=settings.max_save_seconds) + if settings.max_save_seconds > 0 + else datetime.timedelta(days=7) + ) + detail = ( + await max_save_times_desc(settings.max_save_seconds) + if settings.max_save_seconds > 0 + else "7天" + ) + detail = f"限制最长时间为 {detail[0]},可换用其他方式" + + expire_styles = { + "day": lambda: now + datetime.timedelta(days=expire_value), + "hour": lambda: now + datetime.timedelta(hours=expire_value), + "minute": lambda: now + datetime.timedelta(minutes=expire_value), + "count": lambda: (now + datetime.timedelta(days=1), expire_value), + "forever": lambda: (None, None), + } + + if expire_style in expire_styles: + result = expire_styles[expire_style]() + if isinstance(result, tuple): + expired_at, extra = result + if expire_style == "count": + expired_count = extra + else: + expired_at = result + if expired_at and expired_at - now > max_timedelta: + raise HTTPException(status_code=403, detail=detail) + else: + expired_at = now + datetime.timedelta(days=1) + + if not code: + code = await get_random_code() + + return expired_at, expired_count, used_count, code + + +CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" +CODE_LENGTH = 8 +CODE_MAX_ATTEMPTS = 50 + + +def get_code_generate_type() -> str: + code_generate_type = getattr(settings, "code_generate_type", "secret") + if code_generate_type in {"secret", "string"}: + return "secret" + return "number" + + +async def get_random_code(style: str | None = None) -> str: + """生成新的 8 位取件码,并避开所有仍保留的历史审计记录。""" + code_style = style or get_code_generate_type() + if code_style == "num": + code_style = "number" + if code_style == "string": + code_style = "secret" + + for _ in range(CODE_MAX_ATTEMPTS): + code = ( + await get_random_num(CODE_LENGTH) + if code_style == "number" + else await get_random_string(CODE_LENGTH) + ) + if not await FileCodes.filter(code=code).exists(): + return str(code) + raise HTTPException(status_code=503, detail="取件码生成暂时繁忙,请重试") + + +async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str: + sha = hashlib.sha256() + await file.seek(0) + while True: + chunk = await file.read(chunk_size) + if not chunk: + break + sha.update(chunk) + await file.seek(0) + return sha.hexdigest() + + +ip_limit = { + "error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute), + "metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute), + "upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute), + "login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute), +} diff --git a/apps/base/views.py b/apps/base/views.py new file mode 100644 index 0000000..864435e --- /dev/null +++ b/apps/base/views.py @@ -0,0 +1,1004 @@ +import datetime +import hashlib +import os +import uuid +from datetime import timedelta +from urllib.parse import quote, unquote + +from typing import Optional, Tuple, Union + +from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException +from pydantic import BaseModel, ValidationError +from starlette import status +from starlette.responses import Response +from tortoise.expressions import Case, F, Q, When + +from apps.admin.dependencies import share_required_login +from apps.base.models import FileCodes, UploadChunk, PresignUploadSession, TransferStats +from apps.base.quota import release_storage, reserve_storage + +from apps.base.schemas import ( + SelectFileModel, + InitChunkUploadModel, + CompleteUploadModel, + PresignUploadInitRequest, +) +from apps.base.file_validation import validate_file_type, validate_upload_file, validate_header_bytes +from apps.base.utils import ( + get_expire_info, + get_file_path_name, + ip_limit, + get_chunk_file_path_name, + validate_expire_style, +) +from core.response import APIResponse +from core.settings import settings +from core.storage import storages, FileStorageInterface +from core.utils import ( + get_file_url as get_proxy_file_url, + get_select_token, + get_now, + sanitize_filename, +) + +share_api = APIRouter(prefix="/share", tags=["分享"]) + + +# ============ 公共服务层 ============ +class FileUploadService: + """统一的文件上传服务""" + + @staticmethod + async def generate_file_path( + file_name: str, upload_id: Optional[str] = None + ) -> tuple[str, str, str, str, str]: + """统一的路径生成""" + today = datetime.datetime.now() + storage_path = settings.storage_path.strip("/") + file_uuid = upload_id or uuid.uuid4().hex + filename = await sanitize_filename(unquote(file_name)) + base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}" + path = f"{storage_path}/{base_path}" if storage_path else base_path + prefix, suffix = os.path.splitext(filename) + save_path = f"{path}/{filename}" + return path, suffix, prefix, filename, save_path + + @staticmethod + async def create_file_record( + file_name: str, + file_size: int, + file_path: str, + expire_value: int, + expire_style: str, + ip: str = "", + **extra_fields, + ) -> str: + """统一创建FileCodes记录,返回code""" + expired_at, expired_count, used_count, code = await get_expire_info( + expire_value, expire_style + ) + prefix, suffix = os.path.splitext(file_name) + + file_code = await FileCodes.create( + code=code, + prefix=prefix, + suffix=suffix, + uuid_file_name=file_name, + file_path=file_path, + size=file_size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + **extra_fields, + ) + await record_transfer_stat("upload", file_code, file_size, ip) + return code + + +async def validate_file_size(file: UploadFile, max_size: int) -> int: + size = file.size + if size is None: + await file.seek(0, 2) # type: ignore[arg-type] + size = file.file.tell() + await file.seek(0) + if size > max_size: + max_size_mb = max_size / (1024 * 1024) + raise HTTPException( + status_code=403, detail=f"大小超过限制,最大为{max_size_mb:.2f} MB" + ) + return size + + + + +async def create_file_code(code, **kwargs): + return await FileCodes.create(code=code, **kwargs) + + +async def record_transfer_stat( + action: str, + file_code: FileCodes, + size: Optional[int] = None, + ip: str = "", + deleted_at=None, + meta: str = "", +) -> None: + try: + name = ( + f"{file_code.prefix or ''}{file_code.suffix or ''}" + or file_code.uuid_file_name + or file_code.code + ) + await TransferStats.create( + action=action, + file_code_id=file_code.id, + code=file_code.code, + name=name, + size=int(size if size is not None else (file_code.size or 0)), + ip=ip or "", + file_path=file_code.file_path or "", + expired_at=file_code.expired_at, + deleted_at=deleted_at, + meta=meta or "", + ) + except Exception: + pass + + +def normalize_share_code(code: str) -> str: + return str(code or "").strip() + + + +@share_api.post("/text/", dependencies=[Depends(share_required_login)]) +async def share_text( + text: str = Form(...), + expire_value: int = Form(default=1, gt=0), + expire_style: str = Form(default="day"), + ip: str = Depends(ip_limit["upload"]), +): + validate_expire_style(expire_style) + text_size = len(text.encode("utf-8")) + max_txt_size = 222 * 1024 + if text_size > max_txt_size: + raise HTTPException(status_code=403, detail="内容过多,建议采用文件形式") + + reservation_token = f"text:{uuid.uuid4().hex}" + await reserve_storage(reservation_token, text_size, ttl_seconds=300) + try: + expired_at, expired_count, used_count, code = await get_expire_info( + expire_value, expire_style + ) + file_code = await create_file_code( + code=code, + text=text, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + size=text_size, + prefix="Text", + ) + await record_transfer_stat("upload", file_code, text_size, ip) + finally: + await release_storage(reservation_token) + + ip_limit["upload"].add_ip(ip) + return APIResponse(detail={"code": code}) + + +@share_api.post("/file/", dependencies=[Depends(share_required_login)]) +async def share_file( + expire_value: int = Form(default=1, gt=0), + expire_style: str = Form(default="day"), + file: UploadFile = File(...), + ip: str = Depends(ip_limit["upload"]), +): + file_size = await validate_file_size(file, settings.uploadSize) + await validate_upload_file(file) + validate_expire_style(expire_style) + path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file) + reservation_token = f"file:{uuid.uuid4().hex}" + await reserve_storage(reservation_token, file_size, ttl_seconds=3600) + file_storage: FileStorageInterface = storages[settings.file_storage]() + try: + expired_at, expired_count, used_count, code = await get_expire_info( + expire_value, expire_style + ) + await file_storage.save_file(file, save_path) + file_code = await create_file_code( + code=code, + prefix=prefix, + suffix=suffix, + uuid_file_name=uuid_file_name, + file_path=path, + size=file_size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + ) + await record_transfer_stat("upload", file_code, file_size, ip) + except Exception: + try: + await file_storage.delete_file( + FileCodes(file_path=path, uuid_file_name=uuid_file_name) + ) + except Exception: + pass + raise + finally: + await release_storage(reservation_token) + + ip_limit["upload"].add_ip(ip) + return APIResponse(detail={"code": code, "name": file.filename}) + + +async def get_code_file_by_code( + code: str, check: bool = True +) -> Tuple[bool, Union[FileCodes, str]]: + normalized_code = normalize_share_code(code) + if not normalized_code: + return False, "文件不存在" + file_code = await FileCodes.filter(code=normalized_code, is_trashed=False).first() + if not file_code: + return False, "文件不存在" + if await file_code.is_expired() and check: + return False, "文件已过期" + return True, file_code + + +async def consume_file_usage(file_code: FileCodes) -> bool: + """原子校验分享状态并记录一次实际领取。""" + now = await get_now() + eligible = ( + Q(expired_count__gt=0) + | Q(expired_count__lt=0, expired_at__gt=now) + | Q(expired_count__lt=0, expired_at=None) + ) + updated = await FileCodes.filter(Q(id=file_code.id) & eligible).update( + expired_count=Case( + When(expired_count__gt=0, then=F("expired_count") - 1), + default=F("expired_count"), + ), + used_count=F("used_count") + 1, + ) + if not updated: + return False + await file_code.refresh_from_db() + return True + + +def build_file_metadata(file_code: FileCodes) -> dict: + is_text = file_code.text is not None + remaining_downloads = ( + file_code.expired_count if file_code.expired_count > 0 else None + ) + return { + "code": file_code.code, + "name": file_code.prefix + file_code.suffix, + "size": file_code.size, + "type": "text" if is_text else "file", + "is_text": is_text, + "created_at": file_code.created_at, + "expired_at": file_code.expired_at, + "expires_at": file_code.expired_at, + "expired_count": file_code.expired_count, + "used_count": file_code.used_count, + "remaining_downloads": remaining_downloads, + } + + +async def build_select_detail( + file_code: FileCodes, file_storage: FileStorageInterface +) -> dict: + metadata = build_file_metadata(file_code) + if file_code.text is not None: + download_url = None + elif file_code.expired_count >= 0: + # 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。 + download_url = await get_proxy_file_url(file_code.code) + else: + download_url = await file_storage.get_file_url(file_code) + content = file_code.text if file_code.text is not None else None + return { + **metadata, + "text": content if content is not None else download_url, + "content": content, + "download_url": download_url, + } + + +@share_api.get("/metadata/") +async def get_file_metadata(code: str, ip: str = Depends(ip_limit["metadata"])): + has, file_code = await get_code_file_by_code(code) + if not has: + ip_limit["metadata"].add_ip(ip) + return APIResponse(code=404, detail=file_code) + + assert isinstance(file_code, FileCodes) + ip_limit["metadata"].add_ip(ip) + return APIResponse(detail=build_file_metadata(file_code)) + + +@share_api.post("/metadata/") +async def post_file_metadata( + data: SelectFileModel, ip: str = Depends(ip_limit["metadata"]) +): + has, file_code = await get_code_file_by_code(data.code) + if not has: + ip_limit["metadata"].add_ip(ip) + return APIResponse(code=404, detail=file_code) + + assert isinstance(file_code, FileCodes) + ip_limit["metadata"].add_ip(ip) + return APIResponse(detail=build_file_metadata(file_code)) + + +@share_api.get("/select/") +async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])): + file_storage: FileStorageInterface = storages[settings.file_storage]() + has, file_code = await get_code_file_by_code(code) + if not has: + ip_limit["error"].add_ip(ip) + return APIResponse(code=404, detail=file_code) + + assert isinstance(file_code, FileCodes) + if not await consume_file_usage(file_code): + return APIResponse(code=404, detail="文件已过期") + await record_transfer_stat("download", file_code, file_code.size, ip) + if file_code.text is not None: + filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}" + return Response( + content=file_code.text, + media_type="text/plain", + headers={ + "Content-Disposition": ( + f"attachment; filename*=UTF-8''{quote(filename, safe='')}" + ) + }, + ) + + return await file_storage.get_file_response(file_code) + + +@share_api.post("/select/") +async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"])): + file_storage: FileStorageInterface = storages[settings.file_storage]() + has, file_code = await get_code_file_by_code(data.code) + if not has: + ip_limit["error"].add_ip(ip) + return APIResponse(code=404, detail=file_code) + + assert isinstance(file_code, FileCodes) + detail = await build_select_detail(file_code, file_storage) + download_url = detail.get("download_url") + consumes_on_download = isinstance(download_url, str) and download_url.startswith( + "/share/download?" + ) + if not consumes_on_download: + if not await consume_file_usage(file_code): + return APIResponse(code=404, detail="文件已过期") + await record_transfer_stat("download", file_code, file_code.size, ip) + detail.update(build_file_metadata(file_code)) + return APIResponse(detail=detail) + + + +@share_api.get("/download") +async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])): + file_storage: FileStorageInterface = storages[settings.file_storage]() + normalized_code = normalize_share_code(code) + # 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403 + valid_keys = { + await get_select_token(normalized_code, offset=0), + await get_select_token(normalized_code, offset=1), + } + if key not in valid_keys: + ip_limit["error"].add_ip(ip) + raise HTTPException(status_code=403, detail="下载鉴权失败") + has, file_code = await get_code_file_by_code(normalized_code) + if not has: + return APIResponse(code=404, detail=file_code) + assert isinstance(file_code, FileCodes) + if not await consume_file_usage(file_code): + return APIResponse(code=404, detail="文件已过期") + await record_transfer_stat("download", file_code, file_code.size, ip) + + return ( + APIResponse(detail=file_code.text) + if file_code.text + else await file_storage.get_file_response(file_code) + ) + + +chunk_api = APIRouter(prefix="/chunk", tags=["切片"]) + + +async def parse_body_model(request: Request, model_class: type[BaseModel]): + content_type = request.headers.get("content-type", "").lower() + try: + if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type: + payload = dict(await request.form()) + else: + payload = await request.json() + return model_class.model_validate(payload) + except ValidationError as e: + raise HTTPException(status_code=422, detail=e.errors()) + except Exception: + raise HTTPException(status_code=400, detail="请求体格式错误") + + +async def parse_init_chunk_upload(request: Request) -> InitChunkUploadModel: + return await parse_body_model(request, InitChunkUploadModel) + + +async def parse_complete_upload(request: Request) -> CompleteUploadModel: + return await parse_body_model(request, CompleteUploadModel) + + +@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)]) +async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)): + validate_file_type(data.file_name) + # 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量 + total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size + max_possible_size = total_chunks * data.chunk_size + if max_possible_size > settings.uploadSize: + max_size_mb = settings.uploadSize / (1024 * 1024) + raise HTTPException( + status_code=403, detail=f"文件大小超过限制,最大为 {max_size_mb:.2f} MB" + ) + + # # 秒传检查 + # existing = await FileCodes.filter(file_hash=data.file_hash).first() + # if existing: + # if await existing.is_expired(): + # file_storage: FileStorageInterface = storages[settings.file_storage]( + # ) + # await file_storage.delete_file(existing) + # await existing.delete() + # else: + # return APIResponse(detail={ + # "code": existing.code, + # "existed": True, + # "name": f'{existing.prefix}{existing.suffix}' + # }) + + # 断点续传:检查是否存在相同文件的未完成上传会话 + existing_session = await UploadChunk.filter( + chunk_hash=data.file_hash, + chunk_index=-1, + file_size=data.file_size, + file_name=data.file_name, + ).first() + + if existing_session: + if not existing_session.save_path: + await UploadChunk.filter(upload_id=existing_session.upload_id).delete() + await release_storage(f"chunk:{existing_session.upload_id}") + else: + await reserve_storage( + f"chunk:{existing_session.upload_id}", + existing_session.file_size, + ttl_seconds=max( + 1, int(getattr(settings, "chunk_expire_hours", 24)) + ) + * 3600, + ) + uploaded_chunks = await UploadChunk.filter( + upload_id=existing_session.upload_id, completed=True + ).values_list("chunk_index", flat=True) + return APIResponse( + detail={ + "existed": False, + "upload_id": existing_session.upload_id, + "chunk_size": existing_session.chunk_size, + "total_chunks": existing_session.total_chunks, + "uploaded_chunks": list(uploaded_chunks), + } + ) + + # 创建新的上传会话 + upload_id = uuid.uuid4().hex + reservation_token = f"chunk:{upload_id}" + chunk_expire_seconds = max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600 + await reserve_storage( + reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds + ) + _, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id) + try: + await UploadChunk.create( + upload_id=upload_id, + chunk_index=-1, + total_chunks=total_chunks, + file_size=data.file_size, + chunk_size=data.chunk_size, + chunk_hash=data.file_hash, + file_name=data.file_name, + save_path=save_path, + ) + except Exception: + await release_storage(reservation_token) + raise + return APIResponse( + detail={ + "existed": False, + "upload_id": upload_id, + "chunk_size": data.chunk_size, + "total_chunks": total_chunks, + "uploaded_chunks": [], + } + ) + + +@chunk_api.post( + "/upload/chunk/{upload_id}/{chunk_index}", + dependencies=[Depends(share_required_login)], +) +async def upload_chunk( + upload_id: str, + chunk_index: int, + chunk: UploadFile = File(...), +): + # 获取上传会话信息 + chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() + if not chunk_info: + raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + await reserve_storage( + f"chunk:{upload_id}", + chunk_info.file_size, + ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600, + ) + + # 检查分片索引有效性 + if chunk_index < 0 or chunk_index >= chunk_info.total_chunks: + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="无效的分片索引") + + # 检查是否已上传(支持断点续传) + existing_chunk = await UploadChunk.filter( + upload_id=upload_id, chunk_index=chunk_index, completed=True + ).first() + if existing_chunk: + return APIResponse( + detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True} + ) + + # 读取分片数据并计算哈希 + chunk_data = await chunk.read() + if chunk_index == 0: + validate_header_bytes(chunk_info.file_name, None, chunk_data[:64]) + chunk_size = len(chunk_data) + + # 校验分片大小不超过声明的 chunk_size + if chunk_size > chunk_info.chunk_size: + raise HTTPException( + status.HTTP_400_BAD_REQUEST, + detail=f"分片大小超过声明值: 最大 {chunk_info.chunk_size}, 实际 {chunk_size}", + ) + + # 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算) + uploaded_count = await UploadChunk.filter( + upload_id=upload_id, completed=True + ).count() + # 已上传分片的最大可能大小 + 当前分片 + max_uploaded_size = uploaded_count * chunk_info.chunk_size + chunk_size + if max_uploaded_size > settings.uploadSize: + max_size_mb = settings.uploadSize / (1024 * 1024) + raise HTTPException( + status_code=403, detail=f"累计上传大小超过限制,最大为 {max_size_mb:.2f} MB" + ) + + chunk_hash = hashlib.sha256(chunk_data).hexdigest() + + save_path = chunk_info.save_path + + # 保存分片到存储 + storage = storages[settings.file_storage]() + try: + await storage.save_chunk( + upload_id, chunk_index, chunk_data, chunk_hash, save_path + ) + except Exception as e: + raise HTTPException( + status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}" + ) + + # 更新或创建分片记录(保存成功后再记录) + await UploadChunk.update_or_create( + upload_id=upload_id, + chunk_index=chunk_index, + defaults={ + "chunk_hash": chunk_hash, + "completed": True, + "file_size": chunk_info.file_size, + "total_chunks": chunk_info.total_chunks, + "chunk_size": chunk_info.chunk_size, + "file_name": chunk_info.file_name, + "save_path": chunk_info.save_path, + }, + ) + return APIResponse(detail={"chunk_hash": chunk_hash}) + + +@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)]) +async def cancel_upload(upload_id: str): + """取消上传并清理临时文件""" + chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() + if not chunk_info: + raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + + save_path = chunk_info.save_path + + # 清理存储中的临时文件 + storage = storages[settings.file_storage]() + if save_path: + try: + await storage.clean_chunks(upload_id, save_path) + except Exception as e: + pass + + # 清理数据库记录 + await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") + + return APIResponse(detail={"message": "上传已取消"}) + + +@chunk_api.get( + "/upload/status/{upload_id}", dependencies=[Depends(share_required_login)] +) +async def get_upload_status(upload_id: str): + """获取上传状态""" + chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() + if not chunk_info: + raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + + # 获取已上传的分片列表 + uploaded_chunks = await UploadChunk.filter( + upload_id=upload_id, completed=True + ).values_list("chunk_index", flat=True) + + return APIResponse( + detail={ + "upload_id": upload_id, + "file_name": chunk_info.file_name, + "file_size": chunk_info.file_size, + "chunk_size": chunk_info.chunk_size, + "total_chunks": chunk_info.total_chunks, + "uploaded_chunks": list(uploaded_chunks), + "progress": len(uploaded_chunks) / chunk_info.total_chunks * 100, + } + ) + + +@chunk_api.post( + "/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)] +) +async def complete_upload( + upload_id: str, + data: CompleteUploadModel = Depends(parse_complete_upload), + ip: str = Depends(ip_limit["upload"]), +): + # 获取上传基本信息 + chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() + if not chunk_info: + raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + validate_expire_style(data.expire_style) + await reserve_storage( + f"chunk:{upload_id}", + chunk_info.file_size, + ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600, + ) + + storage = storages[settings.file_storage]() + # 验证所有分片 + completed_chunks_list = await UploadChunk.filter( + upload_id=upload_id, completed=True + ).all() + if len(completed_chunks_list) != chunk_info.total_chunks: + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整") + + # 用分片数 * chunk_size 校验最大可能大小 + max_total_size = len(completed_chunks_list) * chunk_info.chunk_size + if max_total_size > settings.uploadSize: + save_path = chunk_info.save_path + if save_path: + try: + await storage.clean_chunks(upload_id, save_path) + except Exception: + pass + await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") + max_size_mb = settings.uploadSize / (1024 * 1024) + raise HTTPException( + status_code=403, detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB" + ) + + save_path = chunk_info.save_path + path = os.path.dirname(save_path) if save_path else "" + prefix, suffix = os.path.splitext(chunk_info.file_name) + + try: + # 合并文件并计算哈希 + _, file_hash = await storage.merge_chunks(upload_id, chunk_info, save_path) + # 创建文件记录 + expired_at, expired_count, used_count, code = await get_expire_info( + data.expire_value, data.expire_style + ) + file_code = await FileCodes.create( + code=code, + file_hash=file_hash, # 使用合并后计算的哈希 + is_chunked=True, + upload_id=upload_id, + size=chunk_info.file_size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + file_path=path, + uuid_file_name=f"{prefix}{suffix}", + prefix=prefix, + suffix=suffix, + ) + await record_transfer_stat("upload", file_code, chunk_info.file_size, ip) + # 清理临时文件 + await storage.clean_chunks(upload_id, save_path) + # 清理数据库中的分片记录 + await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") + ip_limit["upload"].add_ip(ip) + return APIResponse(detail={"code": code, "name": chunk_info.file_name}) + except ValueError as e: + raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + # 合并失败时清理临时文件 + try: + await storage.clean_chunks(upload_id, save_path) + except Exception: + pass + raise HTTPException( + status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"文件合并失败: {str(e)}" + ) + + +# ============ 预签名上传API ============ +presign_api = APIRouter(prefix="/presign", tags=["预签名上传"]) + +PRESIGN_SESSION_EXPIRES = 900 # 15分钟 + + +def build_proxy_upload_urls(upload_id: str) -> dict: + proxy_upload_url = f"/presign/upload/proxy/{upload_id}" + return { + "proxy_upload_url": proxy_upload_url, + "legacy_proxy_upload_url": f"/api{proxy_upload_url}", + } + + +async def _get_valid_session( + upload_id: str, expected_mode: Optional[str] = None +) -> PresignUploadSession: + """获取并验证会话""" + session = await PresignUploadSession.filter(upload_id=upload_id).first() + if not session: + raise HTTPException(404, "上传会话不存在") + if await session.is_expired(): + await session.delete() + await release_storage(f"presign:{upload_id}") + raise HTTPException(404, "上传会话已过期") + if expected_mode and session.mode != expected_mode: + raise HTTPException(400, f"此会话不支持{expected_mode}模式") + return session + + +@presign_api.post("/upload/init", dependencies=[Depends(share_required_login)]) +async def presign_upload_init( + data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"]) +): + """初始化预签名上传,S3返回直传URL,其他存储返回代理URL""" + validate_file_type(data.file_name) + if data.file_size > settings.uploadSize: + raise HTTPException( + 403, + f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB", + ) + validate_expire_style(data.expire_style) + + upload_id = uuid.uuid4().hex + reservation_token = f"presign:{upload_id}" + await reserve_storage( + reservation_token, data.file_size, ttl_seconds=PRESIGN_SESSION_EXPIRES + ) + try: + path, _, _, filename, save_path = await FileUploadService.generate_file_path( + data.file_name, upload_id + ) + storage: FileStorageInterface = storages[settings.file_storage]() + presigned_url = await storage.generate_presigned_upload_url( + save_path, PRESIGN_SESSION_EXPIRES + ) + mode = "direct" if presigned_url else "proxy" + proxy_urls = build_proxy_upload_urls(upload_id) + upload_url = presigned_url or proxy_urls["proxy_upload_url"] + await PresignUploadSession.create( + upload_id=upload_id, + file_name=filename, + file_size=data.file_size, + save_path=save_path, + mode=mode, + expire_value=data.expire_value, + expire_style=data.expire_style, + expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES), + ) + except Exception: + await release_storage(reservation_token) + raise + + ip_limit["upload"].add_ip(ip) + detail = { + "upload_id": upload_id, + "upload_url": upload_url, + "mode": mode, + "expires_in": PRESIGN_SESSION_EXPIRES, + } + if mode == "proxy": + detail.update(proxy_urls) + + return APIResponse( + detail=detail + ) + + +@presign_api.put( + "/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)] +) +async def presign_upload_proxy( + upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"]) +): + """代理模式上传,服务器转存到存储后端""" + session = await _get_valid_session(upload_id, expected_mode="proxy") + await reserve_storage( + f"presign:{upload_id}", + session.file_size, + ttl_seconds=PRESIGN_SESSION_EXPIRES, + ) + + file_size = await validate_file_size(file, settings.uploadSize) + await validate_upload_file(file) + if abs(file_size - session.file_size) > 1024: + raise HTTPException(400, "文件大小与声明不符") + + storage: FileStorageInterface = storages[settings.file_storage]() + try: + await storage.save_file(file, session.save_path) + except Exception as e: + raise HTTPException(500, f"文件保存失败: {str(e)}") + + try: + code = await FileUploadService.create_file_record( + session.file_name, + file_size, + os.path.dirname(session.save_path), + session.expire_value, + session.expire_style, + ip=ip, + ) + except Exception: + try: + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception: + pass + raise + + + await session.delete() + await release_storage(f"presign:{upload_id}") + ip_limit["upload"].add_ip(ip) + return APIResponse(detail={"code": code, "name": session.file_name}) + + +@presign_api.post( + "/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)] +) +async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])): + """直传确认,客户端完成S3直传后调用获取分享码""" + session = await _get_valid_session(upload_id, expected_mode="direct") + try: + await reserve_storage( + f"presign:{upload_id}", + session.file_size, + ttl_seconds=PRESIGN_SESSION_EXPIRES, + ) + except HTTPException: + storage: FileStorageInterface = storages[settings.file_storage]() + try: + if await storage.file_exists(session.save_path): + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + finally: + await session.delete() + await release_storage(f"presign:{upload_id}") + raise + + storage: FileStorageInterface = storages[settings.file_storage]() + if not await storage.file_exists(session.save_path): + raise HTTPException(404, "文件未上传或上传失败") + + try: + code = await FileUploadService.create_file_record( + session.file_name, + session.file_size, + os.path.dirname(session.save_path), + session.expire_value, + session.expire_style, + ip=ip, + ) + except Exception: + try: + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception: + pass + raise + + + await session.delete() + await release_storage(f"presign:{upload_id}") + ip_limit["upload"].add_ip(ip) + return APIResponse(detail={"code": code, "name": session.file_name}) + + +@presign_api.get( + "/upload/status/{upload_id}", dependencies=[Depends(share_required_login)] +) +async def presign_upload_status(upload_id: str): + """查询上传会话状态""" + session = await PresignUploadSession.filter(upload_id=upload_id).first() + if not session: + raise HTTPException(404, "上传会话不存在") + + return APIResponse( + detail={ + "upload_id": session.upload_id, + "file_name": session.file_name, + "file_size": session.file_size, + "mode": session.mode, + "created_at": session.created_at.isoformat(), + "expires_at": session.expires_at.isoformat(), + "is_expired": await session.is_expired(), + } + ) + + +@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)]) +async def presign_upload_cancel(upload_id: str): + """取消上传会话""" + session = await PresignUploadSession.filter(upload_id=upload_id).first() + if not session: + raise HTTPException(404, "上传会话不存在") + + if session.mode == "direct": + storage: FileStorageInterface = storages[settings.file_storage]() + try: + if await storage.file_exists(session.save_path): + temp_file_code = FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + await storage.delete_file(temp_file_code) + except Exception: + pass + + await session.delete() + await release_storage(f"presign:{upload_id}") + return APIResponse(detail={"message": "上传会话已取消"}) diff --git a/core/storage.py b/core/storage.py new file mode 100644 index 0000000..7d2a643 --- /dev/null +++ b/core/storage.py @@ -0,0 +1,1393 @@ +# @Time : 2023/8/11 20:06 +# @Author : Lan +# @File : storage.py +# @Software: PyCharm +import base64 +import hashlib +import os +import tempfile +from core.logger import logger +import shutil +from typing import Optional +from urllib.parse import quote, unquote + +import aiofiles +import aiohttp +import asyncio +from pathlib import Path +import datetime +import re +import aioboto3 +from botocore.config import Config +from fastapi import HTTPException, Response, UploadFile +from core.response import APIResponse +from core.settings import data_root, settings +from apps.base.models import FileCodes, UploadChunk +from core.utils import get_file_url, sanitize_filename +from fastapi.responses import FileResponse, StreamingResponse +from starlette.background import BackgroundTask + + +class FileStorageInterface: + + async def save_file(self, file: UploadFile, save_path: str): + """ + 保存文件 + """ + raise NotImplementedError + + async def delete_file(self, file_code: FileCodes): + """ + 删除文件 + """ + raise NotImplementedError + + async def move_file(self, file_code: FileCodes, target_path: str) -> None: + """将现有文件移动到目标路径,供回收站使用。""" + raise NotImplementedError + + async def get_file_url(self, file_code: FileCodes): + """ + 获取文件分享的url + + 如果服务不支持直接访问文件,可以通过服务器中转下载。 + 此时,此方法可以调用 utils.py 中的 `get_file_url` 方法,获取服务器中转下载的url + """ + raise NotImplementedError + + async def get_file_response(self, file_code: FileCodes): + """ + 获取文件响应 + + 如果服务不支持直接访问文件,则需要实现该方法,返回文件响应 + 其余情况,可以不实现该方法 + """ + raise NotImplementedError + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """ + 保存分片文件 + :param upload_id: 上传会话ID + :param chunk_index: 分片索引 + :param chunk_data: 分片数据 + :param chunk_hash: 分片哈希值 + :param save_path: 文件保存路径 + """ + raise NotImplementedError + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """ + 合并分片文件并返回文件路径和完整哈希值 + :param upload_id: 上传会话ID + :param chunk_info: 分片信息 + :param save_path: 文件保存路径 + :return: (文件路径, 文件哈希值) + """ + raise NotImplementedError + + async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]: + """ + 生成预签名上传URL + :param save_path: 文件保存路径 + :param expires_in: URL过期时间(秒),默认15分钟 + :return: 预签名URL,如果不支持直传则返回None + """ + return None # 默认不支持直传,使用代理模式 + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在 + :param save_path: 文件路径 + :return: 文件是否存在 + """ + raise NotImplementedError + + async def clean_chunks(self, upload_id: str, save_path: str): + """ + 清理临时分片文件 + :param upload_id: 上传会话ID + :param save_path: 文件保存路径 + """ + raise NotImplementedError + + +class SystemFileStorage(FileStorageInterface): + def __init__(self): + self.chunk_size = 256 * 1024 + self.root_path = data_root + + def _resolve_safe_path(self, relative_path: str) -> Path: + """将相对路径解析到数据根目录内,阻止路径穿越。""" + root = self.root_path.resolve() + raw = str(relative_path or "").replace("\\", "/").lstrip("/") + candidate = (root / raw).resolve() + try: + candidate.relative_to(root) + except ValueError as exc: + raise ValueError("非法文件路径") from exc + return candidate + + def _save(self, file, save_path): + with open(save_path, "wb") as f: + chunk = file.read(self.chunk_size) + while chunk: + f.write(chunk) + chunk = file.read(self.chunk_size) + + async def save_file(self, file: UploadFile, save_path: str): + path_obj = Path(str(save_path).replace("\\", "/")) + directory = str(path_obj.parent).replace("\\", "/").lstrip("/") + # 提取原始文件名并进行清理 + filename = await sanitize_filename(path_obj.name) + # 构建安全的完整保存路径 + safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename) + # 确保目录存在 + if not safe_save_path.parent.exists(): + safe_save_path.parent.mkdir(parents=True) + await asyncio.to_thread(self._save, file.file, safe_save_path) + + async def delete_file(self, file_code: FileCodes): + save_path = self._resolve_safe_path(await file_code.get_file_path()) + if save_path.exists(): + save_path.unlink() + + async def move_file(self, file_code: FileCodes, target_path: str) -> None: + source_path = self._resolve_safe_path(await file_code.get_file_path()) + destination_path = self._resolve_safe_path(target_path) + destination_path.parent.mkdir(parents=True, exist_ok=True) + if not source_path.exists(): + raise FileNotFoundError("回收站源文件不存在") + await asyncio.to_thread(source_path.replace, destination_path) + + async def get_file_url(self, file_code: FileCodes): + return await get_file_url(file_code.code) + + async def get_file_response(self, file_code: FileCodes): + file_path = self._resolve_safe_path(await file_code.get_file_path()) + if not file_path.exists(): + return APIResponse(code=404, detail="文件已过期删除") + filename = f"{file_code.prefix}{file_code.suffix}" + encoded_filename = quote(filename, safe='') + content_disposition = f"attachment; filename*=UTF-8''{encoded_filename}" + + # 尝试获取文件系统大小,如果成功则设置 Content-Length + headers = {"Content-Disposition": content_disposition} + try: + content_length = file_path.stat().st_size + headers["Content-Length"] = str(content_length) + except Exception: + # 如果获取文件大小失败,则不提供 Content-Length + pass + + return FileResponse( + file_path, + media_type="application/octet-stream", + headers=headers, + filename=filename # 保留原始文件名以备某些场景使用 + ) + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """ + 保存分片文件到本地文件系统 + :param upload_id: 上传会话ID + :param chunk_index: 分片索引 + :param chunk_data: 分片数据 + :param chunk_hash: 分片哈希值 + :param save_path: 文件保存路径 + """ + # 先校验目标文件路径合法,再将分片落到同级 chunks 目录。 + self._resolve_safe_path(save_path) + chunk_path = self._resolve_safe_path( + str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part") + ) + if not chunk_path.parent.exists(): + chunk_path.parent.mkdir(parents=True, exist_ok=True) + # 使用临时文件写入,确保原子性 + temp_path = chunk_path.with_suffix('.tmp') + try: + async with aiofiles.open(temp_path, "wb") as f: + await f.write(chunk_data) + # 原子重命名 + temp_path.rename(chunk_path) + except Exception as e: + if temp_path.exists(): + temp_path.unlink() + raise e + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """ + 合并本地文件系统的分片文件并返回文件路径和完整哈希值 + :param upload_id: 上传会话ID + :param chunk_info: 分片信息 + :param save_path: 文件保存路径 + :return: (文件路径, 文件哈希值) + """ + output_path = self._resolve_safe_path(save_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + chunk_base_dir = self._resolve_safe_path( + str(Path(save_path).parent / "chunks" / upload_id) + ) + file_sha256 = hashlib.sha256() + + # 使用临时文件写入,确保原子性 + temp_output = output_path.with_suffix('.merging') + try: + async with aiofiles.open(temp_output, "wb") as out_file: + for i in range(chunk_info.total_chunks): + # 获取分片记录 + chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first() + if not chunk_record: + raise ValueError(f"分片{i}记录不存在") + chunk_path = chunk_base_dir / f"{i}.part" + if not chunk_path.exists(): + raise ValueError(f"分片{i}文件不存在") + async with aiofiles.open(chunk_path, "rb") as in_file: + chunk_data = await in_file.read() + current_hash = hashlib.sha256(chunk_data).hexdigest() + if current_hash != chunk_record.chunk_hash: + raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") + file_sha256.update(chunk_data) + await out_file.write(chunk_data) + # 原子重命名 + temp_output.rename(output_path) + except Exception as e: + if temp_output.exists(): + temp_output.unlink() + raise e + return str(output_path), file_sha256.hexdigest() + + async def clean_chunks(self, upload_id: str, save_path: str): + """ + 清理本地文件系统的临时分片文件 + :param upload_id: 上传会话ID + :param save_path: 文件保存路径 + """ + chunk_dir = self._resolve_safe_path( + str(Path(save_path).parent / "chunks" / upload_id) + ) + if chunk_dir.exists(): + try: + shutil.rmtree(chunk_dir) + except Exception as e: + logger.info(f"清理本地分片目录失败: {e}") + # 清理父级 chunks 目录(如果为空) + chunks_parent = chunk_dir.parent + if chunks_parent.exists() and not any(chunks_parent.iterdir()): + try: + chunks_parent.rmdir() + except Exception as e: + logger.info(f"清理 chunks 父目录失败: {e}") + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在于本地文件系统 + :param save_path: 文件路径 + :return: 文件是否存在 + """ + try: + file_path = self._resolve_safe_path(save_path) + except ValueError: + return False + return file_path.exists() + + +class S3FileStorage(FileStorageInterface): + def __init__(self): + self.access_key_id = settings.s3_access_key_id + self.secret_access_key = settings.s3_secret_access_key + self.bucket_name = settings.s3_bucket_name + self.s3_hostname = settings.s3_hostname + self.region_name = settings.s3_region_name + self.signature_version = settings.s3_signature_version + self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}" + self.aws_session_token = settings.aws_session_token + self.addressing_style = str(settings.s3_addressing_style or "auto").lower() + self.proxy = settings.s3_proxy + self.session = aioboto3.Session( + aws_access_key_id=self.access_key_id, + aws_secret_access_key=self.secret_access_key, + ) + if not settings.s3_endpoint_url: + self.endpoint_url = f"https://{self.s3_hostname}" + else: + # 如果提供了 s3_endpoint_url,则优先使用它 + self.endpoint_url = settings.s3_endpoint_url + + def _client_config(self) -> Config: + config = {"signature_version": self.signature_version} + s3_config = {} + if self.addressing_style in {"path", "virtual", "auto"}: + s3_config["addressing_style"] = self.addressing_style + if s3_config: + config["s3"] = s3_config + return Config(**config) + + def _client(self): + return self.session.client( + "s3", + endpoint_url=self.endpoint_url, + aws_session_token=self.aws_session_token, + region_name=self.region_name, + config=self._client_config(), + ) + + async def save_file(self, file: UploadFile, save_path: str): + async with self._client() as s3: + # 使用 upload_fileobj 流式上传,避免将整个文件加载到内存 + await s3.upload_fileobj( + file.file, + self.bucket_name, + save_path, + ExtraArgs={"ContentType": file.content_type or "application/octet-stream"}, + ) + + async def delete_file(self, file_code: FileCodes): + async with self._client() as s3: + await s3.delete_object( + Bucket=self.bucket_name, Key=await file_code.get_file_path() + ) + + async def get_file_response(self, file_code: FileCodes): + try: + filename = file_code.prefix + file_code.suffix + content_length = None # 初始化为 None,表示未知大小 + + async with self._client() as s3: + # 尝试获取文件大小(HEAD请求) + try: + head_response = await s3.head_object( + Bucket=self.bucket_name, + Key=await file_code.get_file_path() + ) + # 从HEAD响应中获取Content-Length + if 'ContentLength' in head_response: + content_length = head_response['ContentLength'] + elif 'Content-Length' in head_response['ResponseMetadata']['HTTPHeaders']: + content_length = int(head_response['ResponseMetadata']['HTTPHeaders']['Content-Length']) + except Exception: + # 如果HEAD请求失败,则不提供 Content-Length + pass + + link = await s3.generate_presigned_url( + "get_object", + Params={ + "Bucket": self.bucket_name, + "Key": await file_code.get_file_path(), + }, + ExpiresIn=3600, + ) + + # 创建ClientSession并传递给生成器复用 + session = aiohttp.ClientSession() + + async def stream_generator(): + try: + async with session.get(link) as resp: + if resp.status != 200: + raise HTTPException( + status_code=resp.status, + detail=f"从S3获取文件失败: {resp.status}" + ) + # 设置块大小(例如64KB) + chunk_size = 65536 + while True: + chunk = await resp.content.read(chunk_size) + if not chunk: + break + yield chunk + finally: + await session.close() + + from fastapi.responses import StreamingResponse + encoded_filename = quote(filename, safe='') + headers = { + "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" + } + if content_length is not None: + headers["Content-Length"] = str(content_length) + return StreamingResponse( + stream_generator(), + media_type="application/octet-stream", + headers=headers, + # 兜底关闭会话:客户端中断时与 generator finally 双保险 + background=BackgroundTask(session.close), + ) + except HTTPException: + raise + except Exception: + raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试") + + async def get_file_url(self, file_code: FileCodes): + if file_code.prefix == "文本分享": + return file_code.text + if self.proxy: + return await get_file_url(file_code.code) + else: + async with self._client() as s3: + result = await s3.generate_presigned_url( + "get_object", + Params={ + "Bucket": self.bucket_name, + "Key": await file_code.get_file_path(), + }, + ExpiresIn=3600, + ) + return result + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """ + 保存分片到 S3(使用独立对象存储每个分片) + 注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储 + """ + chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part") + async with self._client() as s3: + # 将分片作为独立对象上传 + await s3.put_object( + Bucket=self.bucket_name, + Key=chunk_key, + Body=chunk_data, + Metadata={ + 'chunk-hash': chunk_hash, + 'chunk-index': str(chunk_index) + } + ) + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """ + 合并 S3 上的分片文件 + 使用 S3 的 multipart upload API 实现流式合并,避免内存问题 + """ + file_sha256 = hashlib.sha256() + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + + async with self._client() as s3: + # 创建 multipart upload + mpu = await s3.create_multipart_upload( + Bucket=self.bucket_name, + Key=save_path, + ContentType='application/octet-stream' + ) + mpu_id = mpu['UploadId'] + parts = [] + + try: + # 按顺序读取、验证并上传每个分片 + for i in range(chunk_info.total_chunks): + chunk_key = f"{chunk_dir}/{i}.part" + chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first() + if not chunk_record: + raise ValueError(f"分片{i}记录不存在") + + try: + response = await s3.get_object( + Bucket=self.bucket_name, + Key=chunk_key + ) + chunk_data = await response['Body'].read() + except Exception as e: + raise ValueError(f"分片{i}文件不存在: {e}") + + current_hash = hashlib.sha256(chunk_data).hexdigest() + if current_hash != chunk_record.chunk_hash: + raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") + + file_sha256.update(chunk_data) + + # 上传分片到 multipart upload + part_response = await s3.upload_part( + Bucket=self.bucket_name, + Key=save_path, + UploadId=mpu_id, + PartNumber=i + 1, # S3 part numbers start at 1 + Body=chunk_data + ) + parts.append({ + 'PartNumber': i + 1, + 'ETag': part_response['ETag'] + }) + + # 释放内存 + del chunk_data + + # 完成 multipart upload + await s3.complete_multipart_upload( + Bucket=self.bucket_name, + Key=save_path, + UploadId=mpu_id, + MultipartUpload={'Parts': parts} + ) + except Exception as e: + # 出错时取消 multipart upload + await s3.abort_multipart_upload( + Bucket=self.bucket_name, + Key=save_path, + UploadId=mpu_id + ) + raise e + + return save_path, file_sha256.hexdigest() + + async def clean_chunks(self, upload_id: str, save_path: str): + """ + 清理 S3 上的临时分片文件 + :param upload_id: 上传会话ID + :param save_path: 文件保存路径 + """ + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + async with self._client() as s3: + try: + # 列出并删除所有分片对象 + paginator = s3.get_paginator('list_objects_v2') + async for page in paginator.paginate(Bucket=self.bucket_name, Prefix=chunk_dir): + objects = page.get('Contents', []) + if objects: + delete_objects = [{'Key': obj['Key']} for obj in objects] + await s3.delete_objects( + Bucket=self.bucket_name, + Delete={'Objects': delete_objects} + ) + except Exception as e: + logger.info(f"清理 S3 分片数据时出错: {e}") + + async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]: + """ + 生成S3预签名上传URL + :param save_path: 文件保存路径 + :param expires_in: URL过期时间(秒),默认15分钟 + :return: 预签名PUT URL + """ + async with self._client() as s3: + return await s3.generate_presigned_url( + "put_object", + Params={ + "Bucket": self.bucket_name, + "Key": save_path, + }, + ExpiresIn=expires_in, + ) + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在于S3 + :param save_path: 文件路径 + :return: 文件是否存在 + """ + async with self._client() as s3: + last_error = None + for attempt in range(3): + try: + await s3.head_object(Bucket=self.bucket_name, Key=save_path) + return True + except Exception as e: + last_error = e + if attempt < 2: + await asyncio.sleep(0.2 * (attempt + 1)) + + try: + result = await s3.list_objects_v2( + Bucket=self.bucket_name, + Prefix=save_path, + MaxKeys=1, + ) + for item in result.get("Contents", []): + if item.get("Key") == save_path: + return True + except Exception as e: + last_error = e + + logger.warning(f"S3文件确认失败 key={save_path}: {last_error}") + return False + + +class OneDriveFileStorage(FileStorageInterface): + def __init__(self): + try: + import msal + from office365.graph_client import GraphClient + from office365.runtime.client_request_exception import ( + ClientRequestException, + ) + except ImportError: + raise ImportError("请先安装`msal`和`Office365-REST-Python-Client`") + self.msal = msal + self.domain = settings.onedrive_domain + self.client_id = settings.onedrive_client_id + self.username = settings.onedrive_username + self.password = settings.onedrive_password + self.proxy = settings.onedrive_proxy + self._ClientRequestException = ClientRequestException + + try: + client = GraphClient(self.acquire_token_pwd) + self.root_path = ( + client.me.drive.root.get_by_path(settings.onedrive_root_path) + .get() + .execute_query() + ) + except ClientRequestException as e: + if e.code == "itemNotFound": + client.me.drive.root.create_folder(settings.onedrive_root_path) + self.root_path = ( + client.me.drive.root.get_by_path( + settings.onedrive_root_path) + .get() + .execute_query() + ) + else: + raise e + except Exception as e: + raise Exception("OneDrive验证失败,请检查配置是否正确\n" + str(e)) + + def acquire_token_pwd(self): + authority_url = f"https://login.microsoftonline.com/{self.domain}" + app = self.msal.PublicClientApplication( + authority=authority_url, client_id=self.client_id + ) + result = app.acquire_token_by_username_password( + username=self.username, + password=self.password, + scopes=["https://graph.microsoft.com/.default"], + ) + return result + + def _get_path_str(self, path): + if isinstance(path, str): + path = path.replace("\\", "/").replace("//", "/").split("/") + elif isinstance(path, Path): + path = str(path).replace("\\", "/").replace("//", "/").split("/") + else: + raise TypeError("path must be str or Path") + path[-1] = path[-1].split(".")[0] + return "/".join(path) + + def _save(self, file, save_path): + content = file.file.read() + name = save_path(file.filename) + path = self._get_path_str(save_path) + self.root_path.get_by_path(path).upload(name, content).execute_query() + + async def save_file(self, file: UploadFile, save_path: str): + await asyncio.to_thread(self._save, file, save_path) + + def _delete(self, save_path): + path = self._get_path_str(save_path) + try: + self.root_path.get_by_path(path).delete_object().execute_query() + except self._ClientRequestException as e: + if e.code == "itemNotFound": + pass + else: + raise e + + async def delete_file(self, file_code: FileCodes): + await asyncio.to_thread(self._delete, await file_code.get_file_path()) + + def _convert_link_to_download_link(self, link): + p1 = re.search(r"https://(.+)\.sharepoint\.com", link).group(1) + p2 = re.search(r"personal/(.+)/", link).group(1) + p3 = re.search(rf"{p2}/(.+)", link).group(1) + return f"https://{p1}.sharepoint.com/personal/{p2}/_layouts/52/download.aspx?share={p3}" + + def _get_file_url(self, save_path, name): + path = self._get_path_str(save_path) + remote_file = self.root_path.get_by_path(path + "/" + name) + expiration_datetime = datetime.datetime.now( + tz=datetime.timezone.utc + ) + datetime.timedelta(hours=1) + expiration_datetime = expiration_datetime.strftime( + "%Y-%m-%dT%H:%M:%SZ") + permission = remote_file.create_link( + "view", "anonymous", expiration_datetime=expiration_datetime + ).execute_query() + return self._convert_link_to_download_link(permission.link.webUrl) + + async def get_file_response(self, file_code: FileCodes): + try: + filename = file_code.prefix + file_code.suffix + link = await asyncio.to_thread( + self._get_file_url, await file_code.get_file_path(), filename + ) + + content_length = None # 初始化为 None,表示未知大小 + + # 创建ClientSession并复用 + session = aiohttp.ClientSession() + + # 尝试发送HEAD请求获取Content-Length + try: + async with session.head(link) as resp: + if resp.status == 200 and 'Content-Length' in resp.headers: + content_length = int(resp.headers['Content-Length']) + except Exception: + # 如果HEAD请求失败,则不提供 Content-Length + pass + + async def stream_generator(): + try: + async with session.get(link) as resp: + if resp.status != 200: + raise HTTPException( + status_code=resp.status, + detail=f"从OneDrive获取文件失败: {resp.status}" + ) + chunk_size = 65536 + while True: + chunk = await resp.content.read(chunk_size) + if not chunk: + break + yield chunk + finally: + await session.close() + + encoded_filename = quote(filename, safe='') + headers = { + "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" + } + if content_length is not None: + headers["Content-Length"] = str(content_length) + return StreamingResponse( + stream_generator(), + media_type="application/octet-stream", + headers=headers, + # 兜底关闭会话:客户端中断时与 generator finally 双保险 + background=BackgroundTask(session.close), + ) + except HTTPException: + raise + except Exception: + raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试") + + async def get_file_url(self, file_code: FileCodes): + if self.proxy: + return await get_file_url(file_code.code) + else: + return await asyncio.to_thread( + self._get_file_url, + await file_code.get_file_path(), + f"{file_code.prefix}{file_code.suffix}", + ) + + def _save_chunk(self, chunk_path: str, chunk_data: bytes): + """同步保存分片到 OneDrive""" + path_parts = chunk_path.replace("\\", "/").split("/") + filename = path_parts[-1] + dir_path = "/".join(path_parts[:-1]) + + # 确保目录存在 + current_folder = self.root_path + for part in dir_path.split("/"): + if part: + try: + current_folder = current_folder.get_by_path(part).get().execute_query() + except self._ClientRequestException as e: + if e.code == "itemNotFound": + current_folder = current_folder.create_folder(part).execute_query() + else: + raise e + + # 上传分片 + current_folder.upload(filename, chunk_data).execute_query() + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """保存分片到 OneDrive""" + chunk_path = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part") + await asyncio.to_thread(self._save_chunk, chunk_path, chunk_data) + + def _read_chunk(self, chunk_path: str) -> bytes: + """同步读取分片""" + path = self._get_path_str(chunk_path) + file_obj = self.root_path.get_by_path(path).get().execute_query() + return file_obj.get_content().execute_query().value + + def _upload_merged(self, save_path: str, data: bytes): + """同步上传合并后的文件""" + path_parts = save_path.replace("\\", "/").split("/") + filename = path_parts[-1] + dir_path = "/".join(path_parts[:-1]) + + # 确保目录存在 + current_folder = self.root_path + for part in dir_path.split("/"): + if part: + try: + current_folder = current_folder.get_by_path(part).get().execute_query() + except self._ClientRequestException as e: + if e.code == "itemNotFound": + current_folder = current_folder.create_folder(part).execute_query() + else: + raise e + + current_folder.upload(filename, data).execute_query() + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """合并 OneDrive 上的分片文件,使用临时文件避免内存问题""" + file_sha256 = hashlib.sha256() + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + + # 使用临时文件存储合并数据 + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_path = temp_file.name + + try: + async with aiofiles.open(temp_path, 'wb') as out_file: + for i in range(chunk_info.total_chunks): + chunk_path = f"{chunk_dir}/{i}.part" + chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first() + if not chunk_record: + raise ValueError(f"分片{i}记录不存在") + + try: + chunk_data = await asyncio.to_thread(self._read_chunk, chunk_path) + except Exception as e: + raise ValueError(f"分片{i}文件不存在: {e}") + + current_hash = hashlib.sha256(chunk_data).hexdigest() + if current_hash != chunk_record.chunk_hash: + raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") + + file_sha256.update(chunk_data) + await out_file.write(chunk_data) + del chunk_data # 释放内存 + + # 读取临时文件并上传 + async with aiofiles.open(temp_path, 'rb') as f: + merged_content = await f.read() + await asyncio.to_thread(self._upload_merged, save_path, merged_content) + finally: + # 清理临时文件 + if os.path.exists(temp_path): + os.unlink(temp_path) + + return save_path, file_sha256.hexdigest() + + def _delete_chunk_dir(self, chunk_dir: str): + """同步删除分片目录""" + try: + path = self._get_path_str(chunk_dir) + self.root_path.get_by_path(path).delete_object().execute_query() + except self._ClientRequestException as e: + if e.code != "itemNotFound": + raise e + + async def clean_chunks(self, upload_id: str, save_path: str): + """清理 OneDrive 上的临时分片文件""" + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + try: + await asyncio.to_thread(self._delete_chunk_dir, chunk_dir) + except Exception as e: + logger.info(f"清理 OneDrive 分片时出错: {e}") + + def _file_exists(self, save_path: str) -> bool: + """同步检查文件是否存在""" + try: + path = self._get_path_str(save_path) + self.root_path.get_by_path(path).get().execute_query() + return True + except self._ClientRequestException as e: + if e.code == "itemNotFound": + return False + raise e + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在于OneDrive + :param save_path: 文件路径 + :return: 文件是否存在 + """ + return await asyncio.to_thread(self._file_exists, save_path) + + +class OpenDALFileStorage(FileStorageInterface): + def __init__(self): + try: + import opendal + except ImportError: + raise ImportError('请先安装 `opendal`, 例如: "pip install opendal"') + self.service = settings.opendal_scheme + service_settings = {} + for key, value in settings.items(): + if key.startswith("opendal_" + self.service): + setting_name = key.split("_", 2)[2] + service_settings[setting_name] = value + self.operator = opendal.AsyncOperator( + settings.opendal_scheme, **service_settings + ) + + async def save_file(self, file: UploadFile, save_path: str): + # 使用 asyncio.to_thread 避免阻塞事件循环 + content = await asyncio.to_thread(file.file.read) + await self.operator.write(save_path, content) + + async def delete_file(self, file_code: FileCodes): + await self.operator.delete(await file_code.get_file_path()) + + async def get_file_url(self, file_code: FileCodes): + return await get_file_url(file_code.code) + + async def get_file_response(self, file_code: FileCodes): + try: + filename = file_code.prefix + file_code.suffix + content_length = None # 初始化为 None,表示未知大小 + + # 尝试获取文件大小 + try: + stat_result = await self.operator.stat(await file_code.get_file_path()) + if hasattr(stat_result, 'content_length') and stat_result.content_length: + content_length = stat_result.content_length + elif hasattr(stat_result, 'size') and stat_result.size: + content_length = stat_result.size + except Exception: + # 如果获取大小失败,则不提供 Content-Length + pass + + # 尝试使用流式读取器 + try: + # OpenDAL 可能提供 reader 方法返回一个异步读取器 + reader = await self.operator.reader(await file_code.get_file_path()) + except AttributeError: + # 如果 reader 方法不存在,回退到全量读取(兼容旧版本) + content = await self.operator.read(await file_code.get_file_path()) + encoded_filename = quote(filename, safe='') + headers = { + "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" + } + if content_length is not None: + headers["Content-Length"] = str(content_length) + return Response( + content, headers=headers, media_type="application/octet-stream" + ) + + async def stream_generator(): + chunk_size = 65536 + while True: + chunk = await reader.read(chunk_size) + if not chunk: + break + yield chunk + + encoded_filename = quote(filename, safe='') + headers = { + "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" + } + if content_length is not None: + headers["Content-Length"] = str(content_length) + return StreamingResponse( + stream_generator(), + media_type="application/octet-stream", + headers=headers + ) + except Exception as e: + logger.info(e) + raise HTTPException(status_code=404, detail="文件已过期删除") + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """保存分片到 OpenDAL 存储""" + chunk_path = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part") + await self.operator.write(chunk_path, chunk_data) + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """合并 OpenDAL 存储上的分片文件,使用临时文件避免内存问题""" + file_sha256 = hashlib.sha256() + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + + # 使用临时文件存储合并数据 + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_path = temp_file.name + + try: + async with aiofiles.open(temp_path, 'wb') as out_file: + for i in range(chunk_info.total_chunks): + chunk_path = f"{chunk_dir}/{i}.part" + chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first() + if not chunk_record: + raise ValueError(f"分片{i}记录不存在") + + try: + chunk_data = await self.operator.read(chunk_path) + except Exception as e: + raise ValueError(f"分片{i}文件不存在: {e}") + + current_hash = hashlib.sha256(chunk_data).hexdigest() + if current_hash != chunk_record.chunk_hash: + raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") + + file_sha256.update(chunk_data) + await out_file.write(chunk_data) + del chunk_data # 释放内存 + + # 读取临时文件并写入存储 + async with aiofiles.open(temp_path, 'rb') as f: + merged_content = await f.read() + await self.operator.write(save_path, merged_content) + finally: + # 清理临时文件 + if os.path.exists(temp_path): + os.unlink(temp_path) + + return save_path, file_sha256.hexdigest() + + async def clean_chunks(self, upload_id: str, save_path: str): + """清理 OpenDAL 存储上的临时分片文件""" + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + try: + # OpenDAL 支持递归删除 + await self.operator.remove_all(chunk_dir) + except Exception as e: + logger.info(f"清理 OpenDAL 分片时出错: {e}") + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在于OpenDAL存储 + :param save_path: 文件路径 + :return: 文件是否存在 + """ + try: + await self.operator.stat(save_path) + return True + except Exception: + return False + + +class WebDAVFileStorage(FileStorageInterface): + _instance: Optional["WebDAVFileStorage"] = None + + def __init__(self): + if not hasattr(self, "_initialized"): + self.base_url = settings.webdav_url.rstrip("/") + "/" + self.auth = aiohttp.BasicAuth( + login=settings.webdav_username, password=settings.webdav_password + ) + self._initialized = True + + def _build_url(self, path: str) -> str: + encoded_path = quote(str(path.replace("\\", "/").lstrip("/")).lstrip("/")) + return f"{self.base_url}{encoded_path}" + + async def _mkdir_p(self, directory_path: str): + """递归创建目录(类似mkdir -p)""" + path_obj = Path(unquote(directory_path)) + current_path = "" + + async with aiohttp.ClientSession(auth=self.auth) as session: + # 逐级检查目录是否存在 + for part in path_obj.parts: + current_path = str(Path(current_path) / part) + url = self._build_url(current_path) + + # 检查目录是否存在 + async with session.head(url) as resp: + if resp.status == 404: + # 创建目录 + async with session.request("MKCOL", url) as mkcol_resp: + if mkcol_resp.status not in (200, 201, 409): + content = await mkcol_resp.text() + raise HTTPException( + status_code=mkcol_resp.status, + detail=f"目录创建失败: {content[:200]}", + ) + + async def _is_dir_empty(self, dir_path: str) -> bool: + """检查目录是否为空""" + url = self._build_url(dir_path) + + async with aiohttp.ClientSession(auth=self.auth) as session: + async with session.request("PROPFIND", url, headers={"Depth": "1"}) as resp: + if resp.status != 207: # 207 是 Multi-Status 响应 + return False + content = await resp.text() + # 如果只有一个 response(当前目录),说明目录为空 + return content.count("") <= 1 + + async def _delete_empty_dirs(self, file_path: str, session: aiohttp.ClientSession): + """递归删除空目录""" + path_obj = Path(file_path) + current_path = path_obj.parent + + while str(current_path) != ".": + if not await self._is_dir_empty(str(current_path)): + break + + url = self._build_url(str(current_path)) + async with session.delete(url) as resp: + if resp.status not in (200, 204, 404): + break + + current_path = current_path.parent + + async def save_file(self, file: UploadFile, save_path: str): + """保存文件(自动创建目录,流式上传)""" + path_obj = Path(save_path) + directory_path = str(path_obj.parent) + # 提取原始文件名并进行清理 + filename = await sanitize_filename(path_obj.name) + # 构建安全的保存路径 + safe_save_path = str(Path(directory_path) / filename) + + try: + # 先创建目录结构 + await self._mkdir_p(directory_path) + # 上传文件(流式) + url = self._build_url(safe_save_path) + + async def file_sender(): + """流式读取文件内容""" + chunk_size = 256 * 1024 # 256KB chunks + while True: + chunk = await asyncio.to_thread(file.file.read, chunk_size) + if not chunk: + break + yield chunk + + async with aiohttp.ClientSession(auth=self.auth) as session: + async with session.put( + url, + data=file_sender(), + headers={"Content-Type": file.content_type or "application/octet-stream"} + ) as resp: + if resp.status not in (200, 201, 204): + content = await resp.text() + raise HTTPException( + status_code=resp.status, + detail=f"文件上传失败: {content[:200]}", + ) + except aiohttp.ClientError as e: + raise HTTPException( + status_code=503, detail=f"WebDAV连接异常: {str(e)}") + + async def delete_file(self, file_code: FileCodes): + """删除WebDAV文件及空目录""" + file_path = await file_code.get_file_path() + url = self._build_url(file_path) + try: + async with aiohttp.ClientSession(auth=self.auth) as session: + # 删除文件 + async with session.delete(url) as resp: + if resp.status not in (200, 204, 404): + content = await resp.text() + raise HTTPException( + status_code=resp.status, + detail=f"WebDAV删除失败: {content[:200]}", + ) + + # 使用同一个 session 删除空目录 + await self._delete_empty_dirs(file_path, session) + + except aiohttp.ClientError as e: + raise HTTPException( + status_code=503, detail=f"WebDAV连接异常: {str(e)}") + + async def move_file(self, file_code: FileCodes, target_path: str) -> None: + source_path = await file_code.get_file_path() + source_url = self._build_url(source_path) + target_url = self._build_url(target_path) + await self._mkdir_p(str(Path(target_path).parent)) + try: + async with aiohttp.ClientSession(auth=self.auth) as session: + async with session.request("MOVE", source_url, headers={"Destination": target_url, "Overwrite": "F"}) as response: + if response.status not in (201, 204): + content = await response.text() + raise HTTPException( + status_code=response.status, + detail=f"WebDAV移动到回收站失败: {content[:200]}", + ) + except aiohttp.ClientError as e: + raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}") + + async def get_file_url(self, file_code: FileCodes): + return await get_file_url(file_code.code) + + async def get_file_response(self, file_code: FileCodes): + """获取文件响应(代理模式)""" + try: + filename = file_code.prefix + file_code.suffix + url = self._build_url(await file_code.get_file_path()) + content_length = None # 初始化为 None,表示未知大小 + + # 创建ClientSession并复用(包含认证头) + session = aiohttp.ClientSession(headers={ + "Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}" + }) + + # 尝试发送HEAD请求获取Content-Length + try: + async with session.head(url) as resp: + if resp.status == 200 and 'Content-Length' in resp.headers: + content_length = int(resp.headers['Content-Length']) + except Exception: + # 如果HEAD请求失败,则不提供 Content-Length + pass + + async def stream_generator(): + try: + async with session.get(url) as resp: + if resp.status != 200: + raise HTTPException( + status_code=resp.status, + detail=f"文件获取失败{resp.status}: {await resp.text()}", + ) + chunk_size = 65536 + while True: + chunk = await resp.content.read(chunk_size) + if not chunk: + break + yield chunk + finally: + await session.close() + + encoded_filename = quote(filename, safe='') + headers = { + "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" + } + if content_length is not None: + headers["Content-Length"] = str(content_length) + return StreamingResponse( + stream_generator(), + media_type="application/octet-stream", + headers=headers, + # 兜底关闭会话:客户端中断时与 generator finally 双保险 + background=BackgroundTask(session.close), + ) + except aiohttp.ClientError as e: + raise HTTPException( + status_code=503, detail=f"WebDAV连接异常: {str(e)}") + + async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): + """保存分片到 WebDAV""" + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + chunk_path = f"{chunk_dir}/{chunk_index}.part" + + # 先创建目录结构 + await self._mkdir_p(chunk_dir) + + chunk_url = self._build_url(chunk_path) + async with aiohttp.ClientSession(auth=self.auth) as session: + async with session.put(chunk_url, data=chunk_data) as resp: + if resp.status not in (200, 201, 204): + content = await resp.text() + raise HTTPException( + status_code=resp.status, + detail=f"分片上传失败: {content[:200]}" + ) + + async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]: + """ + 合并 WebDAV 上的分片文件 + 使用临时文件避免内存问题 + """ + file_sha256 = hashlib.sha256() + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + + # 使用临时文件存储合并数据,避免内存问题 + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_path = temp_file.name + + try: + async with aiohttp.ClientSession(auth=self.auth) as session: + # 按顺序读取并验证每个分片,写入临时文件 + async with aiofiles.open(temp_path, 'wb') as out_file: + for i in range(chunk_info.total_chunks): + chunk_path = f"{chunk_dir}/{i}.part" + chunk_url = self._build_url(chunk_path) + + # 获取分片记录 + chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first() + if not chunk_record: + raise ValueError(f"分片{i}记录不存在") + + # 下载分片数据 + async with session.get(chunk_url) as resp: + if resp.status != 200: + raise ValueError(f"分片{i}文件不存在或无法访问") + chunk_data = await resp.read() + + # 验证哈希 + current_hash = hashlib.sha256(chunk_data).hexdigest() + if current_hash != chunk_record.chunk_hash: + raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") + + file_sha256.update(chunk_data) + await out_file.write(chunk_data) + del chunk_data # 释放内存 + + # 确保目标目录存在 + output_dir = str(Path(save_path).parent) + await self._mkdir_p(output_dir) + + # 流式上传合并后的文件 + output_url = self._build_url(save_path) + + async def file_sender(): + async with aiofiles.open(temp_path, 'rb') as f: + while True: + chunk = await f.read(256 * 1024) + if not chunk: + break + yield chunk + + async with session.put(output_url, data=file_sender()) as resp: + if resp.status not in (200, 201, 204): + content = await resp.text() + raise HTTPException( + status_code=resp.status, + detail=f"合并文件上传失败: {content[:200]}" + ) + finally: + # 清理临时文件 + if os.path.exists(temp_path): + os.unlink(temp_path) + + return save_path, file_sha256.hexdigest() + + async def clean_chunks(self, upload_id: str, save_path: str): + """ + 清理 WebDAV 上的临时分片文件 + :param upload_id: 上传会话ID + :param save_path: 文件保存路径 + """ + chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + chunk_dir_url = self._build_url(chunk_dir) + async with aiohttp.ClientSession(auth=self.auth) as session: + try: + # 检查分片目录是否存在 + async with session.request("PROPFIND", chunk_dir_url, headers={"Depth": "1"}) as resp: + if resp.status == 207: # 207 表示 Multi-Status + # 获取目录下的所有分片文件 + xml_data = await resp.text() + file_paths = re.findall( + r'(.*?)', xml_data) + for file_path in file_paths: + if file_path.endswith(".part"): + # 删除分片文件 + file_url = self._build_url(file_path) + async with session.delete(file_url) as delete_resp: + if delete_resp.status not in (200, 204, 404): + logger.info(f"删除分片文件失败: {file_path}") + + # 删除分片目录 + async with session.delete(chunk_dir_url) as delete_resp: + if delete_resp.status not in (200, 204, 404): + logger.info(f"删除分片目录失败: {chunk_dir_url}") + else: + logger.info(f"分片目录不存在: {chunk_dir_url}") + except Exception as e: + logger.info(f"清理 WebDAV 分片时出错: {e}") + + async def file_exists(self, save_path: str) -> bool: + """ + 检查文件是否存在于WebDAV + :param save_path: 文件路径 + :return: 文件是否存在 + """ + url = self._build_url(save_path) + async with aiohttp.ClientSession(auth=self.auth) as session: + async with session.head(url) as resp: + return resp.status == 200 + + +storages = { + "local": SystemFileStorage, + "s3": S3FileStorage, + "onedrive": OneDriveFileStorage, + "opendal": OpenDALFileStorage, + "webdav": WebDAVFileStorage, +} diff --git a/core/tasks.py b/core/tasks.py new file mode 100644 index 0000000..08f1fb3 --- /dev/null +++ b/core/tasks.py @@ -0,0 +1,138 @@ +# @Time : 2023/8/15 22:00 +# @Author : Lan +# @File : tasks.py +# @Software: PyCharm +import asyncio +import datetime +import logging +import os + +from tortoise.expressions import Q + +from apps.base.models import ( + FileCodes, + PresignUploadSession, + StorageReservation, + UploadChunk, +) +from apps.admin.services import FileService +from apps.base.utils import ip_limit, get_chunk_file_path_name +from core.config import refresh_settings +from core.settings import settings, data_root +from core.storage import FileStorageInterface, storages +from core.utils import get_now + + +async def delete_expire_files(): + while True: + try: + await refresh_settings() + file_storage: FileStorageInterface = storages[settings.file_storage]() + # 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除 + if settings.file_storage == "local": + for root, dirs, files in os.walk(f"{data_root}/share/data"): + if not dirs and not files: + os.rmdir(root) + await ip_limit["error"].remove_expired_ip() + await ip_limit["metadata"].remove_expired_ip() + await ip_limit["upload"].remove_expired_ip() + await StorageReservation.filter(expires_at__lte=await get_now()).delete() + file_service = FileService() + expire_data = await FileCodes.filter( + is_trashed=False, + ).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all() + for exp in expire_data: + try: + await file_service.move_to_trash(exp, reason="expired") + except Exception as e: + logging.error(f"移入过期文件回收站失败 code={exp.code}: {e}") + expired_trash = await FileCodes.filter( + is_trashed=True, + trash_expires_at__isnull=False, + trash_expires_at__lte=await get_now(), + ).all() + for item in expired_trash: + try: + await file_service.purge_trashed_file(item) + except Exception as e: + logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}") + except Exception as e: + logging.error(e) + finally: + await asyncio.sleep(600) + + +async def clean_incomplete_uploads(): + while True: + try: + await refresh_settings() + file_storage: FileStorageInterface = storages[settings.file_storage]() + expire_hours = getattr(settings, "chunk_expire_hours", 24) + now = await get_now() + expire_time = now - datetime.timedelta(hours=expire_hours) + expired_sessions = await UploadChunk.filter( + chunk_index=-1, created_at__lt=expire_time + ).all() + + for session in expired_sessions: + try: + save_path = session.save_path + if not save_path: + _, _, _, _, save_path = await get_chunk_file_path_name( + session.file_name, session.upload_id + ) + await file_storage.clean_chunks(session.upload_id, save_path) + except Exception as e: + logging.error( + f"清理分片文件失败 upload_id={session.upload_id}: {e}" + ) + + try: + await UploadChunk.filter(upload_id=session.upload_id).delete() + await StorageReservation.filter( + token=f"chunk:{session.upload_id}" + ).delete() + logging.info(f"已清理过期上传会话 upload_id={session.upload_id}") + except Exception as e: + logging.error( + f"删除分片记录失败 upload_id={session.upload_id}: {e}" + ) + + except Exception as e: + logging.error(f"清理未完成上传任务异常: {e}") + finally: + await asyncio.sleep(3600) + + +async def clean_expired_presign_sessions(): + while True: + try: + await refresh_settings() + storage: FileStorageInterface = storages[settings.file_storage]() + now = await get_now() + expired_sessions = await PresignUploadSession.filter( + expires_at__lt=now + ).all() + for session in expired_sessions: + if session.mode == "direct": + try: + if await storage.file_exists(session.save_path): + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception as e: + logging.error( + "清理过期直传文件失败 " + f"upload_id={session.upload_id}: {e}" + ) + await StorageReservation.filter( + token=f"presign:{session.upload_id}" + ).delete() + await session.delete() + except Exception as e: + logging.error(f"清理过期预签名会话异常: {e}") + finally: + await asyncio.sleep(900) diff --git a/core/utils.py b/core/utils.py new file mode 100644 index 0000000..8d5c916 --- /dev/null +++ b/core/utils.py @@ -0,0 +1,164 @@ +# @Time : 2023/8/13 19:54 +# @Author : Lan +# @File : utils.py +# @Software: PyCharm +import datetime +import hashlib +import hmac +import os +import re +import secrets +import time + +from core.settings import settings + + +async def get_random_num(length: int = 8): + """返回指定长度的纯数字取件码。""" + normalized_length = max(1, int(length or 8)) + lower = 10 ** (normalized_length - 1) + return str(secrets.randbelow(9 * lower) + lower) + + +# 排除 0/O、1/I/L,避免人工输入取件码时混淆。 +r_s = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" + + +async def get_random_string(length: int = 8): + """返回指定长度、无易混淆字符的取件码。""" + normalized_length = max(1, int(length or 8)) + return "".join(secrets.choice(r_s) for _ in range(normalized_length)) + + +async def get_now(): + """ + 获取当前时间 + :return: + """ + return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))) + + +async def get_select_token(code: str, offset: int = 0): + """ + 获取下载token + :param code: 取件码 + :param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。 + 用于兼容窗口边界竞态:用户在某窗口末尾获取的 token, + 请求到达服务器时可能已进入下一窗口。 + :return: + """ + token = getattr(settings, "jwt_secret", "") + if not token: + raise RuntimeError("应用签名密钥未初始化") + # 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态 + time_factor = int(time.time() / 1000) - max(0, int(offset)) + return hashlib.sha256( + f"{code}{time_factor}000{token}".encode() + ).hexdigest() + + +async def get_file_url(code: str): + """ + 对于需要通过服务器中转下载的服务,获取文件下载地址 + :param code: + :return: + """ + return f"/share/download?key={await get_select_token(code)}&code={code}" + + +async def max_save_times_desc(max_save_seconds: int): + """ + 获取最大保存时间的描述 + :param max_save_seconds: + :return: + """ + + def gen_desc_zh(value: int, desc: str): + if value > 0: + return f"{value}{desc}" + else: + return "" + + def gen_desc_en(value: int, desc: str): + if value > 0: + ret = f"{value} {desc}" + if value > 1: + ret += "s" + ret += " " + return ret + else: + return "" + + max_timedelta = datetime.timedelta(seconds=max_save_seconds) + desc_zh, desc_en = "最长保存时间:", "Max save time: " + desc_zh += gen_desc_zh(max_timedelta.days, "天") + desc_en += gen_desc_en(max_timedelta.days, "day") + desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时") + desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour") + desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟") + desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute") + desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒") + desc_en += gen_desc_en(max_timedelta.seconds % 60, "second") + return desc_zh, desc_en + + +def hash_password(password: str) -> str: + """ + 使用 SHA256 + salt 哈希密码 + 返回格式: sha256$$ + """ + salt = os.urandom(16).hex() + password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest() + return f"sha256${salt}${password_hash}" + + +def verify_password(password: str, hashed: str) -> bool: + """ + 验证密码是否匹配 + 支持新格式 (sha256$salt$hash) 和旧格式 (明文) + """ + if not hashed: + return False + + # 新格式: sha256$salt$hash + if hashed.startswith("sha256$"): + parts = hashed.split("$") + if len(parts) != 3: + return False + _, salt, stored_hash = parts + password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest() + return hmac.compare_digest(password_hash, stored_hash) + + # 旧格式: 明文比较 (兼容迁移前的数据) + return hmac.compare_digest(str(password), str(hashed)) + + +def is_password_hashed(password: str) -> bool: + """ + 检查密码是否已经是哈希格式 + """ + return password.startswith("sha256$") and len(password.split("$")) == 3 + + +async def sanitize_filename(filename: str) -> str: + """ + 安全处理文件名: + 1. 剥离路径只保留文件名 + 2. 替换非法字符 + 3. 处理空文件名情况 + """ + filename = os.path.basename(filename) + illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符 + # 替换非法字符为下划线 + cleaned = re.sub(illegal_chars, "_", filename) + # 处理空格(可选替换为_) + cleaned = cleaned.replace(" ", "_") + # 处理连续下划线 + cleaned = re.sub(r"_+", "_", cleaned) + # 处理首尾特殊字符 + cleaned = cleaned.strip("._") + # 处理空文件名情况 + if not cleaned: + cleaned = "unnamed_file" + # 长度限制(按需调整) + return cleaned[:255] diff --git a/scripts/patch_admin_timeline_ui.py b/scripts/patch_admin_timeline_ui.py new file mode 100644 index 0000000..1e6d6f2 --- /dev/null +++ b/scripts/patch_admin_timeline_ui.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +from pathlib import Path +import gzip +import re + +ASSETS_ROOT = Path('/app') + + +def rewrite(path: Path, text: str) -> None: + path.write_text(text, encoding='utf-8') + gz_path = path.with_suffix(path.suffix + '.gz') + if gz_path.exists(): + with gzip.open(gz_path, 'wb', compresslevel=9) as gz: + gz.write(text.encode('utf-8')) + + +def patch_file_manage(path: Path) -> bool: + text = path.read_text(encoding='utf-8') + old = text + if 'detailTimeline:It(s.timeline||[])' in text and 'fcbxTimelineCollapsed' not in text: + text = text.replace( + 'detailTimeline:It(s.timeline||[])}},nt=t=>', + 'detailTimeline:It(s.timeline||[]),fcbxTimelineCollapsed:!0}},nt=t=>', + 1, + ) + render_old = 'N(e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}' + render_new = 'N((e(b).fcbxTimelineCollapsed&&e(b).detailTimeline.filter(ga=>ga.key==="retrieved_event").length>3)?e(b).detailTimeline.filter((ga,Qa)=>ga.key!=="retrieved_event"||e(b).detailTimeline.filter(Ja=>Ja.key==="retrieved_event").indexOf(ga)<3):e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}' + if render_old in text and 'ga.key==="retrieved_event"' not in text: + text = text.replace(render_old, render_new, 1) + close_old = ']))),128))],2)])):j("",!0),l("section",kn,' + close_new = ']))),128)),e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length>3?(p(),f("button",{key:0,type:"button",class:o(["mt-3 rounded-lg border px-3 py-2 text-sm font-medium transition",[e(u)?"border-gray-600 text-gray-200 hover:bg-gray-700":"border-gray-200 text-gray-700 hover:bg-gray-50"]]),onClick:m[99]||(m[99]=n=>e(b).fcbxTimelineCollapsed=!e(b).fcbxTimelineCollapsed)},r(e(b).fcbxTimelineCollapsed?`展开全部取件记录(共 ${e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length} 次)":"收起取件记录"),3)):j("",!0)],2)])):j("",!0),l("section",kn,' + if close_old in text and '展开全部取件记录' not in text: + text = text.replace(close_old, close_new, 1) + if text != old: + rewrite(path, text) + return True + return False + + +def patch_clipboard(path: Path) -> bool: + text = path.read_text(encoding='utf-8') + old = text + pattern = re.compile( + r'const (?P[A-Za-z_$][\w$]*)=async\(a,e=\{\}\)=>\{.*?\},' + r'(?=[A-Za-z_$][\w$]*=async\(a,e=\{\}\)=>\{)', + re.S, + ) + match = pattern.search(text) + if not match: + return False + name = match.group('name') + replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}}''' + text = text[:match.start()] + replacement + text[match.end():] + if text != old: + rewrite(path, text) + return True + return False + + +def build_lifecycle_script() -> str: + return r'''(() => { + const LIFE_RE = /(生命周期|Lifecycle)/i; + const RETRIEVAL_RE = /^(第\s*\d+\s*次取件|retrieval\s*#?\d+)/i; + const STATE = new WeakMap(); + const getSection = section => { + const title = section.querySelector('h1,h2,h3,h4,h5'); + if (!title || !LIFE_RE.test(title.textContent || '')) return null; + const box = title.nextElementSibling; + if (!box) return null; + return { title, box }; + }; + const getRows = section => { + const ctx = getSection(section); + if (!ctx) return []; + return [...ctx.box.querySelectorAll(':scope > .fcb-expand-content')]; + }; + const apply = section => { + const ctx = getSection(section); + if (!ctx) return; + const rows = getRows(section); + const events = rows.filter(row => RETRIEVAL_RE.test((row.querySelector('p')?.textContent || '').trim())); + if (events.length <= 3) return; + const expanded = STATE.get(section) === true; + events.forEach((row, idx) => { + row.classList.add('fcbx-retrieval-event'); + row.style.display = expanded || idx < 3 ? '' : 'none'; + }); + let button = section.querySelector(':scope > .fcbx-retrieval-toggle'); + if (!button) { + button = document.createElement('button'); + button.type = 'button'; + button.className = 'fcbx-retrieval-toggle'; + button.style.cssText = 'display:inline-flex;align-items:center;margin:0 0 12px 44px;padding:8px 12px;border:1px solid rgba(148,163,184,.55);border-radius:10px;background:transparent;cursor:pointer;touch-action:manipulation;'; + button.onclick = event => { + event.preventDefault(); + event.stopPropagation(); + STATE.set(section, STATE.get(section) !== true); + apply(section); + }; + ctx.box.parentNode.insertBefore(button, ctx.box); + } + button.textContent = expanded ? '收起取件记录' : `展开全部取件记录(共 ${events.length} 次)`; + button.setAttribute('aria-expanded', expanded ? 'true' : 'false'); + }; + const markRows = root => { + const scope = root?.querySelectorAll ? root : document; + scope.querySelectorAll('section').forEach(section => { + const ctx = getSection(section); + if (!ctx) return; + ctx.box.style.overflow = 'visible'; + if (ctx.box.parentElement) ctx.box.parentElement.style.overflow = 'visible'; + getRows(section).forEach(row => { + row.style.overflow = 'visible'; + row.style.position = 'relative'; + row.style.zIndex = '0'; + const card = row.lastElementChild; + if (card) { + card.style.overflow = 'visible'; + card.style.position = 'relative'; + } + row.onmouseenter = () => { row.style.zIndex = '2'; }; + row.onmouseleave = () => { row.style.zIndex = '0'; }; + }); + apply(section); + }); + }; + let raf = 0; + const schedule = root => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => markRows(root)); }; + window.addEventListener('hashchange', () => schedule(document)); + document.addEventListener('DOMContentLoaded', () => schedule(document)); + new MutationObserver(() => schedule(document)).observe(document.body || document.documentElement, { childList: true, subtree: true }); + schedule(document); +})();''' + + +def write_detail_collapse_script(theme_dir: Path) -> bool: + assets = theme_dir / 'assets' + index = theme_dir / 'index.html' + if not assets.exists() or not index.exists(): + return False + js_path = assets / 'fcb-lifecycle-collapse-v3.js' + js = build_lifecycle_script() + rewrite(js_path, js) + html = index.read_text(encoding='utf-8') + # Remove old detail-collapse injection so browsers cannot keep loading the stale “取件记录” script. + html = html.replace('\n', '') + html = html.replace('', '') + html = html.replace('\n', '') + html = html.replace('', '') + tag = '' + if 'fcb-lifecycle-collapse-v3.js' not in html: + html = html.replace('', tag + '\n') if '' in html else html + '\n' + tag + '\n' + index.write_text(html, encoding='utf-8') + gz = index.with_suffix(index.suffix + '.gz') + if gz.exists(): + with gzip.open(gz, 'wb', compresslevel=9) as fh: + fh.write(html.encode('utf-8')) + return True + + +def main() -> None: + changed = [] + for theme in (ASSETS_ROOT / 'themes/2024', ASSETS_ROOT / 'themes/2026'): + assets = theme / 'assets' + if assets.exists(): + for path in assets.glob('clipboard-*.js'): + if patch_clipboard(path): + changed.append(str(path.relative_to(ASSETS_ROOT))) + if write_detail_collapse_script(theme): + changed.append(str((assets / 'fcb-lifecycle-collapse-v3.js').relative_to(ASSETS_ROOT))) + if not changed: + raise SystemExit('admin timeline/clipboard patch markers not found or already patched') + print('patched admin assets:', ', '.join(changed)) + + +if __name__ == '__main__': + main() diff --git a/tests/retrieval-code.test 2.mjs b/tests/retrieval-code.test 2.mjs new file mode 100644 index 0000000..02fd42b --- /dev/null +++ b/tests/retrieval-code.test 2.mjs @@ -0,0 +1,24 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import ts from 'typescript' +const root = new URL('../', import.meta.url) +test('entry must not truncate new codes or submit before typing is complete', () => { + const form = readFileSync(new URL('src/components/common/RetrieveForm.vue', root), 'utf8') + const view = readFileSync(new URL('src/views/RetrievewFileView.vue', root), 'utf8') + assert.ok(!form.includes('maxlength="5"'), '8-character code is truncated') + assert.ok(!view.includes('watch(code,'), 'typing a legacy prefix must not consume a retrieval') +}) +test('legacy/new codes and URL extraction preserve literal code', async () => { + const source = readFileSync(new URL('src/utils/retrieval-code.ts', root), 'utf8') + const js = ts.transpile(source, {module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}) + const {parseRetrievalCode, isValidRetrievalCode} = await import('data:text/javascript;base64,'+Buffer.from(js).toString('base64')) + for (const code of ['01234','aB12C','00123456','Ab12Cd34']) { + assert.equal(parseRetrievalCode(' '+code+' '),code) + assert.equal(parseRetrievalCode('https://files.example/#/?code='+code),code) + assert.equal(parseRetrievalCode('https://files.example/?code='+code),code) + assert.equal(isValidRetrievalCode(code),true) + } + for (const code of ['1234','123456','1234567','123456789','12 34','../../foo']) assert.equal(isValidRetrievalCode(code),false) + assert.equal(parseRetrievalCode('https://files.example/?code=bad#/?code=01234'),'') +}) diff --git a/tests/scrollLock.test 2.mjs b/tests/scrollLock.test 2.mjs new file mode 100644 index 0000000..c141088 --- /dev/null +++ b/tests/scrollLock.test 2.mjs @@ -0,0 +1,27 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +const body = { style: { overflow: 'scroll' } } +globalThis.document = { body } +const { lockBodyScroll, unlockBodyScroll } = await import('../src/components/common/scrollLock.ts') + +test('restores overflow only after the owning lock is released', () => { + const first = lockBodyScroll() + const second = lockBodyScroll() + unlockBodyScroll(Symbol('unrelated')) + assert.equal(body.style.overflow, 'hidden') + unlockBodyScroll(first) + assert.equal(body.style.overflow, 'hidden') + unlockBodyScroll(second) + assert.equal(body.style.overflow, 'scroll') +}) + +test('releasing an owner twice cannot unlock another owner', () => { + const first = lockBodyScroll() + const second = lockBodyScroll() + unlockBodyScroll(first) + unlockBodyScroll(first) + assert.equal(body.style.overflow, 'hidden') + unlockBodyScroll(second) + assert.equal(body.style.overflow, 'scroll') +}) \ No newline at end of file diff --git a/tests/test_admin_activity_log.py b/tests/test_admin_activity_log.py new file mode 100644 index 0000000..e1b9910 --- /dev/null +++ b/tests/test_admin_activity_log.py @@ -0,0 +1,43 @@ +import asyncio +import unittest + +from tortoise import Tortoise + +from apps.admin.services import FileService + + +class AdminActivityPaginationTests(unittest.TestCase): + def test_activity_log_filters_and_paginates(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: + service = FileService() + await service.record_admin_activity("file.update", "file", 1, "a.txt") + await service.record_admin_activity("trash.purge", "file", 2, "b.txt") + await service.record_admin_activity("config.update", "config", None, "system") + + first = await service.list_admin_activities(page=1, size=2) + self.assertEqual(first["page"], 1) + self.assertEqual(first["size"], 2) + self.assertEqual(first["total"], 3) + self.assertEqual(len(first["items"]), 2) + + filtered = await service.list_admin_activities(page=1, size=20, action="trash.purge") + self.assertEqual(filtered["total"], 1) + self.assertEqual(filtered["items"][0]["targetName"], "b.txt") + finally: + await Tortoise.close_connections() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_patch_admin_timeline_ui.py b/tests/test_patch_admin_timeline_ui.py new file mode 100644 index 0000000..d3baa41 --- /dev/null +++ b/tests/test_patch_admin_timeline_ui.py @@ -0,0 +1,16 @@ +import unittest + +from scripts.patch_admin_timeline_ui import build_lifecycle_script + + +class AdminTimelinePatchTests(unittest.TestCase): + def test_lifecycle_script_collapses_retrieval_events_and_preserves_hover_borders(self): + script = build_lifecycle_script() + + self.assertIn("fcbx-retrieval-event", script) + self.assertIn("展开全部取件记录", script) + self.assertIn("row.style.overflow = 'visible'", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_recycle_bin.py b/tests/test_recycle_bin.py new file mode 100644 index 0000000..0e53f5e --- /dev/null +++ b/tests/test_recycle_bin.py @@ -0,0 +1,74 @@ +import asyncio +import datetime +import unittest +from unittest.mock import AsyncMock, patch + +from tortoise import Tortoise + +from apps.base.models import FileCodes +from apps.base.utils import CODE_LENGTH, get_random_code +from apps.admin.services import FileService +from core.settings import settings + + +class FakeStorage: + moved = [] + deleted = [] + + async def move_file(self, file_code, target_path): + self.moved.append((file_code.id, target_path)) + + async def delete_file(self, file_code): + self.deleted.append((file_code.file_path, file_code.uuid_file_name)) + + +class RecycleBinTests(unittest.TestCase): + def test_trash_restore_and_expiry_policy(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", prefix="demo", suffix=".txt", file_path="share/data/demo", uuid_file_name="demo.txt", expired_count=-1) + service = FileService() + service._file_storage = FakeStorage() + trashed = await service.move_to_trash(item, reason="manual", retention_days=7) + self.assertTrue(trashed.is_trashed) + self.assertEqual(trashed.trash_reason, "manual") + self.assertIsNotNone(trashed.trash_expires_at) + self.assertTrue(FakeStorage.moved) + + await service.purge_trashed_file(trashed) + audit_record = await FileCodes.get(id=item.id) + self.assertTrue(audit_record.is_trashed) + self.assertIsNotNone(audit_record.trash_purged_at) + self.assertTrue(FakeStorage.deleted) + + 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"])): + self.assertEqual(await get_random_code(), "FRESH002") + + generated_code = await get_random_code() + self.assertEqual(len(generated_code), CODE_LENGTH) + self.assertRegex(generated_code, rf"^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{{{CODE_LENGTH}}}$") + + numeric_code = await get_random_code(style="number") + self.assertEqual(len(numeric_code), 8) + self.assertRegex(numeric_code, r"^[1-9][0-9]{7}$") + finally: + await Tortoise.close_connections() + + +if __name__ == "__main__": + unittest.main()