views.py 17.4 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
18

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


Agate's avatar
Agate committed
22
def find_object(queryset, model_field="pk", field="id", cast=int):
23 24 25 26 27 28
    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
29 30 31 32 33 34 35 36
                return response.Response(
                    {
                        "error": {
                            "code": 10,
                            "message": "required parameter '{}' not present".format(
                                field
                            ),
                        }
37
                    }
Agate's avatar
Agate committed
38
                )
39 40
            try:
                value = cast(raw_value)
41
            except (ValueError, TypeError, ValidationError):
Agate's avatar
Agate committed
42 43 44 45 46 47
                return response.Response(
                    {
                        "error": {
                            "code": 0,
                            "message": 'For input string "{}"'.format(raw_value),
                        }
48
                    }
Agate's avatar
Agate committed
49
                )
50
            qs = queryset
Agate's avatar
Agate committed
51
            if hasattr(qs, "__call__"):
52
                qs = qs(request)
53
            try:
54 55
                obj = qs.get(**{model_field: value})
            except qs.model.DoesNotExist:
Agate's avatar
Agate committed
56 57 58 59 60 61 62 63
                return response.Response(
                    {
                        "error": {
                            "code": 70,
                            "message": "{} not found".format(
                                qs.model.__class__.__name__
                            ),
                        }
64
                    }
Agate's avatar
Agate committed
65 66
                )
            kwargs["obj"] = obj
67
            return func(self, request, *args, **kwargs)
Agate's avatar
Agate committed
68

69
        return inner
Agate's avatar
Agate committed
70

71 72 73 74 75 76 77 78
    return decorator


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

79
    def dispatch(self, request, *args, **kwargs):
Agate's avatar
Agate committed
80
        if not preferences.get("subsonic__enabled"):
81 82
            r = response.Response({}, status=405)
            r.accepted_renderer = renderers.JSONRenderer()
Agate's avatar
Agate committed
83
            r.accepted_media_type = "application/json"
84 85 86 87
            r.renderer_context = {}
            return r
        return super().dispatch(request, *args, **kwargs)

88 89 90
    def handle_exception(self, exc):
        # subsonic API sends 200 status code with custom error
        # codes in the payload
Agate's avatar
Agate committed
91 92
        mapping = {exceptions.AuthenticationFailed: (40, "Wrong username or password.")}
        payload = {"status": "failed"}
93
        if exc.__class__ in mapping:
94 95
            code, message = mapping[exc.__class__]
        else:
96
            return super().handle_exception(exc)
Agate's avatar
Agate committed
97
        payload["error"] = {"code": code, "message": message}
98 99 100

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
101
    @list_route(methods=["get", "post"], permission_classes=[])
102
    def ping(self, request, *args, **kwargs):
Agate's avatar
Agate committed
103
        data = {"status": "ok", "version": "1.16.0"}
104 105
        return response.Response(data, status=200)

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

Agate's avatar
Agate committed
125
    @list_route(methods=["get", "post"], url_name="get_artists", url_path="getArtists")
126 127 128
    def get_artists(self, request, *args, **kwargs):
        artists = music_models.Artist.objects.all()
        data = serializers.GetArtistsSerializer(artists).data
Agate's avatar
Agate committed
129
        payload = {"artists": data}
130 131 132

        return response.Response(payload, status=200)

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

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
141
    @list_route(methods=["get", "post"], url_name="get_artist", url_path="getArtist")
142 143
    @find_object(music_models.Artist.objects.all())
    def get_artist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
144
        artist = kwargs.pop("obj")
145
        data = serializers.GetArtistSerializer(artist).data
Agate's avatar
Agate committed
146
        payload = {"artist": data}
147 148 149

        return response.Response(payload, status=200)

150 151 152 153 154 155 156 157 158
    @list_route(methods=["get", "post"], url_name="get_song", url_path="getSong")
    @find_object(music_models.Track.objects.all())
    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)

