views.py 18.2 KB
Newer Older
1 2
import datetime

3
from django.conf import settings
4 5
from django.utils import timezone

6 7
from rest_framework import exceptions
from rest_framework import permissions as rest_permissions
8
from rest_framework import renderers
9 10 11 12 13
from rest_framework import response
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.serializers import ValidationError

14
from funkwhale_api.common import preferences
15
from funkwhale_api.favorites.models import TrackFavorite
16
from funkwhale_api.music import models as music_models
17
from funkwhale_api.music import utils
18
from funkwhale_api.music import views as music_views
19
from funkwhale_api.playlists import models as playlists_models
20 21

from . import authentication
22
from . import filters
23 24 25 26 27 28 29 30 31 32 33 34
from . import negotiation
from . import serializers


def find_object(queryset, model_field='pk', field='id', cast=int):
    def decorator(func):
        def inner(self, request, *args, **kwargs):
            data = request.GET or request.POST
            try:
                raw_value = data[field]
            except KeyError:
                return response.Response({
35 36 37 38
                    'error': {
                        'code': 10,
                        'message': "required parameter '{}' not present".format(field)
                    }
39 40 41 42 43
                })
            try:
                value = cast(raw_value)
            except (TypeError, ValidationError):
                return response.Response({
44 45 46 47
                    'error': {
                        'code': 0,
                        'message': 'For input string "{}"'.format(raw_value)
                    }
48
                })
49 50 51
            qs = queryset
            if hasattr(qs, '__call__'):
                qs = qs(request)
52
            try:
53 54
                obj = qs.get(**{model_field: value})
            except qs.model.DoesNotExist:
55
                return response.Response({
56 57 58 59 60
                    'error': {
                        'code': 70,
                        'message': '{} not found'.format(
                            qs.model.__class__.__name__)
                    }
61 62 63 64 65 66 67 68 69 70 71 72
                })
            kwargs['obj'] = obj
            return func(self, request, *args, **kwargs)
        return inner
    return decorator


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

73 74 75 76 77 78 79 80 81
    def dispatch(self, request, *args, **kwargs):
        if not preferences.get('subsonic__enabled'):
            r = response.Response({}, status=405)
            r.accepted_renderer = renderers.JSONRenderer()
            r.accepted_media_type = 'application/json'
            r.renderer_context = {}
            return r
        return super().dispatch(request, *args, **kwargs)

82 83 84 85 86 87 88 89 90 91 92
    def handle_exception(self, exc):
        # subsonic API sends 200 status code with custom error
        # codes in the payload
        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 97 98 99 100
            return super().handle_exception(exc)
        payload['error'] = {
            'code': code,
            'message': message
        }
101 102 103 104 105 106 107 108 109 110 111 112 113

        return response.Response(payload, status=200)

    @list_route(
        methods=['get', 'post'],
        permission_classes=[])
    def ping(self, request, *args, **kwargs):
        data = {
            'status': 'ok',
            'version': '1.16.0'
        }
        return response.Response(data, status=200)

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

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

        return response.Response(payload, status=200)

145 146 147 148 149 150 151 152 153 154 155 156 157
    @list_route(
        methods=['get', 'post'],
        url_name='get_indexes',
        url_path='getIndexes')
    def get_indexes(self, request, *args, **kwargs):
        artists = music_models.Artist.objects.all()
        data = serializers.GetArtistsSerializer(artists).data
        payload = {
            'indexes': data
        }

        return response.Response(payload, status=200)

158 159 160 161 162 163 164 165 166 167 168 169 170 171
    @list_route(
        methods=['get', 'post'],
        url_name='get_artist',
        url_path='getArtist')
    @find_object(music_models.Artist.objects.all())
    def get_artist(self, request, *args, **kwargs):
        artist = kwargs.pop('obj')
        data = serializers.GetArtistSerializer(artist).data
        payload = {
            'artist': data
        }

        return response.Response(payload, status=200)

