views.py 19.2 KB
Newer Older
1 2
import datetime

3
from django.conf import settings
4
from django.utils import timezone
5 6
from rest_framework import exceptions
from rest_framework import permissions as rest_permissions
Agate's avatar
Agate committed
7
from rest_framework import renderers, response, viewsets
8 9 10
from rest_framework.decorators import list_route
from rest_framework.serializers import ValidationError

11
from funkwhale_api.activity import record
12
from funkwhale_api.common import preferences
13
from funkwhale_api.favorites.models import TrackFavorite
14
from funkwhale_api.music import models as music_models
15
from funkwhale_api.music import utils
16
from funkwhale_api.music import views as music_views
17
from funkwhale_api.playlists import models as playlists_models
Agate's avatar
Agate committed
18
from funkwhale_api.users import models as users_models
19

Agate's avatar
Agate committed
20
from . import authentication, filters, negotiation, serializers
21 22


23 24 25
def find_object(
    queryset, model_field="pk", field="id", cast=int, filter_playable=False
):
26 27 28 29 30 31
    def decorator(func):
        def inner(self, request, *args, **kwargs):
            data = request.GET or request.POST
            try:
                raw_value = data[field]
            except KeyError:
Agate's avatar
Agate committed
32 33 34 35 36 37 38 39
                return response.Response(
                    {
                        "error": {
                            "code": 10,
                            "message": "required parameter '{}' not present".format(
                                field
                            ),
                        }
40
                    }
Agate's avatar
Agate committed
41
                )
42 43
            try:
                value = cast(raw_value)
44
            except (ValueError, TypeError, ValidationError):
Agate's avatar
Agate committed
45 46 47 48 49 50
                return response.Response(
                    {
                        "error": {
                            "code": 0,
                            "message": 'For input string "{}"'.format(raw_value),
                        }
51
                    }
Agate's avatar
Agate committed
52
                )
53
            qs = queryset
Agate's avatar
Agate committed
54
            if hasattr(qs, "__call__"):
55
                qs = qs(request)
56 57 58 59 60

            if filter_playable:
                actor = utils.get_actor_from_request(request)
                qs = qs.playable_by(actor).distinct()

61
            try:
62 63
                obj = qs.get(**{model_field: value})
            except qs.model.DoesNotExist:
Agate's avatar
Agate committed
64 65 66 67 68 69 70 71
                return response.Response(
                    {
                        "error": {
                            "code": 70,
                            "message": "{} not found".format(
                                qs.model.__class__.__name__
                            ),
                        }
72
                    }
Agate's avatar
Agate committed
73 74
                )
            kwargs["obj"] = obj
75
            return func(self, request, *args, **kwargs)
Agate's avatar
Agate committed
76

77
        return inner
Agate's avatar
Agate committed
78

79 80 81 82 83 84 85 86
    return decorator


class SubsonicViewSet(viewsets.GenericViewSet):
    content_negotiation_class = negotiation.SubsonicContentNegociation
    authentication_classes = [authentication.SubsonicAuthentication]
    permissions_classes = [rest_permissions.IsAuthenticated]

87
    def dispatch(self, request, *args, **kwargs):
Agate's avatar
Agate committed
88
        if not preferences.get("subsonic__enabled"):
89 90
            r = response.Response({}, status=405)
            r.accepted_renderer = renderers.JSONRenderer()
Agate's avatar
Agate committed
91
            r.accepted_media_type = "application/json"
92 93 94 95
            r.renderer_context = {}
            return r
        return super().dispatch(request, *args, **kwargs)

96 97 98
    def handle_exception(self, exc):
        # subsonic API sends 200 status code with custom error
        # codes in the payload
Agate's avatar
Agate committed
99 100
        mapping = {exceptions.AuthenticationFailed: (40, "Wrong username or password.")}
        payload = {"status": "failed"}
101
        if exc.__class__ in mapping:
102 103
            code, message = mapping[exc.__class__]
        else:
104
            return super().handle_exception(exc)
Agate's avatar
Agate committed
105
        payload["error"] = {"code": code, "message": message}
106 107 108

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
109
    @list_route(methods=["get", "post"], permission_classes=[])
110
    def ping(self, request, *args, **kwargs):
Agate's avatar
Agate committed
111
        data = {"status": "ok", "version": "1.16.0"}
