test_serializers.py 36.3 KB
Newer Older
1
import datetime
2
import uuid
3

4
import feedparser
5
6
7
import pytest
import pytz

8
from django.templatetags.static import static
9

10
from funkwhale_api.audio import serializers
11
12
from funkwhale_api.common import serializers as common_serializers
from funkwhale_api.common import utils as common_utils
13
from funkwhale_api.federation import actors
14
from funkwhale_api.federation import serializers as federation_serializers
15
from funkwhale_api.federation import utils as federation_utils
16
17
18
from funkwhale_api.music import serializers as music_serializers


19
def test_channel_serializer_create(factories, mocker):
20
    attributed_to = factories["federation.Actor"](local=True)
21
22
    attachment = factories["common.Attachment"](actor=attributed_to)
    request = mocker.Mock(user=mocker.Mock(actor=attributed_to))
23
24
25
    data = {
        "name": "My channel",
        "username": "mychannel",
26
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
27
        "tags": ["hello", "world"],
28
        "content_category": "other",
29
        "cover": attachment.uuid,
30
31
    }

32
    serializer = serializers.ChannelCreateSerializer(
33
        data=data, context={"actor": attributed_to, "request": request}
34
    )
35
36
37
38
39
40
41
42
43
44
    assert serializer.is_valid(raise_exception=True) is True

    channel = serializer.save(attributed_to=attributed_to)

    assert channel.artist.name == data["name"]
    assert channel.artist.attributed_to == attributed_to
    assert (
        sorted(channel.artist.tagged_items.values_list("tag__name", flat=True))
        == data["tags"]
    )
45
    assert channel.artist.description.text == data["description"]["text"]
46
    assert channel.artist.attachment_cover == attachment
47
    assert channel.artist.content_category == data["content_category"]
48
49
50
    assert (
        channel.artist.description.content_type == data["description"]["content_type"]
    )
51
52
53
    assert channel.attributed_to == attributed_to
    assert channel.actor.preferred_username == data["username"]
    assert channel.actor.name == data["name"]
54
    assert channel.library.privacy_level == "everyone"
55
56
57
    assert channel.library.actor == attributed_to


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def test_channel_serializer_create_honor_max_channels_setting(factories, preferences):
    preferences["audio__max_channels"] = 1
    attributed_to = factories["federation.Actor"](local=True)
    factories["audio.Channel"](attributed_to=attributed_to)
    data = {
        "name": "My channel",
        "username": "mychannel",
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "other",
    }

    serializer = serializers.ChannelCreateSerializer(
        data=data, context={"actor": attributed_to}
    )
    with pytest.raises(serializers.serializers.ValidationError, match=r".*max.*"):
        assert serializer.is_valid(raise_exception=True)


77
def test_channel_serializer_create_validates_username_uniqueness(factories):
78
79
80
81
82
83
84
85
86
87
88
89
    attributed_to = factories["federation.Actor"](local=True)
    data = {
        "name": "My channel",
        "username": attributed_to.preferred_username.upper(),
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "other",
    }

    serializer = serializers.ChannelCreateSerializer(
        data=data, context={"actor": attributed_to}
    )
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    with pytest.raises(
        serializers.serializers.ValidationError, match=r".*username is already taken.*"
    ):
        assert serializer.is_valid(raise_exception=True)


def test_channel_serializer_create_validates_username_chars(factories):
    attributed_to = factories["federation.Actor"](local=True)
    data = {
        "name": "My channel",
        "username": "hello world",
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "other",
    }

    serializer = serializers.ChannelCreateSerializer(
        data=data, context={"actor": attributed_to}
    )
    with pytest.raises(
        serializers.serializers.ValidationError, match=r".*Enter a valid username.*"
    ):
        assert serializer.is_valid(raise_exception=True)


def test_channel_serializer_create_validates_blacklisted_username(factories, settings):
    settings.ACCOUNT_USERNAME_BLACKLIST = ["forBidden"]
    attributed_to = factories["federation.Actor"](local=True)
    data = {
        "name": "My channel",
        "username": "FORBIDDEN",
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "other",
    }

    serializer = serializers.ChannelCreateSerializer(
        data=data, context={"actor": attributed_to}
    )
    with pytest.raises(
        serializers.serializers.ValidationError, match=r".*username is already taken.*"
    ):
132
133
134
        assert serializer.is_valid(raise_exception=True)


