portier/source/config/api/stream.py

74 lines
1.8 KiB
Python
Raw Normal View History

2024-04-22 14:25:15 +02:00
from ninja import Router, ModelSchema, Schema
from ninja.errors import HttpError
from config import models
from typing import List
from guardian.shortcuts import get_objects_for_user, assign_perm
from django.shortcuts import get_object_or_404
router = Router()
class Stream(ModelSchema):
class Meta:
model = models.Stream
fields = "__all__"
class StreamPatch(ModelSchema):
class Meta:
model = models.Stream
fields = ["name"]
fields_optional = "__all__"
extra = "forbid"
class StreamCreate(ModelSchema):
class Meta:
model = models.Stream
fields = ["name"]
extra = "forbid"
2024-05-04 14:06:46 +02:00
@router.get('/', response=List[Stream])
2024-04-22 14:25:15 +02:00
def list_streams(request):
return get_objects_for_user(request.user, 'view_stream', models.Stream.objects.all())
2024-05-04 14:06:46 +02:00
@router.post('/', response=Stream)
2024-04-22 14:25:15 +02:00
def create_stream(request, payload: StreamCreate):
stream = models.Stream.objects.create(**payload.dict())
assign_perm('view_stream', request.user, stream)
assign_perm('change_stream', request.user, stream)
assign_perm('delete_stream', request.user, stream)
return stream
2024-05-04 14:06:46 +02:00
@router.get('/{id}', response=Stream)
2024-04-22 14:25:15 +02:00
def get_stream(request, id: int):
stream = get_object_or_404(models.Stream, id=id)
if not request.user.has_perm('view_stream', stream):
raise HttpError(401, "unauthorized")
return stream
2024-05-04 14:06:46 +02:00
@router.patch('/{id}', response=Stream)
2024-04-22 14:25:15 +02:00
def update_stream(request, id: int, payload: StreamPatch):
stream = get_object_or_404(models.Stream, id=id)
if not request.user.has_perm('change_stream', stream):
raise HttpError(401, "unauthorized")
stream.name = payload.name
stream.save()
return stream
2024-05-04 14:06:46 +02:00
@router.delete('/{id}', response=None)
2024-04-22 14:25:15 +02:00
def delete_stream(request, id: int):
stream = get_object_or_404(models.Stream, id=id)
if not request.user.has_perm('delete_stream', stream):
raise HttpError(401, "unauthorized")
stream.delete()