Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Register audio and image models consistently in admin panel (#936)
Dhruv Bhanushali752eec0b156d
diff --git a/api/catalog/api/admin.py b/api/catalog/api/admin/__init__.pysimilarity index 57%rename from api/catalog/api/admin.pyrename to api/catalog/api/admin/__init__.pyindex 5fbf53e97..b34b72a5d 100644--- a/api/catalog/api/admin.py+++ b/api/catalog/api/admin/__init__.py@@ -1,22 +1,31 @@from django.contrib import admin+from catalog.api.admin.site import openverse_adminfrom catalog.api.models import (PENDING,AudioReport,ContentProvider,- DeletedImage,ImageReport,- MatureImage,SourceLogo,)+from catalog.api.models.media import AbstractDeletedMedia, AbstractMatureMedia+++admin.site = openverse_admin+admin.sites.site = openverse_adminclass MediaReportAdmin(admin.ModelAdmin):+ list_display = ("reason", "status", "description", "created_at")+ media_specific_list_display = ()list_filter = ("status", "reason")list_display_links = ("status",)search_fields = ("description", "identifier")actions = None+ def get_list_display(self, request):+ return self.list_display + self.media_specific_list_display+def get_readonly_fields(self, request, obj=None):if obj is None:return []@@ -34,24 +43,34 @@ class MediaReportAdmin(admin.ModelAdmin):return status_readonly[email protected](ImageReport)+class ImageReportAdmin(MediaReportAdmin):+ media_specific_list_display = ("image_url",)++@admin.register(AudioReport)class AudioReportAdmin(MediaReportAdmin):- list_display = ("reason", "status", "audio_url", "description", "created_at")-+ media_specific_list_display = ("audio_url",)[email protected](ImageReport)-class ImageReportAdmin(MediaReportAdmin):- list_display = ("reason", "status", "image_url", "description", "created_at")+class MediaSubreportAdmin(admin.ModelAdmin):+ search_fields = [+ "identifier",+ ]+ readonly_fields = [+ "identifier",+ ][email protected](MatureImage)-class MatureImageAdmin(admin.ModelAdmin):- search_fields = ("identifier",)+ def has_add_permission(self, *args, **kwargs):+ """Create ``_Report`` instances instead."""+ return False[email protected](DeletedImage)-class DeletedImage(admin.ModelAdmin):- search_fields = ("identifier",)+for klass in [+ *AbstractMatureMedia.__subclasses__(),+ *AbstractDeletedMedia.__subclasses__(),+]:+ admin.site.register(klass, MediaSubreportAdmin)class InlineImage(admin.TabularInline):diff --git a/api/catalog/api/admin/site.py b/api/catalog/api/admin/site.pynew file mode 100644index 000000000..9d4f2de59--- /dev/null+++ b/api/catalog/api/admin/site.py@@ -0,0 +1,41 @@+from django.contrib import admin++from catalog.api.constants.media_types import MEDIA_TYPE_CHOICES+++class OpenverseAdmin(admin.AdminSite):+ site_header = "Openverse administration"++ def get_app_list(self, *args, **kwargs):+ """+ Modify the app and model list to present media specific models outside the main+ API group. This makes the long list easier to comprehend and locating the model+ of interest faster.+ """++ app_list = super().get_app_list(*args, **kwargs)+ api_app = next((app for app in app_list if app["app_label"] == "api"), None)+ if api_app is None:+ return app_list++ for media_type, media_type_name in MEDIA_TYPE_CHOICES:+ models = []+ for model in api_app["models"][:]:+ if media_type in model["object_name"].lower():+ models.append(model)+ api_app["models"].remove(model)+ models.sort(key=lambda x: "0" if "report" in x["name"] else x["name"])++ media_app = {+ "name": media_type_name,+ "app_label": media_type,+ "app_url": f"/admin/{media_type}",+ "has_module_perms": True,+ "models": models,+ }+ app_list.insert(0, media_app)++ return app_list+++openverse_admin = OpenverseAdmin()diff --git a/api/catalog/api/examples/audio_responses.py b/api/catalog/api/examples/audio_responses.pyindex 9565903fe..3dc0b9c9d 100644--- a/api/catalog/api/examples/audio_responses.py+++ b/api/catalog/api/examples/audio_responses.py@@ -36,7 +36,7 @@ base_audio = {"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,+ "mature": False,"audio_set": {"title": "Wish You Were Here","foreign_landing_url": "https://www.jamendo.com/album/145774/wish-you-were-here", # noqa: E501@@ -65,7 +65,6 @@ audio_search_200_example = {base_audio| {"fields_matched": ["title"],- "mature": False,"audio_set": None,"attribution": None,"filesize": None,diff --git a/api/catalog/api/examples/image_responses.py b/api/catalog/api/examples/image_responses.pyindex a12ce1543..5c2823fcb 100644--- a/api/catalog/api/examples/image_responses.py+++ b/api/catalog/api/examples/image_responses.py@@ -59,7 +59,6 @@ detailed_image = base_image | {"filesize": 896128,"filetype": "jpg","width": 6016,- "mature": None,}image_search_200_example = {@@ -72,7 +71,6 @@ image_search_200_example = {base_image| {"fields_matched": ["title"],- "mature": False,"height": None,"width": None,"attribution": None,diff --git a/api/catalog/api/migrations/0050_audio_model_plural_names.py b/api/catalog/api/migrations/0050_audio_model_plural_names.pynew file mode 100644index 000000000..6242ed597--- /dev/null+++ b/api/catalog/api/migrations/0050_audio_model_plural_names.py@@ -0,0 +1,21 @@+# Generated by Django 4.0.6 on 2022-09-28 10:29++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ('api', '0049_merge_migrations_number_48'),+ ]++ operations = [+ migrations.AlterModelOptions(+ name='deletedaudio',+ options={'verbose_name_plural': 'Deleted audio'},+ ),+ migrations.AlterModelOptions(+ name='matureaudio',+ options={'verbose_name_plural': 'Mature audio'},+ ),+ ]diff --git a/api/catalog/api/models/audio.py b/api/catalog/api/models/audio.pyindex 77171f74e..8d9380c67 100644--- a/api/catalog/api/models/audio.py+++ b/api/catalog/api/models/audio.py@@ -4,6 +4,7 @@ from django.db import modelsfrom uuslug import uuslug+from catalog.api.constants.media_types import AUDIO_TYPEfrom catalog.api.models import OpenLedgerModelfrom catalog.api.models.media import (AbstractAltFile,@@ -175,6 +176,10 @@ class Audio(AudioFileMixin, AbstractMedia):help_text="JSON describing alternative files for this audio.",)+ @property+ def mature(self) -> bool:+ return MatureAudio.objects.filter(identifier=self.identifier).exists()+@propertydef alternative_files(self):if hasattr(self.alt_files, "__iter__"):@@ -222,39 +227,43 @@ class Audio(AudioFileMixin, AbstractMedia):db_table = "audio"-class AudioReport(AbstractMediaReport):+class DeletedAudio(AbstractDeletedMedia):+ """+ Stores identifiers of audio tracks that have been deleted from the source. Do not+ create instances of this model manually. Create an ``AudioReport`` instance instead.+ """++ media_class = Audio+ es_index = settings.MEDIA_INDEX_MAPPING[AUDIO_TYPE]+class Meta:- db_table = "nsfw_reports_audio"+ verbose_name_plural = "Deleted audio"- @property- def audio_url(self):- return super(AudioReport, self).url("audio")- def save(self, *args, **kwargs):- kwargs.update(- {- "index_name": "audio",- "media_class": Audio,- "mature_class": MatureAudio,- "deleted_class": DeletedAudio,- }- )- super(AudioReport, self).save(*args, **kwargs)+class MatureAudio(AbstractMatureMedia):+ """+ Stores all audio tracks that have been flagged as 'mature'. Do not create instances+ of this model manually. Create an ``AudioReport`` instance instead.+ """+ media_class = Audio+ es_index = settings.MEDIA_INDEX_MAPPING[AUDIO_TYPE]-class DeletedAudio(AbstractDeletedMedia):- pass+ class Meta:+ verbose_name_plural = "Mature audio"-class MatureAudio(AbstractMatureMedia):- """Stores all audios that have been flagged as 'mature'."""-- def delete(self, *args, **kwargs):- es = settings.ES- aud = Audio.objects.get(identifier=self.identifier)- es_id = aud.id- es.update(index="audio", id=es_id, body={"doc": {"mature": False}})- super(MatureAudio, self).delete(*args, **kwargs)+class AudioReport(AbstractMediaReport):+ media_class = Audio+ mature_class = MatureAudio+ deleted_class = DeletedAudio++ class Meta:+ db_table = "nsfw_reports_audio"++ @property+ def audio_url(self):+ return super(AudioReport, self).url("audio")class AudioList(AbstractMediaList):diff --git a/api/catalog/api/models/image.py b/api/catalog/api/models/image.pyindex 1db7833b8..3502c51f7 100644--- a/api/catalog/api/models/image.py+++ b/api/catalog/api/models/image.py@@ -3,6 +3,7 @@ from django.db import modelsfrom uuslug import uuslug+from catalog.api.constants.media_types import IMAGE_TYPEfrom catalog.api.models.media import (AbstractDeletedMedia,AbstractMatureMedia,@@ -48,8 +49,36 @@ class Image(ImageFileMixin, AbstractMedia):class Meta(AbstractMedia.Meta):db_table = "image"+ @property+ def mature(self) -> bool:+ return MatureImage.objects.filter(identifier=self.identifier).exists()+++class DeletedImage(AbstractDeletedMedia):+ """+ Stores identifiers of images that have been deleted from the source. Do not create+ instances of this model manually. Create an ``ImageReport`` instance instead.+ """++ media_class = Image+ es_index = settings.MEDIA_INDEX_MAPPING[IMAGE_TYPE]+++class MatureImage(AbstractMatureMedia):+ """+ Stores all images that have been flagged as 'mature'. Do not create instances of+ this model manually. Create an ``ImageReport`` instance instead.+ """++ media_class = Image+ es_index = settings.MEDIA_INDEX_MAPPING[IMAGE_TYPE]+class ImageReport(AbstractMediaReport):+ media_class = Image+ mature_class = MatureImage+ deleted_class = DeletedImage+class Meta:db_table = "nsfw_reports"@@ -57,32 +86,6 @@ class ImageReport(AbstractMediaReport):def image_url(self):return super(ImageReport, self).url("photos")- def save(self, *args, **kwargs):- kwargs.update(- {- "index_name": "image",- "media_class": Image,- "mature_class": MatureImage,- "deleted_class": DeletedImage,- }- )- super(ImageReport, self).save(*args, **kwargs)---class DeletedImage(AbstractDeletedMedia):- pass---class MatureImage(AbstractMatureMedia):- """Stores all images that have been flagged as 'mature'."""-- def delete(self, *args, **kwargs):- es = settings.ES- img = Image.objects.get(identifier=self.identifier)- es_id = img.id- es.update(index="image", id=es_id, body={"doc": {"mature": False}})- super(MatureImage, self).delete(*args, **kwargs)-class ImageList(AbstractMediaList):images = models.ManyToManyField(diff --git a/api/catalog/api/models/media.py b/api/catalog/api/models/media.pyindex 270e0dc46..2b7cc9788 100644--- a/api/catalog/api/models/media.py+++ b/api/catalog/api/models/media.py@@ -2,6 +2,7 @@ import mimetypesfrom django.conf import settingsfrom django.contrib.postgres.fields import ArrayField+from django.core.exceptions import ValidationErrorfrom django.db import modelsfrom django.utils.html import format_html@@ -130,9 +131,17 @@ class AbstractMediaReport(models.Model):"""Generic model from which to inherit all reported media classes. 'Reported'here refers to content reports such as mature, copyright-violating or- deleted content.+ deleted content. Subclasses must populate ``media_class``, ``mature_class`` and+ ``deleted_class`` fields."""+ media_class: type[models.Model] = None+ """the model class associated with this media type e.g. ``Image`` or ``Audio``"""+ mature_class: type[models.Model] = None+ """the class storing mature media e.g. ``MatureImage`` or ``MatureAudio``"""+ deleted_class: type[models.Model] = None+ """the class storing deleted media e.g. ``DeletedImage`` or ``DeletedAudio``"""+BASE_URL = "https://search.creativecommons.org/"REPORT_CHOICES = [(MATURE, MATURE), (DMCA, DMCA), (OTHER, OTHER)]@@ -163,54 +172,41 @@ class AbstractMediaReport(models.Model):class Meta:abstract = True+ def clean(self):+ """+ This function raises errors that can be handled by Django's admin interface.+ """++ if not self.media_class.objects.filter(identifier=self.identifier).exists():+ raise ValidationError(+ f"No '{self.media_class.__name__}' instance"+ f"with identifier {self.identifier}."+ )+def url(self, media_type):- url = f"{AbstractMediaReport.BASE_URL}" f"{media_type}/" f"{self.identifier}"+ url = f"{AbstractMediaReport.BASE_URL}{media_type}{self.identifier}"return format_html(f"<a href={url}>{url}</a>")def save(self, *args, **kwargs):"""- Extend the ``save()`` functionality with Elastic Search integration to+ Extend the ``save()`` functionality with Elasticsearch integration toupdate records and refresh indices.Media marked as mature or deleted also leads to instantiation of theircorresponding mature or deleted classes.-- Additional kwargs:- index_name : Name of ES index, eg. 'image'- media_class : Class of the media, eg. ``Image``- mature_class : Class that stores mature media, eg. ``MatureImage``- deleted_class : Class that stores deleted media, eg. ``DeletedImage``"""- index_name = kwargs.pop("index_name")- media_class = kwargs.pop("media_class")- mature_class = kwargs.pop("mature_class")- deleted_class = kwargs.pop("deleted_class")-- update_required = {MATURE_FILTERED, DEINDEXED} # ES needs updating- if self.status in update_required:- es = settings.ES- try:- media = media_class.objects.get(identifier=self.identifier)- except media_class.DoesNotExist:- super(AbstractMediaReport, self).save(*args, **kwargs)- return- es_id = media.id- if self.status == MATURE_FILTERED:- # Create an instance of the mature class for this media- mature_class.objects.create(identifier=self.identifier)- # Mark as 'mature' in Elastic Search- es.update(index=index_name, id=es_id, body={"doc": {"mature": True}})- elif self.status == DEINDEXED:- # Delete from the API database, retaining the copy of the- # metadata upstream in the catalog- media.delete()- # Create an instance of the deleted class for this media,- # so that we don't reindex it later- deleted_class.objects.create(identifier=self.identifier)- # Remove from Elastic Search- es.delete(index=index_name, id=es_id)- es.indices.refresh(index=index_name)+ self.clean()++ if self.status == MATURE_FILTERED:+ # Create an instance of the mature class for this media. This will+ # automatically set the ``mature`` field in the ES document.+ self.mature_class.objects.create(identifier=self.identifier)+ elif self.status == DEINDEXED:+ # Create an instance of the deleted class for this media, so that we don't+ # reindex it later. This will automatically delete the ES document and the+ # DB instance.+ self.deleted_class.objects.create(identifier=self.identifier)same_reports = self.__class__.objects.filter(identifier=self.identifier,@@ -219,15 +215,23 @@ class AbstractMediaReport(models.Model):if self.status != DEINDEXED:same_reports = same_reports.filter(reason=self.reason)same_reports.update(status=self.status)+super(AbstractMediaReport, self).save(*args, **kwargs)class AbstractDeletedMedia(OpenLedgerModel):"""Generic model from which to inherit all deleted media classes. 'Deleted'- here refers to media which has been deleted at the source.+ here refers to media which has been deleted at the source or intentionally+ de-indexed by us. Unlike mature reports, this action is irreversible. Subclasses+ must populate ``media_class`` and ``es_index`` fields."""+ media_class: type[models.Model] = None+ """the model class associated with this media type e.g. ``Image`` or ``Audio``"""+ es_index: str = None+ """the name of the ES index from ``settings.MEDIA_INDEX_MAPPING``"""+identifier = models.UUIDField(unique=True, primary_key=True, help_text="The identifier of the deleted media.")@@ -235,18 +239,73 @@ class AbstractDeletedMedia(OpenLedgerModel):class Meta:abstract = True+ def _update_es(self, raise_errors: bool) -> models.Model:+ es = settings.ES+ try:+ obj = self.media_class.objects.get(identifier=self.identifier)+ es.delete(index=self.es_index, id=obj.id)+ es.indices.refresh(index=self.es_index)+ return obj+ except self.media_class.DoesNotExist:+ if raise_errors:+ raise ValidationError(+ f"No '{self.media_class.__name__}' instance"+ f"with identifier {self.identifier}."+ )++ def save(self, *args, **kwargs):+ obj = self._update_es(True)+ obj.delete() # remove the actual model instance+ super().save(*args, **kwargs)+class AbstractMatureMedia(models.Model):"""- Generic model from which to inherit all mature media classes.+ Generic model from which to inherit all mature media classes. Subclasses must+ populate ``media_class`` and ``es_index`` fields."""+ media_class: type[models.Model] = None+ """the model class associated with this media type e.g. ``Image`` or ``Audio``"""+ es_index: str = None+ """the name of the ES index from ``settings.MEDIA_INDEX_MAPPING``"""+created_on = models.DateTimeField(auto_now_add=True)identifier = models.UUIDField(unique=True, primary_key=True)class Meta:abstract = True+ def _update_es(self, is_mature: bool, raise_errors: bool):+ """+ Update the Elasticsearch document associated with the given model.++ :param is_mature: whether to mark the media item as mature+ :param raise_errors: whether to raise an error if the no media item is found+ """++ es = settings.ES+ try:+ obj = self.media_class.objects.get(identifier=self.identifier)+ es.update(+ index=self.es_index, id=obj.id, body={"doc": {"mature": is_mature}}+ )+ es.indices.refresh(index=self.es_index)+ except self.media_class.DoesNotExist:+ if raise_errors:+ raise ValidationError(+ f"No '{self.media_class.__name__}' instance"+ f"with identifier {self.identifier}."+ )++ def save(self, *args, **kwargs):+ self._update_es(True, True)+ super().save(*args, **kwargs)++ def delete(self, *args, **kwargs):+ self._update_es(False, False)+ super().delete(*args, **kwargs)+class AbstractMediaList(OpenLedgerModel):"""diff --git a/api/catalog/api/serializers/media_serializers.py b/api/catalog/api/serializers/media_serializers.pyindex c93c914c4..a69073c9e 100644--- a/api/catalog/api/serializers/media_serializers.py+++ b/api/catalog/api/serializers/media_serializers.py@@ -354,7 +354,6 @@ class MediaSerializer(BaseModelSerializer):)mature = serializers.BooleanField(- allow_null=True, # present in ``Hit`` but not in Django media modelshelp_text="Whether the media item is marked as mature",)diff --git a/api/test/unit/models/media_report_test.py b/api/test/unit/models/media_report_test.pynew file mode 100644index 000000000..d47ebe2c9--- /dev/null+++ b/api/test/unit/models/media_report_test.py@@ -0,0 +1,151 @@+import uuid+from typing import Literal, Union+from unittest.mock import MagicMock, patch++from django.core.exceptions import ValidationError++import pytest++from catalog.api.models import (+ Audio,+ AudioReport,+ DeletedAudio,+ DeletedImage,+ Image,+ ImageReport,+ MatureAudio,+ MatureImage,+)+from catalog.api.models.media import (+ DEINDEXED,+ DMCA,+ MATURE,+ MATURE_FILTERED,+ OTHER,+ PENDING,+)+++pytestmark = pytest.mark.django_db++MediaType = Union[Literal["audio"], Literal["image"]]++reason_params = pytest.mark.parametrize("reason", [DMCA, MATURE, OTHER])+++def media_obj():+ def _get_media_obj(type: MediaType):+ klass = {+ "audio": Audio,+ "image": Image,+ }.get(type)+ identifier = uuid.uuid4()+ obj = klass(identifier=identifier)+ obj.save()+ return obj++ return _get_media_obj+++ "media_type, report_class", [("image", ImageReport), ("audio", AudioReport)]+)+@reason_params+def test_cannot_report_invalid_identifier(media_type, report_class, reason):+ with pytest.raises(ValidationError):+ report_class.objects.create(+ identifier=uuid.uuid4(),+ reason=reason,+ )+++ "media_type, report_class, mature_class, deleted_class",+ [+ ("image", ImageReport, MatureImage, DeletedImage),+ ("audio", AudioReport, MatureAudio, DeletedAudio),+ ],+)+@reason_params+def test_pending_reports_have_no_subreport_models(+ media_type: MediaType, report_class, mature_class, deleted_class, reason, media_obj+):+ media = media_obj(media_type)+ report = report_class.objects.create(+ identifier=media.identifier,+ reason=reason,+ )++ assert report.status == PENDING+ assert not mature_class.objects.filter(identifier=media.identifier).exists()+ assert not deleted_class.objects.filter(identifier=media.identifier).exists()+++ "media_type, report_class, mature_class",+ [("image", ImageReport, MatureImage), ("audio", AudioReport, MatureAudio)],+)+def test_mature_filtering_creates_mature_image_instance(+ media_type: MediaType, report_class, mature_class, media_obj+):+ media = media_obj(media_type)+ mock_es = MagicMock()+ with patch("django.conf.settings.ES", mock_es):+ report_class.objects.create(+ identifier=media.identifier, reason=MATURE, status=MATURE_FILTERED+ )++ assert mature_class.objects.filter(identifier=media.identifier).exists()+ assert mock_es.update.called_with(+ index=media_type, id=media.id, body={"doc": {"mature": True}}+ )+ assert media.mature+++ "media_type, report_class, mature_class",+ [("image", ImageReport, MatureImage), ("audio", AudioReport, MatureAudio)],+)+def test_deleting_mature_image_instance_resets_mature_flag(+ media_type: MediaType, report_class, mature_class, media_obj+):+ media = media_obj(media_type)+ mock_es = MagicMock()+ with patch("django.conf.settings.ES", mock_es):+ # Mark as mature.+ report_class.objects.create(+ identifier=media.identifier, reason=MATURE, status=MATURE_FILTERED+ )+ # Delete ``MatureImage`` instance.+ mature_class.objects.get(identifier=media.identifier).delete()++ assert mock_es.update.call_count == 2+ assert mock_es.update.called_with(id=media.id, body={"doc": {"mature": False}})+ assert not media.mature+++ "media_type, media_class, report_class, deleted_class",+ [+ ("image", Image, ImageReport, DeletedImage),+ ("audio", Audio, AudioReport, DeletedAudio),+ ],+)+def test_deindexing_creates_deleted_image_instance(+ media_type: MediaType, media_class, report_class, deleted_class, media_obj+):+ media = media_obj(media_type)+ # Extracting field values because ``media`` will be deleted.+ image_id = media.id+ identifier = media.identifier++ mock_es = MagicMock()+ with patch("django.conf.settings.ES", mock_es):+ report_class.objects.create(+ identifier=identifier, reason=DMCA, status=DEINDEXED+ )++ assert deleted_class.objects.filter(identifier=identifier).exists()+ assert not media_class.objects.filter(identifier=identifier).exists()+ assert mock_es.delete.called_with(id=image_id)