172 173 174 175 176 177 178 179 180 181 182 183 184
    @list_route(
        methods=['get', 'post'],
        url_name='get_artist_info2',
        url_path='getArtistInfo2')
    @find_object(music_models.Artist.objects.all())
    def get_artist_info2(self, request, *args, **kwargs):
        artist = kwargs.pop('obj')
        payload = {
            'artist-info2': {}
        }

        return response.Response(payload, status=200)

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    @list_route(
        methods=['get', 'post'],
        url_name='get_album',
        url_path='getAlbum')
    @find_object(
        music_models.Album.objects.select_related('artist'))
    def get_album(self, request, *args, **kwargs):
        album = kwargs.pop('obj')
        data = serializers.GetAlbumSerializer(album).data
        payload = {
            'album': data
        }
        return response.Response(payload, status=200)

    @list_route(
        methods=['get', 'post'],
        url_name='stream',
        url_path='stream')
    @find_object(
        music_models.Track.objects.all())
    def stream(self, request, *args, **kwargs):
        track = kwargs.pop('obj')
        queryset = track.files.select_related(
            'library_track',
            'track__album__artist',
            'track__artist',
        )
        track_file = queryset.first()
        if not track_file:
214
            return response.Response(status=404)
215
        return music_views.handle_serve(track_file)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

    @list_route(
        methods=['get', 'post'],
        url_name='star',
        url_path='star')
    @find_object(
        music_models.Track.objects.all())
    def star(self, request, *args, **kwargs):
        track = kwargs.pop('obj')
        TrackFavorite.add(user=request.user, track=track)
        return response.Response({'status': 'ok'})

    @list_route(
        methods=['get', 'post'],
        url_name='unstar',
        url_path='unstar')
    @find_object(
        music_models.Track.objects.all())
    def unstar(self, request, *args, **kwargs):
        track = kwargs.pop('obj')
        request.user.track_favorites.filter(track=track).delete()
        return response.Response({'status': 'ok'})

    @list_route(
        methods=['get', 'post'],
        url_name='get_starred2',
        url_path='getStarred2')
    def get_starred2(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
        data = {
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            'starred2': {
                'song': serializers.get_starred_tracks_data(favorites)
            }
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='get_starred',
        url_path='getStarred')
    def get_starred(self, request, *args, **kwargs):
        favorites = request.user.track_favorites.all()
        data = {
            'starred': {
                'song': serializers.get_starred_tracks_data(favorites)
            }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='get_album_list2',
        url_path='getAlbumList2')
    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:
            offset = int(data['offset'])
        except (TypeError, KeyError, ValueError):
            offset = 0

        try:
            size = int(data['size'])
        except (TypeError, KeyError, ValueError):
            size = 50

        size = min(size, 500)
        queryset = queryset[offset:size]
        data = {
            'albumList2': {
                'album': serializers.get_album_list2_data(queryset)
            }
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='search3',
        url_path='search3')
    def search3(self, request, *args, **kwargs):
        data = request.GET or request.POST
        query = str(data.get('query', '')).replace('*', '')
        conf = [
            {
                'subsonic': 'artist',
                'search_fields': ['name'],
                'queryset': (
                    music_models.Artist.objects
                                       .with_albums_count()
                                       .values('id', '_albums_count', 'name')
                ),
                'serializer': lambda qs: [
                    serializers.get_artist_data(a) for a in qs
                ]
            },
            {
                'subsonic': 'album',
                'search_fields': ['title'],
                'queryset': (
                    music_models.Album.objects
                                .with_tracks_count()
                                .select_related('artist')
                ),
                'serializer': serializers.get_album_list2_data,
            },
            {
                'subsonic': 'song',
                'search_fields': ['title'],
                'queryset': (
                    music_models.Track.objects
                                .prefetch_related('files')
                                .select_related('album__artist')
                ),
                'serializer': serializers.get_song_list_data,
            },
        ]
        payload = {
            'searchResult3': {}
        }
        for c in conf:
            offsetKey = '{}Offset'.format(c['subsonic'])
            countKey = '{}Count'.format(c['subsonic'])
            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)
            queryset = c['queryset']
            if query:
                queryset = c['queryset'].filter(
                    utils.get_query(query, c['search_fields'])
                )
            queryset = queryset[offset:size]
            payload['searchResult3'][c['subsonic']] = c['serializer'](queryset)
        return response.Response(payload)
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

    @list_route(
        methods=['get', 'post'],
        url_name='get_playlists',
        url_path='getPlaylists')
    def get_playlists(self, request, *args, **kwargs):
        playlists = request.user.playlists.with_tracks_count().select_related(
            'user'
        )
        data = {
            'playlists': {
                'playlist': [
                    serializers.get_playlist_data(p) for p in playlists]
            }
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='get_playlist',
        url_path='getPlaylist')
    @find_object(
        playlists_models.Playlist.objects.with_tracks_count())
    def get_playlist(self, request, *args, **kwargs):
        playlist = kwargs.pop('obj')
        data = {
            'playlist': serializers.get_playlist_detail_data(playlist)
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='update_playlist',
        url_path='updatePlaylist')
    @find_object(
        lambda request: request.user.playlists.all(),
        field='playlistId')
    def update_playlist(self, request, *args, **kwargs):
        playlist = kwargs.pop('obj')
        data = request.GET or request.POST
        new_name = data.get('name', '')
        if new_name:
            playlist.name = new_name
            playlist.save(update_fields=['name', 'modification_date'])
        try:
            to_remove = int(data['songIndexToRemove'])
            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)

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        ids = []
        for i in data.getlist('songIdToAdd'):
            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)

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        data = {
            'status': 'ok'
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='delete_playlist',
        url_path='deletePlaylist')
    @find_object(
        lambda request: request.user.playlists.all())
    def delete_playlist(self, request, *args, **kwargs):
        playlist = kwargs.pop('obj')
        playlist.delete()
        data = {
            'status': 'ok'
        }
        return response.Response(data)

    @list_route(
        methods=['get', 'post'],
        url_name='create_playlist',
        url_path='createPlaylist')
    def create_playlist(self, request, *args, **kwargs):
        data = request.GET or request.POST
        name = data.get('name', '')
        if not name:
            return response.Response({
459 460 461 462
                'error': {
                    'code': 10,
                    'message': 'Playlist ID or name must be specified.'
                }
463
            })
