Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Overhaul serializers to eliminate manually defined fields (#696)
Dhruv Bhanushali2e85caf7aede
diff --git a/api/catalog/api/constants/field_order.py b/api/catalog/api/constants/field_order.pynew file mode 100644index 000000000..a67f4b17f--- /dev/null+++ b/api/catalog/api/constants/field_order.py@@ -0,0 +1,48 @@+"""+This file hardcodes the logical order for serializer fields to be defined in so that+their output feels suitable for human consumption.+"""++json_fields = [+ "id",+ "title",+ "foreign_landing_url",+ "url",+ "creator",+ "creator_url",+ "license",+ "license_version",+ "license_url",+ "provider",+ "source",+ "category",+ "genres", # audio-only+ "filesize",+ "filetype",+ "tags",+ "alt_files", # audio-only+ "attribution",+ # Hits+ "fields_matched",+ "mature",+ # Image specific+ "height",+ "width",+ # Audio specific+ "audio_set",+ "duration",+ "bit_rate",+ "sample_rate",+ # Hyperlinks+ "thumbnail",+ "detail_url",+ "related_url",+ "waveform", # audio-only+ # Add-ons+ "peaks", # audio-only+]++field_position_map: dict[str, int] = {+ field: idx for idx, field in enumerate(json_fields)+}+"""mapping of JSON fields to their sort positions"""diff --git a/api/catalog/api/docs/audio_docs.py b/api/catalog/api/docs/audio_docs.pyindex 2cdf31080..a42bd4a0b 100644--- a/api/catalog/api/docs/audio_docs.py+++ b/api/catalog/api/docs/audio_docs.py@@ -25,7 +25,7 @@ from catalog.api.examples import (audio_stats_curl,)from catalog.api.serializers.audio_serializers import (- AudioReportSerializer,+ AudioReportRequestSerializer,AudioSearchRequestSerializer,AudioSearchSerializer,AudioSerializer,@@ -112,7 +112,7 @@ class AudioDetail(MediaDetail):audio_detail is an API endpoint to get the details of a specified audio ID.By using this endpoint, you can get audio details such as-{fields_to_md(AudioSerializer.fields_names)}.+{fields_to_md(AudioSerializer.Meta.fields)}.{MediaDetail.desc}"""@@ -148,7 +148,7 @@ recommendations_audio_read is an API endpoint to get related audio files for a saudio ID.By using this endpoint, you can get the details of related audio such as-{fields_to_md(AudioSerializer.fields_names)}.+{fields_to_md(AudioSerializer.Meta.fields)}.{MediaRelated.desc}"""@@ -192,7 +192,7 @@ mature or sensitive content and others."201": openapi.Response(description="OK",examples=audio_complain_201_example,- schema=AudioReportSerializer,+ schema=AudioReportRequestSerializer,)}diff --git a/api/catalog/api/docs/image_docs.py b/api/catalog/api/docs/image_docs.pyindex ef8b67e5f..2f637edeb 100644--- a/api/catalog/api/docs/image_docs.py+++ b/api/catalog/api/docs/image_docs.py@@ -32,7 +32,7 @@ from catalog.api.serializers.error_serializers import (NotFoundErrorSerializer,)from catalog.api.serializers.image_serializers import (- ImageReportSerializer,+ ImageReportRequestSerializer,ImageSearchRequestSerializer,ImageSearchSerializer,ImageSerializer,@@ -117,7 +117,7 @@ class ImageDetail(MediaDetail):image_detail is an API endpoint to get the details of a specified image ID.By using this endpoint, you can image details such as-{fields_to_md(ImageSerializer.fields_names)}.+{fields_to_md(ImageSerializer.Meta.fields)}.{MediaDetail.desc}"""@@ -148,7 +148,7 @@ recommendations_images_read is an API endpoint to get related images for a speciimage ID.By using this endpoint, you can get the details of related images such as-{fields_to_md(ImageSerializer.fields_names)}.+{fields_to_md(ImageSerializer.Meta.fields)}.{MediaRelated.desc}"""@@ -187,7 +187,7 @@ mature or sensitive content and others."201": openapi.Response(description="OK",examples=image_complain_201_example,- schema=ImageReportSerializer,+ schema=ImageReportRequestSerializer,)}diff --git a/api/catalog/api/examples/audio_responses.py b/api/catalog/api/examples/audio_responses.pyindex ebcb92172..f7b0107bc 100644--- a/api/catalog/api/examples/audio_responses.py+++ b/api/catalog/api/examples/audio_responses.py@@ -9,14 +9,18 @@ base_audio = {"id": identifier,"title": "Wish You Were Here","foreign_landing_url": "https://www.jamendo.com/track/1214935",+ "url": "https://mp3d.jamendo.com/download/track/1214935/mp32","creator": "The.madpix.project","creator_url": "https://www.jamendo.com/artist/441585/the.madpix.project",- "url": "https://mp3d.jamendo.com/download/track/1214935/mp32","license": "by-nc-sa","license_version": "3.0","license_url": "https://creativecommons.org/licenses/by-nc-sa/3.0/","provider": "jamendo","source": "jamendo",+ "category": "music",+ "genres": ["dance", "electronic", "house"],+ "filesize": 7139840,+ "filetype": "mp3","tags": [{"name": "vocal"},{"name": "female"},@@ -29,13 +33,26 @@ base_audio = {{"name": "voice"},{"name": "funkyhouse"},],- "genres": ["dance", "electronic", "house"],+ "alt_files": None,+ "attribution": '"Wish You Were Here" by The.madpix.project is licensed under CC BY-NC-SA 3.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/3.0/.', # noqa: E501,+ "fields_matched": [],+ "mature": None,+ "audio_set": {+ "title": "Wish You Were Here",+ "foreign_landing_url": "https://www.jamendo.com/album/145774/wish-you-were-here", # noqa: E501+ "creator": "The.madpix.project",+ "creator_url": "https://www.jamendo.com/artist/441585/the.madpix.project",+ "url": "https://usercontent.jamendo.com?type=album&id=145774&width=200",+ "filesize": None,+ "filetype": None,+ },+ "duration": 270000,+ "bit_rate": 128000,+ "sample_rate": 44100,"thumbnail": f"{origin}/v1/audio/{identifier}/thumb/",- "waveform": f"{origin}/v1/audio/{identifier}/waveform/","detail_url": f"{origin}/v1/audio/{identifier}/","related_url": f"{origin}/v1/audio/{identifier}/related/",- "category": "music",- "duration": 270000,+ "waveform": f"{origin}/v1/audio/{identifier}/waveform/","peaks": [],}@@ -46,7 +63,15 @@ audio_search_200_example = {"page_size": 20,"page": 1,"results": [- base_audio | {"fields_matched": ["title"]},+ base_audio+ | {+ "fields_matched": ["title"],+ "mature": False,+ "audio_set": None,+ "attribution": None,+ "filesize": None,+ "filetype": None,+ },],},}@@ -78,27 +103,7 @@ audio_stats_200_example = {]}-audio_detail_200_example = {- "application/json": base_audio- | {- "attribution": '"Wish You Were Here" by The.madpix.project is licensed under CC BY-NC-SA 3.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/3.0/.', # noqa: E501- "audio_set": {- "title": "Wish You Were Here",- "foreign_landing_url": "https://www.jamendo.com/album/145774/wish-you-were-here", # noqa: E501- "creator": "The.madpix.project",- "creator_url": "https://www.jamendo.com/artist/441585/the.madpix.project",- "url": "https://usercontent.jamendo.com?type=album&id=145774&width=200",- "filesize": None,- "filetype": None,- },- "duration": 270000,- "bit_rate": None,- "sample_rate": None,- "alt_files": None,- "filesize": None,- "filetype": "mp3",- },-}+audio_detail_200_example = {"application/json": base_audio}audio_detail_404_example = {"application/json": {"detail": "Not found."}}diff --git a/api/catalog/api/examples/image_responses.py b/api/catalog/api/examples/image_responses.pyindex 3717e7ca2..47ee2cd39 100644--- a/api/catalog/api/examples/image_responses.py+++ b/api/catalog/api/examples/image_responses.py@@ -9,15 +9,17 @@ base_image = {"id": identifier,"title": "Train area in Copenhagen South / Tog område i Syd København","foreign_landing_url": "https://www.flickr.com/photos/126744325@N07/51745389858",+ "url": "https://live.staticflickr.com/65535/51745389858_c10358e1a3_b.jpg","creator": "Kristoffer Trolle","creator_url": "https://www.flickr.com/photos/126744325@N07",- "url": "https://live.staticflickr.com/65535/51745389858_c10358e1a3_b.jpg","license": "by","license_version": "2.0","license_url": "https://creativecommons.org/licenses/by/2.0/","provider": "flickr","source": "flickr","category": "photograph",+ "filesize": 157497,+ "filetype": "jpg","tags": [{"name": "copenhagen"},{"name": "danmark"},@@ -33,6 +35,11 @@ base_image = {{"name": "tog"},{"name": "train"},],+ "attribution": '"Train area in Copenhagen South / Tog område i Syd København" by Kristoffer Trolle is licensed under CC BY 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by/2.0/.', # noqa: E501+ "fields_matched": [],+ "mature": None,+ "height": 683,+ "width": 1024,"thumbnail": f"{origin}/v1/images/{identifier}/thumb/","detail_url": f"{origin}/v1/images/{identifier}/","related_url": f"{origin}/v1/images/{identifier}/related/",@@ -48,6 +55,12 @@ image_search_200_example = {base_image| {"fields_matched": ["title"],+ "mature": False,+ "height": None,+ "width": None,+ "attribution": None,+ "filesize": None,+ "filetype": None,}],},@@ -80,16 +93,7 @@ image_stats_200_example = {]}-image_detail_200_example = {- "application/json": base_image- | {- "attribution": '"Train area in Copenhagen South / Tog område i Syd København" by Kristoffer Trolle is licensed under CC BY 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by/2.0/.', # noqa: E501- "height": 683,- "width": 1024,- "filesize": "157497",- "filetype": "jpg",- }-}+image_detail_200_example = {"application/json": base_image}image_detail_404_example = {"application/json": {"detail": "Not found."}}diff --git a/api/catalog/api/migrations/0047_help_text.py b/api/catalog/api/migrations/0047_help_text.pynew file mode 100644index 000000000..db554d0fc--- /dev/null+++ b/api/catalog/api/migrations/0047_help_text.py@@ -0,0 +1,114 @@+# Generated by Django 4.0.4 on 2022-05-13 09:43++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('api', '0046_alter_throttledapplication_user'),+ ]++ operations = [+ migrations.AlterField(+ model_name='audio',+ name='creator',+ field=models.CharField(blank=True, help_text='The name of the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='audio',+ name='creator_url',+ field=models.URLField(blank=True, help_text='A direct link to the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='audio',+ name='genres',+ field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=80), db_index=True, help_text='An array of audio genres such as `rock`, `electronic` for `music` category, or `politics`, `sport`, `education` for `podcast` category', null=True, size=None),+ ),+ migrations.AlterField(+ model_name='audio',+ name='license',+ field=models.CharField(help_text='The name of license for the media.', max_length=50),+ ),+ migrations.AlterField(+ model_name='audio',+ name='license_version',+ field=models.CharField(blank=True, help_text='The version of the media license.', max_length=25, null=True),+ ),+ migrations.AlterField(+ model_name='audio',+ name='tags',+ field=models.JSONField(blank=True, help_text='Tags with detailed metadata, such as accuracy.', null=True),+ ),+ migrations.AlterField(+ model_name='audio',+ name='tags_list',+ field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255), blank=True, help_text='List of tags names without detailed metadata.', null=True, size=None),+ ),+ migrations.AlterField(+ model_name='audio',+ name='title',+ field=models.CharField(blank=True, help_text='The name of the media.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='audioset',+ name='creator',+ field=models.CharField(blank=True, help_text='The name of the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='audioset',+ name='creator_url',+ field=models.URLField(blank=True, help_text='A direct link to the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='audioset',+ name='title',+ field=models.CharField(blank=True, help_text='The name of the media.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='creator',+ field=models.CharField(blank=True, help_text='The name of the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='creator_url',+ field=models.URLField(blank=True, help_text='A direct link to the media creator.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='height',+ field=models.IntegerField(blank=True, help_text='The height of the image in pixels. Not always available.', null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='license',+ field=models.CharField(help_text='The name of license for the media.', max_length=50),+ ),+ migrations.AlterField(+ model_name='image',+ name='license_version',+ field=models.CharField(blank=True, help_text='The version of the media license.', max_length=25, null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='tags',+ field=models.JSONField(blank=True, help_text='Tags with detailed metadata, such as accuracy.', null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='tags_list',+ field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255), blank=True, help_text='List of tags names without detailed metadata.', null=True, size=None),+ ),+ migrations.AlterField(+ model_name='image',+ name='title',+ field=models.CharField(blank=True, help_text='The name of the media.', max_length=2000, null=True),+ ),+ migrations.AlterField(+ model_name='image',+ name='width',+ field=models.IntegerField(blank=True, help_text='The width of the image in pixels. Not always available.', null=True),+ ),+ ]diff --git a/api/catalog/api/models/audio.py b/api/catalog/api/models/audio.pyindex 7ad5ecc3f..9e8e269d1 100644--- a/api/catalog/api/models/audio.py+++ b/api/catalog/api/models/audio.py@@ -158,8 +158,9 @@ class Audio(AudioFileMixin, AbstractMedia):),null=True,db_index=True,- help_text="The artistic style of this audio file, "- "eg. hip-hop (music) / tech (podcasts).",+ help_text="An array of audio genres such as "+ "`rock`, `electronic` for `music` category, or "+ "`politics`, `sport`, `education` for `podcast` category",)duration = models.IntegerField(diff --git a/api/catalog/api/models/image.py b/api/catalog/api/models/image.pyindex c2db5f991..009fde502 100644--- a/api/catalog/api/models/image.py+++ b/api/catalog/api/models/image.py@@ -19,8 +19,16 @@ class ImageFileMixin(FileMixin):mixin. Do not use this as the sole base class."""- width = models.IntegerField(blank=True, null=True)- height = models.IntegerField(blank=True, null=True)+ width = models.IntegerField(+ blank=True,+ null=True,+ help_text="The width of the image in pixels. Not always available.",+ )+ height = models.IntegerField(+ blank=True,+ null=True,+ help_text="The height of the image in pixels. Not always available.",+ )@propertydef resolution_in_mp(self): # ~ MP or megapixelsdiff --git a/api/catalog/api/models/media.py b/api/catalog/api/models/media.pyindex 0e1cbb9f6..7ca538b36 100644--- a/api/catalog/api/models/media.py+++ b/api/catalog/api/models/media.py@@ -35,8 +35,16 @@ class AbstractMedia(watermarked = models.BooleanField(blank=True, null=True)- license = models.CharField(max_length=50)- license_version = models.CharField(max_length=25, blank=True, null=True)+ license = models.CharField(+ max_length=50,+ help_text="The name of license for the media.",+ )+ license_version = models.CharField(+ max_length=25,+ blank=True,+ null=True,+ help_text="The version of the media license.",+ )source = models.CharField(max_length=80,@@ -56,8 +64,17 @@ class AbstractMedia(default=0,)- tags = models.JSONField(blank=True, null=True)- tags_list = ArrayField(models.CharField(max_length=255), blank=True, null=True)+ tags = models.JSONField(+ blank=True,+ null=True,+ help_text="Tags with detailed metadata, such as accuracy.",+ )+ tags_list = ArrayField(+ base_field=models.CharField(max_length=255),+ blank=True,+ null=True,+ help_text="List of tags names without detailed metadata.",+ )category = models.CharField(max_length=80,@@ -70,19 +87,19 @@ class AbstractMedia(meta_data = models.JSONField(blank=True, null=True)@property- def license_url(self):+ def license_url(self) -> str:+ """A direct link to the license deed or legal terms."""+if self.meta_data and (url := self.meta_data.get("license_url")):return urlelse:return get_license_url(self.license.lower(), self.license_version)@property- def attribution(self):+ def attribution(self) -> str:"""- Get the plain-text English attribution for a media item. Refer to the frontend- source code for an internationalised implementation.-- :return: the plain-text English-language attribution for a creative work+ The plain-text English attribution for a media item. Use this to credit creators+ for their work and fulfill legal attribution requirements."""return get_attribution_text(diff --git a/api/catalog/api/models/mixins.py b/api/catalog/api/models/mixins.pyindex d46f53d01..61b736356 100644--- a/api/catalog/api/models/mixins.py+++ b/api/catalog/api/models/mixins.py@@ -9,8 +9,8 @@ class IdentifierMixin(models.Model):any model. Do not use this as the sole base class.The mixins adds+- identifier: UUIDField- - foreign_identifier: CharField"""identifier = models.UUIDField(@@ -27,6 +27,10 @@ class ForeignIdentifierMixin(models.Model):"""This mixin adds fields related to the external unique ID to any model. Donot use this as the sole base class.++ This mixin adds++ - foreign_identifier: CharField"""foreign_identifier = models.CharField(@@ -47,13 +51,21 @@ class MediaMixin(models.Model):the work and info about the artist. Do not use this as the sole base class.The mixin adds+- title: CharField- foreign_landing_url: CharField- creator: CharField- creator_url: CharField+ - thumbnail: URLField+ - provider: CharField"""- title = models.CharField(max_length=2000, blank=True, null=True)+ title = models.CharField(+ max_length=2000,+ blank=True,+ null=True,+ help_text="The name of the media.",+ )foreign_landing_url = models.CharField(max_length=1000,blank=True,@@ -61,12 +73,27 @@ class MediaMixin(models.Model):help_text="The landing page of the work.",)- creator = models.CharField(max_length=2000, blank=True, null=True)- creator_url = models.URLField(max_length=2000, blank=True, null=True)+ creator = models.CharField(+ max_length=2000,+ blank=True,+ null=True,+ help_text="The name of the media creator.",+ )+ creator_url = models.URLField(+ max_length=2000,+ blank=True,+ null=True,+ help_text="A direct link to the media creator.",+ )# Because all forms of media have a thumbnail for visual representation+ # For images, this field is not used as images are generated using ``imaginary``.+ # For audio, this field points to the artwork, or is ``null``.thumbnail = models.URLField(- max_length=1000, blank=True, null=True, help_text="The thumbnail for the media."+ max_length=1000,+ blank=True,+ null=True,+ help_text="The thumbnail for the media.",)# This is different from ``source`` (see ``AbstractMedia``)@@ -86,6 +113,12 @@ class FileMixin(models.Model):"""This mixin adds fields related to file such as the file URL and size to anymodel. Do not use this as the sole base class.++ This mixin adds++ - url: URLField+ - filesize: IntegerField+ - filetype: CharField"""url = models.URLField(diff --git a/api/catalog/api/serializers/audio_serializers.py b/api/catalog/api/serializers/audio_serializers.pyindex 5b769a24b..0de367bb8 100644--- a/api/catalog/api/serializers/audio_serializers.py+++ b/api/catalog/api/serializers/audio_serializers.py@@ -2,49 +2,30 @@ from rest_framework import serializersfrom elasticsearch_dsl.response import Hit+from catalog.api.constants.field_order import field_position_mapfrom catalog.api.constants.field_values import AUDIO_CATEGORIES, LENGTHSfrom catalog.api.docs.media_docs import fields_to_md-from catalog.api.models import AudioReport-from catalog.api.models.audio import Audio-from catalog.api.serializers.base import SchemableHyperlinkedIdentityField+from catalog.api.models import Audio, AudioReport, AudioSet+from catalog.api.serializers.fields import (+ EnumCharField,+ SchemableHyperlinkedIdentityField,+)from catalog.api.serializers.media_serializers import (+ MediaReportRequestSerializer,MediaSearchRequestSerializer,MediaSearchSerializer,MediaSerializer,- _validate_enum,+ get_hyperlinks_serializer,get_search_request_source_serializer,)-from catalog.api.utils.help_text import make_comma_separated_help_text---class AudioSetSerializer(serializers.Serializer):- """An audio set, rendered as a part of the ``AudioSerializer`` output."""- title = serializers.CharField(help_text="The name of the media.", required=False)- foreign_landing_url = serializers.URLField(- required=False, help_text="A foreign landing link for the image."- )-- creator = serializers.CharField(- help_text="The name of the media creator.", required=False, allow_blank=True- )- creator_url = serializers.URLField(- required=False, help_text="A direct link to the media creator."- )- url = serializers.URLField(help_text="The actual URL to the media file.")- filesize = serializers.CharField(- required=False, help_text="Number in bytes, e.g. 1024."- )- filetype = serializers.CharField(- required=False,- help_text="The type of the file, related to the file extension.",- )+#######################+# Request serializers #+#######################-AudioSearchRequestSourceSerializer = get_search_request_source_serializer(- "audio"-) # class+AudioSearchRequestSourceSerializer = get_search_request_source_serializer("audio")class AudioSearchRequestSerializer(@@ -64,107 +45,92 @@ class AudioSearchRequestSerializer(used to generate Swagger documentation."""- category = serializers.CharField(- label="category",- help_text=make_comma_separated_help_text(AUDIO_CATEGORIES, "categories"),+ category = EnumCharField(+ plural="categories",+ enum_class=AUDIO_CATEGORIES,required=False,)- length = serializers.CharField(- label="length",- help_text=make_comma_separated_help_text(LENGTHS, "audio lengths"),+ length = EnumCharField(+ plural="lengths",+ enum_class=LENGTHS,required=False,)- @staticmethod- def validate_category(value):- _validate_enum("category", AUDIO_CATEGORIES, value)- return value.lower()- @staticmethod- def validate_length(value):- _validate_enum("length", LENGTHS, value)- return value.lower()+class AudioReportRequestSerializer(MediaReportRequestSerializer):+ class Meta(MediaReportRequestSerializer.Meta):+ model = AudioReport-class AudioSerializer(MediaSerializer):- """A single audio file. Used in search results."""+########################+# Response serializers #+########################- fields_names = [- *MediaSerializer.fields_names,- "audio_set",- "genre",- "duration",- "bit_rate",- "sample_rate",- "alt_files",- "detail_url",- "related_url",- "category",- ]- """- Keep the fields names in sync with the actual fields below as this list is- used to generate Swagger documentation.- """- audio_set = AudioSetSerializer(- required=False,- help_text="Reference to set of which this track is a part.",- read_only=True,- )+class AudioSetSerializer(serializers.ModelSerializer):+ """An audio set, rendered as a part of the ``AudioSerializer`` output."""- genres = serializers.ListField(- child=serializers.CharField(),- required=False,- help_text="An array of audio genres such as "- "`rock`, `electronic` for `music` category, or "- "`politics`, `sport`, `education` for `podcast` category",- )+ class Meta:+ model = AudioSet+ fields = [+ "title",+ "foreign_landing_url",+ "creator",+ "creator_url",+ "url",+ "filesize",+ "filetype",+ ]- duration = serializers.IntegerField(- required=False, help_text="The time length of the audio file in milliseconds."- )- bit_rate = serializers.IntegerField(- required=False, help_text="Number in bits per second, eg. 128000."- )- sample_rate = serializers.IntegerField(- required=False, help_text="Number in hertz, eg. 44100."- )- alt_files = serializers.JSONField(- required=False, help_text="JSON describing alternative files for this audio."- )+AudioHyperlinksSerializer = get_hyperlinks_serializer("audio")+++class AudioSerializer(AudioHyperlinksSerializer, MediaSerializer):+ """A single audio file. Used in search results."""++ class Meta:+ model = Audio+ fields = sorted( # keep this list ordered logically+ [+ *MediaSerializer.Meta.fields,+ *AudioHyperlinksSerializer.field_names,+ "genres",+ "alt_files",+ "audio_set",+ "duration",+ "bit_rate",+ "sample_rate",+ "waveform", # hyperlink to the endpoint that generates the waveform+ "peaks", # waveform peaks, if they have already been generated+ ],+ key=lambda val: field_position_map.get(val, 999),+ )+ """+ Keep the fields names in sync with the actual fields below as this list is+ used to generate Swagger documentation.+ """- # Hyperlinks- thumbnail = SchemableHyperlinkedIdentityField(+ audio_set = AudioSetSerializer(+ allow_null=True,+ help_text="Reference to set of which this track is a part.",read_only=True,- view_name="audio-thumb",- lookup_field="identifier",- help_text="A direct link to the miniature artwork.",)+waveform = SchemableHyperlinkedIdentityField(read_only=True,view_name="audio-waveform",lookup_field="identifier",help_text="A direct link to the waveform peaks.",)- detail_url = SchemableHyperlinkedIdentityField(- read_only=True,- view_name="audio-detail",- lookup_field="identifier",- help_text="A direct link to the detail view of this audio file.",- )- related_url = SchemableHyperlinkedIdentityField(- read_only=True,- view_name="audio-related",- lookup_field="identifier",- help_text="A link to an endpoint that provides similar audio files.",- )# Add-on data- peaks = serializers.SerializerMethodField()+ peaks = serializers.SerializerMethodField(+ help_text="The list of peaks used to generate the waveform for the audio."+ )@staticmethod- def get_peaks(obj):+ def get_peaks(obj) -> list[int]:if isinstance(obj, Hit):obj = Audio.objects.get(identifier=obj.identifier)return obj.get_waveform()@@ -181,30 +147,14 @@ class AudioSearchSerializer(MediaSearchSerializer):many=True,help_text=("An array of audios and their details such as "- f"{fields_to_md(AudioSerializer.fields_names)}."+ f"{fields_to_md(AudioSerializer.Meta.fields)}."),)-class AudioReportSerializer(serializers.ModelSerializer):- class Meta:- model = AudioReport- fields = ("identifier", "reason", "description")- read_only_fields = ("identifier",)-- def create(self, validated_data):- if (- validated_data["reason"] == "other"- and (- "description" not in validated_data- or len(validated_data["description"])- )- < 20- ):- raise serializers.ValidationError(- "Description must be at least be 20 characters long"- )- return AudioReport.objects.create(**validated_data)+##########################+# Additional serializers #+##########################class AudioWaveformSerializer(serializers.Serializer):diff --git a/api/catalog/api/serializers/base.py b/api/catalog/api/serializers/base.pyindex ca54759b6..1affab8c5 100644--- a/api/catalog/api/serializers/base.py+++ b/api/catalog/api/serializers/base.py@@ -1,24 +1,25 @@-import re--from django.conf import settingsfrom rest_framework import serializers-class SchemableHyperlinkedIdentityField(serializers.HyperlinkedIdentityField):+class BaseModelSerializer(serializers.ModelSerializer):"""- This field returns the link but allows the option to replace the URL scheme.+ Extends model serializer to use docstring of properties as help text."""- def __init__(self, scheme=settings.API_LINK_SCHEME, *args, **kwargs):- super().__init__(*args, **kwargs)-- self.scheme = scheme-- def get_url(self, *args, **kwargs):- url = super().get_url(*args, **kwargs)-- # Only rewrite URLs if a fixed scheme is provided- if self.scheme is not None:- url = re.sub(r"^\w+://", f"{self.scheme}://", url, 1)-- return url+ def build_property_field(self, field_name, model_class):+ """+ Overrides the built-in property field builder to use docstrings as the Swagger+ help text for fields.++ :param field_name: the name of the property for which the field is being built+ :param model_class: the ``class`` instance for the Django model+ :return: the Field subclass to use and the keyword arguments to pass to it+ """++ klass, kwargs = super().build_property_field(field_name, model_class)+ kwargs |= {+ "allow_null": True, # model computed properties are not present in ``Hit``+ }+ if doc := getattr(model_class, field_name).__doc__:+ kwargs.setdefault("help_text", doc)+ return klass, kwargsdiff --git a/api/catalog/api/serializers/fields.py b/api/catalog/api/serializers/fields.pynew file mode 100644index 000000000..f21e2c7ba--- /dev/null+++ b/api/catalog/api/serializers/fields.py@@ -0,0 +1,66 @@+import re++from django.conf import settings+from rest_framework import serializers++from catalog.api.utils.help_text import make_comma_separated_help_text+++class SchemableHyperlinkedIdentityField(serializers.HyperlinkedIdentityField):+ """+ This field returns the link but allows the option to replace the URL scheme.++ This is useful when the API runs on ``http`` behind a proxy that serves ``https``.+ In these cases, the scheme in hyperlinks must be forced to ``https``.+ """++ def __init__(self, scheme=settings.API_LINK_SCHEME, *args, **kwargs):+ super().__init__(*args, **kwargs)++ self.scheme = scheme++ def get_url(self, *args, **kwargs):+ url = super().get_url(*args, **kwargs)++ # Only rewrite URLs if a fixed scheme is provided+ if self.scheme is not None:+ url = re.sub(r"^\w+://", f"{self.scheme}://", url, 1)++ return url+++class EnumCharField(serializers.CharField):+ """+ This field extends the ``CharField`` to add enum validation.+ """++ default_error_messages = serializers.CharField.default_error_messages | {+ "outside_enum": "Invalid value: {given}. Allowed values: {allowed}"+ }++ def __init__(self, plural: str, enum_class: set[str], **kwargs):+ kwargs["help_text"] = make_comma_separated_help_text(enum_class, plural)+ super().__init__(**kwargs)++ self.enum_class = enum_class++ def _validate_enum(self, given_value: str):+ """+ Validate whether the given values are all members of the given enum.++ :param given_value: the comma separated list received in the input+ :return: the lower cased form of the input, if the input is valid+ :raise: ``ValidationError``, if the input is invalid+ """++ lower = given_value.lower()+ input_values = lower.split(",")+ for value in input_values:+ if value not in self.enum_class:+ self.fail("outside_enum", given=value, allowed=self.enum_class)+ return lower++ def to_internal_value(self, data):+ data = super().to_internal_value(data)+ self._validate_enum(data)+ return datadiff --git a/api/catalog/api/serializers/image_serializers.py b/api/catalog/api/serializers/image_serializers.pyindex 2380932f0..fcae44eac 100644--- a/api/catalog/api/serializers/image_serializers.py+++ b/api/catalog/api/serializers/image_serializers.py@@ -1,5 +1,6 @@from rest_framework import serializers+from catalog.api.constants.field_order import field_position_mapfrom catalog.api.constants.field_values import (ASPECT_RATIOS,IMAGE_CATEGORIES,@@ -7,21 +8,25 @@ from catalog.api.constants.field_values import ()from catalog.api.docs.media_docs import fields_to_mdfrom catalog.api.models import Image, ImageReport-from catalog.api.serializers.base import SchemableHyperlinkedIdentityField+from catalog.api.serializers.base import BaseModelSerializer+from catalog.api.serializers.fields import EnumCharFieldfrom catalog.api.serializers.media_serializers import (+ MediaReportRequestSerializer,MediaSearchRequestSerializer,MediaSearchSerializer,MediaSerializer,- _add_protocol,- _validate_enum,+ get_hyperlinks_serializer,get_search_request_source_serializer,)-from catalog.api.utils.help_text import make_comma_separated_help_text+from catalog.api.utils.url import add_protocol-ImageSearchRequestSourceSerializer = get_search_request_source_serializer(- "image"-) # class+#######################+# Request serializers #+#######################+++ImageSearchRequestSourceSerializer = get_search_request_source_serializer("image")class ImageSearchRequestSerializer(@@ -43,82 +48,53 @@ class ImageSearchRequestSerializer("""# Ref: ingestion_server/ingestion_server/categorize.py#Category- category = serializers.CharField(- label="category",- help_text=make_comma_separated_help_text(IMAGE_CATEGORIES, "categories"),+ category = EnumCharField(+ plural="categories",+ enum_class=IMAGE_CATEGORIES,required=False,)- aspect_ratio = serializers.CharField(- label="aspect_ratio",- help_text=make_comma_separated_help_text(ASPECT_RATIOS, "aspect ratios"),+ aspect_ratio = EnumCharField(+ plural="aspect ratios",+ enum_class=ASPECT_RATIOS,required=False,)- size = serializers.CharField(- label="size",- help_text=make_comma_separated_help_text(IMAGE_SIZES, "image sizes"),+ size = EnumCharField(+ plural="image sizes",+ enum_class=IMAGE_SIZES,required=False,)- @staticmethod- def validate_category(value):- _validate_enum("category", IMAGE_CATEGORIES, value)- return value.lower()- @staticmethod- def validate_aspect_ratio(value):- _validate_enum("aspect ratio", ASPECT_RATIOS, value)- return value.lower()+class ImageReportRequestSerializer(MediaReportRequestSerializer):+ class Meta(MediaReportRequestSerializer.Meta):+ model = ImageReport- @staticmethod- def validate_size(value):- _validate_enum("size", IMAGE_SIZES, value)- return value.lower()+########################+# Response serializers #+########################-class ImageSerializer(MediaSerializer):- """A single image. Used in search results."""+ImageHyperlinksSerializer = get_hyperlinks_serializer("image")- fields_names = [- *MediaSerializer.fields_names,- "thumbnail",- "height",- "width",- "detail_url",- "related_url",- ]- """- Keep the fields names in sync with the actual fields below as this list is- used to generate Swagger documentation.- """- height = serializers.IntegerField(- required=False,- help_text="The height of the image in pixels. Not always available.",- )- width = serializers.IntegerField(- required=False,- help_text="The width of the image in pixels. Not always available.",- )+class ImageSerializer(ImageHyperlinksSerializer, MediaSerializer):+ """A single image. Used in search results."""- # Hyperlinks- thumbnail = SchemableHyperlinkedIdentityField(- read_only=True,- view_name="image-thumb",- lookup_field="identifier",- help_text="A direct link to the miniature image.",- )- detail_url = SchemableHyperlinkedIdentityField(- read_only=True,- view_name="image-detail",- lookup_field="identifier",- help_text="A direct link to the detail view of this image.",- )- related_url = SchemableHyperlinkedIdentityField(- view_name="image-related",- lookup_field="identifier",- read_only=True,- help_text="A link to an endpoint that provides similar images.",- )+ class Meta:+ model = Image+ fields = sorted( # keep this list ordered logically+ [+ *MediaSerializer.Meta.fields,+ *ImageHyperlinksSerializer.field_names,+ "height",+ "width",+ ],+ key=lambda val: field_position_map.get(val, 999),+ )+ """+ Keep the fields names in sync with the actual fields below as this list is+ used to generate Swagger documentation.+ """class ImageSearchSerializer(MediaSearchSerializer):@@ -132,54 +108,40 @@ class ImageSearchSerializer(MediaSearchSerializer):many=True,help_text=("An array of images and their details such as "- f"{fields_to_md(ImageSerializer.fields_names)}."+ f"{fields_to_md(ImageSerializer.Meta.fields)}."),)+##########################+# Additional serializers #+##########################++class OembedRequestSerializer(serializers.Serializer):"""Parse and validate Oembed parameters."""url = serializers.CharField(help_text="The link to an image.",- required=True,)@staticmethoddef validate_url(value):- return _add_protocol(value)+ return add_protocol(value)-class ImageReportSerializer(serializers.ModelSerializer):- class Meta:- model = ImageReport- fields = ("identifier", "reason", "description")- read_only_fields = ("identifier",)-- def create(self, validated_data):- if (- validated_data["reason"] == "other"- and (- "description" not in validated_data- or len(validated_data["description"])- )- < 20- ):- raise serializers.ValidationError(- "Description must be at least be 20 characters long"- )- return ImageReport.objects.create(**validated_data)---class OembedSerializer(serializers.ModelSerializer):- """The embedded content from a specified image URL."""+class OembedSerializer(BaseModelSerializer):+ """+ The embedded content from a specified image URL. This is essentially an+ ``ImageSerializer`` with some changes to match the oEmbed spec: https://oembed.com.+ """version = serializers.ReadOnlyField(- help_text="The image version.",+ help_text="The oEmbed version number. This must be 1.0.",default="1.0",)type = serializers.ReadOnlyField(- help_text="Type of data.",+ help_text="The resource type. This must be 'photo' for images.",default="photo",)width = serializers.SerializerMethodField(@@ -188,18 +150,14 @@ class OembedSerializer(serializers.ModelSerializer):height = serializers.SerializerMethodField(help_text="The height of the image in pixels.")- title = serializers.CharField(help_text="The name of image.")author_name = serializers.CharField(- help_text="The name of author for image.",+ help_text="The name of the media creator.", # ``copied from ``Image``source="creator",)author_url = serializers.URLField(- help_text="A direct link to the author.",+ help_text="A direct link to the media creator.", # copied from ``Image``source="creator_url",)- license_url = serializers.URLField(- help_text="A direct link to the license for image."- )class Meta:model = Imagediff --git a/api/catalog/api/serializers/media_serializers.py b/api/catalog/api/serializers/media_serializers.pyindex f4467eacd..4d10c0583 100644--- a/api/catalog/api/serializers/media_serializers.py+++ b/api/catalog/api/serializers/media_serializers.py@@ -1,116 +1,19 @@from collections import namedtuple-from urllib.parse import urlparsefrom rest_framework import serializersfrom catalog.api.constants.licenses import LICENSE_GROUPSfrom catalog.api.controllers import search_controller+from catalog.api.models.media import AbstractMedia+from catalog.api.serializers.base import BaseModelSerializer+from catalog.api.serializers.fields import SchemableHyperlinkedIdentityFieldfrom catalog.api.utils.help_text import make_comma_separated_help_text+from catalog.api.utils.url import add_protocol-def _validate_enum(enum_name, valid_values: set, given_values: str):- """- Validate whether the given values are all members of the given enum.-- :param valid_values: Allowed values for an enum- :param given_values: A comma separated list of values.- :return: whether the input is valid- """- input_values = given_values.lower().split(",")- for value in input_values:- if value not in valid_values:- raise serializers.ValidationError(- f"Invalid {enum_name}: {value}." f" Available options: {valid_values}"- )- return given_values.lower()---def _add_protocol(url: str):- """- Some fields in the database contain incomplete URLs, leading to unexpected- behavior in downstream consumers. This helper verifies that we always return- fully formed URLs in such situations.- """- parsed = urlparse(url)- if parsed.scheme == "":- return f"https://{url}"- else:- return url---def format_enums(values: list[str]) -> str:- """- Format a list of strings into a combined string where items are comma separated and- surrounded by backticks.-- :param values: the list of valid values- :return: a string representation of these values- """-- return ",".join([f"`{value}`" for value in values])---class TagSerializer(serializers.Serializer):- name = serializers.CharField(required=True, help_text="The name of a detailed tag.")- accuracy = serializers.FloatField(- required=False,- help_text="The accuracy of a machine-generated tag. Human-generated "- "tags do not have an accuracy field.",- )---def get_search_request_source_serializer(media_type):- class MediaSearchRequestSourceSerializer(serializers.Serializer):- """- This serializer parses and validates the source/not_source fields from the query- parameters.- """-- field_names = [- "source",- "excluded_source",- ]- """- Keep the fields names in sync with the actual fields below as this list is- used to generate Swagger documentation.- """-- _field_attrs = {- "help_text": make_comma_separated_help_text(- search_controller.get_sources(media_type).keys(), "data sources"- ),- "required": False,- }-- source = serializers.CharField(label="provider", **_field_attrs)- excluded_source = serializers.CharField(- label="excluded_provider", **_field_attrs- )-- @staticmethod- def validate_source_field(input_sources):- allowed_sources = list(search_controller.get_sources(media_type).keys())- input_sources = input_sources.split(",")- input_sources = [x for x in input_sources if x in allowed_sources]- input_sources = ",".join(input_sources)- return input_sources.lower()-- def validate_source(self, input_sources):- return self.validate_source_field(input_sources)-- def validate_excluded_source(self, input_sources):- return self.validate_source(input_sources)-- def validate(self, data):- data = super().validate(data)- if "source" in self.initial_data and "excluded_source" in self.initial_data:- raise serializers.ValidationError(- "Cannot set both 'source' and 'excluded_source'. "- "Use exactly one of these."- )- return data-- return MediaSearchRequestSourceSerializer+#######################+# Request serializers #+#######################class MediaSearchRequestSerializer(serializers.Serializer):@@ -220,7 +123,7 @@ class MediaSearchRequestSerializer(serializers.Serializer):raise serializers.ValidationError(f"License '{_license}' does not exist.")- return value.lower()+ return value@staticmethoddef validate_license_type(value):@@ -264,163 +167,265 @@ class MediaSearchRequestSerializer(serializers.Serializer):return data-class MediaSerializer(serializers.Serializer):+class MediaThumbnailRequestSerializer(serializers.Serializer):"""- This serializer serializes a single media file. The class should be- inherited by all individual media serializers.+ This serializer parses and validates thumbnail query string parameters."""- fields_names = [- "id",- "title",- "foreign_landing_url",- "creator",- "creator_url",- "url",- "filesize",- "filetype",- "license",- "license_version",- "license_url",- "provider",- "source",- "category",- "tags",- "fields_matched",- "attribution",- ]- """- Keep the fields names in sync with the actual fields below as this list is- used to generate Swagger documentation.- """+ full_size = serializers.BooleanField(+ source="is_full_size",+ allow_null=True,+ required=False,+ default=False,+ help_text="whether to render the actual image and not a thumbnail version",+ )+ compressed = serializers.BooleanField(+ source="is_compressed",+ allow_null=True,+ default=None,+ required=False,+ help_text="whether to compress the output image to reduce file size,"+ "defaults to opposite of `full_size`",+ )- requires_context = True+ def validate(self, data):+ if data.get("is_compressed") is None:+ data["is_compressed"] = not data["is_full_size"]+ return data- # Fields corresponding to IdentifierMixin- id = serializers.CharField(- required=True,- help_text="Our unique identifier for an open-licensed work.",- source="identifier",- )- # Fields corresponding to MediaMixin- title = serializers.CharField(help_text="The name of the media.", required=False)- foreign_landing_url = serializers.URLField(- required=False, help_text="A foreign landing link for the image."- )+class MediaReportRequestSerializer(serializers.ModelSerializer):+ class Meta:+ model = None+ fields = ["identifier", "reason", "description"]+ read_only_fields = ["identifier"]- creator = serializers.CharField(- help_text="The name of the media creator.", required=False, allow_blank=True- )- creator_url = serializers.URLField(- required=False, help_text="A direct link to the media creator."- )+ def validate(self, attrs):+ if (+ attrs["reason"] == "other"+ and ("description" not in attrs or len(attrs["description"])) < 20+ ):+ raise serializers.ValidationError(+ "Description must be at least be 20 characters long"+ )+ return attrs+++########################+# Response serializers #+########################- # Fields corresponding to FileMixin- url = serializers.URLField(help_text="The actual URL to the media file.")- filesize = serializers.CharField(- required=False, help_text="Number in bytes, e.g. 1024."++class TagSerializer(serializers.Serializer):+ """+ This output serializer serializes a singular tag.+ """++ name = serializers.CharField(+ help_text="The name of a detailed tag.",)- filetype = serializers.CharField(+ accuracy = serializers.FloatField(required=False,- help_text="The type of the file, related to the file extension.",+ help_text="The accuracy of a machine-generated tag. Human-generated "+ "tags do not have an accuracy field.",)- # Fields corresponding to AbstractMedia- license = serializers.SerializerMethodField(- help_text="The name of license for the media."++class MediaSearchSerializer(serializers.Serializer):+ """+ This serializer serializes the full media search response. The class should+ be inherited by all individual media serializers.+ """++ result_count = serializers.IntegerField(+ help_text="The total number of items returned by search result.",)- license_version = serializers.CharField(- required=False, help_text="The type of license for the media."+ page_count = serializers.IntegerField(+ help_text="The total number of pages returned by search result.",)- license_url = serializers.URLField(help_text="A direct link to the media license.")-- provider = serializers.CharField(required=False, help_text="The content provider.")- source = serializers.CharField(- required=False,- help_text="The source of the data, meaning a particular dataset.",+ page_size = serializers.IntegerField(+ help_text="The number of items per page.",)+ page = serializers.IntegerField(+ help_text="The current page number returned in the response.",+ )+ # ``results`` field added by child serializers+++class MediaSerializer(BaseModelSerializer):+ """+ This serializer serializes a single media file. The class should be+ inherited by all individual media serializers.+ """- category = serializers.CharField(- required=True, allow_null=True, help_text="The category of the media."+ class Meta:+ model = AbstractMedia+ fields = [+ "id",+ "title",+ "foreign_landing_url",+ "url",+ "creator",+ "creator_url",+ "license",+ "license_version",+ "license_url", # property+ "provider",+ "source",+ "category",+ "filesize",+ "filetype",+ "tags",+ "attribution", # property+ "fields_matched",+ "mature",+ ]+ """+ Keep the fields names in sync with the actual fields below as this list is+ used to generate Swagger documentation.+ """++ id = serializers.CharField(+ help_text="Our unique identifier for an open-licensed work.",+ source="identifier",)tags = TagSerializer(- allow_null=True,+ allow_null=True, # replaced with ``[]`` in ``to_representation`` belowmany=True,help_text="Tags with detailed metadata, such as accuracy.",)- # Additional fieldsfields_matched = serializers.ListField(- required=False,+ allow_null=True, # replaced with ``[]`` in ``to_representation`` belowhelp_text="List the fields that matched the query for this result.",)- attribution = serializers.CharField(- required=False,- help_text="The attribution of the work in English as plain-text. Use this to"- "credit creators for their work and fulfill legal attribution requirements.",++ mature = serializers.BooleanField(+ allow_null=True, # present in ``Hit`` but not in Django media models+ help_text="Whether the media item is marked as mature",)- def get_license(self, obj):- return obj.license.lower()+ def to_representation(self, *args, **kwargs):+ output = super().to_representation(*args, **kwargs)- def validate_url(self, value):- return _add_protocol(value)+ # Ensure lists are ``[]`` instead of ``None``+ # TODO: These fields are still marked 'Nullable' in the API docs+ list_fields = ["tags", "fields_matched"]+ for list_field in list_fields:+ if output[list_field] is None:+ output[list_field] = []- def validate_creator_url(self, value):- return _add_protocol(value)+ # Ensure license is lowercase+ output["license"] = output["license"].lower()- def validate_foreign_landing_url(self, value):- return _add_protocol(value)+ # Ensure URLs have scheme+ url_fields = ["url", "creator_url", "foreign_landing_url"]+ for url_field in url_fields:+ output[url_field] = add_protocol(output[url_field])- def to_representation(self, *args, **kwargs):- repr = super().to_representation(*args, **kwargs)- if repr["tags"] is None:- repr["tags"] = [] # ``tags`` should always be a list, even if empty- return repr+ return output-class MediaSearchSerializer(serializers.Serializer):- """- This serializer serializes the full media search response. The class should- be inherited by all individual media serializers.- """+#######################+# Dynamic serializers #+#######################- result_count = serializers.IntegerField(- help_text="The total number of items returned by search result."- )- page_count = serializers.IntegerField(- help_text="The total number of pages returned by search result."- )- page_size = serializers.IntegerField(help_text="The number of items per page.")- page = serializers.IntegerField(- help_text="The current page number returned in the response."- )+def get_search_request_source_serializer(media_type):+ class MediaSearchRequestSourceSerializer(serializers.Serializer):+ """+ This serializer parses and validates the source/not_source fields from the query+ parameters.+ """-class MediaThumbnailRequestSerializer(serializers.Serializer):- """- This serializer parses and validates thumbnail query string parameters.- """+ field_names = [+ "source",+ "excluded_source",+ ]+ """+ Keep the fields names in sync with the actual fields below as this list is+ used to generate Swagger documentation.+ """- full_size = serializers.BooleanField(- source="is_full_size",- allow_null=True,- required=False,- default=False,- help_text="whether to render the actual image and not a thumbnail version",- )- compressed = serializers.BooleanField(- source="is_compressed",- allow_null=True,- default=None,- required=False,- help_text="whether to compress the output image to reduce file size,"- "defaults to opposite of `full_size`",- )+ _field_attrs = {+ "help_text": make_comma_separated_help_text(+ search_controller.get_sources(media_type).keys(), "data sources"+ ),+ "required": False,+ }- def validate(self, data):- if data.get("is_compressed") is None:- data["is_compressed"] = not data["is_full_size"]- return data+ source = serializers.CharField(+ label="provider",+ **_field_attrs,+ )+ excluded_source = serializers.CharField(+ label="excluded_provider",+ **_field_attrs,+ )++ @staticmethod+ def validate_source_field(value):+ """Checks whether source is a valid source."""++ allowed_sources = list(search_controller.get_sources(media_type).keys())+ sources = value.lower().split(",")+ sources = [source for source in sources if source in allowed_sources]+ value = ",".join(sources)+ return value++ def validate_source(self, input_sources):+ return self.validate_source_field(input_sources)++ def validate_excluded_source(self, input_sources):+ return self.validate_source(input_sources)++ def validate(self, data):+ data = super().validate(data)+ if "source" in self.initial_data and "excluded_source" in self.initial_data:+ raise serializers.ValidationError(+ "Cannot set both 'source' and 'excluded_source'. "+ "Use exactly one of these."+ )+ return data++ return MediaSearchRequestSourceSerializer+++def get_hyperlinks_serializer(media_type):+ class MediaHyperlinksSerializer(serializers.Serializer):+ """+ This serializer creates URLs pointing to other endpoints related with this media+ item such as details and related media.+ """++ field_names = [+ "thumbnail", # Not suffixed with `_url` because it points to an image+ "detail_url",+ "related_url",+ ]+ """+ Keep the fields names in sync with the actual fields below as this list is+ used to generate Swagger documentation.+ """++ thumbnail = SchemableHyperlinkedIdentityField(+ read_only=True,+ view_name=f"{media_type}-thumb",+ lookup_field="identifier",+ help_text="A direct link to the miniature artwork.",+ )+ detail_url = SchemableHyperlinkedIdentityField(+ read_only=True,+ view_name=f"{media_type}-detail",+ lookup_field="identifier",+ help_text="A direct link to the detail view of this audio file.",+ )+ related_url = SchemableHyperlinkedIdentityField(+ read_only=True,+ view_name=f"{media_type}-related",+ lookup_field="identifier",+ help_text="A link to an endpoint that provides similar audio files.",+ )++ return MediaHyperlinksSerializerdiff --git a/api/catalog/api/utils/url.py b/api/catalog/api/utils/url.pynew file mode 100644index 000000000..6e5ad28a8--- /dev/null+++ b/api/catalog/api/utils/url.py@@ -0,0 +1,18 @@+from urllib.parse import urlparse+++def add_protocol(url: str) -> str:+ """+ Some fields in the database contain incomplete URLs, leading to unexpected+ behavior in downstream consumers. This helper verifies that we always return+ fully formed URLs in such situations.++ :param url: the URL to check and add scheme+ :return: the URL with the existing scheme, or ``https`` if one did not exist+ """++ parsed = urlparse(url)+ if parsed.scheme == "":+ return f"https://{url}"+ else:+ return urldiff --git a/api/catalog/api/views/audio_views.py b/api/catalog/api/views/audio_views.pyindex f3ba2ac5f..620e6cebd 100644--- a/api/catalog/api/views/audio_views.py+++ b/api/catalog/api/views/audio_views.py@@ -16,7 +16,7 @@ from catalog.api.docs.audio_docs import ()from catalog.api.models import Audiofrom catalog.api.serializers.audio_serializers import (- AudioReportSerializer,+ AudioReportRequestSerializer,AudioSearchRequestSerializer,AudioSerializer,AudioWaveformSerializer,@@ -87,6 +87,10 @@ class AudioViewSet(MediaViewSet):except Exception as e:raise get_api_exception(getattr(e, "message", str(e)))- @action(detail=True, methods=["post"], serializer_class=AudioReportSerializer)+ @action(+ detail=True,+ methods=["post"],+ serializer_class=AudioReportRequestSerializer,+ )def report(self, *args, **kwargs):return super().report(*args, **kwargs)diff --git a/api/catalog/api/views/image_views.py b/api/catalog/api/views/image_views.pyindex eb3d056cd..6b3f40498 100644--- a/api/catalog/api/views/image_views.py+++ b/api/catalog/api/views/image_views.py@@ -23,7 +23,7 @@ from catalog.api.docs.image_docs import ()from catalog.api.models import Imagefrom catalog.api.serializers.image_serializers import (- ImageReportSerializer,+ ImageReportRequestSerializer,ImageSearchRequestSerializer,ImageSerializer,OembedRequestSerializer,@@ -160,7 +160,11 @@ class ImageViewSet(MediaViewSet):self._save_wrapper(watermarked, exif_bytes, response)return response- @action(detail=True, methods=["post"], serializer_class=ImageReportSerializer)+ @action(+ detail=True,+ methods=["post"],+ serializer_class=ImageReportRequestSerializer,+ )def report(self, *args, **kwargs):return super().report(*args, **kwargs)diff --git a/api/test/run_test.sh b/api/test/run_test.shindex e4fcb2bbe..9e6223300 100755--- a/api/test/run_test.sh+++ b/api/test/run_test.sh@@ -8,7 +8,11 @@ endcol="\e[0m"# ```# $ ./test/run_test.sh test/audio_integration_test.py# ```-TEST_ARG="${1:-test/}"+if [ $# -ge 1 ]; then+ TEST_ARG="$@"+else+ TEST_ARG="test/"+fiPYTHONWARNINGS="ignore:Unverified HTTPS request" \PYTHONPATH=. \diff --git a/ingestion_server/ingestion_server/elasticsearch_models.py b/ingestion_server/ingestion_server/elasticsearch_models.pyindex 3efe60cb8..0b1dc3a35 100644--- a/ingestion_server/ingestion_server/elasticsearch_models.py+++ b/ingestion_server/ingestion_server/elasticsearch_models.py@@ -214,8 +214,8 @@ class Image(Media):class AspectRatios(Enum):"""- These aspect ratios are also hardcoded in the `aspect_ratio` field in- api/catalog/api/serializers/image_serializers.py.+ These aspect ratios are also defined in+ ``api/catalog/api/constants/field_values.py.``"""TALL = auto()@@ -226,8 +226,8 @@ class Image(Media):"""Maximum threshold for each image size band- These sizes are also hardcoded in the `aspect_ratio` field in- api/catalog/api/serializers/image_serializers.py.+ These sizes are also defined in+ ``api/catalog/api/constants/field_values.py.``"""SMALL = 640 * 480@@ -300,8 +300,8 @@ class Audio(Media):"""Maximum threshold for each audio duration band- These durations are also hardcoded in the `duration` field in- api/catalog/api/serializers/audio_serializers.py.+ These durations are also defined in+ ``api/catalog/api/constants/field_values.py.``"""SHORTEST = 30 * 1e3 # under 30 secondsdiff --git a/ingestion_server/test/run_test.sh b/ingestion_server/test/run_test.shindex 7a5da9494..616a66275 100755--- a/ingestion_server/test/run_test.sh+++ b/ingestion_server/test/run_test.sh@@ -8,7 +8,11 @@ endcol="\e[0m"# ```# $ ./test/run_test.sh test/unit_test.py# ```-TEST_ARG="${1:-test/}"+if [ $# -ge 1 ]; then+ TEST_ARG="$@"+else+ TEST_ARG="test/"+fiPYTHONWARNINGS="ignore:Unverified HTTPS request" \PYTHONPATH=. \diff --git a/justfile b/justfileindex aaf39c134..24d31b26a 100644--- a/justfile+++ b/justfile@@ -184,11 +184,11 @@ _api-install:exit 0# Run API tests inside Docker-@api-test tests="": _api-up- just exec web ./test/run_test.sh {{ tests }}+@api-test *args: _api-up+ just exec web ./test/run_test.sh {{ args }}# Run API tests locally-api-testlocal args="":+api-testlocal *args:cd api && pipenv run ./test/run_test.sh {{ args }}# Run Django administrative commands locallydiff --git a/sample_data/sample_audio.csv b/sample_data/sample_audio.csvindex 16f2973c9..bae9abae5 100644--- a/sample_data/sample_audio.csv+++ b/sample_data/sample_audio.csv@@ -1,5 +1,5 @@identifier,created_on,updated_on,ingestion_type,provider,source,foreign_identifier,foreign_landing_url,url,thumbnail,filetype,duration,bit_rate,sample_rate,category,genres,audio_set,audio_set_position,alt_files,filesize,license,license_version,creator,creator_url,title,meta_data,tags,watermarked,last_synced_with_source,removed_from_source,standardized_popularity-8624ba61-57f1-4f98-8a85-ece206c319cf,2021-09-30 19:00:43.800462+00,2021-09-30 19:00:43.800462+00,provider_api,jamendo,jamendo,1214935,https://www.jamendo.com/track/1214935,https://mp3d.jamendo.com/download/track/1214935/mp32,https://usercontent.jamendo.com?type=album&id=145774&width=200&trackid=1214935,mp3,270000,,,music,"{dance,electronic,house}","{""url"": ""https://usercontent.jamendo.com?type=album&id=145774&width=200"", ""title"": ""Wish You Were Here"", ""creator"": ""The.madpix.project"", ""creator_url"": ""https://www.jamendo.com/artist/441585/the.madpix.project"", ""foreign_identifier"": ""145774"", ""foreign_landing_url"": ""https://www.jamendo.com/album/145774/wish-you-were-here""}",1,,,by-nc-sa,3.0,The.madpix.project,https://www.jamendo.com/artist/441585/the.madpix.project,Wish You Were Here,"{""lyrics"": ""There's not a single day that passes, without you on my mind. Not even one minute can end up, before you come around. I aim for the days when I see your face here before me. I long for the days when you held me in your arms. How I wish that you were here to give me everything I want. But I know that live's unfair and we can't always have it all.. I wish that you were here."", ""listens"": ""17959942"", ""downloads"": ""0"", ""playlists"": ""0"", ""license_url"": ""https://creativecommons.org/licenses/by-nc-sa/3.0/"", ""release_date"": ""2015-03-29"", ""raw_license_url"": ""http://creativecommons.org/licenses/by-nc-sa/3.0/""}","[{""name"": ""vocal"", ""provider"": ""jamendo""}, {""name"": ""female"", ""provider"": ""jamendo""}, {""name"": ""speed_medium"", ""provider"": ""jamendo""}, {""name"": ""guitar"", ""provider"": ""jamendo""}, {""name"": ""strings"", ""provider"": ""jamendo""}, {""name"": ""energetic"", ""provider"": ""jamendo""}, {""name"": ""acoustic"", ""provider"": ""jamendo""}, {""name"": ""vocal"", ""provider"": ""jamendo""}, {""name"": ""voice"", ""provider"": ""jamendo""}, {""name"": ""funkyhouse"", ""provider"": ""jamendo""}]",false,2021-09-30 19:00:43.800462+00,false,0.9920463953771244+8624ba61-57f1-4f98-8a85-ece206c319cf,2021-09-30 19:00:43.800462+00,2021-09-30 19:00:43.800462+00,provider_api,jamendo,jamendo,1214935,https://www.jamendo.com/track/1214935,https://mp3d.jamendo.com/download/track/1214935/mp32,https://usercontent.jamendo.com?type=album&id=145774&width=200&trackid=1214935,mp3,270000,128000,44100,music,"{dance,electronic,house}","{""url"": ""https://usercontent.jamendo.com?type=album&id=145774&width=200"", ""title"": ""Wish You Were Here"", ""creator"": ""The.madpix.project"", ""creator_url"": ""https://www.jamendo.com/artist/441585/the.madpix.project"", ""foreign_identifier"": ""145774"", ""foreign_landing_url"": ""https://www.jamendo.com/album/145774/wish-you-were-here""}",1,,7139840,by-nc-sa,3.0,The.madpix.project,https://www.jamendo.com/artist/441585/the.madpix.project,Wish You Were Here,"{""lyrics"": ""There's not a single day that passes, without you on my mind. Not even one minute can end up, before you come around. I aim for the days when I see your face here before me. I long for the days when you held me in your arms. How I wish that you were here to give me everything I want. But I know that live's unfair and we can't always have it all.. I wish that you were here."", ""listens"": ""17959942"", ""downloads"": ""0"", ""playlists"": ""0"", ""license_url"": ""https://creativecommons.org/licenses/by-nc-sa/3.0/"", ""release_date"": ""2015-03-29"", ""raw_license_url"": ""http://creativecommons.org/licenses/by-nc-sa/3.0/""}","[{""name"": ""vocal"", ""provider"": ""jamendo""}, {""name"": ""female"", ""provider"": ""jamendo""}, {""name"": ""speed_medium"", ""provider"": ""jamendo""}, {""name"": ""guitar"", ""provider"": ""jamendo""}, {""name"": ""strings"", ""provider"": ""jamendo""}, {""name"": ""energetic"", ""provider"": ""jamendo""}, {""name"": ""acoustic"", ""provider"": ""jamendo""}, {""name"": ""vocal"", ""provider"": ""jamendo""}, {""name"": ""voice"", ""provider"": ""jamendo""}, {""name"": ""funkyhouse"", ""provider"": ""jamendo""}]",false,2021-09-30 19:00:43.800462+00,false,0.992046395377124457ccad4d-2306-49b2-9e7e-10e951d4dc95,2021-09-30 19:04:04.688567+00,2021-09-30 19:04:04.688567+00,provider_api,wikimedia_audio,wikimedia_audio,35030939,https://commons.wikimedia.org/w/index.php?curid=35030939,https://upload.wikimedia.org/wikipedia/commons/a/aa/De-Vulkan.ogg,,ogg,1940,80000,44100,pronunciation,,,,,18968,by-sa,4.0,Jeuwre,https://commons.wikimedia.org/wiki/User:Jeuwre,De-Vulkan,"{""channels"": ""1"", ""categories"": [""Audio files made by jeuwre"", ""Audio files made using a Rode NT-USB (supported by Wikimedia Deutschland)"", ""Created with Audacity"", ""German pronunciation of Latinisms"", ""German pronunciation of nouns"", ""German pronunciation of words relating to geology"", ""Self-published work"", ""Supported by Wikimedia Deutschland""], ""description"": ""Pronunciation recording of German term 'Vulkan' (volcano). Male voice, recorded by native German speaker from Berlin, Germany."", ""license_url"": ""https://creativecommons.org/licenses/by-sa/4.0/"", ""raw_license_url"": ""https://creativecommons.org/licenses/by-sa/4.0"", ""global_usage_count"": ""15"", ""date_originally_created"": ""30 August 2014, 23:31:38"", ""last_modified_at_source"": ""2021-09-26 08:37:23""}",,false,2021-09-30 19:04:04.688567+00,false,0.98837209302325594b739ffb-a3ae-4d4a-9cdb-520f6b31eaa2,2021-09-30 19:04:04.688567+00,2021-09-30 19:04:04.688567+00,provider_api,wikimedia_audio,wikimedia_audio,49649670,https://commons.wikimedia.org/w/index.php?curid=49649670,https://upload.wikimedia.org/wikipedia/commons/3/37/De-Kreuz.ogg,,ogg,1680,80000,44100,pronunciation,,,,,16630,by-sa,4.0,Jeuwre,https://commons.wikimedia.org/wiki/User:Jeuwre,De-Kreuz,"{""channels"": ""1"", ""categories"": [""Audio files made by jeuwre"", ""Audio files made using a Rode NT-USB (supported by Wikimedia Deutschland)"", ""Created with Audacity"", ""German pronunciation of nouns"", ""German pronunciation of words relating to Christianity"", ""German pronunciation of words relating to anatomy"", ""Self-published work"", ""Supported by Wikimedia Deutschland"", ""Uploaded with VicuñaUploader""], ""description"": ""Pronunciation recording of German term 'Kreuz'. Male voice, recorded by native German speaker from Berlin, Germany."", ""license_url"": ""https://creativecommons.org/licenses/by-sa/4.0/"", ""raw_license_url"": ""https://creativecommons.org/licenses/by-sa/4.0"", ""global_usage_count"": ""15"", ""date_originally_created"": ""14 June 2016"", ""last_modified_at_source"": ""2021-09-26 08:37:53""}",,false,2021-09-30 19:04:04.688567+00,false,0.988372093023255998e4ac46-9ffa-4c7f-a37f-4e64ea1eb04c,2021-09-30 19:01:22.920161+00,2021-09-30 19:01:22.920161+00,provider_api,wikimedia_audio,wikimedia_audio,35923902,https://commons.wikimedia.org/w/index.php?curid=35923902,https://upload.wikimedia.org/wikipedia/commons/5/5a/De-Platz.ogg,,ogg,1500,80000,44100,pronunciation,,,,,15352,by-sa,4.0,Jeuwre,https://commons.wikimedia.org/wiki/User:Jeuwre,De-Platz,"{""channels"": ""1"", ""categories"": [""Audio files made by jeuwre"", ""Created with Audacity"", ""German pronunciation of nouns"", ""Self-published work""], ""description"": ""Platz"", ""license_url"": ""https://creativecommons.org/licenses/by-sa/4.0/"", ""raw_license_url"": ""https://creativecommons.org/licenses/by-sa/4.0"", ""global_usage_count"": ""13"", ""date_originally_created"": ""5 October 2014, 21:29:51"", ""last_modified_at_source"": ""2021-09-29 15:37:37""}",,false,2021-09-30 19:01:22.920161+00,false,0.9866071428571429