advent22/api/advent22_api/routers/days.py

70 lines
1.5 KiB
Python
Raw Normal View History

2022-11-15 23:43:13 +00:00
from datetime import date
2022-11-15 23:43:13 +00:00
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from PIL import Image
2022-10-10 23:46:04 +00:00
from ..core.config import Config
from ..core.depends import get_image, get_part, shuffle_solution
from ..core.image_helpers import api_return_image
2022-11-15 23:43:13 +00:00
from .user import user_is_admin
router = APIRouter(prefix="/days", tags=["days"])
@router.on_event("startup")
2022-10-14 21:42:05 +00:00
async def startup() -> None:
cfg = await Config.get_config()
2022-11-18 01:39:05 +00:00
print(cfg.puzzle.solution)
shuffled_solution = await shuffle_solution(cfg)
print(shuffled_solution)
2022-11-15 23:53:30 +00:00
@router.get("/date")
async def get_date() -> str:
return date.today().isoformat()
2022-11-04 20:00:43 +00:00
2022-12-21 23:38:33 +00:00
@router.get("/visible_days")
async def get_visible_days() -> int:
2022-11-15 23:43:13 +00:00
today = date.today()
2022-12-14 02:48:35 +00:00
if today.month == 12:
return today.day
2022-11-15 23:43:13 +00:00
if today.month in (1, 2, 3):
2022-12-14 02:48:35 +00:00
return 24
2022-11-15 23:43:13 +00:00
2022-12-14 02:48:35 +00:00
return 0
2022-11-15 23:43:13 +00:00
2022-12-14 02:48:35 +00:00
async def user_can_view(
day: int,
2022-12-14 02:48:35 +00:00
) -> bool:
return day < await get_visible_days()
2022-11-15 23:43:13 +00:00
@router.get("/part/{day}")
async def get_part_for_day(part: str = Depends(get_part)) -> str:
return part
@router.get(
"/image/{day}",
response_class=StreamingResponse,
)
2022-11-15 22:58:04 +00:00
async def get_image_for_day(
image: Image.Image = Depends(get_image),
2022-11-15 23:43:13 +00:00
can_view: bool = Depends(user_can_view),
is_admin: bool = Depends(user_is_admin),
) -> StreamingResponse:
2022-10-10 20:22:56 +00:00
"""
Bild für einen Tag erstellen
"""
2022-11-15 23:43:13 +00:00
if not (can_view or is_admin):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Wie unhöflich!!!")
return await api_return_image(image)