464 465 466 467

        playlist = request.user.playlists.create(
            name=name
        )
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        ids = []
        for i in data.getlist('songId'):
            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)
486 487 488 489 490 491
        playlist = request.user.playlists.with_tracks_count().get(
            pk=playlist.pk)
        data = {
            'playlist': serializers.get_playlist_detail_data(playlist)
        }
        return response.Response(data)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

    @list_route(
        methods=['get', 'post'],
        url_name='get_music_folders',
        url_path='getMusicFolders')
    def get_music_folders(self, request, *args, **kwargs):
        data = {
            'musicFolders': {
                'musicFolder': [{
                    'id': 1,
                    'name': 'Music'
                }]
            }
        }
        return response.Response(data)
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

    @list_route(
        methods=['get', 'post'],
        url_name='get_cover_art',
        url_path='getCoverArt')
    def get_cover_art(self, request, *args, **kwargs):
        data = request.GET or request.POST
        id = data.get('id', '')
        if not id:
            return response.Response({
                'error': {
                    'code': 10,
                    'message': 'cover art ID must be specified.'
                }
            })
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        if id.startswith('al-'):
            try:
                album_id = int(id.replace('al-', ''))
                album = music_models.Album.objects.exclude(
                    cover__isnull=True
                ).exclude(cover='').get(pk=album_id)
            except (TypeError, ValueError, music_models.Album.DoesNotExist):
                return response.Response({
                    'error': {
                        'code': 70,
                        'message': 'cover art not found.'
                    }
                })
            cover = album.cover
        else:
            return response.Response({
                'error': {
                    'code': 70,
                    'message': 'cover art not found.'
                }
            })

        mapping = {
            'nginx': 'X-Accel-Redirect',
            'apache2': 'X-Sendfile',
        }
        path = music_views.get_file_path(cover)
        file_header = mapping[settings.REVERSE_PROXY_TYPE]
        # let the proxy set the content-type
        r = response.Response({}, content_type='')
        r[file_header] = path
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        return r

    @list_route(
        methods=['get', 'post'],
        url_name='scrobble',
        url_path='scrobble')
    def scrobble(self, request, *args, **kwargs):
        data = request.GET or request.POST
        serializer = serializers.ScrobbleSerializer(
            data=data, context={'user': request.user})
        if not serializer.is_valid():
            return response.Response({
                'error': {
                    'code': 0,
                    'message': 'Invalid payload'
                }
            })
        if serializer.validated_data['submission']:
            serializer.save()
        return response.Response({})