Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Refactor license constants and utils (#1393)
Dhruv Bhanushali0ef2bba38d65
diff --git a/src/components/VFilters/VLicenseExplanation.vue b/src/components/VFilters/VLicenseExplanation.vueindex 9ed48d9b0..ba877cd0b 100644--- a/src/components/VFilters/VLicenseExplanation.vue+++ b/src/components/VFilters/VLicenseExplanation.vue@@ -1,7 +1,7 @@<template><div class="license-explanation w-full max-w-xs p-6"><h5 class="text-base font-semibold">- <template v-if="isTechnicallyLicense">{{+ <template v-if="isLicense(license)">{{$t('filters.license-explanation.license-definition')}}</template><template v-else>{{@@ -20,13 +20,13 @@<i18n:path="`filters.license-explanation.more.${- isTechnicallyLicense ? 'license' : 'mark'+ isLicense(license) ? 'license' : 'mark'}`"tag="p"class="text-sm"><template #read-more>- <VLink :href="`${getLicenseDeedLink(license)}`">{{+ <VLink :href="`${getLicenseUrl(license)}`">{{$t('filters.license-explanation.more.read-more')}}</VLink></template>@@ -36,7 +36,7 @@</template><script>-import { isLicense, isDeprecated } from '~/utils/license'+import { isLicense, getLicenseUrl } from '~/utils/license'import VLicenseElements from '~/components/VLicense/VLicenseElements.vue'import VLink from '~/components/VLink.vue'@@ -60,29 +60,11 @@ export default {required: true,},},- computed: {- /**- * Public domain marks such as CC0 and PDM are not technically licenses.- * @return {boolean} true if the license is not CC0 or PDM, false otherwise- */- isTechnicallyLicense() {- return isLicense(this.license)- },- },- methods: {- getLicenseDeedLink(licenseTerm) {- let fragment- if (licenseTerm === 'cc0') {- fragment = 'publicdomain/zero/1.0'- } else if (licenseTerm === 'pdm') {- fragment = 'publicdomain/mark/1.0'- } else if (isDeprecated(licenseTerm)) {- fragment = `licenses/${licenseTerm}/1.0`- } else {- fragment = `licenses/${licenseTerm}/4.0`- }- return `https://creativecommons.org/${fragment}/?ref=openverse`- },+ setup() {+ return {+ isLicense,+ getLicenseUrl,+ }},}</script>diff --git a/src/locales/en.json b/src/locales/en.jsonindex 756f0deb5..adbffb6e3 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -423,13 +423,13 @@"credit": {"generic-title": "This work","actual-title": "\"{title}\"",- "text": "{title}{creator}{marked-licensed}{license}. {view-legal}",- "creator-text": " by {creator-name}",- "marked": " is marked with ",- "licensed": " is licensed under ",- "view-legal-text": "To view {terms-copy} visit {URL}.",- "terms-text": "the terms,",- "copy-text": "a copy of this license,"+ "text": "{title} {creator} {marked-licensed} {license}. {view-legal}",+ "creator-text": "by {creator-name}",+ "marked": "is marked with",+ "licensed": "is licensed under",+ "view-legal-text": "To view {terms-copy}, visit {url}.",+ "terms-text": "the terms",+ "copy-text": "a copy of this license"},"copy-license": {"title": "Credit the creator",diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 19ba60171..10d35a1ab 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -678,33 +678,33 @@ msgstr ""#. Do not translate words between ### ###.msgctxt "media-details.reuse.credit.text"-msgid "###title######creator######marked-licensed######license###. ###view-legal###"+msgid "###title### ###creator### ###marked-licensed### ###license###. ###view-legal###"msgstr ""#. Do not translate words between ### ###.msgctxt "media-details.reuse.credit.creator-text"-msgid " by ###creator-name###"+msgid "by ###creator-name###"msgstr ""msgctxt "media-details.reuse.credit.marked"-msgid " is marked with "+msgid "is marked with"msgstr ""msgctxt "media-details.reuse.credit.licensed"-msgid " is licensed under "+msgid "is licensed under"msgstr ""#. Do not translate words between ### ###.msgctxt "media-details.reuse.credit.view-legal-text"-msgid "To view ###terms-copy### visit ###URL###."+msgid "To view ###terms-copy###, visit ###url###."msgstr ""msgctxt "media-details.reuse.credit.terms-text"-msgid "the terms,"+msgid "the terms"msgstr ""msgctxt "media-details.reuse.credit.copy-text"-msgid "a copy of this license,"+msgid "a copy of this license"msgstr ""#. Do not translate words between ### ###.diff --git a/src/models/media.ts b/src/models/media.tsindex e945d6829..368d0d759 100644--- a/src/models/media.ts+++ b/src/models/media.ts@@ -21,7 +21,7 @@ export interface Media {license: Licenselicense_version: LicenseVersion- license_url: string+ license_url?: stringattribution: stringfrontendMediaType: SupportedMediaTypediff --git a/src/utils/attribution-html.ts b/src/utils/attribution-html.tsindex 544f8e4e9..00435f6ef 100644--- a/src/utils/attribution-html.ts+++ b/src/utils/attribution-html.ts@@ -1,3 +1,9 @@+/*+ * This module highly mirrors the Python code present in the backend repository.+ * For any changes made here, please make the corresponding changes in the+ * backend, or open an issue to track it.+ */+import type { Media } from '~/models/media'import {getElements,@@ -6,6 +12,8 @@ import {} from '~/utils/license'import type { LicenseElement } from '~/constants/license'+import enJson from '~/locales/en.json'+import type VueI18n from 'vue-i18n'/* Helper functions */@@ -31,6 +39,48 @@ const h = (return `${opening}${(children ?? []).join('\n')}${closing}`}+/**+ * Format the given string by replacing all placeholder keys with their values.+ * The pairs of placeholders and values are passed as a dictionary.+ *+ * @param text - the string in which to perform the formatting+ * @param replacements - the mapping of placeholders to values+ * @returns the formatted string+ */+const fmt = (text: string, replacements: Record<string, string>): string => {+ Object.entries(replacements).forEach(([key, value]) => {+ text = text.replace(`{${key}}`, value)+ })+ return text+}++/**+ * Perform the same role as `i18n.t` except that it's restricted to reading+ * English from `en.json`.+ *+ * @param path - the key to the JSON value to read+ * @param replacements - the pair of placeholders and their replacement strings+ * @returns the English string with placeholders substituted+ */+const fakeT = (+ path: string,+ replacements: Record<string, string> = {}+): string => {+ interface NestedRecord {+ [key: string]: string | NestedRecord+ }++ const segments = path.split('.')+ let fraction: NestedRecord = enJson['media-details'].reuse.credit+ let text: string | undefined = undefined+ segments.forEach((segment) => {+ const piece = fraction[segment]+ if (typeof piece === 'string') text = piece+ else fraction = piece+ })+ return text ? fmt(text, replacements) : ''+}+/*** Get an `<img>` tag corresponding to a license element.*@@ -102,17 +152,20 @@ export const getAttribution = (): string => {if (!mediaItem) return ''- /* Title */+ const isPd = isPublicDomain(mediaItem.license)- let titleLink = mediaItem.title || ''- if (!isPlaintext && mediaItem.foreign_landing_url && titleLink)- titleLink = extLink(mediaItem.foreign_landing_url, titleLink)+ const i18nBase = 'media-details.reuse.credit'+ const tFn = i18n+ ? (key: string, values?: VueI18n.Values) =>+ i18n.t(`${i18nBase}.${key}`, values).toString()+ : fakeT- /* Creator */+ /* Title */- let creatorLink = mediaItem.creator || ''- if (!isPlaintext && mediaItem.creator_url && creatorLink)- creatorLink = extLink(mediaItem.creator_url, creatorLink)+ let title = mediaItem.title || tFn('generic-title')+ if (!isPlaintext && mediaItem.foreign_landing_url)+ title = extLink(mediaItem.foreign_landing_url, title)+ if (mediaItem.title) title = tFn('actual-title', { title })/* License */@@ -126,73 +179,40 @@ export const getAttribution = (const elements = getElements(mediaItem.license)const icons = elements.map((element) => licenseElementImg(element))// Icons are only rendered if present for every element- if (!icons.includes('')) {- licenseIcons = icons.join('')- }- }-- let licenseLink = `${fullLicenseName} ${licenseIcons}`.trim()- if (!isPlaintext && mediaItem.license_url) {- licenseLink = extLink(`${mediaItem.license_url}?ref=openverse`, licenseLink)+ if (!icons.includes('')) licenseIcons = icons.join('')}+ let license = `${fullLicenseName} ${licenseIcons}`.trim()+ if (!isPlaintext && mediaItem.license_url)+ license = extLink(`${mediaItem.license_url}?ref=openverse`, license)/* Attribution */- const i18nBase = 'media-details.reuse.credit'- const isPd = isPublicDomain(mediaItem.license)+ const attributionParts: Record<string, string> = {+ title,+ 'marked-licensed': tFn(isPd ? 'marked' : 'licensed'),+ license: license,+ 'view-legal': '',+ creator: '',+ }- let attribution: string- if (i18n) {- let fillers: Record<string, string> = {- title: titleLink- ? i18n.t(`${i18nBase}.actual-title`, { title: titleLink }).toString()- : i18n.t(`${i18nBase}.generic-title`).toString(),- creator: creatorLink- ? i18n- .t(`${i18nBase}.creator-text`, {- 'creator-name': creatorLink,- })- .toString()- : '',- 'marked-licensed': i18n- .t(`${i18nBase}.${isPd ? 'marked' : 'licensed'}`)- .toString(),- license: licenseLink,- }- if (isPlaintext) {- fillers = {- ...fillers,- 'view-legal': i18n- .t(`${i18nBase}.view-legal-text`, {- 'terms-copy': i18n.t(- `${i18nBase}.${isPd ? 'terms-text' : 'copy-text'}`- ),- URL: `${mediaItem.license_url}?ref=openverse`,- })- .toString(),- }- }- attribution = i18n.t(`${i18nBase}.text`, fillers).toString()- } else {- const attributionParts = []- attributionParts.push(titleLink ? `"${titleLink}"` : 'This work')- if (creatorLink) attributionParts.push(' by ', creatorLink)- attributionParts.push(- isPd ? ' is marked with ' : ' is licensed under ',- licenseLink,- '.'- )- if (isPlaintext)- attributionParts.push(- ' To view ',- isPd ? 'the terms,' : 'a copy of this license,',- ' visit',- mediaItem.license_url,- '.'- )-- attribution = attributionParts.join('')+ if (isPlaintext && mediaItem.license_url) {+ attributionParts['view-legal'] = tFn('view-legal-text', {+ 'terms-copy': tFn(isPd ? 'terms-text' : 'copy-text'),+ url: `${mediaItem.license_url}?ref=openverse`,+ })}++ if (mediaItem.creator) {+ let creator = mediaItem.creator+ if (!isPlaintext && mediaItem.creator_url)+ creator = extLink(mediaItem.creator_url, creator)+ attributionParts.creator = tFn('creator-text', {+ 'creator-name': creator,+ })+ }++ const attribution = tFn('text', attributionParts).replace(/\s{2}/g, ' ')+return isPlaintext? attribution: h('p', { class: 'attribution' }, [attribution])diff --git a/src/utils/license.ts b/src/utils/license.tsindex 3656c3f33..3ccd9322a 100644--- a/src/utils/license.ts+++ b/src/utils/license.ts@@ -1,3 +1,9 @@+/*+ * This module highly mirrors the Python code present in the backend repository.+ * For any changes made here, please make the corresponding changes in the+ * backend, or open an issue to track it.+ */+import type {License,LicenseVersion,@@ -46,6 +52,30 @@ export const getFullLicenseName = (return licenseName.trim()}+/**+ * Get the URL to the deed of the license.+ *+ * @param license - the slug of license+ * @param licenseVersion - the version number of the license+ * @returns the URL to the license deed+ */+export const getLicenseUrl = (+ license: License,+ licenseVersion: LicenseVersion = ''+) => {+ let fragment+ if (license === 'cc0') {+ fragment = 'publicdomain/zero/1.0'+ } else if (license === 'pdm') {+ fragment = 'publicdomain/mark/1.0'+ } else if (isDeprecated(license)) {+ fragment = `licenses/${license}/1.0`+ } else {+ fragment = `licenses/${license}/${licenseVersion || '4.0'}`+ }+ return `https://creativecommons.org/${fragment}/?ref=openverse`+}+/*** 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@@ -54,8 +84,7 @@ export const getFullLicenseName = (* @param license - the license slug to check* @returns `false` if `license` is 'cc0' or 'pdm', `true` otherwise*/-export const isLicense = (license: string): boolean =>- !(PUBLIC_DOMAIN_MARKS as ReadonlyArray<string>).includes(license)+export const isLicense = (license: License): boolean => !isPublicDomain(license)/*** CC licenses have different legal status from the public domain marks@@ -65,7 +94,8 @@ export const isLicense = (license: string): boolean =>* @param license - the license slug to check* @returns `true` if `license` is 'cc0' or 'pdm', `false` otherwise*/-export const isPublicDomain = (license: License): boolean => !isLicense(license)+export const isPublicDomain = (license: License): boolean =>+ (PUBLIC_DOMAIN_MARKS as ReadonlyArray<string>).includes(license)/*** Check if the given name belongs to a deprecated CC license. The full list of@@ -84,7 +114,7 @@ export const isDeprecated = (license: License): boolean =>* includes CC0, which although not technically a license, is offered by CC.** @param license - the license slug to check- * @returns `true` if the license is a deprecated CC license, `false` otherwise+ * @returns `true` if the license is a CC license, `false` otherwise*/export const isCc = (license: License): boolean =>license == 'cc0' ||diff --git a/test/unit/specs/utils/attribution-html.spec.ts b/test/unit/specs/utils/attribution-html.spec.tsindex 284d86c53..0c3fbcb31 100644--- a/test/unit/specs/utils/attribution-html.spec.ts+++ b/test/unit/specs/utils/attribution-html.spec.ts@@ -78,6 +78,15 @@ describe('getAttribution', () => {expect(attrText).toEqual(expectation)})+ it('skips the link if URL is missing', () => {+ const mediaItemNoLicenseUrl = { ...mediaItem, license_url: undefined }+ const attrText = getAttribution(mediaItemNoLicenseUrl, i18n, {+ isPlaintext: true,+ })+ const antiExpectation = 'To view'+ expect(attrText).not.toContain(antiExpectation)+ })+it('does not add license element icons in no-icons mode', () => {document.body.innerHTML = getAttribution(mediaItem, i18n)expect(document.getElementsByTagName('img').length !== 0)