serializers.py 10.5 KB
Newer Older
1
2
import collections

Eliot Berriot's avatar
Eliot Berriot committed
3
from django.db.models import Count, functions
4
5
from rest_framework import serializers

6
from funkwhale_api.history import models as history_models
7
from funkwhale_api.music import models as music_models
8
from funkwhale_api.music import utils as music_utils
9
10


11
12
13
14
15
16
17
18
19
20
21
def to_subsonic_date(date):
    """
    Subsonic expects this kind of date format: 2012-04-17T19:55:49.000Z
    """

    if not date:
        return

    return date.strftime("%Y-%m-%dT%H:%M:%S.000Z")


22
23
24
25
26
27
28
29
30
31
32
33
34
35
def get_valid_filepart(s):
    """
    Return a string suitable for use in a file path. Escape most non-ASCII
    chars, and truncate the string to a suitable length too.
    """
    max_length = 50
    keepcharacters = " ._()[]-+"
    final = "".join(
        c if c.isalnum() or c in keepcharacters else "_" for c in s
    ).rstrip()
    return final[:max_length]


def get_track_path(track, suffix):
36
37
38
39
    parts = []
    parts.append(get_valid_filepart(track.artist.name))
    if track.album:
        parts.append(get_valid_filepart(track.album.title))
40
41
42
    track_part = get_valid_filepart(track.title) + "." + suffix
    if track.position:
        track_part = "{} - {}".format(track.position, track_part)
43
44
    parts.append(track_part)
    return "/".join(parts)
45
46


47
48
def get_artist_data(artist_values):
    return {
Eliot Berriot's avatar
Eliot Berriot committed
49
50
51
        "id": artist_values["id"],
        "name": artist_values["name"],
        "albumCount": artist_values["_albums_count"],
52
53
    }

54
55
56

class GetArtistsSerializer(serializers.Serializer):
    def to_representation(self, queryset):
Eliot Berriot's avatar
Eliot Berriot committed
57
        payload = {"ignoredArticles": "", "index": []}
58
        queryset = queryset.with_albums_count()
Eliot Berriot's avatar
Eliot Berriot committed
59
60
        queryset = queryset.order_by(functions.Lower("name"))
        values = queryset.values("id", "_albums_count", "name")
61
62
63

        first_letter_mapping = collections.defaultdict(list)
        for artist in values:
64
65
            if artist["name"]:
                first_letter_mapping[artist["name"][0].upper()].append(artist)
66
67
68

        for letter, artists in sorted(first_letter_mapping.items()):
            letter_data = {
Eliot Berriot's avatar
Eliot Berriot committed
69
70
                "name": letter,
                "artist": [get_artist_data(v) for v in artists],
71
            }
Eliot Berriot's avatar
Eliot Berriot committed
72
            payload["index"].append(letter_data)
73
74
75
76
77
        return payload


class GetArtistSerializer(serializers.Serializer):
    def to_representation(self, artist):
Eliot Berriot's avatar
Eliot Berriot committed
78
        albums = artist.albums.prefetch_related("tracks__uploads")
79
        payload = {
Eliot Berriot's avatar
Eliot Berriot committed
80
81
82
83
            "id": artist.pk,
            "name": artist.name,
            "albumCount": len(albums),
            "album": [],
84
85
86
        }
        for album in albums:
            album_data = {
Eliot Berriot's avatar
Eliot Berriot committed
87
88
89
90
                "id": album.id,
                "artistId": artist.id,
                "name": album.title,
                "artist": artist.name,
91
                "created": to_subsonic_date(album.creation_date),
Eliot Berriot's avatar
Eliot Berriot committed
92
                "songCount": len(album.tracks.all()),
93
            }
Eliot Berriot's avatar
Eliot Berriot committed
94
            if album.attachment_cover_id:
Eliot Berriot's avatar
Eliot Berriot committed
95
                album_data["coverArt"] = "al-{}".format(album.id)
96
            if album.release_date:
Eliot Berriot's avatar
Eliot Berriot committed
97
98
                album_data["year"] = album.release_date.year
            payload["album"].append(album_data)
99
100
101
        return payload