135
136
137
138
139
140
141
142
143
144
145
146
147
def test_channel_serializer_create_podcast(factories):
    attributed_to = factories["federation.Actor"](local=True)

    data = {
        # TODO: cover
        "name": "My channel",
        "username": "mychannel",
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "podcast",
        "metadata": {"itunes_category": "Sports", "language": "en"},
    }

148
149
150
    serializer = serializers.ChannelCreateSerializer(
        data=data, context={"actor": attributed_to}
    )
151
152
153
154
155
156
    assert serializer.is_valid(raise_exception=True) is True

    channel = serializer.save(attributed_to=attributed_to)
    assert channel.metadata == data["metadata"]


157
158
159
160
161
162
163
def test_channel_serializer_update(factories, mocker):
    channel = factories["audio.Channel"](
        artist__set_tags=["rock"], attributed_to__local=True
    )
    attributed_to = channel.attributed_to
    attachment = factories["common.Attachment"](actor=attributed_to)
    request = mocker.Mock(user=mocker.Mock(actor=attributed_to))
164
165
    data = {
        "name": "My channel",
166
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
167
        "tags": ["hello", "world"],
168
        "content_category": "other",
169
        "cover": attachment.uuid,
170
171
    }

172
173
174
    serializer = serializers.ChannelUpdateSerializer(
        channel, data=data, context={"request": request}
    )
175
176
177
178
179
180
    assert serializer.is_valid(raise_exception=True) is True

    serializer.save()
    channel.refresh_from_db()

    assert channel.artist.name == data["name"]
181
    assert channel.artist.attachment_cover == attachment
182
    assert channel.artist.content_category == data["content_category"]
183
184
185
186
    assert (
        sorted(channel.artist.tagged_items.values_list("tag__name", flat=True))
        == data["tags"]
    )
187
188
    assert channel.artist.description.text == data["description"]["text"]
    assert channel.artist.description.content_type == "text/markdown"
189
190
191
    assert channel.actor.name == data["name"]


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def test_channel_serializer_update_podcast(factories):
    channel = factories["audio.Channel"](artist__set_tags=["rock"])

    data = {
        # TODO: cover
        "name": "My channel",
        "description": {"text": "This is my channel", "content_type": "text/markdown"},
        "tags": ["hello", "world"],
        "content_category": "podcast",
        "metadata": {"language": "en", "itunes_category": "Sports"},
    }

    serializer = serializers.ChannelUpdateSerializer(channel, data=data)
    assert serializer.is_valid(raise_exception=True) is True

    serializer.save()
    channel.refresh_from_db()

    assert channel.metadata == data["metadata"]


213
def test_channel_serializer_representation(factories, to_api_date):
214
215
    content = factories["common.Content"]()
    channel = factories["audio.Channel"](artist__description=content)
216
217
218
219
220
221
222
223
224

    expected = {
        "artist": music_serializers.serialize_artist_simple(channel.artist),
        "uuid": str(channel.uuid),
        "creation_date": to_api_date(channel.creation_date),
        "actor": federation_serializers.APIActorSerializer(channel.actor).data,
        "attributed_to": federation_serializers.APIActorSerializer(
            channel.attributed_to
        ).data,
225
        "metadata": {},
226
        "rss_url": channel.get_rss_url(),
227
        "url": channel.actor.url,
228
    }
229
230
231
    expected["artist"]["description"] = common_serializers.ContentSerializer(
        content
    ).data
232
233

    assert serializers.ChannelSerializer(channel).data == expected
234
235


236
237
238
239
240
241
242
243
244
245
246
247
248
249
def test_channel_serializer_external_representation(factories, to_api_date):
    content = factories["common.Content"]()
    channel = factories["audio.Channel"](artist__description=content, external=True)

    expected = {
        "artist": music_serializers.serialize_artist_simple(channel.artist),
        "uuid": str(channel.uuid),
        "creation_date": to_api_date(channel.creation_date),
        "actor": None,
        "attributed_to": federation_serializers.APIActorSerializer(
            channel.attributed_to
        ).data,
        "metadata": {},
        "rss_url": channel.get_rss_url(),
250
        "url": channel.actor.url,
251
252
253
254
255
256
257
258
    }
    expected["artist"]["description"] = common_serializers.ContentSerializer(
        content
    ).data

    assert serializers.ChannelSerializer(channel).data == expected


