portier/source/config/api/restream.py

79 lines
2.2 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 Restream(ModelSchema):
class Meta:
model = models.Restream
fields = "__all__"
class RestreamPatch(ModelSchema):
class Meta:
model = models.Restream
exclude = ["id"]
fields_optional = "__all__"
extra = "forbid"
2024-05-04 14:06:46 +02:00
@router.get('/', response=List[Restream])
2024-04-22 14:25:15 +02:00
def list_restreams(request):
return get_objects_for_user(request.user, 'view_restream', models.Restream.objects.all())
2024-05-04 14:06:46 +02:00
@router.post('/', response=Restream)
2024-04-22 14:25:15 +02:00
def create_restream(request, payload: Restream):
if not request.user.has_perm('view_stream', payload.stream):
raise HttpError(401, "unauthorized")
restream = models.Restream.objects.create(**payload.dict())
assign_perm('view_restream', request.user, restream)
assign_perm('change_restream', request.user, restream)
assign_perm('delete_restream', request.user, restream)
return restream
2024-05-04 14:06:46 +02:00
@router.get('/{id}', response=Restream)
2024-04-22 14:25:15 +02:00
def get_restream(request, id: int):
restream = get_object_or_404(models.Restream, id=id)
if not request.user.has_perm('view_restream', restream):
raise HttpError(401, "unauthorized")
return restream
2024-05-04 14:06:46 +02:00
@router.patch('/{id}', response=Restream)
2024-04-22 14:25:15 +02:00
def update_restream(request, id: int, payload: RestreamPatch):
restream = get_object_or_404(models.Restream, id=id)
if not request.user.has_perm('change_restream', restream):
raise HttpError(401, "unauthorized")
if payload.stream:
payload.stream = get_object_or_404(models.Stream, id=payload.stream)
if not request.user.has_perm('view_stream', payload.stream):
raise HttpError(401, "unauthorized")
for key, value in payload.dict(exclude_unset=True).items():
setattr(restream, key, value)
restream.save()
return restream
2024-05-04 14:06:46 +02:00
@router.delete('/{id}', response=None)
2024-04-22 14:25:15 +02:00
def delete_restream(request, id: int):
restream = get_object_or_404(models.Restream, id=id)
if not request.user.has_perm('delete_restream', restream):
raise HttpError(401, "unauthorized")
restream.delete()