159
    @list_route(
Agate's avatar
Agate committed
160 161
        methods=["get", "post"], url_name="get_artist_info2", url_path="getArtistInfo2"
    )
162 163
    @find_object(music_models.Artist.objects.all())
    def get_artist_info2(self, request, *args, **kwargs):
Agate's avatar
Agate committed
164
        payload = {"artist-info2": {}}
165 166 167

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
168 169
    @list_route(methods=["get", "post"], url_name="get_album", url_path="getAlbum")
    @find_object(music_models.Album.objects.select_related("artist"))
170
    def get_album(self, request, *args, **kwargs):
Agate's avatar
Agate committed
171
        album = kwargs.pop("obj")
172
        data = serializers.GetAlbumSerializer(album).data
Agate's avatar
Agate committed
173
        payload = {"album": data}
174 175
        return response.Response(payload, status=200)

Agate's avatar
Agate committed
176 177
    @list_route(methods=["get", "post"], url_name="stream", url_path="stream")
    @find_object(music_models.Track.objects.all())
178
    def stream(self, request, *args, **kwargs):
Agate's avatar
Agate committed
179
        track = kwargs.pop("obj")
Agate's avatar
Agate committed
180 181 182
        queryset = track.uploads.select_related("track__album__artist", "track__artist")
        upload = queryset.first()
        if not upload:
183
            return response.Response(status=404)
Agate's avatar
Agate committed
184
        return music_views.handle_serve(upload=upload, user=request.user)
185

Agate's avatar
Agate committed
186 187
    @list_route(methods=["get", "post"], url_name="star", url_path="star")
    @find_object(music_models.Track.objects.all())
188
    def star(self, request, *args, **kwargs):
Agate's avatar
Agate committed
189
        track = kwargs.pop("obj")
190
        TrackFavorite.add(user=request.user, track=track)
Agate's avatar
Agate committed
191
        return response.Response({"status": "ok"})
192

Agate's avatar
Agate committed
193 194
    @list_route(methods=["get", "post"], url_name="unstar", url_path="unstar")
    @find_object(music_models.Track.objects.all())
195
    def unstar(self, request, *args, **kwargs):
Agate's avatar
Agate committed
196
        track = kwargs.pop("obj")
197
        request.user.track_favorites.filter(track=track).delete()
Agate's avatar
Agate committed
198
        return response.Response({"status": "ok"})
199 200

    @list_route(
Agate's avatar
Agate committed
201 202
        methods=["get", "post"], url_name="get_starred2", url_path="getStarred2"
    )