259
260
261
262
263
264
265
266
267
268
def test_channel_serializer_representation_subscriptions_count(factories, to_api_date):
    channel = factories["audio.Channel"]()
    factories["federation.Follow"](target=channel.actor)
    factories["federation.Follow"](target=channel.actor, approved=False)
    serializer = serializers.ChannelSerializer(
        channel, context={"subscriptions_count": True}
    )
    assert serializer.data["subscriptions_count"] == 1


269
270
271
272
273
274
275
276
277
278
279
def test_subscription_serializer(factories, to_api_date):
    subscription = factories["audio.Subscription"]()
    expected = {
        "channel": serializers.ChannelSerializer(subscription.target.channel).data,
        "uuid": str(subscription.uuid),
        "creation_date": to_api_date(subscription.creation_date),
        "approved": subscription.approved,
        "fid": subscription.fid,
    }

    assert serializers.SubscriptionSerializer(subscription).data == expected
280
281
282
283
284
285
286
287
288
289


def test_rss_item_serializer(factories):
    description = factories["common.Content"]()
    upload = factories["music.Upload"](
        playable=True,
        track__set_tags=["pop", "rock"],
        track__description=description,
        track__disc_number=4,
        track__position=42,
290
        track__with_cover=True,
291
292
293
294
295
296
297
298
299
300
301
302
303
    )
    setattr(
        upload.track,
        "_prefetched_tagged_items",
        upload.track.tagged_items.order_by("tag__name"),
    )
    expected = {
        "title": [{"value": upload.track.title}],
        "itunes:title": [{"value": upload.track.title}],
        "itunes:subtitle": [{"value": description.truncate(255)}],
        "itunes:summary": [{"cdata_value": description.rendered}],
        "description": [{"value": description.as_plain_text}],
        "guid": [{"cdata_value": str(upload.uuid), "isPermalink": "false"}],
Eliot Berriot's avatar
Eliot Berriot committed
304
        "pubDate": [{"value": serializers.rfc822_date(upload.creation_date)}],
305
306
307
308
309
310
311
312
313
        "itunes:duration": [{"value": serializers.rss_duration(upload.duration)}],
        "itunes:keywords": [{"value": "pop rock"}],
        "itunes:explicit": [{"value": "no"}],
        "itunes:episodeType": [{"value": "full"}],
        "itunes:season": [{"value": upload.track.disc_number}],
        "itunes:episode": [{"value": upload.track.position}],
        "itunes:image": [{"href": upload.track.attachment_cover.download_url_original}],
        "link": [{"value": federation_utils.full_url(upload.track.get_absolute_url())}],
        "enclosure": [
314
            {
Agate's avatar
Agate committed
315
316
317
                "url": federation_utils.full_url(
                    upload.get_listen_url("mp3", download=False)
                ),
318
                "length": upload.size,
319
                "type": "audio/mpeg",
320
            }
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        ],
    }

    assert serializers.rss_serialize_item(upload) == expected