Eliot Berriot's avatar
Eliot Berriot committed
102
def get_track_data(album, track, upload):
103
    data = {
Eliot Berriot's avatar
Eliot Berriot committed
104
105
106
        "id": track.pk,
        "isDir": "false",
        "title": track.title,
107
        "album": album.title if album else "",
Agate's avatar
Agate committed
108
        "artist": track.artist.name,
Eliot Berriot's avatar
Eliot Berriot committed
109
        "track": track.position or 1,
110
        "discNumber": track.disc_number or 1,
111
112
113
114
115
116
117
118
        # Ugly fallback to mp3 but some subsonic clients fail if the value is empty or null, and we don't always
        # have the info on legacy uploads
        "contentType": upload.mimetype
        or (
            music_utils.get_type_from_ext(upload.extension)
            if upload.extension
            else "audio/mpeg"
        ),
Eliot Berriot's avatar
Eliot Berriot committed
119
        "suffix": upload.extension or "",
120
        "path": get_track_path(track, upload.extension or "mp3"),
Eliot Berriot's avatar
Eliot Berriot committed
121
        "duration": upload.duration or 0,
122
        "created": to_subsonic_date(track.creation_date),
123
124
        "albumId": album.pk if album else "",
        "artistId": album.artist.pk if album else track.artist.pk,
Eliot Berriot's avatar
Eliot Berriot committed
125
        "type": "music",
126
    }
127
128
    if album and album.attachment_cover_id:
        data["coverArt"] = "al-{}".format(album.id)
Eliot Berriot's avatar
Eliot Berriot committed
129
130
131
132
    if upload.bitrate:
        data["bitrate"] = int(upload.bitrate / 1000)
    if upload.size:
        data["size"] = upload.size
133
    if album and album.release_date:
Eliot Berriot's avatar
Eliot Berriot committed
134
        data["year"] = album.release_date.year
135
136
    else:
        data["year"] = track.creation_date.year
137
138
139
140
141
    return data


def get_album2_data(album):
    payload = {
Eliot Berriot's avatar
Eliot Berriot committed
142
143
144
145
        "id": album.id,
        "artistId": album.artist.id,
        "name": album.title,
        "artist": album.artist.name,
146
        "created": to_subsonic_date(album.creation_date),
147
    }
Eliot Berriot's avatar
Eliot Berriot committed
148
    if album.attachment_cover_id:
Eliot Berriot's avatar
Eliot Berriot committed
149
        payload["coverArt"] = "al-{}".format(album.id)
150

151
    try:
Eliot Berriot's avatar
Eliot Berriot committed
152
        payload["songCount"] = album._tracks_count
153
    except AttributeError:
Eliot Berriot's avatar
Eliot Berriot committed
154
        payload["songCount"] = len(album.tracks.prefetch_related("uploads"))
155
156
157
158
159
160
161
    return payload


def get_song_list_data(tracks):
    songs = []
    for track in tracks:
        try:
Eliot Berriot's avatar
Eliot Berriot committed
162
            uploads = [upload for upload in track.uploads.all()][0]
163
164
        except IndexError:
            continue
Eliot Berriot's avatar
Eliot Berriot committed
165
        track_data = get_track_data(track.album, track, uploads)
166
167
168
169
        songs.append(track_data)
    return songs


170
171
class GetAlbumSerializer(serializers.Serializer):
    def to_representation(self, album):
Eliot Berriot's avatar
Eliot Berriot committed
172
        tracks = album.tracks.prefetch_related("uploads").select_related("album")
173
        payload = get_album2_data(album)
174
        if album.release_date:
Eliot Berriot's avatar
Eliot Berriot committed
175
            payload["year"] = album.release_date.year
176

Eliot Berriot's avatar
Eliot Berriot committed
177
        payload["song"] = get_song_list_data(tracks)
178
        return payload
179
180


181
182
class GetSongSerializer(serializers.Serializer):
    def to_representation(self, track):
Eliot Berriot's avatar
Eliot Berriot committed
183
184
        uploads = track.uploads.all()
        if not len(uploads):
185
            return {}
Eliot Berriot's avatar
Eliot Berriot committed
186
        return get_track_data(track.album, track, uploads[0])
187
188


189
def get_starred_tracks_data(favorites):
Eliot Berriot's avatar
Eliot Berriot committed
190
191
192
193
    by_track_id = {f.track_id: f for f in favorites}
    tracks = (
        music_models.Track.objects.filter(pk__in=by_track_id.keys())
        .select_related("album__artist")
Eliot Berriot's avatar
Eliot Berriot committed
194
        .prefetch_related("uploads")
Eliot Berriot's avatar
Eliot Berriot committed
195
196
    )
    tracks = tracks.order_by("-creation_date")
197
198
199
    data = []
    for t in tracks:
        try:
Eliot Berriot's avatar
Eliot Berriot committed
200
            uploads = [upload for upload in t.uploads.all()][0]
201
202
        except IndexError:
            continue
Eliot Berriot's avatar
Eliot Berriot committed
203
        td = get_track_data(t.album, t, uploads)
204
        td["starred"] = to_subsonic_date(by_track_id[t.pk].creation_date)
205
206
207
208
209
        data.append(td)
    return data


def get_album_list2_data(albums):
Eliot Berriot's avatar
Eliot Berriot committed
210
    return [get_album2_data(a) for a in albums]
