from datetime import date from io import BytesIO from fastapi import APIRouter, Depends, HTTPException, status from fastapi.responses import StreamingResponse from ..config import Config, get_config from ._image import AdventImage from ._misc import get_image, shuffle from .user import user_is_admin router = APIRouter(prefix="/days", tags=["days"]) @router.on_event("startup") async def startup() -> None: cfg = await get_config() print(cfg.solution) print("".join(await shuffle(cfg.solution))) @router.get("/letter/{index}") async def get_letter( index: int, cfg: Config = Depends(get_config), ) -> str: return (await shuffle(cfg.solution))[index] # @router.get("/date") # def get_date() -> int: # return date.today().day # @router.get( # "/picture", # response_class=StreamingResponse, # ) # async def get_picture(): # img = Image.open("hand.png").convert("RGBA") # d1 = ImageDraw.Draw(img) # font = ImageFont.truetype("Lena.ttf", 50) # d1.text((260, 155), "W", font=font, fill=(0, 0, 255)) # # d1.text(xy=(400, 210), text="Deine Hände auch?", # # font=Font, fill=(255, 0, 0)) # img_buffer = BytesIO() # img.save(img_buffer, format="PNG", quality=85) # img_buffer.seek(0) # return StreamingResponse( # content=img_buffer, # media_type="image/png", # ) async def user_can_view( index: int, ) -> bool: today = date.today() if today.month in (1, 2, 3): return True elif today.month == 12: return index < today.day return False @router.get( "/image/{index}", response_class=StreamingResponse, ) async def get_image_for_day( image: AdventImage = Depends(get_image), can_view: bool = Depends(user_can_view), is_admin: bool = Depends(user_is_admin), ) -> StreamingResponse: """ Bild für einen Tag erstellen """ if not (can_view or is_admin): raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Wie unhöflich!!!") # Bilddaten in Puffer laden img_buffer = BytesIO() image.img.save(img_buffer, format="JPEG", quality=85) img_buffer.seek(0) return StreamingResponse( content=img_buffer, media_type="image/jpeg", )