def test_rss_channel_serializer(factories):
    metadata = {
        "language": "fr",
        "itunes_category": "Parent",
        "itunes_subcategory": "Child",
        "copyright": "Myself",
        "owner_name": "Name",
        "owner_email": "name@domain.com",
        "explicit": True,
    }
    description = factories["common.Content"]()
    channel = factories["audio.Channel"](
        artist__set_tags=["pop", "rock"],
        artist__description=description,
        metadata=metadata,
342
        artist__with_cover=True,
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
    )
    setattr(
        channel.artist,
        "_prefetched_tagged_items",
        channel.artist.tagged_items.order_by("tag__name"),
    )

    expected = {
        "title": [{"value": channel.artist.name}],
        "language": [{"value": metadata["language"]}],
        "copyright": [{"value": metadata["copyright"]}],
        "itunes:subtitle": [{"value": description.truncate(255)}],
        "itunes:summary": [{"cdata_value": description.rendered}],
        "description": [{"value": description.as_plain_text}],
        "itunes:keywords": [{"value": "pop rock"}],
        "itunes:category": [
            {
                "text": metadata["itunes_category"],
                "itunes:category": [{"text": metadata["itunes_subcategory"]}],
            }
        ],
        "itunes:explicit": [{"value": "yes"}],
        "itunes:owner": [
            {
                "itunes:name": [{"value": metadata["owner_name"]}],
                "itunes:email": [{"value": metadata["owner_email"]}],
            }
        ],
        "itunes:author": [{"value": metadata["owner_name"]}],
        "itunes:type": [{"value": "episodic"}],
        "itunes:image": [
            {"href": channel.artist.attachment_cover.download_url_original}
        ],
        "link": [{"value": channel.get_absolute_url()}],
        "atom:link": [
            {
                "href": channel.get_rss_url(),
                "rel": "self",
                "type": "application/rss+xml",
382
383
384
385
386
387
            },
            {
                "href": channel.actor.fid,
                "rel": "alternate",
                "type": "application/activity+json",
            },
388
389
390
391
392
393
        ],
    }

    assert serializers.rss_serialize_channel(channel) == expected


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def test_rss_channel_serializer_placeholder_image(factories):
    description = factories["common.Content"]()
    channel = factories["audio.Channel"](
        artist__set_tags=["pop", "rock"],
        artist__description=description,
        artist__attachment_cover=None,
    )
    setattr(
        channel.artist,
        "_prefetched_tagged_items",
        channel.artist.tagged_items.order_by("tag__name"),
    )

    expected = [
        {
            "href": federation_utils.full_url(
                static("images/podcasts-cover-placeholder.png")
            )
        }
    ]

    assert serializers.rss_serialize_channel(channel)["itunes:image"] == expected


418
419
420
421
422
423
424
425
426
427
428
429
430
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
459
def test_serialize_full_channel(factories):
    channel = factories["audio.Channel"]()
    upload1 = factories["music.Upload"](playable=True)
    upload2 = factories["music.Upload"](playable=True)

    expected = serializers.rss_serialize_channel(channel)
    expected["item"] = [
        serializers.rss_serialize_item(upload1),
        serializers.rss_serialize_item(upload2),
    ]
    expected = {"channel": expected}

    result = serializers.rss_serialize_channel_full(
        channel=channel, uploads=[upload1, upload2]
    )

    assert result == expected


@pytest.mark.parametrize(
    "seconds, expected",
    [
        (0, "00:00:00"),
        (None, "00:00:00"),
        (61, "00:01:01"),
        (3601, "01:00:01"),
        (7345, "02:02:25"),
    ],
)
def test_rss_duration(seconds, expected):
    assert serializers.rss_duration(seconds) == expected


@pytest.mark.parametrize(
    "dt, expected",
    [
        (
            datetime.datetime(2020, 1, 30, 6, 0, 49, tzinfo=pytz.UTC),
            "Thu, 30 Jan 2020 06:00:49 +0000",
        ),
    ],
)
Eliot Berriot's avatar
Eliot Berriot committed
460
461
def test_rfc822_date(dt, expected):
    assert serializers.rfc822_date(dt) == expected
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481


def test_channel_metadata_serializer_validation():
    payload = {
        "language": "fr",
        "copyright": "Me",
        "owner_email": "contact@me.com",
        "owner_name": "Me",
        "itunes_category": "Health & Fitness",
        "itunes_subcategory": "Sexuality",
        "unknown_key": "noop",
    }

    serializer = serializers.ChannelMetadataSerializer(data=payload)

    assert serializer.is_valid(raise_exception=True) is True

    payload.pop("unknown_key")

    assert serializer.validated_data == payload
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794


