import re from asyncreq import request from fastapi import APIRouter, BackgroundTasks, Depends, Response from sqlalchemy.orm import Session from src.api.config import API_FLIGHTS from src.api.cruds import chat as notif_crud from src.api.cruds import subscription as subs_crud from src.api.db import get_db from src.api.schemas.chat import Chat, Update from src.api.utils import telegram from src.api.utils.messages import get_flight_message, get_invalid_message router = APIRouter() msg_options = re.compile(r"^/(flight \d+|stop|start)$") @router.post("") async def create_chat( chat: Update, background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): print(chat.model_dump()) message = chat.message text = message["text"] if not msg_options.match(text): msg = get_invalid_message() chat_id = str(message["chat"]["id"]) background_tasks.add_task(telegram.send_message, chat_id, msg) return Response(status_code=204) action = text.partition(" ")[0] if action == "/start": user_id = int(message["text"].partition(" ")[2]) new_chat = Chat(chat_id=str(message["chat"]["id"]), user_id=user_id) notif_crud.create_chat(db=db, chat=new_chat) elif action == "/stop": chat_id = str(message["chat"]["id"]) user_id = notif_crud.get_user_from_chat(db=db, chat_id=chat_id).user_id subs_crud.remove_subscriptions(user_id) notif_crud.remove_chat(db=db, chat_id=chat_id) elif action == "/flight": chat_id = str(message["chat"]["id"]) flight_id = int(message["text"].partition(" ")[2]) (response, status, _) = await request(f"{API_FLIGHTS}/{flight_id}", "GET") if status < 200 or status > 204: msg = f"Could not get flight '{flight_id}'. Sorry!" msg = get_flight_message(response) background_tasks.add_task(telegram.send_message, chat_id, msg) return Response(status_code=204)