Files
comfy-discord-web/web/routers/share_router.py
Khoa (Revenovich) Tran Gia 6004b000a7 manual submit
2026-03-07 21:49:16 +07:00

106 lines
3.6 KiB
Python

"""GET /api/share/{token}; GET /api/share/{token}/file/{filename}"""
from __future__ import annotations
import base64
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import Response
from web.auth import optional_auth
router = APIRouter()
def _auth_gate(gen: dict, user: Optional[dict]) -> None:
"""Raise 401 if the share is private and the user is not authenticated."""
if not gen.get("is_public") and user is None:
raise HTTPException(401, "Authentication required")
@router.get("/{token}")
async def get_share(token: str, user: Optional[dict] = Depends(optional_auth)):
"""Fetch share metadata and images. Public shares require no login; private shares require auth."""
from generation_db import get_share_by_token, get_files
gen = get_share_by_token(token)
if gen is None:
raise HTTPException(404, "Share not found, expired, or revoked")
_auth_gate(gen, user)
files = get_files(gen["prompt_id"])
return {
"prompt_id": gen["prompt_id"],
"created_at": gen["created_at"],
"overrides": gen["overrides"],
"seed": gen["seed"],
"is_public": bool(gen["is_public"]),
"expires_at": gen["expires_at"],
"max_views": gen["max_views"],
"view_count": gen["view_count"],
"images": [
{
"filename": f["filename"],
"data": base64.b64encode(f["data"]).decode() if not f["mime_type"].startswith("video/") else None,
"mime_type": f["mime_type"],
}
for f in files
],
}
@router.get("/{token}/file/{filename}")
async def get_share_file(
token: str,
filename: str,
request: Request,
user: Optional[dict] = Depends(optional_auth),
):
"""Stream a single output file via share token, with HTTP range support for video seeking."""
from generation_db import get_share_meta, get_files
gen = get_share_meta(token)
if gen is None:
raise HTTPException(404, "Share not found, expired, or revoked")
_auth_gate(gen, user)
files = get_files(gen["prompt_id"])
matched = next((f for f in files if f["filename"] == filename), None)
if matched is None:
raise HTTPException(404, f"File {filename!r} not found")
data: bytes = matched["data"]
mime: str = matched["mime_type"]
total = len(data)
range_header = request.headers.get("range")
if range_header:
range_val = range_header.replace("bytes=", "")
start_str, _, end_str = range_val.partition("-")
start = int(start_str) if start_str else 0
end = int(end_str) if end_str else total - 1
end = min(end, total - 1)
if start < 0 or start > end:
return Response(
status_code=416,
headers={"Content-Range": f"bytes */{total}"},
)
chunk = data[start : end + 1]
return Response(
content=chunk,
status_code=206,
media_type=mime,
headers={
"Content-Range": f"bytes {start}-{end}/{total}",
"Accept-Ranges": "bytes",
"Content-Length": str(len(chunk)),
"Cache-Control": "public, max-age=3600" if gen.get("is_public") else "private",
},
)
return Response(
content=data,
media_type=mime,
headers={
"Accept-Ranges": "bytes",
"Content-Length": str(total),
"Cache-Control": "public, max-age=3600" if gen.get("is_public") else "private",
},
)