ticketfrei3/backend/src/kibicara/webapi/hoods/__init__.py

121 lines
3 KiB
Python

# Copyright (C) 2020, 2023 by Thomas Lindner <tom@dl6tom.de>
# Copyright (C) 2020 by Cathy Hu <cathy.hu@fau.de>
# Copyright (C) 2020 by Martin Rey <martin.rey@mailbox.org>
#
# SPDX-License-Identifier: 0BSD
"""REST API Endpoints for managing hoods."""
from fastapi import APIRouter, Depends, HTTPException, Response, status
from pydantic import BaseModel
from tortoise.exceptions import DoesNotExist, IntegrityError
from kibicara.model import Admin, Hood, IncludePattern
from kibicara.platforms.email.bot import spawner
from kibicara.webapi.admin import get_admin
from kibicara.webapi.utils import delete_hood
class BodyHood(BaseModel):
name: str
landingpage: str = "Default Landing Page"
async def get_hood_unauthorized(hood_id: int) -> Hood:
try:
return await Hood.get(id=hood_id)
except DoesNotExist:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
async def get_hood(
hood: Hood = Depends(get_hood_unauthorized), admin: Admin = Depends(get_admin)
) -> Hood:
await hood.fetch_related("admins")
if admin in hood.admins:
return hood
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
headers={"WWW-Authenticate": "Bearer"},
)
router = APIRouter()
@router.get(
"/",
# TODO response_model,
operation_id="get_hoods",
tags=["hoods"],
)
async def hood_read_all():
"""Get all existing hoods."""
return await Hood.all()
@router.post(
"/",
status_code=status.HTTP_201_CREATED,
# TODO response_model,
operation_id="create_hood",
tags=["hoods"],
)
async def hood_create(
values: BodyHood, response: Response, admin: Admin = Depends(get_admin)
):
"""Creates a hood.
- **name**: Name of the hood
- **landingpage**: Markdown formatted description of the hood
"""
try:
hood = await Hood.create(**values.__dict__)
await admin.hoods.add(hood)
spawner.start(hood)
# Initialize Triggers to match all
await IncludePattern.create(hood=hood, pattern=".")
response.headers["Location"] = str(hood.id)
return hood
except IntegrityError:
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
@router.get(
"/{hood_id}",
# TODO response_model,
operation_id="get_hood",
tags=["hoods"],
)
async def hood_read(hood: Hood = Depends(get_hood_unauthorized)):
"""Get hood with id **hood_id**."""
return hood
@router.put(
"/{hood_id}",
operation_id="update_hood",
tags=["hoods"],
)
async def hood_update(values: BodyHood, hood: Hood = Depends(get_hood)):
"""Updates hood with id **hood_id**.
- **name**: New name of the hood
- **landingpage**: New Markdown formatted description of the hood
"""
await Hood.filter(id=hood).update(**values.__dict__)
return hood
@router.delete(
"/{hood_id}",
status_code=status.HTTP_204_NO_CONTENT,
operation_id="delete_hood",
tags=["hoods"],
)
async def hood_delete(hood=Depends(get_hood)):
"""Deletes hood with id **hood_id**."""
await delete_hood(hood)