203 204
    def get_starred2(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
Agate's avatar
Agate committed
205
        data = {"starred2": {"song": serializers.get_starred_tracks_data(favorites)}}
206 207
        return response.Response(data)

Agate's avatar
Agate committed
208
    @list_route(methods=["get", "post"], url_name="get_starred", url_path="getStarred")
209 210
    def get_starred(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
Agate's avatar
Agate committed
211
        data = {"starred": {"song": serializers.get_starred_tracks_data(favorites)}}
212 213 214
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
215 216
        methods=["get", "post"], url_name="get_album_list2", url_path="getAlbumList2"
    )
217
    def get_album_list2(self, request, *args, **kwargs):
218 219 220
        queryset = music_models.Album.objects.with_tracks_count().order_by(
            "artist__name"
        )
221 222 223 224
        data = request.GET or request.POST
        filterset = filters.AlbumList2FilterSet(data, queryset=queryset)
        queryset = filterset.qs
        try:
Agate's avatar
Agate committed
225
            offset = int(data["offset"])
226 227 228 229
        except (TypeError, KeyError, ValueError):
            offset = 0

        try:
Agate's avatar
Agate committed
230
            size = int(data["size"])
231 232 233 234
        except (TypeError, KeyError, ValueError):
            size = 50

        size = min(size, 500)
235
        queryset = queryset[offset : offset + size]
Agate's avatar
Agate committed
236
        data = {"albumList2": {"album": serializers.get_album_list2_data(queryset)}}
237 238
        return response.Response(data)

Agate's avatar
Agate committed
239
    @list_route(methods=["get", "post"], url_name="search3", url_path="search3")
240 241
    def search3(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
242
        query = str(data.get("query", "")).replace("*", "")
243 244
        conf = [
            {
Agate's avatar
Agate committed
245 246 247 248 249 250
                "subsonic": "artist",
                "search_fields": ["name"],
                "queryset": (
                    music_models.Artist.objects.with_albums_count().values(
                        "id", "_albums_count", "name"
                    )
251
                ),
Agate's avatar
Agate committed
252
                "serializer": lambda qs: [serializers.get_artist_data(a) for a in qs],
253 254
            },
            {
Agate's avatar
Agate committed
255 256 257 258 259 260
                "subsonic": "album",
                "search_fields": ["title"],
                "queryset": (
                    music_models.Album.objects.with_tracks_count().select_related(
                        "artist"
                    )
261
                ),
Agate's avatar
Agate committed
262
                "serializer": serializers.get_album_list2_data,
263 264
            },
            {
Agate's avatar
Agate committed
265 266 267
                "subsonic": "song",
                "search_fields": ["title"],
                "queryset": (
Agate's avatar
Agate committed
268 269 270
                    music_models.Track.objects.prefetch_related(
                        "uploads"
                    ).select_related("album__artist")
271
                ),
Agate's avatar
Agate committed
272
                "serializer": serializers.get_song_list_data,
273 274
            },
        ]
Agate's avatar
Agate committed
275
        payload = {"searchResult3": {}}
276
        for c in conf:
Agate's avatar
Agate committed
277 278
            offsetKey = "{}Offset".format(c["subsonic"])
            countKey = "{}Count".format(c["subsonic"])
279 280 281 282 283 284 285 286 287 288 289
            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
290
            queryset = c["queryset"]
291
            if query:
Agate's avatar
Agate committed
292 293
                queryset = c["queryset"].filter(
                    utils.get_query(query, c["search_fields"])
294
                )
295
            queryset = queryset[offset : offset + size]
Agate's avatar
Agate committed
296
            payload["searchResult3"][c["subsonic"]] = c["serializer"](queryset)
297
        return response.Response(payload)
298 299

    @list_route(
Agate's avatar
Agate committed
300 301
        methods=["get", "post"], url_name="get_playlists", url_path="getPlaylists"
    )
302
    def get_playlists(self, request, *args, **kwargs):
Agate's avatar
Agate committed
303
        playlists = request.user.playlists.with_tracks_count().select_related("user")
304
        data = {
Agate's avatar
Agate committed
305 306
            "playlists": {
                "playlist": [serializers.get_playlist_data(p) for p in playlists]
307 308 309 310 311
            }
        }
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
312 313 314
        methods=["get", "post"], url_name="get_playlist", url_path="getPlaylist"
    )
    @find_object(playlists_models.Playlist.objects.with_tracks_count())
315
    def get_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
316 317
        playlist = kwargs.pop("obj")
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
318 319 320
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
321 322 323
        methods=["get", "post"], url_name="update_playlist", url_path="updatePlaylist"
    )
    @find_object(lambda request: request.user.playlists.all(), field="playlistId")
324
    def update_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
325
        playlist = kwargs.pop("obj")
326
        data = request.GET or request.POST
Agate's avatar
Agate committed
327
        new_name = data.get("name", "")
328 329
        if new_name:
            playlist.name = new_name
Agate's avatar
Agate committed
330
            playlist.save(update_fields=["name", "modification_date"])
331
        try:
Agate's avatar
Agate committed
332
            to_remove = int(data["songIndexToRemove"])
333 334 335 336 337 338 339 340
            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)