112 113
        return response.Response(data, status=200)

114
    @list_route(
Agate's avatar
Agate committed
115 116
        methods=["get", "post"],
        url_name="get_license",
117
        permissions_classes=[],
Agate's avatar
Agate committed
118 119
        url_path="getLicense",
    )
120 121 122
    def get_license(self, request, *args, **kwargs):
        now = timezone.now()
        data = {
Agate's avatar
Agate committed
123 124 125 126 127 128 129
            "status": "ok",
            "version": "1.16.0",
            "license": {
                "valid": "true",
                "email": "valid@valid.license",
                "licenseExpires": now + datetime.timedelta(days=365),
            },
130 131 132
        }
        return response.Response(data, status=200)

Agate's avatar
Agate committed
133
    @list_route(methods=["get", "post"], url_name="get_artists", url_path="getArtists")
134
    def get_artists(self, request, *args, **kwargs):
135 136 137
        artists = music_models.Artist.objects.all().playable_by(
            utils.get_actor_from_request(request)
        )
138
        data = serializers.GetArtistsSerializer(artists).data
Agate's avatar
Agate committed
139
        payload = {"artists": data}
140 141 142

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
143
    @list_route(methods=["get", "post"], url_name="get_indexes", url_path="getIndexes")
144
    def get_indexes(self, request, *args, **kwargs):
145 146 147
        artists = music_models.Artist.objects.all().playable_by(
            utils.get_actor_from_request(request)
        )
148
        data = serializers.GetArtistsSerializer(artists).data
Agate's avatar
Agate committed
149
        payload = {"indexes": data}
150 151 152

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
153
    @list_route(methods=["get", "post"], url_name="get_artist", url_path="getArtist")
154
    @find_object(music_models.Artist.objects.all(), filter_playable=True)
155
    def get_artist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
156
        artist = kwargs.pop("obj")
157
        data = serializers.GetArtistSerializer(artist).data
Agate's avatar
Agate committed
158
        payload = {"artist": data}
159 160 161

        return response.Response(payload, status=200)

162
    @list_route(methods=["get", "post"], url_name="get_song", url_path="getSong")
163
    @find_object(music_models.Track.objects.all(), filter_playable=True)
164 165 166 167 168 169 170
    def get_song(self, request, *args, **kwargs):
        track = kwargs.pop("obj")
        data = serializers.GetSongSerializer(track).data
        payload = {"song": data}

        return response.Response(payload, status=200)

171
    @list_route(
Agate's avatar
Agate committed
172 173
        methods=["get", "post"], url_name="get_artist_info2", url_path="getArtistInfo2"
    )
174
    @find_object(music_models.Artist.objects.all(), filter_playable=True)
175
    def get_artist_info2(self, request, *args, **kwargs):
Agate's avatar
Agate committed
176
        payload = {"artist-info2": {}}
177 178 179

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
180
    @list_route(methods=["get", "post"], url_name="get_album", url_path="getAlbum")
181 182 183
    @find_object(
        music_models.Album.objects.select_related("artist"), filter_playable=True
    )
184
    def get_album(self, request, *args, **kwargs):
Agate's avatar
Agate committed
185
        album = kwargs.pop("obj")
186
        data = serializers.GetAlbumSerializer(album).data
Agate's avatar
Agate committed
187
        payload = {"album": data}
188 189
        return response.Response(payload, status=200)

Agate's avatar
Agate committed
190
    @list_route(methods=["get", "post"], url_name="stream", url_path="stream")
191
    @find_object(music_models.Track.objects.all(), filter_playable=True)
192
    def stream(self, request, *args, **kwargs):
Agate's avatar
Agate committed
193
        track = kwargs.pop("obj")
Agate's avatar
Agate committed
194 195 196
        queryset = track.uploads.select_related("track__album__artist", "track__artist")
        upload = queryset.first()
        if not upload:
197
            return response.Response(status=404)
Agate's avatar
Agate committed
198
        return music_views.handle_serve(upload=upload, user=request.user)
199

Agate's avatar
Agate committed
200 201
    @list_route(methods=["get", "post"], url_name="star", url_path="star")
    @find_object(music_models.Track.objects.all())
202
    def star(self, request, *args, **kwargs):
Agate's avatar
Agate committed
203
        track = kwargs.pop("obj")
