mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 13:29:56 +08:00
* fix: constant-time comparison for download tokens (security item 5) Replace the set-membership key check in /share/download with hmac.compare_digest over the two valid window tokens; add negative-path tests (wrong key 403, both windows accepted, foreign-code token 403). * fix: single source for attachment headers + guard tests (security item 2) All six Content-Disposition construction sites across the five storage backends now go through build_attachment_headers; the header is what neutralizes stored XSS on the same-origin download path. Guard tests assert every get_file_response uses the builder and no hand-built disposition reappears. * fix: reject internal-network endpoints for storage config (security item 7) s3_endpoint_url/s3_hostname/webdav_url are fetched server-side; with APP_ENV=production the write entry now enforces http(s) schemes and a loopback/private/link-local/metadata host blacklist. Development env stays open for local minio/webdav. Already-stored values are never re-validated, so existing deployments are unaffected. * fix: JSON 404 for handler-raised 404s; negative-path test batch Starlette status-code handlers take precedence over the HTTPException class handler, so registering the theme index as the 404 handler turned every HTTPException(404) app-wide into a 200 HTML page (found by the new negative-path tests). The new not_found_handler serves the theme page only to browsers (Accept: text/html) and JSON 404 to API clients. Negative-path batch: download count exhaustion, missing chunk session 404s, expired presign session deletion, admin update_file uniqueness/ existence. * fix: run container as non-root app user with compat volume chown (security item 3) Entrypoint starts as root only to fix the data-dir ownership (skipped when nothing needs changing or when the deployer sets an explicit user), then drops to uid 10001 via gosu. Verified in-container: uvicorn runs as app (uid 10001), setup and share round-trip work against a root-owned volume. * fix: compare download tokens as bytes (non-ASCII key caused 500) * test: lock changed-only semantics for endpoint config saves Integration regression for the background lesson: a stored internal endpoint must not block unrelated settings saves in production mode; changing to an internal endpoint (URL or bare-hostname form) is 400. * fix: resolve-based SSRF check — deny IP shorthands, hex/decimal IPs, DNS maps Probe found the static blacklist bypassed by glibc shorthands (127.1, 10.1), decimal (2130706433) and hex IP forms, *.localhost, and loopback-mapping DNS services. Both validators now resolve the host and re-check every resolved address; hostname tier extracts the host part correctly for [v6]/host:port/bare-v6 forms. 44 tests. * test: pin 404 handler dual-branch behavior (browser theme page vs API JSON) * fix: write back normalized endpoint values; hostname dev-gate test * test: header-injection negative paths for attachment disposition * fix: S3 merge buffers parts to >=5MiB; missing object 404 upfront - S3 multipart rejects parts <5MiB (EntityTooSmall) except the last; chunk size is client-controlled (commonly 2-4MB) so multi-chunk merges always failed with 500. Merge now buffers chunks into >=5MiB parts (memory bound: 5MB + one chunk). - get_file_response: a 404 head_object now raises StorageError(404) upfront instead of signing a doomed presigned URL and failing mid-stream (aligns with local backend semantics from the M2 behavior unification). * test: S3 backend coverage via in-process moto server (13 cases) mock_aws cannot intercept aioboto3's aiohttp stack, so tests run against a real in-process ThreadedMotoServer endpoint. Covers roundtrips, missing object 404, merge failure modes (missing chunk / hash mismatch -> abort, no leftover object), cleanup scoping, presign shapes, proxy dispatch. Also adds moto[s3,server] to the dev group and CI. * fix: WebDAV missing object 404 upfront; connection errors map to 503 HEAD 404 was silently swallowed (signed a 200 bad stream that failed mid-download, same family as the S3 bug), and HEAD connection errors were also swallowed so the 503 mapping never fired. Both now surface properly; the aiohttp session is reclaimed on pre-stream exception paths. * test: WebDAV backend coverage via in-process WebDAV server (9 cases) Real HTTP (HEAD/GET/PUT/DELETE/MKCOL/PROPFIND) against a minimal aiohttp WebDAV server over a temp dir: roundtrips, missing object 404, connection error 503, delete with empty-parent cleanup, merge failure modes, chunk cleanup scoping. * fix: OneDrive missing object maps to 404 upfront; OpenDAL behavior pinned OneDrive get_file_response translated graph itemNotFound into the outer 503 catch-all; now raises StorageError(404) like local/S3/WebDAV. OpenDAL already mapped missing objects to 404 via its outer catch — pinned with fake-operator tests (SDK not in runtime deps, instances built via __new__). Also tightens the S3 presign URL assertion. * test: admin write-path coverage (batch/single delete, batch update, policy actions) 13 negative-path cases for the previously untested data-modifying admin endpoints: mixed-id aggregation with duplicates and missing records, empty-list rejections, clear_expired_at permanence semantics, policy action boundaries (zero limit 400, unknown action 400, missing 404), and the DoesNotExist->404 mapping pinned for single delete. * test: admin read-path and view-preset CRUD coverage (22 cases) Detail/metadata/preview/admin-download/activities/local-lists+delete/ verify: missing-record 404s, note/tag truncation limits, preview max_chars truncation, activity filtering and the 80-event clamp, local path traversal rejection. Presets: update-vs-create by id, name truncation, filter normalization clamps, 24-preset cap, delete-missing 404. * refactor: move auth primitives to apps/base/auth, kill base->admin dep JWT create/verify, bearer extraction and the share-upload gate move to apps.base.auth (consumed by both surfaces); admin.dependencies keeps admin session gating and service providers, re-exporting the primitives for import-path compatibility. base.views no longer imports from apps.admin — the last cross-app reverse dependency is gone. * refactor: split admin services god-module (ConfigService/LocalFile out) apps/admin/services.py (1697 lines) becomes FileService (~1200 lines) + a compatibility facade re-exporting ConfigService, LocalFileService, LocalFileClass and keyvalue_write_lock from their new homes (config_service.py holds the D5 KeyValue lock; one-way imports, no cycle). test_admin_security patch targets follow ConfigService to its new module. Behavior unchanged; 247 tests green. * fix: size-less uploads no longer crash (upstream seek bug) validate_file_size's size-None branch called UploadFile.seek(0, 2), which raises TypeError (UploadFile.seek takes one arg); the underlying SpooledTemporaryFile.seek is sync, so awaiting it also fails. Use the underlying file object with sync seek(0, SEEK_END). Surface discovered by the mypy pilot run; regression test covers the size-None branch. * chore: bump direct deps (patch/minor) fastapi 0.139.2->0.141.1, pydantic 2.12.5->2.13.5, uvicorn 0.51.0->0.53.0, aiohttp 3.14.2->3.14.3; lockfile regenerated. tortoise-orm 0.x->1.x major deliberately deferred pending API-change review. * ci: gradual mypy adoption via baseline ratchet scripts/mypy_ratchet.py compares mypy output against scripts/mypy-baseline.txt (line numbers stripped for edit stability): new type errors fail CI, fixes are folded back via --regenerate. Baseline starts at 30 known errors; the seek bug found in the pilot was fixed before baselining. mypy joins the dev group and CI. * fix: migrate WebDAV auth off aiohttp.BasicAuth (deprecated in 4.0) Dependency-upgrade probe on aiohttp 3.14.3 surfaced the BasicAuth deprecation; switch to aiohttp.encode_basic_auth() headers so the aiohttp 4.0 upgrade does not break the WebDAV backend. * chore: drop dead code (WebDAV _instance stub, unused LocalFileClass.write) * test: file-validation negative paths (13 cases) Magic-bytes spoofing (text-as-png, exe-as-pdf, mp4/webp box detection), whitelist rule semantics (star/image-wildcard/content mismatch), chunk-0 header validation parity, and end-to-end UploadFile rejection. * test: migration runner coverage (5 cases) Full chain executes 001-007 in filename order and registers; rerun is idempotent; pre-registered entries are skipped (DDL not re-executed); the resulting schema matches deployment; a failing migration propagates and is not registered. Uses a fresh :memory: DB without generate_schemas so the migrations themselves build the schema (the real deployment path). * refactor: split core/storage.py into a package (per-backend modules) core/storage.py (1400+ lines, six backends) becomes core/storage/ with _base.py (data contracts, interface, shared header builder), and local/s3/onedrive/opendal/webdav modules. The package __init__ re-exports the full historical public surface; test patch targets move to the precise backend modules (core.storage.local.data_root etc.) and the attachment guard scans the package. Import-only change; 264 tests green. Storage-layer DI deferred: current tests construct instances against patched settings, so the added surface isn't justified yet. * refactor: TypedDict for IPRateLimit records The rate-limit ledger mixed int and datetime under a loose Union typing, producing 5 mypy noise errors. A TypedDict gives precise per-key types; setdefault replaces the get-then-assign pattern. One mypy baseline error family resolved; 264 tests green. * chore: tighten mypy baseline after IPRateLimit TypedDict * refactor: resolve all 26 baseline mypy errors; precise test assertions Per-error treatment (no bulk script): honest annotations for StoredDownload (Path/bytes/Callable), KeyValue.value (Any for JSONField), dict[str, Any] for form/config dicts; signature split in create_token; str() normalization in config int(); platform/type-ignore only where the checker cannot follow (msvcrt, FastAPI Request injection). Baseline file and ratchet compare now redundant at zero errors but kept as the guard against regressions. Tests: assertions tightened to status_code == 403 with HTTPException raises; _create_share explicit parameters replace **extra passthrough; seek-fix pointer-reset assertion persisted.
635 lines
19 KiB
Python
635 lines
19 KiB
Python
# @Time : 2023/8/14 14:38
|
||
# @Author : Lan
|
||
# @File : views.py
|
||
# @Software: PyCharm
|
||
import datetime
|
||
from typing import Any
|
||
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,
|
||
FileMetadataData,
|
||
FileViewPresetData,
|
||
FileViewPresetDeleteData,
|
||
ShareItem,
|
||
DeleteItem,
|
||
LoginData,
|
||
UpdateFileData,
|
||
)
|
||
from core.response import APIResponse
|
||
from apps.base.models import FileCodes, KeyValue
|
||
from apps.base.quota import owned_storage_queryset
|
||
from tortoise.expressions import Q
|
||
from tortoise.functions import Count, Sum
|
||
from apps.admin.dependencies import (
|
||
create_token,
|
||
get_admin_session_expire_seconds,
|
||
verify_token,
|
||
)
|
||
from core.logger import logger
|
||
from core.settings import settings
|
||
from core.utils import get_now, hash_password, password_needs_rehash, 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 频率限制,超过 login_count/login_minute 后暂时锁定
|
||
if not verify_password(data.password, settings.admin_token):
|
||
ip_limit["login"].add_ip(ip)
|
||
raise HTTPException(status_code=401, detail="密码错误")
|
||
|
||
# 透明重哈希:存量 sha256/明文口令在登录成功(已证明持有口令)时升级为 scrypt
|
||
if password_needs_rehash(settings.admin_token):
|
||
try:
|
||
record = await KeyValue.filter(key="settings").first()
|
||
if record:
|
||
stored = dict(record.value or {})
|
||
stored["admin_token"] = hash_password(data.password)
|
||
record.value = stored
|
||
await record.save()
|
||
settings.admin_token = stored["admin_token"]
|
||
logger.info("管理员口令已升级为 scrypt 哈希")
|
||
except Exception:
|
||
logger.warning("口令哈希升级失败,保持旧格式", exc_info=True)
|
||
|
||
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,
|
||
"expired_at": file_code.expired_at,
|
||
"expired_count": file_code.expired_count,
|
||
"used_count": file_code.used_count,
|
||
"created_at": file_code.created_at,
|
||
"is_expired": is_expired,
|
||
}
|
||
|
||
|
||
def _expired_predicate(now: datetime.datetime) -> Q:
|
||
"""SQL version of FileCodes.is_expired:
|
||
expired_at IS NOT NULL AND ((expired_count < 0 AND expired_at < now) OR expired_count = 0)
|
||
"""
|
||
return Q(expired_at__isnull=False) & (
|
||
Q(expired_count__lt=0, expired_at__lt=now) | Q(expired_count=0)
|
||
)
|
||
|
||
|
||
async def _sum_size(queryset) -> int:
|
||
rows = await queryset.annotate(total=Sum("size")).values("total")
|
||
return rows[0]["total"] or 0
|
||
|
||
|
||
@admin_api.get("/dashboard")
|
||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||
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)
|
||
|
||
# 简单计数全部走 SQL 聚合,避免整表载入内存(D3)。
|
||
# 健康摘要依赖逐行 rules engine(_build_file_status_insights),保留一次遍历。
|
||
total_files = await FileCodes.all().count()
|
||
expired_count = await FileCodes.filter(_expired_predicate(now)).count()
|
||
all_size = await _sum_size(owned_storage_queryset())
|
||
used_count = (
|
||
await FileCodes.all().annotate(total=Sum("used_count")).values("total")
|
||
)[0]["total"] or 0
|
||
text_count = await FileCodes.filter(text__isnull=False).count()
|
||
chunked_count = await FileCodes.filter(is_chunked=True).count()
|
||
yesterday_count = await FileCodes.filter(
|
||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||
).count()
|
||
yesterday_size = await _sum_size(
|
||
owned_storage_queryset(
|
||
FileCodes.filter(created_at__gte=yesterday_start, created_at__lte=yesterday_end)
|
||
)
|
||
)
|
||
today_count = await FileCodes.filter(created_at__gte=today_start).count()
|
||
today_size = await _sum_size(
|
||
owned_storage_queryset(FileCodes.filter(created_at__gte=today_start))
|
||
)
|
||
|
||
suffix_rows = (
|
||
await FileCodes.filter(text__isnull=True)
|
||
.annotate(count=Count("id"))
|
||
.values("suffix", "count")
|
||
)
|
||
suffix_counter = Counter(
|
||
{((row["suffix"] or "file") or "file"): row["count"] for row in suffix_rows}
|
||
)
|
||
|
||
recent_file_codes = await FileCodes.all().order_by("-created_at").limit(8)
|
||
health_summary = await file_service.build_file_health_summary(
|
||
await FileCodes.all(), now=now
|
||
)
|
||
recent_activities = await file_service.list_admin_activities(limit=8)
|
||
return APIResponse(
|
||
detail={
|
||
"total_files": total_files,
|
||
"storage_used": str(all_size),
|
||
"sys_uptime": sys_start.value if sys_start else None,
|
||
"yesterday_count": yesterday_count,
|
||
"yesterday_size": str(yesterday_size),
|
||
"today_count": today_count,
|
||
"today_size": str(today_size),
|
||
"active_count": total_files - expired_count,
|
||
"expired_count": expired_count,
|
||
"text_count": text_count,
|
||
"file_count": total_files - text_count,
|
||
"chunked_count": chunked_count,
|
||
"used_count": used_count,
|
||
"storage_backend": settings.file_storage,
|
||
"upload_size_limit": settings.upload_size,
|
||
"open_upload": settings.open_upload,
|
||
"enable_chunk": settings.enable_chunk,
|
||
"max_save_seconds": settings.max_save_seconds,
|
||
**health_summary,
|
||
"health_summary": health_summary,
|
||
"top_suffixes": [
|
||
{"suffix": suffix, "count": count}
|
||
for suffix, count in suffix_counter.most_common(8)
|
||
],
|
||
"recent_files": [
|
||
await build_dashboard_recent_file(file_code)
|
||
for file_code in recent_file_codes
|
||
],
|
||
"recent_activities": recent_activities["activities"],
|
||
}
|
||
)
|
||
|
||
|
||
@admin_api.get("/activities")
|
||
async def admin_activities(
|
||
limit: int = 20,
|
||
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(
|
||
limit=limit,
|
||
action=action,
|
||
target_type=_pick_query_text(targetType, target_type),
|
||
keyword=keyword,
|
||
)
|
||
return APIResponse(detail=result)
|
||
|
||
|
||
@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)
|
||
|
||
|
||
async def batch_update_files(
|
||
data: BatchUpdateFileData,
|
||
file_service: FileService,
|
||
):
|
||
if not data.ids:
|
||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||
|
||
update_data: dict[str, Any] = {}
|
||
fields_set = data.model_fields_set
|
||
should_clear_expired_at = bool(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 != "":
|
||
# schema 声明 Union[datetime, str]——透传两种形态,tortoise 均可序列化
|
||
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.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.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 = "",
|
||
sort_by: str = "created_at",
|
||
sort_order: 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=sort_by,
|
||
sort_order=sort_order,
|
||
)
|
||
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("themes_choices", 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,
|
||
max_chars: int = 4000,
|
||
file_service: FileService = Depends(get_file_service),
|
||
):
|
||
preview = await file_service.preview_file(id, max_chars)
|
||
return APIResponse(detail=preview)
|
||
|
||
|
||
@admin_api.get("/local/lists")
|
||
async def get_local_lists(
|
||
path: str = "",
|
||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||
):
|
||
files = await local_file_service.list_files(path)
|
||
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={
|
||
"expire_value": item.expire_value,
|
||
"expire_style": 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),
|
||
):
|
||
await file_service.update_file(
|
||
file_id=data.id,
|
||
code=data.code,
|
||
prefix=data.prefix,
|
||
suffix=data.suffix,
|
||
expired_at=data.expired_at,
|
||
expired_count=data.expired_count,
|
||
)
|
||
return APIResponse(detail="更新成功")
|