341
        ids = []
Agate's avatar
Agate committed
342
        for i in data.getlist("songIdToAdd"):
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            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
359
        data = {"status": "ok"}
360 361 362
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
363 364 365
        methods=["get", "post"], url_name="delete_playlist", url_path="deletePlaylist"
    )
    @find_object(lambda request: request.user.playlists.all())
366
    def delete_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
367
        playlist = kwargs.pop("obj")
368
        playlist.delete()
Agate's avatar
Agate committed
369
        data = {"status": "ok"}
370 371 372
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
373 374
        methods=["get", "post"], url_name="create_playlist", url_path="createPlaylist"
    )
375 376
    def create_playlist(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
377
        name = data.get("name", "")
378
        if not name:
Agate's avatar
Agate committed
379 380 381 382 383 384
            return response.Response(
                {
                    "error": {
                        "code": 10,
                        "message": "Playlist ID or name must be specified.",
                    }
385
                }
Agate's avatar
Agate committed
386
            )
387

Agate's avatar
Agate committed
388
        playlist = request.user.playlists.create(name=name)
389
        ids = []
Agate's avatar
Agate committed
390
        for i in data.getlist("songId"):
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
            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
407 408
        playlist = request.user.playlists.with_tracks_count().get(pk=playlist.pk)
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
409
        return response.Response(data)
410 411

    @list_route(
Agate's avatar
Agate committed
412 413 414 415
        methods=["get", "post"],
        url_name="get_music_folders",
        url_path="getMusicFolders",
    )
416
    def get_music_folders(self, request, *args, **kwargs):
Agate's avatar
Agate committed
417
        data = {"musicFolders": {"musicFolder": [{"id": 1, "name": "Music"}]}}
418
        return response.Response(data)
419 420

    @list_route(
Agate's avatar
Agate committed
421 422
        methods=["get", "post"], url_name="get_cover_art", url_path="getCoverArt"
    )
423 424
    def get_cover_art(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
425
        id = data.get("id", "")
426
        if not id:
Agate's avatar
Agate committed
427 428 429
            return response.Response(
                {"error": {"code": 10, "message": "cover art ID must be specified."}}
            )
430

Agate's avatar
Agate committed
431
        if id.startswith("al-"):
432
            try:
Agate's avatar
Agate committed
433 434 435 436 437 438
                album_id = int(id.replace("al-", ""))
                album = (
                    music_models.Album.objects.exclude(cover__isnull=True)
                    .exclude(cover="")
                    .get(pk=album_id)
                )
439
            except (TypeError, ValueError, music_models.Album.DoesNotExist):
Agate's avatar
Agate committed
440 441 442
                return response.Response(
                    {"error": {"code": 70, "message": "cover art not found."}}
                )
443 444
            cover = album.cover
        else:
Agate's avatar
Agate committed
445 446 447
            return response.Response(
                {"error": {"code": 70, "message": "cover art not found."}}
            )
448

Agate's avatar
Agate committed
449
        mapping = {"nginx": "X-Accel-Redirect", "apache2": "X-Sendfile"}
450 451 452
        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
453
        r = response.Response({}, content_type="")
454
        r[file_header] = path
455 456
        return r

Agate's avatar
Agate committed
457
    @list_route(methods=["get", "post"], url_name="scrobble", url_path="scrobble")
458 459 460
    def scrobble(self, request, *args, **kwargs):
        data = request.GET or request.POST
        serializer = serializers.ScrobbleSerializer(
Agate's avatar
Agate committed
461 462
            data=data, context={"user": request.user}
        )
463
        if not serializer.is_valid():
Agate's avatar
Agate committed
464 465 466 467
            return response.Response(
                {"error": {"code": 0, "message": "Invalid payload"}}
            )
        if serializer.validated_data["submission"]:
468 469
            listening = serializer.save()
            record.send(listening)
470
        return response.Response({})