204
        TrackFavorite.add(user=request.user, track=track)
Agate's avatar
Agate committed
205
        return response.Response({"status": "ok"})
206

Agate's avatar
Agate committed
207 208
    @list_route(methods=["get", "post"], url_name="unstar", url_path="unstar")
    @find_object(music_models.Track.objects.all())
209
    def unstar(self, request, *args, **kwargs):
Agate's avatar
Agate committed
210
        track = kwargs.pop("obj")
211
        request.user.track_favorites.filter(track=track).delete()
Agate's avatar
Agate committed
212
        return response.Response({"status": "ok"})
213 214

    @list_route(
Agate's avatar
Agate committed
215 216
        methods=["get", "post"], url_name="get_starred2", url_path="getStarred2"
    )
217 218
    def get_starred2(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
Agate's avatar
Agate committed
219
        data = {"starred2": {"song": serializers.get_starred_tracks_data(favorites)}}
220 221
        return response.Response(data)

Agate's avatar
Agate committed
222
    @list_route(methods=["get", "post"], url_name="get_starred", url_path="getStarred")
223 224
    def get_starred(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
Agate's avatar
Agate committed
225
        data = {"starred": {"song": serializers.get_starred_tracks_data(favorites)}}
226 227 228
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
229 230
        methods=["get", "post"], url_name="get_album_list2", url_path="getAlbumList2"
    )
231
    def get_album_list2(self, request, *args, **kwargs):
232 233 234
        queryset = music_models.Album.objects.with_tracks_count().order_by(
            "artist__name"
        )
235 236 237
        data = request.GET or request.POST
        filterset = filters.AlbumList2FilterSet(data, queryset=queryset)
        queryset = filterset.qs
238 239 240
        actor = utils.get_actor_from_request(request)
        queryset = queryset.playable_by(actor)

241
        try:
Agate's avatar
Agate committed
242
            offset = int(data["offset"])
243 244 245 246
        except (TypeError, KeyError, ValueError):
            offset = 0

        try:
Agate's avatar
Agate committed
247
            size = int(data["size"])
248 249 250 251
        except (TypeError, KeyError, ValueError):
            size = 50

        size = min(size, 500)
252
        queryset = queryset[offset : offset + size]
Agate's avatar
Agate committed
253
        data = {"albumList2": {"album": serializers.get_album_list2_data(queryset)}}
254 255
        return response.Response(data)

Agate's avatar
Agate committed
256
    @list_route(methods=["get", "post"], url_name="search3", url_path="search3")
257 258
    def search3(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
259
        query = str(data.get("query", "")).replace("*", "")
260
        actor = utils.get_actor_from_request(request)
261 262
        conf = [
            {
Agate's avatar
Agate committed
263 264 265 266 267 268
                "subsonic": "artist",
                "search_fields": ["name"],
                "queryset": (
                    music_models.Artist.objects.with_albums_count().values(
                        "id", "_albums_count", "name"
                    )
269
                ),
Agate's avatar
Agate committed
270
                "serializer": lambda qs: [serializers.get_artist_data(a) for a in qs],
271 272
            },
            {
Agate's avatar
Agate committed
273 274 275 276 277 278
                "subsonic": "album",
                "search_fields": ["title"],
                "queryset": (
                    music_models.Album.objects.with_tracks_count().select_related(
                        "artist"
                    )
279
                ),
Agate's avatar
Agate committed
280
                "serializer": serializers.get_album_list2_data,
281 282
            },
            {
Agate's avatar
Agate committed
283 284 285
                "subsonic": "song",
                "search_fields": ["title"],
                "queryset": (
Agate's avatar
Agate committed
286 287 288
                    music_models.Track.objects.prefetch_related(
                        "uploads"
                    ).select_related("album__artist")
289
                ),
Agate's avatar
Agate committed
290
                "serializer": serializers.get_song_list_data,
291 292
            },
        ]
Agate's avatar
Agate committed
293
        payload = {"searchResult3": {}}
294
        for c in conf:
Agate's avatar
Agate committed
295 296
            offsetKey = "{}Offset".format(c["subsonic"])
            countKey = "{}Count".format(c["subsonic"])
297 298 299 300 301 302 303 304 305 306 307
            try:
                offset = int(data[offsetKey])
            except (TypeError, KeyError, ValueError):
                offset = 0

            try:
                size = int(data[countKey])
            except (TypeError, KeyError, ValueError):
                size = 20

            size = min(size, 100)
Agate's avatar
Agate committed
308
            queryset = c["queryset"]
309
            if query:
Agate's avatar
Agate committed
310 311
                queryset = c["queryset"].filter(
                    utils.get_query(query, c["search_fields"])
312
                )
313
            queryset = queryset.playable_by(actor)
314
            queryset = queryset[offset : offset + size]
Agate's avatar
Agate committed
315
            payload["searchResult3"][c["subsonic"]] = c["serializer"](queryset)
316
        return response.Response(payload)
317 318

    @list_route(
Agate's avatar
Agate committed
319 320
        methods=["get", "post"], url_name="get_playlists", url_path="getPlaylists"
    )
321
    def get_playlists(self, request, *args, **kwargs):
Agate's avatar
Agate committed
322
        playlists = request.user.playlists.with_tracks_count().select_related("user")
323
        data = {
Agate's avatar
Agate committed
324 325
            "playlists": {
                "playlist": [serializers.get_playlist_data(p) for p in playlists]
326 327 328 329 330
            }
        }
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
331 332 333
        methods=["get", "post"], url_name="get_playlist", url_path="getPlaylist"
    )
    @find_object(playlists_models.Playlist.objects.with_tracks_count())
334
    def get_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
335 336
        playlist = kwargs.pop("obj")
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
337 338 339
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
340 341 342
        methods=["get", "post"], url_name="update_playlist", url_path="updatePlaylist"
    )
    @find_object(lambda request: request.user.playlists.all(), field="playlistId")
