views.py 17 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 41
            try:
                value = cast(raw_value)
            except (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
    @list_route(
Agate's avatar
Agate committed
151 152
        methods=["get", "post"], url_name="get_artist_info2", url_path="getArtistInfo2"
    )
153 154
    @find_object(music_models.Artist.objects.all())
    def get_artist_info2(self, request, *args, **kwargs):
Agate's avatar
Agate committed
155
        payload = {"artist-info2": {}}
156 157 158

        return response.Response(payload, status=200)

Agate's avatar
Agate committed
159 160
    @list_route(methods=["get", "post"], url_name="get_album", url_path="getAlbum")
    @find_object(music_models.Album.objects.select_related("artist"))
161
    def get_album(self, request, *args, **kwargs):
Agate's avatar
Agate committed
162
        album = kwargs.pop("obj")
163
        data = serializers.GetAlbumSerializer(album).data
Agate's avatar
Agate committed
164
        payload = {"album": data}
165 166
        return response.Response(payload, status=200)

Agate's avatar
Agate committed
167 168
    @list_route(methods=["get", "post"], url_name="stream", url_path="stream")
    @find_object(music_models.Track.objects.all())
169
    def stream(self, request, *args, **kwargs):
Agate's avatar
Agate committed
170
        track = kwargs.pop("obj")
171
        queryset = track.files.select_related(
Agate's avatar
Agate committed
172
            "library_track", "track__album__artist", "track__artist"
173 174 175
        )
        track_file = queryset.first()
        if not track_file:
176
            return response.Response(status=404)
177
        return music_views.handle_serve(track_file)
178

Agate's avatar
Agate committed
179 180
    @list_route(methods=["get", "post"], url_name="star", url_path="star")
    @find_object(music_models.Track.objects.all())
181
    def star(self, request, *args, **kwargs):
Agate's avatar
Agate committed
182
        track = kwargs.pop("obj")
183
        TrackFavorite.add(user=request.user, track=track)
Agate's avatar
Agate committed
184
        return response.Response({"status": "ok"})
185

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

    @list_route(
Agate's avatar
Agate committed
194 195
        methods=["get", "post"], url_name="get_starred2", url_path="getStarred2"
    )
196 197
    def get_starred2(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
Agate's avatar
Agate committed
198
        data = {"starred2": {"song": serializers.get_starred_tracks_data(favorites)}}
199 200
        return response.Response(data)

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

    @list_route(
Agate's avatar
Agate committed
208 209
        methods=["get", "post"], url_name="get_album_list2", url_path="getAlbumList2"
    )
210 211 212 213 214 215
    def get_album_list2(self, request, *args, **kwargs):
        queryset = music_models.Album.objects.with_tracks_count()
        data = request.GET or request.POST
        filterset = filters.AlbumList2FilterSet(data, queryset=queryset)
        queryset = filterset.qs
        try:
Agate's avatar
Agate committed
216
            offset = int(data["offset"])
217 218 219 220
        except (TypeError, KeyError, ValueError):
            offset = 0

        try:
Agate's avatar
Agate committed
221
            size = int(data["size"])
222 223 224 225 226
        except (TypeError, KeyError, ValueError):
            size = 50

        size = min(size, 500)
        queryset = queryset[offset:size]
Agate's avatar
Agate committed
227
        data = {"albumList2": {"album": serializers.get_album_list2_data(queryset)}}
228 229
        return response.Response(data)

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

    @list_route(
Agate's avatar
Agate committed
291 292
        methods=["get", "post"], url_name="get_playlists", url_path="getPlaylists"
    )
293
    def get_playlists(self, request, *args, **kwargs):
Agate's avatar
Agate committed
294
        playlists = request.user.playlists.with_tracks_count().select_related("user")
295
        data = {
Agate's avatar
Agate committed
296 297
            "playlists": {
                "playlist": [serializers.get_playlist_data(p) for p in playlists]
298 299 300 301 302
            }
        }
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
303 304 305
        methods=["get", "post"], url_name="get_playlist", url_path="getPlaylist"
    )
    @find_object(playlists_models.Playlist.objects.with_tracks_count())
306
    def get_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
307 308
        playlist = kwargs.pop("obj")
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
309 310 311
        return response.Response(data)

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

332
        ids = []
Agate's avatar
Agate committed
333
        for i in data.getlist("songIdToAdd"):
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
            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
350
        data = {"status": "ok"}
351 352 353
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
354 355 356
        methods=["get", "post"], url_name="delete_playlist", url_path="deletePlaylist"
    )
    @find_object(lambda request: request.user.playlists.all())
