171 lines
5.9 KiB
Python
171 lines
5.9 KiB
Python
"""用户媒体库接口 ``/api/media``:TF 卡文件管理的数据源。
|
||
|
||
上传即入库,入库即进入设备同步清单;删除则设备会在下一次同步时清掉 TF 卡
|
||
上的同名文件。设备侧的接口在 device_v1(manifest / download / report)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
|
||
from fastapi import APIRouter, HTTPException, UploadFile, status
|
||
from fastapi.responses import FileResponse
|
||
from pydantic import BaseModel
|
||
from sqlalchemy import delete, select
|
||
|
||
from app.api.deps import CurrentUser, CurrentUserAny, SessionDep
|
||
from app.models import DeviceMedia, MediaFile
|
||
from app.services import media as msvc
|
||
|
||
router = APIRouter(prefix="/media", tags=["media"])
|
||
|
||
|
||
class MediaOut(BaseModel):
|
||
id: uuid.UUID
|
||
kind: str
|
||
name: str
|
||
size: int
|
||
crc32: int
|
||
width: int
|
||
height: int
|
||
original_name: str
|
||
created_at: str
|
||
synced_devices: int = 0
|
||
has_cover: bool = False
|
||
|
||
@staticmethod
|
||
def of(mf: MediaFile, synced: int = 0) -> "MediaOut":
|
||
return MediaOut(
|
||
id=mf.id,
|
||
kind=mf.kind,
|
||
name=mf.name,
|
||
size=mf.size,
|
||
crc32=mf.crc32,
|
||
width=mf.width,
|
||
height=mf.height,
|
||
original_name=mf.original_name,
|
||
created_at=mf.created_at.isoformat() if mf.created_at else "",
|
||
synced_devices=synced,
|
||
has_cover=bool(mf.cover_file),
|
||
)
|
||
|
||
|
||
@router.get("", response_model=list[MediaOut])
|
||
async def list_media(db: SessionDep, user: CurrentUser) -> list[MediaOut]:
|
||
rows = list(
|
||
(
|
||
await db.execute(
|
||
select(MediaFile).where(MediaFile.owner_user_id == user.id).order_by(MediaFile.created_at.desc())
|
||
)
|
||
).scalars()
|
||
)
|
||
states = await msvc.sync_states(db, user.id)
|
||
return [MediaOut.of(r, states.get(r.id, 0)) for r in rows]
|
||
|
||
|
||
@router.post("", response_model=MediaOut, status_code=201)
|
||
async def upload_media(db: SessionDep, user: CurrentUser, file: UploadFile) -> MediaOut:
|
||
"""上传一个文件。音乐原样入库;图片服务端转 JPEG(限边/去 EXIF)。"""
|
||
raw = await file.read()
|
||
if not raw:
|
||
raise HTTPException(400, "empty file")
|
||
|
||
try:
|
||
kind = msvc.kind_of(file.filename or "")
|
||
name = msvc.sanitize_name(file.filename or "")
|
||
except msvc.MediaError as e:
|
||
raise HTTPException(400, str(e)) from e
|
||
|
||
if len(raw) > msvc.max_size_for(kind):
|
||
cap = msvc.max_size_for(kind) // (1024 * 1024)
|
||
raise HTTPException(400, f"文件超过 {cap} MB 上限")
|
||
|
||
width = height = 0
|
||
cover_file = ""
|
||
if kind == "image":
|
||
try:
|
||
raw, width, height = msvc.process_image(raw)
|
||
except msvc.MediaError as e:
|
||
raise HTTPException(400, str(e)) from e
|
||
|
||
# 同名即视为「重新上传」:替换内容、保留 id,设备端按 crc32 不同重新下载
|
||
existing = await db.scalar(
|
||
select(MediaFile).where(MediaFile.owner_user_id == user.id, MediaFile.name == name)
|
||
)
|
||
filename, size, crc = msvc.save_bytes(kind, name, raw)
|
||
cover_id = existing.id if existing is not None else uuid.uuid4()
|
||
if kind == "music":
|
||
cover_file = msvc.extract_cover(raw, cover_id)
|
||
if existing is None:
|
||
mf = MediaFile(
|
||
owner_user_id=user.id,
|
||
kind=kind,
|
||
name=name,
|
||
size=size,
|
||
crc32=crc,
|
||
filename=filename,
|
||
original_name=file.filename or name,
|
||
width=width,
|
||
height=height,
|
||
cover_file=cover_file,
|
||
)
|
||
db.add(mf)
|
||
else:
|
||
msvc.remove_file(existing)
|
||
msvc.remove_cover(existing)
|
||
existing.kind = kind
|
||
existing.size = size
|
||
existing.crc32 = crc
|
||
existing.filename = filename
|
||
existing.original_name = file.filename or name
|
||
existing.width = width
|
||
existing.height = height
|
||
existing.cover_file = cover_file
|
||
# 内容换了:清掉各设备的「已同步」记录,让它们重新进入待同步
|
||
await db.execute(delete(DeviceMedia).where(DeviceMedia.media_id == existing.id))
|
||
mf = existing
|
||
await db.commit()
|
||
await db.refresh(mf)
|
||
return MediaOut.of(mf, 0)
|
||
|
||
|
||
@router.delete("/{media_id}", status_code=204)
|
||
async def delete_media(media_id: uuid.UUID, db: SessionDep, user: CurrentUser) -> None:
|
||
mf = await db.get(MediaFile, media_id)
|
||
if mf is None or mf.owner_user_id != user.id:
|
||
raise HTTPException(404, "media not found")
|
||
# TF 卡上的文件由设备 diff 清单后删除;这里只管服务端这份
|
||
await db.execute(delete(MediaFile).where(MediaFile.id == mf.id))
|
||
await db.commit()
|
||
msvc.remove_file(mf)
|
||
msvc.remove_cover(mf)
|
||
|
||
|
||
@router.get("/{media_id}/cover")
|
||
async def media_cover(media_id: uuid.UUID, db: SessionDep, user: CurrentUserAny) -> FileResponse:
|
||
"""MP3 内嵌封面缩略图(上传时已抽取压好)。没有封面返回 404。"""
|
||
mf = await db.get(MediaFile, media_id)
|
||
if mf is None or mf.owner_user_id != user.id or not mf.cover_file:
|
||
raise HTTPException(404, "no cover")
|
||
path = msvc.COVERS_DIR / mf.cover_file
|
||
if not path.exists():
|
||
raise HTTPException(status.HTTP_410_GONE, "cover missing on server")
|
||
return FileResponse(path, media_type="image/jpeg")
|
||
|
||
|
||
@router.get("/{media_id}/file")
|
||
async def media_file(media_id: uuid.UUID, db: SessionDep, user: CurrentUserAny) -> FileResponse:
|
||
"""网页预览/试听。
|
||
|
||
用 ``CurrentUserAny``:``<img>``/``<audio>`` 带不了 Authorization 头,
|
||
网页端把 token 拼在 ``?t=`` 上。
|
||
"""
|
||
mf = await db.get(MediaFile, media_id)
|
||
if mf is None or mf.owner_user_id != user.id:
|
||
raise HTTPException(404, "media not found")
|
||
path = msvc.path_of(mf)
|
||
if not path.exists():
|
||
raise HTTPException(status.HTTP_410_GONE, "file missing on server")
|
||
mt = "audio/mpeg" if mf.kind == "music" else "image/jpeg"
|
||
return FileResponse(path, media_type=mt, filename=mf.name)
|