343
    def update_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
344
        playlist = kwargs.pop("obj")
345
        data = request.GET or request.POST
Agate's avatar
Agate committed
346
        new_name = data.get("name", "")
347 348
        if new_name:
            playlist.name = new_name
Agate's avatar
Agate committed
349
            playlist.save(update_fields=["name", "modification_date"])
350
        try:
Agate's avatar
Agate committed
351
            to_remove = int(data["songIndexToRemove"])
352 353 354 355 356 357 358 359
            plt = playlist.playlist_tracks.get(index=to_remove)
        except (TypeError, ValueError, KeyError):
            pass
        except playlists_models.PlaylistTrack.DoesNotExist:
            pass
        else:
            plt.delete(update_indexes=True)

360
        ids = []
Agate's avatar
Agate committed
361
        for i in data.getlist("songIdToAdd"):
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            try:
                ids.append(int(i))
            except (TypeError, ValueError):
                pass
        if ids:
            tracks = music_models.Track.objects.filter(pk__in=ids)
            by_id = {t.id: t for t in tracks}
            sorted_tracks = []
            for i in ids:
                try:
                    sorted_tracks.append(by_id[i])
                except KeyError:
                    pass
            if sorted_tracks:
                playlist.insert_many(sorted_tracks)

Agate's avatar
Agate committed
378
        data = {"status": "ok"}
379 380 381
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
382 383 384
        methods=["get", "post"], url_name="delete_playlist", url_path="deletePlaylist"
    )
    @find_object(lambda request: request.user.playlists.all())
385
    def delete_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
386
        playlist = kwargs.pop("obj")
387
        playlist.delete()
Agate's avatar
Agate committed
388
        data = {"status": "ok"}
389 390 391
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
392 393
        methods=["get", "post"], url_name="create_playlist", url_path="createPlaylist"
    )