211
212
213
214


def get_playlist_data(playlist):
    return {
Eliot Berriot's avatar
Eliot Berriot committed
215
216
217
218
219
220
        "id": playlist.pk,
        "name": playlist.name,
        "owner": playlist.user.username,
        "public": "false",
        "songCount": playlist._tracks_count,
        "duration": 0,
221
        "created": to_subsonic_date(playlist.creation_date),
222
223
224
225
226
    }


def get_playlist_detail_data(playlist):
    data = get_playlist_data(playlist)
Eliot Berriot's avatar
Eliot Berriot committed
227
228
    qs = (
        playlist.playlist_tracks.select_related("track__album__artist")
Eliot Berriot's avatar
Eliot Berriot committed
229
        .prefetch_related("track__uploads")
Eliot Berriot's avatar
Eliot Berriot committed
230
231
232
        .order_by("index")
    )
    data["entry"] = []
233
234
    for plt in qs:
        try:
Eliot Berriot's avatar
Eliot Berriot committed
235
            uploads = [upload for upload in plt.track.uploads.all()][0]
236
237
        except IndexError:
            continue
Eliot Berriot's avatar
Eliot Berriot committed
238
        td = get_track_data(plt.track.album, plt.track, uploads)
Eliot Berriot's avatar
Eliot Berriot committed
239
        data["entry"].append(td)
240
    return data
241
242


243
def get_folders(user):
244
245
246
247
248
    return [
        # Dummy folder ID to match what is returned in the getMusicFolders endpoint
        # cf https://dev.funkwhale.audio/funkwhale/funkwhale/issues/624
        {"id": 1, "name": "Music"}
    ]
249
250
251
252
253
254
255
256
257
258


def get_user_detail_data(user):
    return {
        "username": user.username,
        "email": user.email,
        "scrobblingEnabled": "true",
        "adminRole": "false",
        "settingsRole": "false",
        "commentRole": "false",
259
        "podcastRole": "true",
260
261
262
263
264
265
266
        "coverArtRole": "false",
        "shareRole": "false",
        "uploadRole": "true",
        "downloadRole": "true",
        "playlistRole": "true",
        "streamRole": "true",
        "jukeboxRole": "true",
267
        "folder": [{"value": f["id"]} for f in get_folders(user)],
268
269
270
    }


271
272
273
class ScrobbleSerializer(serializers.Serializer):
    submission = serializers.BooleanField(default=True, required=False)
    id = serializers.PrimaryKeyRelatedField(
Eliot Berriot's avatar
Eliot Berriot committed
274
275
276
        queryset=music_models.Track.objects.annotate(
            uploads_count=Count("uploads")
        ).filter(uploads_count__gt=0)
277
278
279
280
    )

    def create(self, data):
        return history_models.Listening.objects.create(
Eliot Berriot's avatar
Eliot Berriot committed
281
            user=self.context["user"], track=data["id"]
282
        )
283
284
285
286
287
288
289
290


def get_genre_data(tag):
    return {
        "songCount": getattr(tag, "_tracks_count", 0),
        "albumCount": getattr(tag, "_albums_count", 0),
        "value": tag.name,
    }
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


def get_channel_data(channel, uploads):
    data = {
        "id": str(channel.uuid),
        "url": channel.get_rss_url(),
        "title": channel.artist.name,
        "description": channel.artist.description.as_plain_text
        if channel.artist.description
        else "",
        "coverArt": "at-{}".format(channel.artist.attachment_cover.uuid)
        if channel.artist.attachment_cover
        else "",
        "originalImageUrl": channel.artist.attachment_cover.url
        if channel.artist.attachment_cover
        else "",
        "status": "completed",
    }
    if uploads:
        data["episode"] = [
            get_channel_episode_data(upload, channel.uuid) for upload in uploads
        ]

    return data


def get_channel_episode_data(upload, channel_id):
    return {
        "id": str(upload.uuid),
        "channelId": str(channel_id),
        "streamId": upload.track.id,
        "title": upload.track.title,
        "description": upload.track.description.as_plain_text
        if upload.track.description
        else "",
        "coverArt": "at-{}".format(upload.track.attachment_cover.uuid)
        if upload.track.attachment_cover
        else "",
        "isDir": "false",
        "year": upload.track.creation_date.year,
        "publishDate": upload.track.creation_date.isoformat(),
        "created": upload.track.creation_date.isoformat(),
        "genre": "Podcast",
        "size": upload.size if upload.size else "",
        "duration": upload.duration if upload.duration else "",
        "bitrate": upload.bitrate / 1000 if upload.bitrate else "",
        "contentType": upload.mimetype or "audio/mpeg",
        "suffix": upload.extension or "mp3",
        "status": "completed",
    }