ovdashboard/api/ovdashboard_api/routers/v1/file.py

77 lines
1.7 KiB
Python

"""
Router "file" provides:
- listing files
- finding files by name prefix
- getting files by name prefix
"""
import logging
from io import BytesIO
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from magic import Magic
from ...core.dav_common import webdav_ensure_files, webdav_ensure_path
from ...core.webdav import WebDAV
from ._common import LM_FILE, RP_FILE
_logger = logging.getLogger(__name__)
_magic = Magic(mime=True)
router = APIRouter(prefix="/file", tags=["file"])
@router.on_event("startup")
async def start_router() -> None:
_logger.debug(f"{router.prefix} router starting.")
remote_path = await RP_FILE()
if not webdav_ensure_path(remote_path):
webdav_ensure_files(
remote_path,
"logo.svg",
"thw.svg",
)
@router.get(
"/list",
responses=LM_FILE.lister.responses,
)
async def list_all_files(
names: list[str] = Depends(LM_FILE.lister.func),
) -> list[str]:
return names
@router.get(
"/find/{prefix}",
responses=LM_FILE.filter.responses,
)
async def find_files_by_prefix(
names: list[str] = Depends(LM_FILE.filter.func),
) -> list[str]:
return names
@router.get(
"/get/{prefix}",
responses=LM_FILE.getter.responses,
response_class=StreamingResponse,
)
async def get_file_by_prefix(
remote_path: str = Depends(RP_FILE),
name: str = Depends(LM_FILE.getter.func),
) -> StreamingResponse:
buffer = BytesIO(await WebDAV.read_bytes(f"{remote_path}/{name}"))
mime = _magic.from_buffer(buffer.read(2048))
buffer.seek(0)
return StreamingResponse(
content=buffer,
media_type=mime,
headers={"Content-Disposition": f"filename={name}"},
)