def test_rss_feed_serializer_create(db, now):
    rss_url = "http://example.rss/"

    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>http://public.url</link>
                <atom:link rel="self" type="application/rss+xml" href="http://real.rss.url"/>
                <lastBuildDate>Wed, 11 Mar 2020 16:01:08 GMT</lastBuildDate>
                <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                <ttl>30</ttl>
                <language>en</language>
                <copyright>2019 Tests</copyright>
                <itunes:keywords>pop rock</itunes:keywords>
                <image>
                    <url>
                        https://image.url
                    </url>
                    <title>Image caption</title>
                </image>
                <itunes:image href="https://image.url"/>
                <itunes:subtitle>Subtitle</itunes:subtitle>
                <itunes:type>episodic</itunes:type>
                <itunes:author>Author</itunes:author>
                <itunes:summary><![CDATA[Some content]]></itunes:summary>
                <itunes:owner>
                    <itunes:name>Name</itunes:name>
                    <itunes:email>email@domain</itunes:email>
                </itunes:owner>
                <itunes:explicit>yes</itunes:explicit>
                <itunes:keywords/>
                <itunes:category text="Business">
                    <itunes:category text="Entrepreneurship">
                </itunes:category>
            </channel>
        </rss>
    """
    parsed_feed = feedparser.parse(xml_payload)
    serializer = serializers.RssFeedSerializer(data=parsed_feed.feed)

    assert serializer.is_valid(raise_exception=True) is True

    channel = serializer.save(rss_url)

    assert channel.rss_url == "http://real.rss.url"
    assert channel.attributed_to == actors.get_service_actor()
    assert channel.library.actor == actors.get_service_actor()
    assert channel.artist.name == "Hello"
    assert channel.artist.attributed_to == actors.get_service_actor()
    assert channel.artist.description.content_type == "text/plain"
    assert channel.artist.description.text == "Some content"
    assert channel.artist.attachment_cover.url == "https://image.url"
    assert channel.artist.get_tags() == ["pop", "rock"]
    assert channel.actor.url == "http://public.url"
    assert channel.actor.last_fetch_date == now
    assert channel.metadata == {
        "explicit": True,
        "copyright": "2019 Tests",
        "owner_name": "Name",
        "owner_email": "email@domain",
        "itunes_category": "Business",
        "itunes_subcategory": "Entrepreneurship",
        "language": "en",
    }


def test_rss_feed_serializer_update(factories, now):
    rss_url = "http://example.rss/"
    channel = factories["audio.Channel"](rss_url=rss_url, external=True)

    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>http://public.url</link>
                <atom:link rel="self" type="application/rss+xml" href="http://real.rss.url"/>
                <lastBuildDate>Wed, 11 Mar 2020 16:01:08 GMT</lastBuildDate>
                <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                <ttl>30</ttl>
                <language>en</language>
                <copyright>2019 Tests</copyright>
                <itunes:keywords>pop rock</itunes:keywords>
                <image>
                    <url>
                        https://image.url
                    </url>
                    <title>Image caption</title>
                </image>
                <itunes:image href="https://image.url"/>
                <itunes:subtitle>Subtitle</itunes:subtitle>
                <itunes:type>episodic</itunes:type>
                <itunes:author>Author</itunes:author>
                <itunes:summary><![CDATA[Some content]]></itunes:summary>
                <itunes:owner>
                    <itunes:name>Name</itunes:name>
                    <itunes:email>email@domain</itunes:email>
                </itunes:owner>
                <itunes:explicit>yes</itunes:explicit>
                <itunes:keywords/>
                <itunes:category text="Business">
                    <itunes:category text="Entrepreneurship">
                </itunes:category>
            </channel>
        </rss>
    """
    parsed_feed = feedparser.parse(xml_payload)
    serializer = serializers.RssFeedSerializer(data=parsed_feed.feed)

    assert serializer.is_valid(raise_exception=True) is True

    serializer.save(rss_url)

    channel.refresh_from_db()

    assert channel.rss_url == "http://real.rss.url"
    assert channel.attributed_to == actors.get_service_actor()
    assert channel.library.actor == actors.get_service_actor()
    assert channel.library.fid is not None
    assert channel.artist.name == "Hello"
    assert channel.artist.attributed_to == actors.get_service_actor()
    assert channel.artist.description.content_type == "text/plain"
    assert channel.artist.description.text == "Some content"
    assert channel.artist.attachment_cover.url == "https://image.url"
    assert channel.artist.get_tags() == ["pop", "rock"]
    assert channel.actor.url == "http://public.url"
    assert channel.actor.last_fetch_date == now
    assert channel.metadata == {
        "explicit": True,
        "copyright": "2019 Tests",
        "owner_name": "Name",
        "owner_email": "email@domain",
        "itunes_category": "Business",
        "itunes_subcategory": "Entrepreneurship",
        "language": "en",
    }


