views.py 1.74 KB
Newer Older
1 2
from rest_framework import mixins, viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
3

4 5
from django.db.models import Prefetch

6
from funkwhale_api.activity import record
7
from funkwhale_api.common import fields, permissions
8 9
from funkwhale_api.music.models import Track
from funkwhale_api.music import utils as music_utils
Eliot Berriot's avatar
Eliot Berriot committed
10
from . import models, serializers
11

12 13

class ListeningViewSet(
14 15 16 17
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet,
Eliot Berriot's avatar
Eliot Berriot committed
18
):
19 20

    serializer_class = serializers.ListeningSerializer
21
    queryset = models.Listening.objects.all().select_related("user")
22 23 24 25 26 27 28 29 30 31 32
    permission_classes = [
        permissions.ConditionalAuthentication,
        permissions.OwnerPermission,
        IsAuthenticatedOrReadOnly,
    ]
    owner_checks = ["write"]

    def get_serializer_class(self):
        if self.request.method.lower() in ["head", "get", "options"]:
            return serializers.ListeningSerializer
        return serializers.ListeningWriteSerializer
33

34 35
    def perform_create(self, serializer):
        r = super().perform_create(serializer)
36
        record.send(serializer.instance)
37 38
        return r

39 40
    def get_queryset(self):
        queryset = super().get_queryset()
41
        queryset = queryset.filter(
42 43
            fields.privacy_level_query(self.request.user, "user__privacy_level")
        )
44
        tracks = Track.objects.with_playable_uploads(
45 46 47
            music_utils.get_actor_from_request(self.request)
        ).select_related("artist", "album__artist")
        return queryset.prefetch_related(Prefetch("track", queryset=tracks))
48 49 50

    def get_serializer_context(self):
        context = super().get_serializer_context()
Eliot Berriot's avatar
Eliot Berriot committed
51
        context["user"] = self.request.user
52
        return context