Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Refactor license constants and utils (#685)

Dhruv Bhanushali6cc0551c6390
diff --git a/api/catalog/api/constants/licenses.py b/api/catalog/api/constants/licenses.py
new file mode 100644
index 000000000..76e4c7bf6
--- /dev/null
+++ b/api/catalog/api/constants/licenses.py
@@ -0,0 +1,23 @@
+# This differs from the frontend which does not consider CC0 as a CC license
+CC_LICENSES = {"by", "by-sa", "by-nd", "by-nc", "by-nc-sa", "by-nc-nd", "cc0"}
+
+DEPRECATED_CC_LICENSES = {"sampling+", "nc-sampling+"}
+
+PUBLIC_DOMAIN_MARKS = {"cc0", "pdm"}
+
+ALL_CC_LICENSES = CC_LICENSES | DEPRECATED_CC_LICENSES
+
+ACTIVE_LICENSES = PUBLIC_DOMAIN_MARKS | CC_LICENSES
+
+ALL_LICENSES = ACTIVE_LICENSES | DEPRECATED_CC_LICENSES
+
+LICENSE_GROUPS = {
+ # All available licenses and marks
+ "all": ALL_LICENSES,
+ # All CC licenses
+ "all-cc": ALL_CC_LICENSES,
+ # All licenses allowing commercial use
+ "commercial": {_license for _license in ALL_LICENSES if "nc" not in _license},
+ # All licenses allowing creation of derivative works
+ "modification": {_license for _license in ALL_LICENSES if "nd" not in _license},
+}
diff --git a/api/catalog/api/examples/audio_responses.py b/api/catalog/api/examples/audio_responses.py
index a236aafef..ebcb92172 100644
--- a/api/catalog/api/examples/audio_responses.py
+++ b/api/catalog/api/examples/audio_responses.py
@@ -81,7 +81,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
+ "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
diff --git a/api/catalog/api/examples/image_responses.py b/api/catalog/api/examples/image_responses.py
index ba913f5cd..3717e7ca2 100644
--- a/api/catalog/api/examples/image_responses.py
+++ b/api/catalog/api/examples/image_responses.py
@@ -83,7 +83,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
+ "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",
diff --git a/api/catalog/api/licenses.py b/api/catalog/api/licenses.py
deleted file mode 100644
index 5b086cab5..000000000
--- a/api/catalog/api/licenses.py
+++ /dev/null
@@ -1,36 +0,0 @@
-LICENSES = (
- ("BY", "Attribution"),
- ("BY-NC", "Attribution NonCommercial"),
- ("BY-ND", "Attribution NoDerivatives"),
- ("BY-SA", "Attribution ShareAlike"),
- ("BY-NC-ND", "Attribution NonCommercial NoDerivatives"),
- ("BY-NC-SA", "Attribution NonCommercial ShareAlike"),
- ("PDM", "Public Domain Mark"),
- ("CC0", "Public Domain Dedication"),
-)
-
-LICENSE_GROUPS = {
- # All open licenses
- "all": {"BY", "BY-NC", "BY-ND", "BY-SA", "BY-NC-ND", "BY-NC-SA", "PDM", "CC0"},
- # All CC licenses
- "all-cc": {"BY", "BY-NC", "BY-ND", "BY-SA", "BY-NC-ND", "BY-NC-SA", "CC0"},
- # All licenses allowing commercial use
- "commercial": {"BY", "BY-SA", "BY-ND", "CC0", "PDM"},
- # All licenses allowing modifications
- "modification": {"BY", "BY-SA", "BY-NC", "BY-NC-SA", "CC0", "PDM"},
-}
-
-ATTRIBUTION = (
- "{title} {creator}is licensed under CC-{_license} {version}. To view a "
- "copy of this license, visit {license_url}."
-)
-
-
-def get_license_url(_license, version, meta_data=None):
- license_overridden = meta_data and "license_url" in meta_data
- if license_overridden and meta_data["license_url"] is not None:
- return meta_data["license_url"]
- elif _license.lower() == "pdm":
- return "https://creativecommons.org/publicdomain/mark/1.0/"
- else:
- return f"https://creativecommons.org/licenses/{_license}/{version}/"
diff --git a/api/catalog/api/models/media.py b/api/catalog/api/models/media.py
index a6ebb12c9..0e1cbb9f6 100644
--- a/api/catalog/api/models/media.py
+++ b/api/catalog/api/models/media.py
@@ -5,13 +5,14 @@ from django.db import models
from django.utils.html import format_html
import catalog.api.controllers.search_controller as search_controller
-from catalog.api.licenses import ATTRIBUTION, get_license_url
from catalog.api.models.base import OpenLedgerModel
from catalog.api.models.mixins import (
ForeignIdentifierMixin,
IdentifierMixin,
MediaMixin,
)
+from catalog.api.utils.attribution import get_attribution_text
+from catalog.api.utils.licenses import get_license_url
PENDING = "pending_review"
@@ -70,30 +71,27 @@ class AbstractMedia(
@property
def license_url(self):
- _license = str(self.license)
- license_version = str(self.license_version)
- return get_license_url(_license, license_version)
+ if self.meta_data and (url := self.meta_data.get("license_url")):
+ return url
+ else:
+ return get_license_url(self.license.lower(), self.license_version)
@property
def attribution(self):
- _license = str(self.license)
- license_version = str(self.license_version)
- if self.title:
- title = f'"{self.title}"'
- else:
- title = "This work"
- if self.creator:
- creator = f"by {self.creator} "
- else:
- creator = ""
- attribution = ATTRIBUTION.format(
- title=title,
- creator=creator,
- _license=_license.upper(),
- version=license_version,
- license_url=str(self.license_url),
+ """
+ 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
+ """
+
+ return get_attribution_text(
+ self.title,
+ self.creator,
+ self.license.lower(),
+ self.license_version,
+ self.license_url,
)
- return attribution
class Meta:
"""
diff --git a/api/catalog/api/serializers/media_serializers.py b/api/catalog/api/serializers/media_serializers.py
index ca6322565..f4467eacd 100644
--- a/api/catalog/api/serializers/media_serializers.py
+++ b/api/catalog/api/serializers/media_serializers.py
@@ -3,9 +3,7 @@ from urllib.parse import urlparse
from rest_framework import serializers
-from drf_yasg.utils import swagger_serializer_method
-
-import catalog.api.licenses as license_helpers
+from catalog.api.constants.licenses import LICENSE_GROUPS
from catalog.api.controllers import search_controller
from catalog.api.utils.help_text import make_comma_separated_help_text
@@ -18,7 +16,7 @@ def _validate_enum(enum_name, valid_values: set, given_values: str):
:param given_values: A comma separated list of values.
:return: whether the input is valid
"""
- input_values = [x.lower() for x in given_values.split(",")]
+ input_values = given_values.lower().split(",")
for value in input_values:
if value not in valid_values:
raise serializers.ValidationError(
@@ -27,34 +25,6 @@ def _validate_enum(enum_name, valid_values: set, given_values: str):
return given_values.lower()
-def _validate_lt(value):
- license_types = [x.lower() for x in value.split(",")]
- license_groups = []
- for _type in license_types:
- if _type not in license_helpers.LICENSE_GROUPS:
- raise serializers.ValidationError(f"License type '{_type}' does not exist.")
- license_groups.append(license_helpers.LICENSE_GROUPS[_type])
- intersected = set.intersection(*license_groups)
- cleaned = {_license.lower() for _license in intersected}
-
- return ",".join(list(cleaned))
-
-
-def _validate_li(value):
- licenses = [x.upper() for x in value.split(",")]
- for _license in licenses:
- if _license not in license_helpers.LICENSE_GROUPS["all"]:
- raise serializers.ValidationError(f"License '{_license}' does not exist.")
- return value.lower()
-
-
-def _validate_page(value):
- if value < 1:
- return 1
- else:
- return value
-
-
def _add_protocol(url: str):
"""
Some fields in the database contain incomplete URLs, leading to unexpected
@@ -179,15 +149,13 @@ class MediaSearchRequestSerializer(serializers.Serializer):
)
license = serializers.CharField(
label="licenses",
- help_text=make_comma_separated_help_text(
- license_helpers.LICENSE_GROUPS["all"], "licenses"
- ),
+ help_text=make_comma_separated_help_text(LICENSE_GROUPS["all"], "licenses"),
required=False,
)
license_type = serializers.CharField(
label="license type",
help_text=make_comma_separated_help_text(
- license_helpers.LICENSE_GROUPS.keys(), "license types"
+ LICENSE_GROUPS.keys(), "license types"
),
required=False,
)
@@ -245,12 +213,29 @@ class MediaSearchRequestSerializer(serializers.Serializer):
@staticmethod
def validate_license(value):
"""Checks whether license is a valid license code."""
- return _validate_li(value)
+
+ licenses = value.lower().split(",")
+ for _license in licenses:
+ if _license not in LICENSE_GROUPS["all"]:
+ raise serializers.ValidationError(
+ f"License '{_license}' does not exist."
+ )
+ return value.lower()
@staticmethod
def validate_license_type(value):
"""Checks whether license type is a known collection of licenses."""
- return _validate_lt(value)
+
+ license_types = value.lower().split(",")
+ license_groups = []
+ for _type in license_types:
+ if _type not in LICENSE_GROUPS:
+ raise serializers.ValidationError(
+ f"License type '{_type}' does not exist."
+ )
+ license_groups.append(LICENSE_GROUPS[_type])
+ intersected = set.intersection(*license_groups)
+ return ",".join(intersected)
def validate_creator(self, value):
return self._truncate(value)
@@ -348,9 +333,7 @@ class MediaSerializer(serializers.Serializer):
license_version = serializers.CharField(
required=False, help_text="The type of license for the media."
)
- license_url = serializers.SerializerMethodField(
- help_text="A direct link to the media license."
- )
+ 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(
@@ -375,27 +358,13 @@ class MediaSerializer(serializers.Serializer):
)
attribution = serializers.CharField(
required=False,
- help_text="The Creative Commons attribution of the work. Use this to "
- "give credit to creators to their works and fulfill "
- "legal attribution requirements.",
+ 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.",
)
def get_license(self, obj):
return obj.license.lower()
- @swagger_serializer_method(serializer_or_field=serializers.URLField)
- def get_license_url(self, obj):
- if hasattr(obj, "meta_data"):
- return license_helpers.get_license_url(
- obj.license, obj.license_version, obj.meta_data
- )
- elif hasattr(obj, "license_url") and obj.license_url is not None:
- return obj.license_url
- else:
- return license_helpers.get_license_url(
- obj.license, obj.license_version, None
- )
-
def validate_url(self, value):
return _add_protocol(value)
diff --git a/api/catalog/api/utils/attribution.py b/api/catalog/api/utils/attribution.py
new file mode 100644
index 000000000..8aa97f3c0
--- /dev/null
+++ b/api/catalog/api/utils/attribution.py
@@ -0,0 +1,61 @@
+"""
+This module highly mirrors the JavaScript code present in the frontend repository.
+For any changes made here, please make the corresponding changes in the
+frontend, or open an issue to track it.
+"""
+
+from typing import Optional
+
+from catalog.api.utils.licenses import get_full_license_name, is_public_domain
+
+
+def get_attribution_text(
+ title: Optional[str],
+ creator: Optional[str],
+ _license: str,
+ license_version: Optional[str],
+ license_url: Optional[str],
+) -> str:
+ """
+ Get the attribution text to properly and legally attribute a creative work to its
+ creator. This text is only in plain-text English. Refer to the frontend for an
+ internationalised implementation with rich-text and HTML variants.
+
+ :param title: the title of the creative work
+ :param creator: the name of the owner of the creative work
+ :param _license: the license (or mark) associated with the creative work
+ :param license_version: the version of the license
+ :param license_url: the URL at which the complete license terms can be found
+ :return: the full attribution text
+ """
+
+ is_pd = is_public_domain(_license)
+
+ title = f'"{title}"' if title else "This work"
+ _license = get_full_license_name(_license, license_version)
+
+ attribution = "{title} {creator} {marked-licensed} {license}. {view-legal}"
+ attribution_parts = {
+ "title": title,
+ "marked-licensed": "is marked with" if is_pd else "is licensed under",
+ "license": _license,
+ "view-legal": "",
+ "creator": "",
+ }
+
+ if license_url:
+ view_legal_temp = "To view {terms-copy}, visit {url}."
+ view_legal_parts = {
+ "terms-copy": "the terms" if is_pd else "a copy of this license",
+ "url": license_url,
+ }
+ attribution_parts["view-legal"] = view_legal_temp.format(**view_legal_parts)
+
+ if creator:
+ creator_temp = "by {creator-name}"
+ creator_parts = {"creator-name": creator}
+ attribution_parts["creator"] = creator_temp.format(**creator_parts)
+
+ attribution = attribution.format(**attribution_parts)
+
+ return attribution.strip().replace(" ", " ")
diff --git a/api/catalog/api/utils/licenses.py b/api/catalog/api/utils/licenses.py
new file mode 100644
index 000000000..9c6a89dcf
--- /dev/null
+++ b/api/catalog/api/utils/licenses.py
@@ -0,0 +1,94 @@
+"""
+This module highly mirrors the JavaScript code present in the frontend repository.
+For any changes made here, please make the corresponding changes in the
+frontend, or open an issue to track it.
+"""
+
+from typing import Optional
+
+from catalog.api.constants.licenses import (
+ ALL_CC_LICENSES,
+ DEPRECATED_CC_LICENSES,
+ PUBLIC_DOMAIN_MARKS,
+)
+
+
+def get_license_url(_license: str, license_version: Optional[str]) -> str:
+ """
+ Get the URL to the deed of the license.
+
+ :param _license: the slug of the license
+ :param license_version: the version number of the license
+ :return: the URL to the license deed
+ """
+
+ if _license == "cc0":
+ fragment = "publicdomain/zero/1.0"
+ elif _license == "pdm":
+ fragment = "publicdomain/mark/1.0/"
+ elif is_deprecated(_license):
+ fragment = f"licenses/{_license}/1.0"
+ else:
+ fragment = f"licenses/{_license}/{license_version or '4.0'}"
+ return f"https://creativecommons.org/{fragment}/"
+
+
+def get_full_license_name(_license: str, license_version: Optional[str]) -> str:
+ """
+ Get the full name of the license in a displayable format from the license
+ slug and version.
+
+ :param _license: the slug of the license
+ :param license_version: the version number of the license
+ :return: the full name of the license
+ """
+
+ license_name: str
+ if _license == "pdm":
+ license_name = "Public Domain Mark"
+ else:
+ license_name = _license.upper().replace("SAMPLING", "Sampling")
+ if license_version:
+ license_name = f"{license_name} {license_version}"
+ if not is_public_domain(_license):
+ license_name = f"CC {license_name}"
+ return license_name.strip()
+
+
+def is_public_domain(_license: str) -> bool:
+ """
+ CC licenses have different legal status from the public domain marks
+ such as CC0 and PDM, and need different wording. Check if the given name
+ belongs to a public-domain mark and is not a license.
+
+ :param _license: the license slug to check
+ :return: ``True`` if the license is a public domain mark, ``False`` otherwise
+ """
+
+ return _license in PUBLIC_DOMAIN_MARKS
+
+
+def is_cc(_license: str) -> bool:
+ """
+ Check if the given name belongs to a CC license, active or deprecated. This
+ includes CC0, which although not technically a license, is offered by CC.
+
+ :param _license: the license slug to check
+ :return: ``True`` if the license is a CC license, ``False`` otherwise
+ """
+
+ return _license in ALL_CC_LICENSES
+
+
+def is_deprecated(_license: str) -> bool:
+ """
+ Check if the given name belongs to a deprecated CC license. The full list of
+ deprecated licenses can be found on the
+ [Retired Legal Tools page](https://creativecommons.org/retiredlicenses/) on
+ the CC.org site.
+
+ :param _license: the license slug to check
+ :return: ``True`` if the license is a deprecated CC license, ``False`` otherwise
+ """
+
+ return _license in DEPRECATED_CC_LICENSES
diff --git a/api/test/api_live_integration.py b/api/test/api_live_integration.py
index 787634e35..edbe2d7b0 100644
--- a/api/test/api_live_integration.py
+++ b/api/test/api_live_integration.py
@@ -5,7 +5,7 @@ import uuid
import pytest
import requests
-from catalog.api.licenses import LICENSE_GROUPS
+from catalog.api.constants.licenses import LICENSE_GROUPS
from catalog.api.models import Image
from catalog.api.utils.watermark import watermark
diff --git a/api/test/factory/models/media.py b/api/test/factory/models/media.py
index 444ada6a8..55d2c41e2 100644
--- a/api/test/factory/models/media.py
+++ b/api/test/factory/models/media.py
@@ -4,7 +4,7 @@ from uuid import uuid4
import factory
from factory.django import DjangoModelFactory
-from catalog.api.licenses import LICENSES
+from catalog.api.constants.licenses import ALL_LICENSES
class MediaFactory(DjangoModelFactory):
@@ -18,9 +18,7 @@ class MediaFactory(DjangoModelFactory):
foreign_identifier = factory.sequence(lambda _: uuid4())
"""The foreign identifier isn't necessarily a UUID but for test purposes it's fine if it looks like one"""
- license = Faker(
- "random_element", elements=[the_license[0] for the_license in LICENSES]
- )
+ license = Faker("random_element", elements=ALL_LICENSES)
foreign_landing_url = Faker("url")
diff --git a/api/test/unit/utils/attribution_test.py b/api/test/unit/utils/attribution_test.py
new file mode 100644
index 000000000..7697e0380
--- /dev/null
+++ b/api/test/unit/utils/attribution_test.py
@@ -0,0 +1,44 @@
+import re
+
+import pytest
+
+from catalog.api.utils.attribution import get_attribution_text
+
+
+ "args, expectation",
+ [
+ (
+ ("Title", "Creator", "xy", "0.0", "https://license/url"),
+ '"Title" by Creator is licensed under CC XY 0.0. '
+ "To view a copy of this license, visit https://license/url.",
+ ),
+ (
+ ("", "Creator", "xy", "0.0", "https://license/url"), # No title
+ "This work by Creator is licensed under",
+ ),
+ (
+ ("Title", "", "xy", "0.0", "https://license/url"), # No creator
+ '"Title" is licensed under CC XY 0.0.',
+ ),
+ (
+ ("Title", "Creator", "xy", "0.0", ""), # No URL
+ r'^"Title" by Creator is licensed under CC XY 0.0.$',
+ ),
+ (
+ ("Title", "Creator", "pdm", "0.0", "https://license/url"), # PDM
+ '"Title" by Creator is marked with Public Domain Mark 0.0.',
+ ),
+ (
+ ("Title", "Creator", "cc0", "0.0", "https://license/url"), # CC0
+ '"Title" by Creator is marked with CC0 0.0.',
+ ),
+ (
+ (None, None, "xy", None, None),
+ "This work is licensed under CC XY.", # almost nothing known about the work
+ ),
+ ],
+)
+def test_attribution_text(args: tuple[str, str, str, str, str], expectation: str):
+ attribution = get_attribution_text(*args)
+ assert re.match(expectation, attribution)
diff --git a/api/test/v1_integration_test.py b/api/test/v1_integration_test.py
index 4d22deb6c..63038e181 100644
--- a/api/test/v1_integration_test.py
+++ b/api/test/v1_integration_test.py
@@ -9,7 +9,7 @@ from test.constants import API_URL
import pytest
import requests
-from catalog.api.licenses import LICENSE_GROUPS
+from catalog.api.constants.licenses import LICENSE_GROUPS
from catalog.api.models import Image
from catalog.api.utils.watermark import watermark
@@ -76,7 +76,7 @@ def test_license_type_filtering():
)
parsed = json.loads(response.text)
for result in parsed["results"]:
- assert result["license"].upper() in commercial_and_modification
+ assert result["license"] in commercial_and_modification
def test_single_license_type_filtering():
@@ -86,7 +86,7 @@ def test_single_license_type_filtering():
)
parsed = json.loads(response.text)
for result in parsed["results"]:
- assert result["license"].upper() in commercial
+ assert result["license"] in commercial
def test_specific_license_filter():