def test_rss_feed_item_serializer_create(factories):
    rss_url = "http://example.rss/"
    channel = factories["audio.Channel"](rss_url=rss_url, external=True)

    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>http://public.url</link>
                <atom:link rel="self" type="application/rss+xml" href="http://real.rss.url"/>
                <item>
                    <title>Episode 33</title>
                    <itunes:subtitle>Subtitle</itunes:subtitle>
                    <itunes:summary><![CDATA[<p>Html content</p>]]></itunes:summary>
                    <guid isPermaLink="false"><![CDATA[16f66fff-41ae-4a1c-9101-2746218c4f32]]></guid>
                    <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                    <itunes:duration>00:22:37</itunes:duration>
                    <itunes:keywords>pop rock</itunes:keywords>
                    <itunes:season>2</itunes:season>
                    <itunes:episode>33</itunes:episode>
                    <itunes:image href="https://image.url/" />
                    <description><![CDATA[Html content]]></description>
                    <link>http://public.url/</link>
                    <enclosure url="https://file.domain/audio.mp3" length="54315884" type="audio/mpeg"/>
                </item>
            </channel>
        </rss>
    """
    parsed_feed = feedparser.parse(xml_payload)
    entry = parsed_feed.entries[0]
    serializer = serializers.RssFeedItemSerializer(data=entry)

    assert serializer.is_valid(raise_exception=True) is True

    upload = serializer.save(channel, copyright="test something")

    expected_uuid = uuid.uuid3(
        uuid.NAMESPACE_URL,
        "rss://{}-16f66fff-41ae-4a1c-9101-2746218c4f32".format(channel.pk),
    )
    assert upload.library == channel.library
    assert upload.import_status == "finished"
    assert upload.source == "https://file.domain/audio.mp3"
    assert upload.size == 54315884
    assert upload.duration == 1357
    assert upload.mimetype == "audio/mpeg"
    assert upload.track.uuid == expected_uuid
    assert upload.track.artist == channel.artist
    assert upload.track.copyright == "test something"
    assert upload.track.position == 33
    assert upload.track.disc_number == 2
    assert upload.track.creation_date == datetime.datetime(2020, 3, 11, 16).replace(
        tzinfo=pytz.utc
    )
    assert upload.track.get_tags() == ["pop", "rock"]
    assert upload.track.attachment_cover.url == "https://image.url/"
    assert upload.track.description.text == "<p>Html content</p>"
    assert upload.track.description.content_type == "text/html"


def test_rss_feed_item_serializer_update(factories):
    rss_url = "http://example.rss/"
    channel = factories["audio.Channel"](rss_url=rss_url, external=True)
    expected_uuid = uuid.uuid3(
        uuid.NAMESPACE_URL,
        "rss://{}-16f66fff-41ae-4a1c-9101-2746218c4f32".format(channel.pk),
    )
    upload = factories["music.Upload"](
        track__uuid=expected_uuid,
        source="https://file.domain/audio.mp3",
        library=channel.library,
        track__artist=channel.artist,
    )
    track = upload.track

    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>http://public.url</link>
                <atom:link rel="self" type="application/rss+xml" href="http://real.rss.url"/>
                <item>
                    <title>Episode 33</title>
                    <itunes:subtitle>Subtitle</itunes:subtitle>
                    <itunes:summary><![CDATA[<p>Html content</p>]]></itunes:summary>
                    <guid isPermaLink="false"><![CDATA[16f66fff-41ae-4a1c-9101-2746218c4f32]]></guid>
                    <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                    <itunes:duration>00:22:37</itunes:duration>
                    <itunes:keywords>pop rock</itunes:keywords>
                    <itunes:season>2</itunes:season>
                    <itunes:episode>33</itunes:episode>
                    <itunes:image href="https://image.url/" />
                    <description><![CDATA[Html content]]></description>
                    <link>http://public.url/</link>
                    <enclosure url="https://file.domain/audio.mp3" length="54315884" type="audio/mpeg"/>
                </item>
            </channel>
        </rss>
    """
    parsed_feed = feedparser.parse(xml_payload)
    entry = parsed_feed.entries[0]
    serializer = serializers.RssFeedItemSerializer(data=entry)

    assert serializer.is_valid(raise_exception=True) is True

    serializer.save(channel, copyright="test something")
    upload.refresh_from_db()

    assert upload.track == track
    assert upload.library == channel.library
    assert upload.import_status == "finished"
    assert upload.source == "https://file.domain/audio.mp3"
    assert upload.size == 54315884
    assert upload.duration == 1357
    assert upload.mimetype == "audio/mpeg"
    assert upload.track.uuid == expected_uuid
    assert upload.track.artist == channel.artist
    assert upload.track.copyright == "test something"
    assert upload.track.position == 33
    assert upload.track.disc_number == 2
    assert upload.track.creation_date == datetime.datetime(2020, 3, 11, 16).replace(
        tzinfo=pytz.utc
    )
    assert upload.track.get_tags() == ["pop", "rock"]
    assert upload.track.attachment_cover.url == "https://image.url/"
    assert upload.track.description.text == "<p>Html content</p>"
    assert upload.track.description.content_type == "text/html"


