Files
aurora-moments/api/apps/moments/views.py
T

70 lines
2.7 KiB
Python
Raw Normal View History

from rest_framework import permissions, viewsets
from rest_framework.exceptions import PermissionDenied
from .models import Comment, Moment, Reaction
from .permissions import IsOwnerOrReadOnly
from .serializers import CommentSerializer, MomentSerializer, ReactionSerializer
class MomentViewSet(viewsets.ModelViewSet):
"""list() is the home feed: everything visible to the requesting user,
newest first. Filter to one user's posts (for a profile page) with
?owner__username=<username> — still scoped by visible_to() below, so a
private/followers-only post won't leak through the filter."""
serializer_class = MomentSerializer
permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]
filterset_fields = ["owner__username"]
def get_queryset(self):
return (
Moment.objects.visible_to(self.request.user)
.select_related("owner")
.prefetch_related("items__library_item__renditions", "reactions")
)
class CommentViewSet(viewsets.ModelViewSet):
serializer_class = CommentSerializer
permission_classes = [permissions.IsAuthenticated]
http_method_names = ["get", "post", "delete", "head", "options"]
def _get_moment(self):
return Moment.objects.visible_to(self.request.user).get(pk=self.kwargs["moment_pk"])
def get_queryset(self):
return Comment.objects.filter(moment=self._get_moment()).select_related("author")
def get_serializer_context(self):
context = super().get_serializer_context()
context["moment"] = self._get_moment()
return context
def perform_create(self, serializer):
serializer.save(moment=self._get_moment(), author=self.request.user)
def perform_destroy(self, instance):
if instance.author_id != self.request.user.id and instance.moment.owner_id != self.request.user.id:
raise PermissionDenied("Cannot delete another user's comment.")
instance.delete()
class ReactionViewSet(viewsets.ModelViewSet):
serializer_class = ReactionSerializer
permission_classes = [permissions.IsAuthenticated]
http_method_names = ["get", "post", "delete", "head", "options"]
def _get_moment(self):
return Moment.objects.visible_to(self.request.user).get(pk=self.kwargs["moment_pk"])
def get_queryset(self):
return Reaction.objects.filter(moment=self._get_moment()).select_related("user")
def perform_create(self, serializer):
serializer.save(moment=self._get_moment(), user=self.request.user)
def perform_destroy(self, instance):
if instance.user_id != self.request.user.id:
raise PermissionDenied("Cannot remove another user's reaction.")
instance.delete()