394 395
    def create_playlist(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
396
        name = data.get("name", "")
397
        if not name:
Agate's avatar
Agate committed
398 399 400 401 402 403
            return response.Response(
                {
                    "error": {
                        "code": 10,
                        "message": "Playlist ID or name must be specified.",
                    }
404
                }
Agate's avatar
Agate committed
405
            )
406

Agate's avatar
Agate committed
407
        playlist = request.user.playlists.create(name=name)
408
        ids = []
Agate's avatar
Agate committed
409
        for i in data.getlist("songId"):
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            try:
                ids.append(int(i))
            except (TypeError, ValueError):
                pass

        if ids:
            tracks = music_models.Track.objects.filter(pk__in=ids)
            by_id = {t.id: t for t in tracks}
            sorted_tracks = []
            for i in ids:
                try:
                    sorted_tracks.append(by_id[i])
                except KeyError:
                    pass
            if sorted_tracks:
                playlist.insert_many(sorted_tracks)
Agate's avatar
Agate committed
426 427
        playlist = request.user.playlists.with_tracks_count().get(pk=playlist.pk)
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
428
        return response.Response(data)
429

Agate's avatar
Agate committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    @list_route(methods=["get", "post"], url_name="get_avatar", url_path="getAvatar")
    @find_object(
        queryset=users_models.User.objects.exclude(avatar=None).exclude(avatar=""),
        model_field="username__iexact",
        field="username",
        cast=str,
    )
    def get_avatar(self, request, *args, **kwargs):
        user = kwargs.pop("obj")
        mapping = {"nginx": "X-Accel-Redirect", "apache2": "X-Sendfile"}
        path = music_views.get_file_path(user.avatar)
        file_header = mapping[settings.REVERSE_PROXY_TYPE]
        # let the proxy set the content-type
        r = response.Response({}, content_type="")
        r[file_header] = path
        return r

Agate's avatar
Agate committed
447 448 449 450 451 452 453 454 455 456 457
    @list_route(methods=["get", "post"], url_name="get_user", url_path="getUser")
    @find_object(
        queryset=lambda request: users_models.User.objects.filter(pk=request.user.pk),
        model_field="username__iexact",
        field="username",
        cast=str,
    )
    def get_user(self, request, *args, **kwargs):
        data = {"user": serializers.get_user_detail_data(request.user)}
        return response.Response(data)

458
    @list_route(
Agate's avatar
Agate committed
459 460 461 462
        methods=["get", "post"],
        url_name="get_music_folders",
        url_path="getMusicFolders",
    )
463
    def get_music_folders(self, request, *args, **kwargs):
Agate's avatar
Agate committed
464
        data = {"musicFolders": {"musicFolder": [{"id": 1, "name": "Music"}]}}
465
        return response.Response(data)
466 467

    @list_route(
Agate's avatar
Agate committed
468 469
        methods=["get", "post"], url_name="get_cover_art", url_path="getCoverArt"
    )
470 471
    def get_cover_art(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
472
        id = data.get("id", "")
473
        if not id:
Agate's avatar
Agate committed
474 475 476
            return response.Response(
                {"error": {"code": 10, "message": "cover art ID must be specified."}}
            )
477

Agate's avatar
Agate committed
478
        if id.startswith("al-"):
479
            try:
Agate's avatar
Agate committed
480 481 482 483 484 485
                album_id = int(id.replace("al-", ""))
                album = (
                    music_models.Album.objects.exclude(cover__isnull=True)
                    .exclude(cover="")
                    .get(pk=album_id)
                )
486
            except (TypeError, ValueError, music_models.Album.DoesNotExist):
Agate's avatar
Agate committed
487 488 489
                return response.Response(
                    {"error": {"code": 70, "message": "cover art not found."}}
                )
490 491
            cover = album.cover
        else:
Agate's avatar
Agate committed
492 493 494
            return response.Response(
                {"error": {"code": 70, "message": "cover art not found."}}
            )
495

Agate's avatar
Agate committed
496
        mapping = {"nginx": "X-Accel-Redirect", "apache2": "X-Sendfile"}
497 498 499
        path = music_views.get_file_path(cover)
        file_header = mapping[settings.REVERSE_PROXY_TYPE]
        # let the proxy set the content-type
Agate's avatar
Agate committed
500
        r = response.Response({}, content_type="")
501
        r[file_header] = path
502 503
        return r

Agate's avatar
Agate committed
504
    @list_route(methods=["get", "post"], url_name="scrobble", url_path="scrobble")
505 506 507
    def scrobble(self, request, *args, **kwargs):
        data = request.GET or request.POST
        serializer = serializers.ScrobbleSerializer(
Agate's avatar
Agate committed
508 509
            data=data, context={"user": request.user}
        )
510
        if not serializer.is_valid():
Agate's avatar
Agate committed
511 512 513 514
            return response.Response(
                {"error": {"code": 0, "message": "Invalid payload"}}
            )
        if serializer.validated_data["submission"]:
515 516
            listening = serializer.save()
            record.send(listening)
517
        return response.Response({})