357
    def delete_playlist(self, request, *args, **kwargs):
Agate's avatar
Agate committed
358
        playlist = kwargs.pop("obj")
359
        playlist.delete()
Agate's avatar
Agate committed
360
        data = {"status": "ok"}
361 362 363
        return response.Response(data)

    @list_route(
Agate's avatar
Agate committed
364 365
        methods=["get", "post"], url_name="create_playlist", url_path="createPlaylist"
    )
366 367
    def create_playlist(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
368
        name = data.get("name", "")
369
        if not name:
Agate's avatar
Agate committed
370 371 372 373 374 375
            return response.Response(
                {
                    "error": {
                        "code": 10,
                        "message": "Playlist ID or name must be specified.",
                    }
376
                }
Agate's avatar
Agate committed
377
            )
378

Agate's avatar
Agate committed
379
        playlist = request.user.playlists.create(name=name)
380
        ids = []
Agate's avatar
Agate committed
381
        for i in data.getlist("songId"):
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
            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
398 399
        playlist = request.user.playlists.with_tracks_count().get(pk=playlist.pk)
        data = {"playlist": serializers.get_playlist_detail_data(playlist)}
400
        return response.Response(data)
401 402

    @list_route(
Agate's avatar
Agate committed
403 404 405 406
        methods=["get", "post"],
        url_name="get_music_folders",
        url_path="getMusicFolders",
    )
407
    def get_music_folders(self, request, *args, **kwargs):
Agate's avatar
Agate committed
408
        data = {"musicFolders": {"musicFolder": [{"id": 1, "name": "Music"}]}}
409
        return response.Response(data)
410 411

    @list_route(
Agate's avatar
Agate committed
412 413
        methods=["get", "post"], url_name="get_cover_art", url_path="getCoverArt"
    )
414 415
    def get_cover_art(self, request, *args, **kwargs):
        data = request.GET or request.POST
Agate's avatar
Agate committed
416
        id = data.get("id", "")
417
        if not id:
Agate's avatar
Agate committed
418 419 420
            return response.Response(
                {"error": {"code": 10, "message": "cover art ID must be specified."}}
            )
421

Agate's avatar
Agate committed
422
        if id.startswith("al-"):
423
            try:
Agate's avatar
Agate committed
424 425 426 427 428 429
                album_id = int(id.replace("al-", ""))
                album = (
                    music_models.Album.objects.exclude(cover__isnull=True)
                    .exclude(cover="")
                    .get(pk=album_id)
                )
430
            except (TypeError, ValueError, music_models.Album.DoesNotExist):
Agate's avatar
Agate committed
431 432 433
                return response.Response(
                    {"error": {"code": 70, "message": "cover art not found."}}
                )
434 435
            cover = album.cover
        else:
Agate's avatar
Agate committed
436 437 438
            return response.Response(
                {"error": {"code": 70, "message": "cover art not found."}}
            )
439

Agate's avatar
Agate committed
440
        mapping = {"nginx": "X-Accel-Redirect", "apache2": "X-Sendfile"}
441 442 443
        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
444
        r = response.Response({}, content_type="")
445
        r[file_header] = path
446 447
        return r

Agate's avatar
Agate committed
448
    @list_route(methods=["get", "post"], url_name="scrobble", url_path="scrobble")
449 450 451
    def scrobble(self, request, *args, **kwargs):
        data = request.GET or request.POST
        serializer = serializers.ScrobbleSerializer(
Agate's avatar
Agate committed
452 453
            data=data, context={"user": request.user}
        )
454
        if not serializer.is_valid():
Agate's avatar
Agate committed
455 456 457 458
            return response.Response(
                {"error": {"code": 0, "message": "Invalid payload"}}
            )
        if serializer.validated_data["submission"]:
459 460
            l = serializer.save()
            record.send(l)
461
        return response.Response({})