87 lines
3.3 KiB
Python
87 lines
3.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""文件接口:上传 / 列表 / 删除 / 下载。"""
|
|
from __future__ import annotations
|
|
|
|
import mimetypes
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
|
from fastapi.responses import FileResponse
|
|
|
|
from fileserver.core import auth, store
|
|
|
|
router = APIRouter(tags=["files"])
|
|
|
|
|
|
@router.post("/api/upload")
|
|
async def api_upload(upload: UploadFile, who: str = Depends(auth.check_admin)) -> dict:
|
|
"""上传文件:存唯一 id,返回 {id, filename, sha256, size, url}。"""
|
|
raw = await upload.read()
|
|
if not raw:
|
|
raise HTTPException(400, "上传内容为空")
|
|
m = store.save(raw, upload.filename or "", uploader=who)
|
|
return {"ok": True, "id": m["fid"], "fid": m["fid"],
|
|
"filename": m["filename"], "sha256": m["sha256"], "size": m["size"],
|
|
"created": m["created"], "uploader": m["uploader"],
|
|
"url": store.file_url(m["fid"], m["filename"])}
|
|
|
|
|
|
@router.get("/api/files")
|
|
def api_files(_: str = Depends(auth.check_admin)) -> dict:
|
|
"""列表已上传文件(管理)。"""
|
|
items = []
|
|
for m in store.list_files():
|
|
m = dict(m)
|
|
m["url"] = store.file_url(m["fid"], m["filename"])
|
|
items.append(m)
|
|
return {"files": items}
|
|
|
|
|
|
@router.delete("/api/files/{fid}")
|
|
def api_delete(fid: str, _: str = Depends(auth.check_admin)) -> dict:
|
|
"""删除文件与元数据(管理)。"""
|
|
try:
|
|
removed = store.remove(fid)
|
|
except ValueError:
|
|
raise HTTPException(400, "非法的文件 id")
|
|
return {"ok": True, "removed": removed, "id": fid}
|
|
|
|
|
|
def _inline_media(name: str) -> str:
|
|
"""按文件名推断可内联预览的 Content-Type;非图片/音视频/PDF/纯文本返回空(仍按附件下载)。"""
|
|
media = mimetypes.guess_type(name or "")[0] or ""
|
|
if media.startswith(("image/", "video/", "audio/")) or media in ("application/pdf", "text/plain"):
|
|
return media
|
|
return ""
|
|
|
|
|
|
@router.get("/files/{fid}/{name}")
|
|
def api_download_named(fid: str, name: str):
|
|
"""带文件名的开放直链(/files/{fid}/xxx.png):按扩展名 inline 返回,便于钉钉等聊天工具渲染图片。"""
|
|
p = store.path_of(fid)
|
|
if p is None:
|
|
raise HTTPException(404, "文件不存在")
|
|
store.increment_downloads(fid)
|
|
media = _inline_media(name)
|
|
if media:
|
|
return FileResponse(p, filename=name, media_type=media,
|
|
content_disposition_type="inline")
|
|
return FileResponse(p, filename=name, media_type="application/octet-stream")
|
|
|
|
|
|
@router.get("/files/{fid}")
|
|
def api_download(fid: str, dl: str = ""):
|
|
"""开放下载(内网直链);?dl=文件名 时以该名 attachment 落盘;图片等按扩展名 inline 便于群内直接显示。"""
|
|
p = store.path_of(fid)
|
|
if p is None:
|
|
raise HTTPException(404, "文件不存在")
|
|
store.increment_downloads(fid)
|
|
m = store.meta(fid)
|
|
default_name = m.get("filename") or fid
|
|
if dl:
|
|
return FileResponse(p, filename=dl, media_type="application/octet-stream")
|
|
media = _inline_media(default_name)
|
|
if media:
|
|
return FileResponse(p, filename=default_name, media_type=media,
|
|
content_disposition_type="inline")
|
|
return FileResponse(p, filename=default_name, media_type="application/octet-stream")
|