ovdashboard/api/ovdashboard_api/routers/image.py

63 lines
1.4 KiB
Python
Raw Normal View History

2022-08-31 10:21:24 +00:00
import re
from io import BytesIO
from typing import Iterator
2022-08-31 10:21:24 +00:00
2022-09-02 14:51:11 +00:00
from fastapi import APIRouter, Depends
2022-08-31 10:21:24 +00:00
from fastapi.responses import StreamingResponse
from PIL import Image
from ..dav_file import DavFile
2022-09-04 14:14:22 +00:00
from ._common import FileNameLister, PrefixFinder, PrefixUnique
2022-08-31 10:21:24 +00:00
router = APIRouter(prefix="/image", tags=["image"])
2022-09-02 13:22:35 +00:00
_lister = FileNameLister(
remote_path="img",
re=re.compile(
r"\.(gif|jpe?g|tiff?|png|bmp)$",
flags=re.IGNORECASE,
),
2022-08-31 10:21:24 +00:00
)
_finder = PrefixFinder(_lister)
2022-09-04 14:14:22 +00:00
_unique = PrefixUnique(_finder)
2022-08-31 10:21:24 +00:00
@router.get("/list", response_model=list[str])
async def list_images(
2022-09-04 14:14:22 +00:00
names: Iterator[str] = Depends(_lister),
2022-08-31 10:21:24 +00:00
) -> list[str]:
2022-09-04 14:14:22 +00:00
return list(names)
2022-08-31 10:21:24 +00:00
@router.get("/find/{prefix}", response_model=list[str])
async def find_images(
2022-09-04 14:14:22 +00:00
names: Iterator[str] = Depends(_finder),
2022-08-31 10:21:24 +00:00
) -> list[str]:
2022-09-04 14:14:22 +00:00
return list(names)
2022-08-31 10:21:24 +00:00
@router.get(
"/get/{prefix}",
2022-08-31 14:03:29 +00:00
response_class=StreamingResponse,
2022-09-04 14:14:22 +00:00
responses=_unique.responses,
2022-08-31 10:21:24 +00:00
)
async def get_image(
prefix: str,
2022-09-04 14:14:22 +00:00
name: str = Depends(_unique),
2022-09-02 14:51:11 +00:00
) -> str:
2022-09-04 14:14:22 +00:00
dav_file = DavFile(f"{_lister.remote_path}/{name}")
2022-09-02 14:51:11 +00:00
img = Image.open(BytesIO(await dav_file.bytes)).convert("RGB")
img_buffer = BytesIO()
img.save(img_buffer, format='JPEG', quality=85)
2022-08-31 10:21:24 +00:00
img_buffer.seek(0)
return StreamingResponse(
2022-08-31 10:41:36 +00:00
content=img_buffer,
2022-08-31 10:21:24 +00:00
media_type="image/jpeg",
headers={
"Content-Disposition": f"filename={prefix}.jpg"
},
)