Vetsi sada zmen

This commit is contained in:
Michal Kváček
2023-08-21 22:45:33 +02:00
parent 33e0a35f4b
commit 9314d31186
22 changed files with 352 additions and 201 deletions
+55 -102
View File
@@ -1,27 +1,27 @@
from datetime import timedelta
from functools import wraps
from typing import List, Optional, Annotated, TYPE_CHECKING, Tuple
import strawberry
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy import select, insert, delete
from starlette.status import HTTP_401_UNAUTHORIZED
from strawberry.file_uploads import Upload
from database import models
from database.models import flight_has_copilot
from decorators.endpoints import authenticated_user_only
from decorators.error_logging import error_logging
from graphql_schema.dataloaders import copilots_dataloader
from graphql_schema.dataloaders.aircraft import aircraft_dataloader
from graphql_schema.dataloaders.airport import airport_dataloader
from graphql_schema.dataloaders.copilots import flight_copilots_dataloader
from graphql_schema.dataloaders.photos import photos_dataloader, cover_photo_loader
from graphql_schema.dataloaders.poi import flight_track_dataloader, poi_dataloader
from graphql_schema.dataloaders.weather import airport_weather_info_loader
from graphql_schema.entities.aircraft import Aircraft
from graphql_schema.entities.airport import Airport
from graphql_schema.entities.photo import Photo
from graphql_schema.entities.poi import PointOfInterest
from graphql_schema.sqlalchemy_to_strawberry_type import strawberry_sqlalchemy_type, strawberry_sqlalchemy_input
from upload_utils import handle_file_upload, file_exists, delete_file
from .helpers.flight import handle_aircraft_save, handle_track_edit, handle_copilot_edit, handle_weather_info
from ..dataloaders.weather import airport_weather_info_loader
from upload_utils import get_public_url
from .helpers.flight import handle_aircraft_save, handle_track_edit, handle_copilots_edit, handle_weather_info, get_airports, handle_upload_gpx, handle_airport_changed
from ..types import ComboboxInput
if TYPE_CHECKING:
@@ -55,9 +55,6 @@ class Flight:
async def load_aircraft(root):
return await aircraft_dataloader.load(root.aircraft_id)
async def load_copilot(root):
return await copilots_dataloader.load(root.copilot_id)
async def load_photos(root):
return await photos_dataloader.load(root.id)
@@ -65,10 +62,10 @@ class Flight:
return await cover_photo_loader.load(root.id)
async def load_takeoff_weather_info(root):
return await airport_weather_info_loader.load(root.weather_info_takeoff_id)
return await airport_weather_info_loader.load(root.takeoff_weather_info_id)
async def load_landing_weather_info(root):
return await airport_weather_info_loader.load(root.weather_info_landing_id)
return await airport_weather_info_loader.load(root.landing_weather_info_id)
def duration_min_calculated(root):
if root.duration_total:
@@ -84,10 +81,14 @@ class Flight:
if not root.gpx_track_filename:
return None
return f"http://localhost:8000/uploads/tracks/{root.gpx_track_filename}"
return get_public_url(f"/tracks/{root.gpx_track_filename}")
@authenticated_user_only(raise_when_unauthorized=False, return_value_unauthorized=[])
async def load_copilots(root):
return await flight_copilots_dataloader.load(root.id)
duration_min_calculated: int = strawberry.field(resolver=duration_min_calculated)
copilot: Optional[Annotated["Copilot", strawberry.lazy(".copilot")]] = strawberry.field(resolver=load_copilot)
copilots: Optional[List[Annotated["Copilot", strawberry.lazy(".copilot")]]] = strawberry.field(resolver=load_copilots)
aircraft: Aircraft = strawberry.field(resolver=load_aircraft)
takeoff_airport: Airport = strawberry.field(resolver=load_takeoff_airport)
landing_airport: Airport = strawberry.field(resolver=load_landing_airport)
@@ -110,7 +111,7 @@ def get_base_query(user_id: Optional[int], username: Optional[str] = None, is_au
query = query.filter(models.Flight.created_by_id == user_id)
if username:
query = query.filter(models.Flight.created_by.public_username == username)
query = query.join(models.Flight.created_by).filter(models.User.public_username == username)
if not is_auth:
query = query.filter(models.Flight.is_public.is_(True))
@@ -121,10 +122,10 @@ def get_base_query(user_id: Optional[int], username: Optional[str] = None, is_au
@strawberry.type
class FlightQueries:
@strawberry.field
@strawberry.field()
async def flights(root, info, username: Optional[str] = None) -> List[Flight]:
if not info.context.user_id and not username:
raise HTTPException(HTTP_401_UNAUTHORIZED)
raise HTTPException(HTTP_401_UNAUTHORIZED, f"user_id={info.context.user_id}, {username=}")
query = (
get_base_query(user_id=info.context.user_id, username=username, is_auth=bool(info.context.user_id))
@@ -132,7 +133,7 @@ class FlightQueries:
)
return (await info.context.db.scalars(query)).all()
@strawberry.field
@strawberry.field()
@error_logging
async def flight(root, info, id: int, username: Optional[str] = None) -> Flight:
if not info.context.user_id and not username:
@@ -141,26 +142,10 @@ class FlightQueries:
query = (
get_base_query(user_id=info.context.user_id, username=username, is_auth=bool(info.context.user_id))
.filter(models.Flight.id == id)
.filter(models.Flight.deleted.is_(False))
)
return (await info.context.db.scalars(query)).one()
async def get_airports(db, takeoff_airport_id: int, landing_airport_id: int) -> Tuple[models.Airport, models.Airport]:
takeoff_airport = (await db.scalars(
select(models.Airport).filter(models.Airport.id == takeoff_airport_id)
)).one()
if takeoff_airport_id == landing_airport_id:
landing_airport = takeoff_airport
else:
landing_airport = (await db.scalars(
select(models.Airport).filter(models.Airport.id == landing_airport_id)
)).one()
return takeoff_airport, landing_airport
@strawberry.type
class CreateFlightMutation:
@strawberry_sqlalchemy_input(models.Flight, exclude_fields=[
@@ -173,24 +158,20 @@ class CreateFlightMutation:
takeoff_airport: ComboboxInput
@strawberry.mutation
@authenticated_user_only
@authenticated_user_only()
async def create_flight(self, info, input: CreateFlightInput) -> Flight:
db = info.context.db
aircraft_id = await handle_aircraft_save(db, info.context.user_id, input.aircraft)
data = input.to_dict()
data['takeoff_datetime'] = data['takeoff_datetime'].astimezone()
data['landing_datetime'] = data['landing_datetime'].astimezone()
takeoff_airport, landing_airport = await get_airports(db, input.takeoff_airport.id, input.landing_airport.id)
weather_takeoff = await handle_weather_info(db, input.takeoff_datetime, takeoff_airport)
weather_landing = await handle_weather_info(db, input.landing_datetime, landing_airport)
weather_takeoff = await handle_weather_info(db, data['takeoff_datetime'], takeoff_airport)
weather_landing = await handle_weather_info(db, data['landing_datetime'], landing_airport)
return await models.Flight.create(db, data={
**data,
"weather_info_takeoff_id": weather_takeoff.id,
"weather_info_landing_id": weather_landing.id,
"takeoff_weather_info_id": weather_takeoff.id,
"landing_weather_info_id": weather_landing.id,
"takeoff_airport_id": takeoff_airport.id,
"landing_airport_id": landing_airport.id,
"aircraft_id": aircraft_id,
@@ -198,106 +179,78 @@ class CreateFlightMutation:
})
@strawberry.type
class EditFlightMutation:
@strawberry_sqlalchemy_input(models.Flight, exclude_fields=[
"id", "aircraft_id", "copilot_id", "deleted", "landing_airport_id", "takeoff_airport_id",
"weather_info_takeoff_id", "weather_info_landing_id", "gpx_track_filename"
"id", "aircraft_id", "deleted", "landing_airport_id", "takeoff_airport_id"
"takeoff_weather_info_id", "landing_weather_info_id", "gpx_track_filename"
], all_optional=True)
class EditFlightInput:
gpx_track: Optional[Upload] = None
gpx_track: Optional[Upload] = None # TODO: poresit validaci uploadovaneho souboru!
track: Optional[List[ComboboxInput]] = None
copilot: Optional[ComboboxInput] = None
copilots: Optional[List[ComboboxInput]] = None
aircraft: Optional[ComboboxInput] = None
landing_airport: Optional[ComboboxInput] = None
takeoff_airport: Optional[ComboboxInput] = None
@strawberry.mutation
@authenticated_user_only
@authenticated_user_only()
async def edit_flight(self, info, id: int, input: EditFlightInput) -> Flight:
db = info.context.db
user_id = info.context.user_id
flight = (await db.scalars(
get_base_query(user_id=user_id, is_auth=bool(user_id))
.filter(models.Flight.id == id)
get_base_query(user_id=user_id, is_auth=bool(user_id)).filter(models.Flight.id == id)
)).one()
data = input.to_dict()
if input.takeoff_datetime:
data['takeoff_datetime'] = data['takeoff_datetime'].astimezone()
if input.landing_datetime:
data['landing_datetime'] = data['landing_datetime'].astimezone()
if input.gpx_track is not None:
# TODO: poresit validaci uploadovaneho souboru!
path = "/app/uploads/tracks"
if flight.gpx_track_filename and file_exists(path + "/" + flight.gpx_track_filename):
delete_file(path + "/" + flight.gpx_track_filename)
data['gpx_track_filename'] = await handle_file_upload(input.gpx_track, path)
update_takeoff_weather = False
update_landing_weather = False
if input.takeoff_airport is not None and input.takeoff_airport.id != flight.takeoff_airport_id:
data['takeoff_airport_id'] = input.takeoff_airport.id
update_takeoff_weather = True
if input.landing_airport is not None and input.landing_airport.id != flight.landing_airport_id:
data['landing_airport_id'] = input.landing_airport.id
update_landing_weather = True
takeoff_airport, landing_airport = await get_airports(
db,
takeoff_airport_id=input.takeoff_airport.id if input.takeoff_airport else flight.takeoff_airport_id,
landing_airport_id=input.landing_airport.id if input.landing_airport else flight.landing_airport_id,
)
if input.takeoff_datetime is not None and input.takeoff_datetime != flight.takeoff_datetime:
update_takeoff_weather = True
data = input.to_dict()
if input.landing_datetime is not None and input.landing_datetime != flight.landing_datetime:
update_landing_weather = True
if input.gpx_track is not None:
data['gpx_track_filename'] = await handle_upload_gpx(flight, input.gpx_track)
if update_takeoff_weather:
weather = await handle_weather_info(db, input.takeoff_datetime, takeoff_airport)
if input.takeoff_airport and input.takeoff_airport.id != flight.takeoff_airport_id:
await handle_airport_changed(
db,
flight,
takeoff_airport,
type_="takeoff",
input_datetime=data.get('takeoff_datetime')
)
# if flight.weather_info_takeoff_id:
# db.delete(flight.weather_info_takeoff)
data['weather_info_takeoff_id'] = weather.id
if update_landing_weather:
weather = await handle_weather_info(db, input.landing_datetime, landing_airport)
# if flight.weather_info_landing_id:
# db.delete(flight.weather_info_landing)
data['weather_info_landing_id'] = weather.id
# TODO: ^^ to pocasi smrdi zbytecne duplicitnim kodem, neslo by to nejak sjednotit?
if input.landing_airport and input.landing_airport.id != flight.landing_airport_id:
await handle_airport_changed(
db,
flight,
landing_airport,
type_="landing",
input_datetime=data.get('landing_datetime')
)
if input.aircraft is not None:
data['aircraft_id'] = await handle_aircraft_save(db, user_id, input.aircraft)
data['copilot_id'] = await handle_copilot_edit(db, input.copilot, user_id) if input.copilot else None
flight = await models.Flight.update(db, id=id, data=data)
if input.track is not None:
await handle_track_edit(db=db, flight=flight, track=input.track, user_id=user_id)
return flight
copilots = await handle_copilots_edit(db, input.copilots or [], user_id)
await db.execute(delete(flight_has_copilot).filter_by(flight_id=flight.id))
for copilot_id in copilots:
await db.execute(insert(flight_has_copilot).values(flight_id=flight.id, copilot_id=copilot_id))
return await models.Flight.update(db, obj=flight, data=data)
@strawberry.type
class DeleteFlightMutation:
@strawberry.mutation
@authenticated_user_only()
async def delete_flight(self, info, id: int) -> Flight:
flight = (
(await info.context.db.scalars(