def test_get_channel_from_rss_url(db, r_mock, mocker):
    rss_url = "http://example.rss/"
    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>http://public.url</link>
                <atom:link rel="self" type="application/rss+xml" href="http://real.rss.url"/>
                <lastBuildDate>Wed, 11 Mar 2020 16:01:08 GMT</lastBuildDate>
                <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                <ttl>30</ttl>
                <language>en</language>
                <copyright>2019 Tests</copyright>
                <itunes:keywords>pop rock</itunes:keywords>
                <image>
                    <url>
                        https://image.url
                    </url>
                    <title>Image caption</title>
                </image>
                <itunes:image href="https://image.url"/>
                <itunes:subtitle>Subtitle</itunes:subtitle>
                <itunes:type>episodic</itunes:type>
                <itunes:author>Author</itunes:author>
                <itunes:summary><![CDATA[Some content]]></itunes:summary>
                <itunes:owner>
                    <itunes:name>Name</itunes:name>
                    <itunes:email>email@domain</itunes:email>
                </itunes:owner>
                <itunes:explicit>yes</itunes:explicit>
                <itunes:keywords/>
                <itunes:category text="Business">
                    <itunes:category text="Entrepreneurship">
                </itunes:category>
                <item>
                    <title>Episode 33</title>
                    <itunes:subtitle>Subtitle</itunes:subtitle>
                    <itunes:summary><![CDATA[<p>Html content</p>]]></itunes:summary>
                    <guid isPermaLink="false"><![CDATA[16f66fff-41ae-4a1c-9101-2746218c4f32]]></guid>
795
                    <pubDate>Wed, 11 Mar 2020 18:00:00 GMT</pubDate>
796
797
798
799
800
801
802
803
804
805
806
807
808
809
                    <itunes:duration>00:22:37</itunes:duration>
                    <itunes:keywords>pop rock</itunes:keywords>
                    <itunes:season>2</itunes:season>
                    <itunes:episode>33</itunes:episode>
                    <itunes:image href="https://image.url/" />
                    <description><![CDATA[Html content]]></description>
                    <link>http://public.url/</link>
                    <enclosure url="https://file.domain/audio.mp3" length="54315884" type="audio/mpeg"/>
                </item>
                <item>
                    <title>Episode 32</title>
                    <itunes:subtitle>Subtitle</itunes:subtitle>
                    <itunes:summary><![CDATA[<p>Html content</p>]]></itunes:summary>
                    <guid isPermaLink="false"><![CDATA[16f66fff-41ae-4a1c-910e-2746218c4f32]]></guid>
810
                    <pubDate>Wed, 11 Mar 2020 17:00:00 GMT</pubDate>
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
                    <itunes:duration>00:22:37</itunes:duration>
                    <itunes:keywords>pop rock</itunes:keywords>
                    <itunes:season>2</itunes:season>
                    <itunes:episode>32</itunes:episode>
                    <itunes:image href="https://image.url/" />
                    <description><![CDATA[Html content]]></description>
                    <link>http://public.url/</link>
                    <enclosure url="https://file.domain/audio2.mp3" length="54315884" type="audio/mpeg"/>
                </item>
                <item>
                    <title>Ignored, missing enĉlosure</title>
                    <itunes:subtitle>Subtitle</itunes:subtitle>
                    <itunes:summary><![CDATA[<p>Html content</p>]]></itunes:summary>
                    <guid isPermaLink="false"><![CDATA[16f66fff-41ae-4a1c-910e-2746218c4f32]]></guid>
                    <pubDate>Wed, 11 Mar 2020 16:00:00 GMT</pubDate>
                    <itunes:duration>00:22:37</itunes:duration>
                    <itunes:keywords>pop rock</itunes:keywords>
                    <itunes:season>2</itunes:season>
                    <itunes:episode>32</itunes:episode>
                    <itunes:image href="https://image.url/" />
                    <description><![CDATA[Html content]]></description>
                    <link>http://public.url/</link>
                </item>
            </channel>
        </rss>
    """
    parsed_feed = feedparser.parse(xml_payload)
    r_mock.get(rss_url, text=xml_payload)

840
    update_modification_date = mocker.spy(common_utils, "update_modification_date")
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
    feed_init = mocker.spy(serializers.RssFeedSerializer, "__init__")
    feed_save = mocker.spy(serializers.RssFeedSerializer, "save")
    item_init = mocker.spy(serializers.RssFeedItemSerializer, "__init__")
    item_save = mocker.spy(serializers.RssFeedItemSerializer, "save")
    on_commit = mocker.spy(common_utils, "on_commit")
    channel, uploads = serializers.get_channel_from_rss_url(rss_url)

    assert channel.artist.name == "Hello"

    serializer_instance = feed_init.call_args[0][0]
    feed_init.assert_called_once_with(serializer_instance, data=parsed_feed.feed)
    feed_save.assert_called_once_with(serializer_instance, rss_url)

    for i in [0, 1]:
        serializer_instance = item_init.call_args_list[i][0][0]
        item_init.assert_any_call(serializer_instance, data=parsed_feed.entries[i])
        item_save.assert_any_call(
            serializer_instance, channel, existing_uploads=[], copyright="2019 Tests"
        )

    assert len(uploads) == 2
    assert channel.library.uploads.count() == 2

    on_commit.assert_any_call(
        serializers.music_models.TrackActor.create_entries,
        library=channel.library,
        delete_existing=True,
    )
869
870
871
    update_modification_date.assert_called_once_with(
        channel.artist, date=uploads[0].track.creation_date
    )
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921


def test_get_channel_from_rss_honor_mrf_inbox_before_http(
    mrf_inbox_registry, factories, mocker
):
    apply = mocker.patch.object(mrf_inbox_registry, "apply", return_value=(None, False))
    rss_url = "https://rss.domain/test"

    with pytest.raises(serializers.FeedFetchException, match=r".*blocked.*"):
        serializers.get_channel_from_rss_url(rss_url)

    apply.assert_any_call({"id": rss_url})


def test_get_channel_from_rss_honor_mrf_inbox_after_http(
    mrf_inbox_registry, r_mock, mocker, db
):
    apply = mocker.patch.object(
        mrf_inbox_registry,
        "apply",
        side_effect=[(True, False), (True, False), (None, False)],
    )
    rss_url = "https://rss.domain/test"
    # the feed has a redirection, we check both urls
    final_rss_url = "https://real.rss.domain/test"
    public_url = "http://public.url"
    xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0">
            <channel>
                <title>Hello</title>
                <description>Description</description>
                <link>{}</link>
                <atom:link rel="self" type="application/rss+xml" href="{}"/>
                <language>en</language>
                <copyright>2019 Tests</copyright>
                <itunes:keywords>pop rock</itunes:keywords>
            </channel>
        </rss>
    """.format(
        public_url, final_rss_url
    )

    r_mock.get(rss_url, text=xml_payload)

    with pytest.raises(serializers.FeedFetchException, match=r".*blocked.*"):
        serializers.get_channel_from_rss_url(rss_url)

    apply.assert_any_call({"id": rss_url})
    apply.assert_any_call({"id": final_rss_url})
    apply.assert_any_call({"id": public_url})
Eliot Berriot's avatar
Eliot Berriot committed
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965


def test_opml_serializer(factories, now):
    channels = [
        factories["audio.Channel"](),
        factories["audio.Channel"](),
        factories["audio.Channel"](),
    ]

    title = "Hello world"
    expected = {
        "version": "2.0",
        "head": [
            {
                "date": [{"value": serializers.rfc822_date(now)}],
                "title": [{"value": title}],
            }
        ],
        "body": [
            {
                "outline": [
                    serializers.get_opml_outline(channels[0]),
                    serializers.get_opml_outline(channels[1]),
                    serializers.get_opml_outline(channels[2]),
                ],
            }
        ],
    }

    assert serializers.get_opml(channels=channels, date=now, title=title) == expected


def test_opml_outline_serializer(factories, now):
    channel = factories["audio.Channel"]()

    expected = {
        "title": channel.artist.name,
        "text": channel.artist.name,
        "type": "rss",
        "xmlUrl": channel.get_rss_url(),
        "htmlUrl": channel.actor.url,
    }

    assert serializers.get_opml_outline(channel) == expected