Skip to content

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

Implement media properties documentation for the API and frontend (#3966)

Dhruv Bhanushali68f3a7a685e8
diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml
index 3ec96cb52..b64cfc4c5 100644
--- a/.github/workflows/ci_cd.yml
+++ b/.github/workflows/ci_cd.yml
@@ -450,6 +450,7 @@ jobs:
- validate_openapi
- check_migrations
- test_doc
+ - test_media_props
include:
- name: check_django
recipe: api/dj check
@@ -459,6 +460,8 @@ jobs:
recipe: api/dj makemigrations --check
- name: test_doc
recipe: api/doc-test
+ - name: test_media_props
+ recipe: api/generate-docs
steps:
- name: Checkout repository
@@ -554,9 +557,12 @@ jobs:
matrix:
name:
- unit_test
+ - test_media_props
include:
- name: unit_test
- script: "test:unit"
+ recipe: frontend/run test:unit
+ - name: test_media_props
+ recipe: frontend/generate-docs
steps:
- name: Checkout repository
@@ -568,8 +574,8 @@ jobs:
setup_python: false
install_recipe: node-install
- - name: Run Nuxt checks
- run: just frontend/run ${{ matrix.script }}
+ - name: Run check recipe
+ run: just ${{ matrix.recipe }}
# This job runs when `nuxt-checks` doesn't and always passes, thus allowing
# PRs to meet the required checks criteria and be merged.
diff --git a/api/api/docs/media_properties/preamble.md b/api/api/docs/media_properties/preamble.md
new file mode 100644
index 000000000..de2b8da5b
--- /dev/null
+++ b/api/api/docs/media_properties/preamble.md
@@ -0,0 +1,14 @@
+# API Media Properties
+
+_This document is auto-generated from the source code in
+[/api/api/management/commands/documentmedia.py](https://github.com/WordPress/openverse/blob/main/api/api/management/commands/documentmedia.py)._
+
+This is a list of the media properties, with the descriptions of corresponding
+database columns and Python objects that are used to store and retrieve media
+data.
+
+## General notes
+
+The columns are sorted alphabetically and separated into relations (used to
+establish relationships to other models) and values (used to hold some data
+value). Note that relation fields are always nullable.
diff --git a/api/api/management/commands/documentmedia.py b/api/api/management/commands/documentmedia.py
new file mode 100644
index 000000000..f7a064887
--- /dev/null
+++ b/api/api/management/commands/documentmedia.py
@@ -0,0 +1,331 @@
+from dataclasses import dataclass
+from inspect import getdoc
+from pathlib import Path
+
+from django.core.management import BaseCommand
+from django.db import connection
+from django.db.models import NOT_PROVIDED
+from django.db.models.fields import Field
+
+import yaml
+
+from api.models.media import AbstractMedia
+
+
+PREAMBLE_PATH = Path(__file__).parents[2] / "docs" / "media_properties" / "preamble.md"
+OUTPUT_PATH = Path(__file__).parents[3] / "media_properties.md"
+
+
+@dataclass
+class RelationInfo:
+ """Store information about a relational field."""
+
+ nature: str
+ to: str
+
+
+@dataclass
+class ValueInfo:
+ """Store information about a value-based field."""
+
+ allows_blank: bool
+ allows_null: bool
+ is_pk: bool
+ needs_unique: bool
+ default: str
+ help_text: str
+
+
+@dataclass
+class FieldInfo:
+ """Store common information that is applicable to all types of fields."""
+
+ name: str
+ field: type[Field]
+ db_type: str
+ is_relation: bool
+ notes: str | None
+
+ relation_info: RelationInfo | None = None
+ value_info: ValueInfo | None = None
+
+ @staticmethod
+ def dj_docs_url(internal_type: str) -> str | None:
+ if internal_type == "ForeignObject":
+ # ``ForeignObject`` doesn't have any official documentation.
+ return None
+ if internal_type == "ArrayField":
+ # ``ArrayField`` is a PostgreSQL-specific field.
+ return "https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#arrayfield"
+ return f"https://docs.djangoproject.com/en/stable/ref/models/fields/#{internal_type.lower()}"
+
+ @property
+ def internal_type(self) -> str | tuple[str, str]:
+ internal_type = self.field.get_internal_type()
+ if internal_type == "ArrayField":
+ return internal_type, self.field.base_field.get_internal_type()
+ return internal_type
+
+ @property
+ def type_repr(self) -> str:
+ internal_types = self.internal_type
+ if not isinstance(internal_types, tuple):
+ internal_types = (internal_types,)
+ output = " of ".join(
+ f"[`{internal_type}`]({docs})"
+ if (docs := FieldInfo.dj_docs_url(internal_type))
+ else f"`{internal_type}`"
+ for internal_type in internal_types
+ )
+ return output
+
+
+def parse_notes(model_class: type[AbstractMedia]) -> dict[str, str]:
+ """
+ Parse additional notes about model fields from model docstring.
+
+ :param model_class: the model class whose docstring is being parsed
+ :return: the mapping of field name to manual notes about the field
+ """
+
+ documentation = getdoc(model_class)
+ if not documentation:
+ return {}
+
+ heading = "Properties\n=========="
+ if (pos := documentation.find(heading)) == -1:
+ return {}
+
+ props = documentation[pos + len(heading) :].strip()
+ info = yaml.safe_load(props)
+
+ return info
+
+
+def parse_fields(model_class: type[AbstractMedia]) -> list[FieldInfo]:
+ """
+ Parse the fields from a model class. This function generates a list of
+ ``FieldInfo`` objects representing the fields of the model.
+
+ :param model_class: the model class to parse
+ :return: a list of ``FieldInfo`` objects
+ """
+
+ notes = {}
+ for ancestor in reversed(model_class.__mro__):
+ notes |= parse_notes(ancestor)
+
+ fields = list(model_class._meta.get_fields())
+ fields.sort(key=lambda x: x.name)
+ field_infos = []
+ for field in fields:
+ field_info = FieldInfo(
+ name=field.name,
+ field=field,
+ db_type=field.db_type(connection),
+ is_relation=field.is_relation,
+ notes=notes.get(field.name),
+ )
+ field_infos.append(field_info)
+
+ if field_info.is_relation:
+ natures = [
+ "many_to_many",
+ "many_to_one",
+ "one_to_many",
+ "one_to_one",
+ ]
+ field_info.relation_info = RelationInfo(
+ nature=next(
+ nature for nature in natures if getattr(field, nature, False)
+ ),
+ to=field.related_model.__name__,
+ )
+ else:
+ field_info.value_info = ValueInfo(
+ allows_blank=field.blank,
+ allows_null=field.null,
+ is_pk=field.primary_key,
+ needs_unique=field.unique,
+ default=field.default,
+ help_text=field.help_text,
+ )
+
+ return field_infos
+
+
+def parse_models() -> dict[str, list[FieldInfo]]:
+ """
+ Parse all non-abstract descendants of ``AbstractMedia`` that represent media
+ types indexed by Openverse and return a mapping of a model to its fields.
+
+ :return: the mapping of a model to a list of its fields
+ """
+
+ media_models = AbstractMedia.__subclasses__()
+ return {
+ model_class.__name__: parse_fields(model_class) for model_class in media_models
+ }
+
+
+def generate_docs(props: dict[str, list[FieldInfo]]) -> str:
+ """
+ Generate the Markdown output for the media properties. This returns a string
+ that can be compared to the existing contents on disk.
+
+ :param props: the mapping of a model to a list of its fields
+ :return: the Markdown output for the media properties
+ """
+
+ output = ""
+
+ output += PREAMBLE_PATH.read_text()
+ output += "\n"
+
+ for model, fields in props.items():
+ relations, values = [], []
+ for field in fields:
+ if field.is_relation:
+ relations.append(field)
+ else:
+ values.append(field)
+
+ notes, noted_fields = generate_notes(model, fields)
+
+ output += f"## {model}\n\n"
+ output += generate_relation_table(model, noted_fields, relations)
+ output += "\n"
+ output += generate_value_table(model, noted_fields, values)
+ output += "\n"
+ output += notes
+
+ return output
+
+
+def generate_relation_table(
+ model: str,
+ noted_fields: set[str],
+ relations: list[FieldInfo],
+) -> str:
+ """
+ Generate the data-type table for the relation fields.
+
+ :param model: the parent model of the fields being documented
+ :param noted_fields: the set of fields that have associated notes
+ :param relations: the list of relation fields
+ :return: the table generated for the relation fields
+ """
+
+ columns = ["Name", "Type", "DB type", "Nature", "To"]
+ table = "### Relations\n\n"
+ table += f"|{'|'.join(columns)}|\n"
+ table += f"|{'-|'*len(columns)}\n"
+ for relation in relations:
+ name = f"`{relation.name}`"
+ if relation.name in noted_fields:
+ name = f"[{name}](#{model}-{relation.name}-notes)"
+ cells = (
+ name,
+ relation.type_repr,
+ f"`{relation.db_type}`" if relation.db_type else " ",
+ relation.relation_info.nature.replace("_", " ").title(),
+ f"`{relation.relation_info.to}`",
+ )
+ table += f"|{'|'.join(cells)}|\n"
+ return table
+
+
+def generate_value_table(
+ model: str,
+ noted_fields: set[str],
+ values: list[FieldInfo],
+) -> str:
+ """
+ Generate the data-type table for the value fields.
+
+ :param model: the parent model of the fields being documented
+ :param noted_fields: the set of fields that have associated notes
+ :param values: the list of value fields
+ :return: the table generated for the value fields
+ """
+
+ columns = ["Name", "Type", "DB type", "Constraints", "Default"]
+ table = "### Values\n\n"
+ table += f"|{'|'.join(columns)}|\n"
+ table += f"|{'-|'*len(columns)}\n"
+ for value in values:
+ name = f"`{value.name}`"
+ if value.name in noted_fields:
+ name = f"[{name}](#{model}-{value.name}-notes)"
+ cells = (
+ name,
+ value.type_repr,
+ f"`{value.db_type}`" if value.db_type else " ",
+ get_constraints(value.value_info),
+ f"`{value.value_info.default}`"
+ if value.value_info.default != NOT_PROVIDED
+ else " ",
+ )
+ table += f"|{'|'.join(cells)}|\n"
+ return table
+
+
+def generate_notes(model: str, fields: list[FieldInfo]) -> tuple[str, set[str]]:
+ """
+ Generate notes for the fields. These notes come from the help text and the
+ model docstrings.
+
+ :param model: the parent model of the fields being documented
+ :param fields: the fields for which to generate notes
+ :return: the notes section for all relation and value fields
+ """
+
+ output = "### Notes\n\n"
+
+ noted_fields = set()
+ for field in fields:
+ field_output = f"({model}-{field.name}-notes)=\n"
+ field_output += f"#### `{field.name}`\n\n"
+ record = False
+ if field.notes:
+ field_output += f"{field.notes}\n\n"
+ record = True
+ if not field.is_relation and field.value_info.help_text:
+ field_output += f"**Help text:** {field.value_info.help_text}\n\n"
+ record = True
+ if record:
+ noted_fields.add(field.name)
+ output += field_output
+
+ return output, noted_fields
+
+
+def get_constraints(value_info: ValueInfo) -> str:
+ """
+ Present the constraints in a succinct human-readable format. This function
+ inverts the presentation of ``null`` and ``blank`` since they are usually
+ ``True``.
+
+ :param value_info: the information for the value field
+ :return: a string representing the constraints
+ """
+
+ constraints = []
+ if not value_info.allows_null:
+ constraints.append("not null")
+ if not value_info.allows_blank:
+ constraints.append("not blank")
+ if value_info.needs_unique:
+ constraints.append("unique")
+ if value_info.is_pk:
+ constraints.append("primary key")
+ return "; ".join(constraints) or " "
+
+
+class Command(BaseCommand):
+ help = "Update docs for media properties in the documentation site."
+
+ def handle(self, **options):
+ props = parse_models()
+ docs = generate_docs(props)
+ OUTPUT_PATH.write_text(docs)
diff --git a/api/api/models/audio.py b/api/api/models/audio.py
index a081e6357..917be115f 100644
--- a/api/api/models/audio.py
+++ b/api/api/models/audio.py
@@ -144,6 +144,12 @@ class Audio(AudioFileMixin, AbstractMedia):
Inherited fields
================
category: eg. music, sound_effect, podcast, news & audiobook
+
+ Properties
+ ==========
+ audioset: >-
+ This is a virtual foreign-key to `AudioSet` built on top of the fields
+ `audio_set_foreign_identifier` and `provider`.
"""
audioset = models.ForeignObject(
diff --git a/api/api/models/media.py b/api/api/models/media.py
index 955b44177..ed0444be8 100644
--- a/api/api/models/media.py
+++ b/api/api/models/media.py
@@ -35,6 +35,12 @@ class AbstractMedia(
Generic model from which to inherit all media classes.
This class stores information common to all media types indexed by Openverse.
+
+ Properties
+ ==========
+ id: >-
+ This is Django's automatic primary key, used for models that do not
+ define one explicitly.
"""
watermarked = models.BooleanField(blank=True, null=True)
diff --git a/api/justfile b/api/justfile
index 9bcc93400..edeb2ea4a 100644
--- a/api/justfile
+++ b/api/justfile
@@ -106,6 +106,35 @@ ipython:
dbshell:
just dj dbshell
+# Generate the specified kind of documentation
+generate-docs doc="media-props" fail_on_diff="true":
+ #!/bin/bash
+ set -e
+ if [ "{{ doc }}" == "media-props" ]; then
+ FINAL_FILE="documentation/meta/media_properties/api.md"
+ NAME="Media properties"
+ just dj documentmedia
+ mv media_properties.md ../$FINAL_FILE
+ # Take ownership of media properties file.
+ if [ "$(ls -l ../$FINAL_FILE | awk '{print $3}')" != "$(whoami)" ]; then
+ sudo chown $(whoami) ../$FINAL_FILE
+ fi
+ else
+ echo "Invalid documentation type specified, use \`media-props\`. Exiting."
+ exit 1
+ fi
+ echo -n "Running linting..."
+ just ../lint prettier $FINAL_FILE &>/dev/null || true
+ echo "Done!"
+ if {{ fail_on_diff }}; then
+ set +e
+ git diff --exit-code ../$FINAL_FILE
+ if [ $? -ne 0 ]; then
+ printf "\n\n\e[31m!! Changes found in $NAME documentation, please run 'just api/generate-docs {{ doc }}' locally and commit difference !!\n\n"
+ exit 1
+ fi
+ fi
+
#########
# Tests #
#########
diff --git a/documentation/meta/ci_cd/jobs/api.md b/documentation/meta/ci_cd/jobs/api.md
index 56942caf8..7e615491d 100644
--- a/documentation/meta/ci_cd/jobs/api.md
+++ b/documentation/meta/ci_cd/jobs/api.md
@@ -46,6 +46,7 @@ recipes.
| `validate_openapi` | `api/dj spectacular --format openapi-json --validate --file openapi.json` |
| `check_migrations` | `api/dj makemigrations --check --noinput --merge` |
| `test_doc` | `api/doc-test` |
+| `test_media_props` | `api/generate-docs` |
This job is skipped if the API codebase has not changed. Its counterpart is
[`nuxt-checks`](/meta/ci_cd/jobs/frontend.md#nuxt-checks) for the frontend.
diff --git a/documentation/meta/ci_cd/jobs/frontend.md b/documentation/meta/ci_cd/jobs/frontend.md
index dfd177f3b..61166b74c 100644
--- a/documentation/meta/ci_cd/jobs/frontend.md
+++ b/documentation/meta/ci_cd/jobs/frontend.md
@@ -18,11 +18,12 @@ are
## `nuxt-checks`
Runs a matrix for various Nuxt checks for the frontend using the following
-Node.js script.
+`just` recipes.
-| Name | Script |
-| ----------- | ----------- |
-| `unit_test` | `test:unit` |
+| Name | Script |
+| ------------------ | ------------------------ |
+| `unit_test` | `frontend/run test:unit` |
+| `test_media_props` | `frontend/generate-docs` |
This job is skipped if the frontend codebase has not changed. Its counterpart is
[`django-checks`](/meta/ci_cd/jobs/api.md#django-checks) for the API.
diff --git a/documentation/meta/index.md b/documentation/meta/index.md
index 23d71cf44..7f9f44989 100644
--- a/documentation/meta/index.md
+++ b/documentation/meta/index.md
@@ -11,4 +11,5 @@ decision_making/index
documentation/index
monitoring/index
maintenance/index
+media_properties/index
```
diff --git a/documentation/meta/media_properties/api.md b/documentation/meta/media_properties/api.md
new file mode 100644
index 000000000..9ac76770c
--- /dev/null
+++ b/documentation/meta/media_properties/api.md
@@ -0,0 +1,382 @@
+# API Media Properties
+
+_This document is auto-generated from the source code in
+[/api/api/management/commands/documentmedia.py](https://github.com/WordPress/openverse/blob/main/api/api/management/commands/documentmedia.py)._
+
+This is a list of the media properties, with the descriptions of corresponding
+database columns and Python objects that are used to store and retrieve media
+data.
+
+## General notes
+
+The columns are sorted alphabetically and separated into relations (used to
+establish relationships to other models) and values (used to hold some data
+value). Note that relation fields are always nullable.
+
+## Audio
+
+### Relations
+
+| Name | Type | DB type | Nature | To |
+| ----------------------------------- | ------------------------------------------------------------------------------------------------ | ------- | ------------ | ---------------- |
+| `audio_report` | [`ForeignKey`](https://docs.djangoproject.com/en/stable/ref/models/fields/#foreignkey) | `uuid` | One To Many | `AudioReport` |
+| `audiodecision` | [`ManyToManyField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#manytomanyfield) | | Many To Many | `AudioDecision` |
+| [`audioset`](#Audio-audioset-notes) | `ForeignObject` | | Many To One | `AudioSet` |
+| `deleted_audio` | [`OneToOneField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#onetoonefield) | `uuid` | One To One | `DeletedAudio` |
+| `lists` | [`ManyToManyField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#manytomanyfield) | | Many To Many | `AudioList` |
+| `sensitive_audio` | [`OneToOneField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#onetoonefield) | `uuid` | One To One | `SensitiveAudio` |
+
+### Values
+
+| Name | Type | DB type | Constraints | Default |
+| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ----------------------------- | ------- |
+| [`alt_files`](#Audio-alt_files-notes) | [`JSONField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#jsonfield) | `jsonb` | | |
+| [`audio_set_foreign_identifier`](#Audio-audio_set_foreign_identifier-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`audio_set_position`](#Audio-audio_set_position-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`bit_rate`](#Audio-bit_rate-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`category`](#Audio-category-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| `created_on` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | not null | |
+| [`creator`](#Audio-creator-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| [`creator_url`](#Audio-creator_url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| [`duration`](#Audio-duration-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`filesize`](#Audio-filesize-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`filetype`](#Audio-filetype-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| [`foreign_identifier`](#Audio-foreign_identifier-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`foreign_landing_url`](#Audio-foreign_landing_url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`genres`](#Audio-genres-notes) | [`ArrayField`](https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#arrayfield) of [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)[]` | not blank | |
+| [`id`](#Audio-id-notes) | [`AutoField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#autofield) | `integer` | not null; unique; primary key | |
+| [`identifier`](#Audio-identifier-notes) | [`UUIDField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#uuidfield) | `uuid` | not null; not blank; unique | |
+| `last_synced_with_source` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | | |
+| [`license`](#Audio-license-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(50)` | not null; not blank | |
+| [`license_version`](#Audio-license_version-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(25)` | | |
+| `meta_data` | [`JSONField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#jsonfield) | `jsonb` | | |
+| [`provider`](#Audio-provider-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| `removed_from_source` | [`BooleanField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield) | `boolean` | not null; not blank | `False` |
+| [`sample_rate`](#Audio-sample_rate-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`source`](#Audio-source-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| [`tags`](#Audio-tags-notes) | [`JSONField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#jsonfield) | `jsonb` | | |
+| [`thumbnail`](#Audio-thumbnail-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`title`](#Audio-title-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| `updated_on` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | not null | |
+| [`url`](#Audio-url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | unique | |
+| `view_count` | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | `0` |
+| `watermarked` | [`BooleanField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield) | `boolean` | | |
+
+### Notes
+
+(Audio-alt_files-notes)=
+
+#### `alt_files`
+
+**Help text:** JSON describing alternative files for this audio.
+
+(Audio-audio_set_foreign_identifier-notes)=
+
+#### `audio_set_foreign_identifier`
+
+**Help text:** Reference to set of which this track is a part.
+
+(Audio-audio_set_position-notes)=
+
+#### `audio_set_position`
+
+**Help text:** Ordering of the audio in the set.
+
+(Audio-audioset-notes)=
+
+#### `audioset`
+
+This is a virtual foreign-key to `AudioSet` built on top of the fields
+`audio_set_foreign_identifier` and `provider`.
+
+(Audio-bit_rate-notes)=
+
+#### `bit_rate`
+
+**Help text:** Number in bits per second, eg. 128000.
+
+(Audio-category-notes)=
+
+#### `category`
+
+**Help text:** The top-level classification of this media file.
+
+(Audio-creator-notes)=
+
+#### `creator`
+
+**Help text:** The name of the media creator.
+
+(Audio-creator_url-notes)=
+
+#### `creator_url`
+
+**Help text:** A direct link to the media creator.
+
+(Audio-duration-notes)=
+
+#### `duration`
+
+**Help text:** The time length of the audio file in milliseconds.
+
+(Audio-filesize-notes)=
+
+#### `filesize`
+
+**Help text:** Number in bytes, e.g. 1024.
+
+(Audio-filetype-notes)=
+
+#### `filetype`
+
+**Help text:** The type of the file, related to the file extension.
+
+(Audio-foreign_identifier-notes)=
+
+#### `foreign_identifier`
+
+**Help text:** The identifier provided by the upstream source.
+
+(Audio-foreign_landing_url-notes)=
+
+#### `foreign_landing_url`
+
+**Help text:** The landing page of the work.
+
+(Audio-genres-notes)=
+
+#### `genres`
+
+**Help text:** An array of audio genres such as `rock`, `electronic` for `music`
+category, or `politics`, `sport`, `education` for `podcast` category
+
+(Audio-id-notes)=
+
+#### `id`
+
+This is Django's automatic primary key, used for models that do not define one
+explicitly.
+
+(Audio-identifier-notes)=
+
+#### `identifier`
+
+**Help text:** Our unique identifier for an open-licensed work.
+
+(Audio-license-notes)=
+
+#### `license`
+
+**Help text:** The name of license for the media.
+
+(Audio-license_version-notes)=
+
+#### `license_version`
+
+**Help text:** The version of the media license.
+
+(Audio-provider-notes)=
+
+#### `provider`
+
+**Help text:** The content provider, e.g. Flickr, Jamendo...
+
+(Audio-sample_rate-notes)=
+
+#### `sample_rate`
+
+**Help text:** Number in hertz, eg. 44100.
+
+(Audio-source-notes)=
+
+#### `source`
+
+**Help text:** The source of the data, meaning a particular dataset. Source and
+provider can be different. Eg: the Google Open Images dataset is
+source=openimages, but provider=flickr.
+
+(Audio-tags-notes)=
+
+#### `tags`
+
+**Help text:** Tags with detailed metadata, such as accuracy.
+
+(Audio-thumbnail-notes)=
+
+#### `thumbnail`
+
+**Help text:** The thumbnail for the media.
+
+(Audio-title-notes)=
+
+#### `title`
+
+**Help text:** The name of the media.
+
+(Audio-url-notes)=
+
+#### `url`
+
+**Help text:** The actual URL to the media file.
+
+## Image
+
+### Relations
+
+| Name | Type | DB type | Nature | To |
+| ----------------- | ------------------------------------------------------------------------------------------------ | ------- | ------------ | ---------------- |
+| `deleted_image` | [`OneToOneField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#onetoonefield) | `uuid` | One To One | `DeletedImage` |
+| `image_report` | [`ForeignKey`](https://docs.djangoproject.com/en/stable/ref/models/fields/#foreignkey) | `uuid` | One To Many | `ImageReport` |
+| `imagedecision` | [`ManyToManyField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#manytomanyfield) | | Many To Many | `ImageDecision` |
+| `lists` | [`ManyToManyField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#manytomanyfield) | | Many To Many | `ImageList` |
+| `sensitive_image` | [`OneToOneField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#onetoonefield) | `uuid` | One To One | `SensitiveImage` |
+
+### Values
+
+| Name | Type | DB type | Constraints | Default |
+| --------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------- | ----------------------------- | ------- |
+| [`category`](#Image-category-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| `created_on` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | not null | |
+| [`creator`](#Image-creator-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| [`creator_url`](#Image-creator_url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| [`filesize`](#Image-filesize-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`filetype`](#Image-filetype-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| [`foreign_identifier`](#Image-foreign_identifier-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`foreign_landing_url`](#Image-foreign_landing_url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`height`](#Image-height-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+| [`id`](#Image-id-notes) | [`AutoField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#autofield) | `integer` | not null; unique; primary key | |
+| [`identifier`](#Image-identifier-notes) | [`UUIDField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#uuidfield) | `uuid` | not null; not blank; unique | |
+| `last_synced_with_source` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | | |
+| [`license`](#Image-license-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(50)` | not null; not blank | |
+| [`license_version`](#Image-license_version-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(25)` | | |
+| `meta_data` | [`JSONField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#jsonfield) | `jsonb` | | |
+| [`provider`](#Image-provider-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| `removed_from_source` | [`BooleanField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield) | `boolean` | not null; not blank | `False` |
+| [`source`](#Image-source-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(80)` | | |
+| [`tags`](#Image-tags-notes) | [`JSONField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#jsonfield) | `jsonb` | | |
+| [`thumbnail`](#Image-thumbnail-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | | |
+| [`title`](#Image-title-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(2000)` | | |
+| `updated_on` | [`DateTimeField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#datetimefield) | `timestamp with time zone` | not null | |
+| [`url`](#Image-url-notes) | [`CharField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#charfield) | `varchar(1000)` | unique | |
+| `view_count` | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | `0` |
+| `watermarked` | [`BooleanField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield) | `boolean` | | |
+| [`width`](#Image-width-notes) | [`IntegerField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#integerfield) | `integer` | | |
+
+### Notes
+
+(Image-category-notes)=
+
+#### `category`
+
+**Help text:** The top-level classification of this media file.
+
+(Image-creator-notes)=
+
+#### `creator`
+
+**Help text:** The name of the media creator.
+
+(Image-creator_url-notes)=
+
+#### `creator_url`
+
+**Help text:** A direct link to the media creator.
+
+(Image-filesize-notes)=
+
+#### `filesize`
+
+**Help text:** Number in bytes, e.g. 1024.
+
+(Image-filetype-notes)=
+
+#### `filetype`
+
+**Help text:** The type of the file, related to the file extension.
+
+(Image-foreign_identifier-notes)=
+
+#### `foreign_identifier`
+
+**Help text:** The identifier provided by the upstream source.
+
+(Image-foreign_landing_url-notes)=
+
+#### `foreign_landing_url`
+
+**Help text:** The landing page of the work.
+
+(Image-height-notes)=
+
+#### `height`
+
+**Help text:** The height of the image in pixels. Not always available.
+
+(Image-id-notes)=
+
+#### `id`
+
+This is Django's automatic primary key, used for models that do not define one
+explicitly.
+
+(Image-identifier-notes)=
+
+#### `identifier`
+
+**Help text:** Our unique identifier for an open-licensed work.
+
+(Image-license-notes)=
+
+#### `license`
+
+**Help text:** The name of license for the media.
+
+(Image-license_version-notes)=
+
+#### `license_version`
+
+**Help text:** The version of the media license.
+
+(Image-provider-notes)=
+
+#### `provider`
+
+**Help text:** The content provider, e.g. Flickr, Jamendo...
+
+(Image-source-notes)=
+
+#### `source`
+
+**Help text:** The source of the data, meaning a particular dataset. Source and
+provider can be different. Eg: the Google Open Images dataset is
+source=openimages, but provider=flickr.
+
+(Image-tags-notes)=
+
+#### `tags`
+
+**Help text:** Tags with detailed metadata, such as accuracy.
+
+(Image-thumbnail-notes)=
+
+#### `thumbnail`
+
+**Help text:** The thumbnail for the media.
+
+(Image-title-notes)=
+
+#### `title`
+
+**Help text:** The name of the media.
+
+(Image-url-notes)=
+
+#### `url`
+
+**Help text:** The actual URL to the media file.
+
+(Image-width-notes)=
+
+#### `width`
+
+**Help text:** The width of the image in pixels. Not always available.
diff --git a/documentation/meta/media_properties/frontend.md b/documentation/meta/media_properties/frontend.md
new file mode 100644
index 000000000..e3b28413f
--- /dev/null
+++ b/documentation/meta/media_properties/frontend.md
@@ -0,0 +1,154 @@
+# Frontend Media Properties
+
+_This document is auto-generated from the source code in
+[/frontend/scripts/document-media.js](https://github.com/WordPress/openverse/blob/main/frontend/scripts/document-media.js)._
+
+This is a list of the media properties, with the descriptions of corresponding
+TypeScript types that are used in the frontend to hold media objects.
+
+## General notes
+
+The columns are sorted alphabetically. Both interfaces `ImageDetail` and
+`AudioDetail` inherit from interface `Media` so the tables for those interfaces
+only show their additional fields.
+
+Some types in the "Type" column may refer to interfaces or types defined in the
+frontend codebase. In such cases it is advised to refer to the source file
+[/frontend/src/types/media.ts](https://github.com/WordPress/openverse/blob/main/frontend/src/types/media.ts)
+and trace the source of the type definitions. Such types are italicised for
+clarity.
+
+## Interface `Media`
+
+### Fields
+
+| Name | Type | Optional? |
+| --------------------------------------------- | ----------------------------- | --------- |
+| `attribution` | `string` | |
+| `category` | `string \| null` | |
+| `creator` | `string` | ✓ |
+| `creator_url` | `string` | ✓ |
+| `description` | `string` | ✓ |
+| `detail_url` | `string` | |
+| `fields_matched` | `string[]` | ✓ |
+| `filesize` | `string` | ✓ |
+| `filetype` | `string` | ✓ |
+| `foreign_landing_url` | `string` | |
+| `frontendMediaType` | `SupportedMediaType` (custom) | |
+| [`id`](#Media-id-notes) | `string` | |
+| `isSensitive` | `boolean` | |
+| `license` | `License` (custom) | |
+| `license_url` | `string` | ✓ |
+| `license_version` | `LicenseVersion` (custom) | |
+| [`originalTitle`](#Media-originalTitle-notes) | `string` | |
+| `provider` | `string` | |
+| `providerName` | `string` | ✓ |
+| `related_url` | `string` | |
+| `sensitivity` | `Sensitivity[]` (custom) | |
+| `source` | `string` | ✓ |
+| `sourceName` | `string` | ✓ |
+| `tags` | `Tag[]` (custom) | |
+| `thumbnail` | `string` | ✓ |
+| [`title`](#Media-title-notes) | `string` | |
+| `url` | `string` | |
+
+### Notes
+
+(Media-id-notes)=
+
+#### `id`
+
+the UUID4 identifier of the media item
+
+**See also:**
+
+- [UUID4](<https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)>)
+
+(Media-originalTitle-notes)=
+
+#### `originalTitle`
+
+the raw name of the creative work, as returned by the API
+
+(Media-title-notes)=
+
+#### `title`
+
+the name of the creative work; This involves the following kinds of changes to
+the original title:
+
+- remove the file extension
+- escape HTML
+- handle empty titles
+
+## Interface `ImageDetail`
+
+### Fields
+
+| Name | Type | Optional? |
+| ------------------------------------- | ------------------- | --------- |
+| `frontendMediaType` | `"image"` (literal) | |
+| [`height`](#ImageDetail-height-notes) | `number` | ✓ |
+| [`width`](#ImageDetail-width-notes) | `number` | ✓ |
+
+### Notes
+
+(ImageDetail-height-notes)=
+
+#### `height`
+
+the vertical length of the image in pixels
+
+(ImageDetail-width-notes)=
+
+#### `width`
+
+the horizontal length of the image in pixels
+
+## Interface `AudioDetail`
+
+### Fields
+
+| Name | Type | Optional? |
+| ----------------------------------------------- | ------------------------------------------ | --------- |
+| `alt_files` | `{ provider: string; filetype: string }[]` | ✓ |
+| `audio_set` | `AudioSet` (custom) | ✓ |
+| [`bit_rate`](#AudioDetail-bit_rate-notes) | `number` | ✓ |
+| [`duration`](#AudioDetail-duration-notes) | `number` | ✓ |
+| `frontendMediaType` | `"audio"` (literal) | |
+| `genres` | `string[]` | ✓ |
+| `hasLoaded` | `boolean` | ✓ |
+| `length` | `string` | ✓ |
+| `peaks` | `number[]` | ✓ |
+| [`sample_rate`](#AudioDetail-sample_rate-notes) | `number` | ✓ |
+| `waveform` | `string` | ✓ |
+
+### Notes
+
+(AudioDetail-bit_rate-notes)=
+
+#### `bit_rate`
+
+amount of digital audio data transmitted or processed in unit time; This field
+holds numbers measured in bits per second.
+
+**See also:**
+
+- [Wikipedia](https://en.wikipedia.org/wiki/Bit_rate#Audio)
+
+(AudioDetail-duration-notes)=
+
+#### `duration`
+
+the time period of the track in milliseconds
+
+(AudioDetail-sample_rate-notes)=
+
+#### `sample_rate`
+
+number of samples for digital representation taken in unit time; This field
+holds numbers measured in hertz.
+
+**See also:**
+
+- [Wikipedia](<https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Audio_sampling>)
diff --git a/documentation/meta/media_properties/index.md b/documentation/meta/media_properties/index.md
new file mode 100644
index 000000000..220877201
--- /dev/null
+++ b/documentation/meta/media_properties/index.md
@@ -0,0 +1,11 @@
+# Media properties
+
+This part of the documentation documents media properties at each layer of the
+Openverse stack.
+
+```{toctree}
+:titlesonly:
+
+api
+frontend
+```
diff --git a/frontend/justfile b/frontend/justfile
index 24543d1d5..d70e59609 100644
--- a/frontend/justfile
+++ b/frontend/justfile
@@ -69,6 +69,31 @@ init: wait-up
run *args:
pnpm run {{ args }}
+# Generate the specified kind of documentation
+generate-docs doc="media-props" fail_on_diff="true":
+ #!/bin/bash
+ set -e
+ if [ "{{ doc }}" == "media-props" ]; then
+ FINAL_FILE="documentation/meta/media_properties/frontend.md"
+ NAME="Media properties"
+ just run doc:media-props
+ mv media_properties.md ../$FINAL_FILE
+ else
+ echo "Invalid documentation type specified, use \`media-props\`. Exiting."
+ exit 1
+ fi
+ echo -n "Running linting..."
+ just ../lint prettier $FINAL_FILE &>/dev/null || true
+ echo "Done!"
+ if {{ fail_on_diff }}; then
+ set +e
+ git diff --exit-code ../$FINAL_FILE
+ if [ $? -ne 0 ]; then
+ printf "\n\n\e[31m!! Changes found in $NAME documentation, please run 'just frontend/generate-docs {{ doc }}' locally and commit difference !!\n\n"
+ exit 1
+ fi
+ fi
+
types:
cd .. && pnpm exec vue-tsc -p frontend --noEmit
diff --git a/frontend/package.json b/frontend/package.json
index 79a142af2..8e4e193ca 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -53,7 +53,8 @@
"create:component-storybook-test": "remake component-storybook-test",
"create:component-unit-test": "remake component-unit-test",
"create:component-scaffolding": "npm-run-all \"create:component-sfc --output=src/components --name={1}\" \"create:story --output=src/components/{1}/meta --name={1}\" \"create:component-unit-test --output=test/unit/specs/components/{1} --name={1} --fileName={2}\" \"create:component-storybook-test --output=test/storybook/visual-regression --fileName={2} --name={1}\" --",
- "create:component": "./bin/create-component.sh"
+ "create:component": "./bin/create-component.sh",
+ "doc:media-props": "node ./scripts/document-media.js"
},
"dependencies": {
"@floating-ui/dom": "^1.5.3",
diff --git a/frontend/scripts/document-media.js b/frontend/scripts/document-media.js
new file mode 100644
index 000000000..52d974d52
--- /dev/null
+++ b/frontend/scripts/document-media.js
@@ -0,0 +1,243 @@
+const fs = require("fs")
+const path = require("path")
+
+const ts = require("typescript")
+
+/**
+ * @typedef {{text: string, links: {text: string, dest?: string}[]}} Comment
+ * @typedef {{name: string, type: string, isOptional: boolean, documentation: Comment | undefined}} Field
+ */
+
+const preamblePath = path.resolve(__dirname, "preamble.md")
+const docsFilePath = path.resolve(__dirname, "../media_properties.md")
+
+/**
+ * Generate Markdown documentation for an interface. This generates both the
+ * data type table and the following long-form descriptions from the TSDoc
+ * docstrings.
+ *
+ * @param node {ts.Node} the interface node to document
+ * @param ast {ts.SourceFile} the AST for the media types file
+ * @returns {string} the Markdown documentation for the interface
+ */
+function documentInterface(node, ast) {
+ const fields = getInterfaceFields(node, ast).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ )
+
+ /** @type {string[]} */
+ const output = []
+
+ output.push(`## Interface \`${node.name.text}\``)
+
+ output.push("### Fields")
+
+ // Notes
+ const notes = []
+ const noted_fields = []
+ for (const field of fields) {
+ if (field.documentation) {
+ noted_fields.push(field.name)
+ notes.push(`\n(${node.name.text}-${field.name}-notes)=`)
+ notes.push(`#### \`${field.name}\``)
+ notes.push(field.documentation.text)
+ if (field.documentation.links.length) {
+ notes.push("\n**See also:**")
+ for (const link of field.documentation.links) {
+ notes.push(`- [${link.text}](${link.dest || link.text})`)
+ }
+ }
+ }
+ }
+
+ // Table
+ output.push("| Name | Type | Optional? |")
+ output.push("|-|-|-|")
+
+ for (const field of fields) {
+ let fieldName = `\`${field.name}\``
+ if (noted_fields.includes(field.name)) {
+ fieldName = `[${fieldName}](#${node.name.text}-${field.name}-notes)`
+ }
+
+ let fieldType = field.type.replace("|", "\\|")
+ fieldType = `\`${fieldType}\``
+ if (fieldType[1] >= "A" && fieldType[1] <= "Z") {
+ // hack to identify custom types
+ fieldType = `${fieldType} (custom)`
+ }
+ if (fieldType[1] === '"' && fieldType.at(-2) === '"') {
+ // hack to identify literal types
+ fieldType = `${fieldType} (literal)`
+ }
+
+ const columns = [fieldName, fieldType, field.isOptional ? "✓" : ""]
+ output.push(`|${columns.join("|")}|`)
+ }
+
+ // Notes
+ output.push("### Notes")
+ output.push(...notes)
+
+ return output.join("\n")
+}
+
+/**
+ * Determine whether the interface node is, or extends from, interface `Media`.
+ *
+ * @param node {ts.Node} the node to check for being, or extending from, `Media`
+ * @returns {boolean} whether the node is, or extends from, interface `Media`
+ */
+function isOfInterest(node) {
+ return (
+ node.name.text === "Media" ||
+ (node.heritageClauses &&
+ node.heritageClauses.some((clause) =>
+ clause.types.some((type) => type.expression.text === "Media")
+ ))
+ )
+}
+
+/**
+ * Extract all the properties from the interface.
+ *
+ * @param node {ts.Node} the interface node to extract fields from
+ * @param ast {ts.SourceFile} the AST for the media types file
+ * @returns {Field[]} the fields of the interface
+ */
+function getInterfaceFields(node, ast) {
+ return node.members.map((member) => {
+ if (ts.isPropertySignature(member) && member.name) {
+ const name = member.name.text
+ const documentation = extractComments(member, ast)
+ const type = member.type ? member.type.getText(ast) : "unknown"
+ const isOptional = Boolean(member.questionToken)
+ return { name, type, isOptional, documentation }
+ }
+ })
+}
+
+/**
+ * Extracts and parses the JSDoc comment for a node.
+ *
+ * @param node {ts.Node} the AST node for which to get the comments
+ * @param ast {ts.SourceFile}
+ * @returns {Comment | undefined} the parsed docstring comment
+ */
+function extractComments(node, ast) {
+ const fullText = node.getFullText(ast)
+
+ let commentRanges = ts.getLeadingCommentRanges(fullText, 0)
+ if (!commentRanges) {
+ return undefined
+ }
+
+ const comments = commentRanges
+ .filter((range) => range.kind === ts.SyntaxKind.MultiLineCommentTrivia)
+ .map((range) => fullText.substring(range.pos, range.end))
+ .filter((comment) => comment.startsWith("/**"))
+ if (!comments.length) {
+ return undefined
+ }
+
+ let links = []
+ let text = comments
+ .at(-1) // retain only the last doc comment
+ .split("\n")
+ .map((line) =>
+ line
+ .replace("/**", "") // remove start of docstring
+ .replace("*/", "") // remove end of docstring
+ .replace(/^\s*\*/, "") // remove leading asterisks
+ .trim()
+ )
+ .filter((line) => {
+ if (!line) {
+ return false
+ }
+ if (!line.startsWith("@see")) {
+ return true // keep the line as text, and move to the next line
+ }
+
+ const match = line.match(/\{@link (?<dest>[^|]*)(\|(?<text>.*))?}/)
+ if (match) {
+ links.push({
+ dest: match.groups.dest,
+ text: match.groups.text || match.groups.dest,
+ })
+ } else {
+ links.push({ text: line.replace("@see", "").trim() })
+ }
+ return false // remove the line from text as it will be in links
+ })
+ .join("\n")
+
+ return { text, links }
+}
+
+/**
+ * Convert the file with media types and interfaces into an AST using the
+ * TypeScript compiler.
+ *
+ * @returns {ts.SourceFile} the AST for the media types file
+ */
+function getAst() {
+ const tsFilePath = path.resolve(__dirname, "../src/types/media.ts")
+ console.log(`Parsing ${tsFilePath}.`)
+
+ return ts.createSourceFile(
+ "media.ts",
+ fs.readFileSync(tsFilePath, "utf-8"),
+ ts.ScriptTarget.Latest
+ )
+}
+
+/**
+ * Get all interfaces that are, or extend from, interface `Media` from the
+ * source code.
+ *
+ * @param ast {ts.SourceFile} the AST to search for interfaces
+ * @returns {ts.Node[]} the interface `Media` and interfaces that extend from it
+ */
+function getMediaInterfaces(ast) {
+ /** @type {ts.Node[]} */
+ const mediaInterfaces = []
+
+ const visit = (node) => {
+ if (ts.isInterfaceDeclaration(node) && isOfInterest(node)) {
+ mediaInterfaces.push(node)
+ }
+ ts.forEachChild(node, visit)
+ }
+ visit(ast)
+
+ return mediaInterfaces
+}
+
+/**
+ * Write the generated documentation with preamble to the output file.
+ *
+ * @param docs {string} the generated documentation to write below the preamble
+ */
+function writeDocs(docs) {
+ const preamble = fs.readFileSync(preamblePath, "utf-8")
+ console.log(`Writing to ${docsFilePath}.`)
+ fs.writeFileSync(docsFilePath, [preamble, docs].join("\n"))
+}
+
+/*
+ **************
+ * Entrypoint *
+ **************
+ */
+
+function main() {
+ const ast = getAst()
+ const mediaInterfaces = getMediaInterfaces(ast)
+ const docs = mediaInterfaces
+ .map((mediaInterface) => documentInterface(mediaInterface, ast))
+ .join("\n")
+ writeDocs(docs)
+}
+
+main()
diff --git a/frontend/scripts/preamble.md b/frontend/scripts/preamble.md
new file mode 100644
index 000000000..db587eb1f
--- /dev/null
+++ b/frontend/scripts/preamble.md
@@ -0,0 +1,19 @@
+# Frontend Media Properties
+
+_This document is auto-generated from the source code in
+[/frontend/scripts/document-media.js](https://github.com/WordPress/openverse/blob/main/frontend/scripts/document-media.js)._
+
+This is a list of the media properties, with the descriptions of corresponding
+TypeScript types that are used in the frontend to hold media objects.
+
+## General notes
+
+The columns are sorted alphabetically. Both interfaces `ImageDetail` and
+`AudioDetail` inherit from interface `Media` so the tables for those interfaces
+only show their additional fields.
+
+Some types in the "Type" column may refer to interfaces or types defined in the
+frontend codebase. In such cases it is advised to refer to the source file
+[/frontend/src/types/media.ts](https://github.com/WordPress/openverse/blob/main/frontend/src/types/media.ts)
+and trace the source of the type definitions. Such types are italicised for
+clarity.
diff --git a/frontend/src/types/media.ts b/frontend/src/types/media.ts
index 063f68cc2..9fd7b8491 100644
--- a/frontend/src/types/media.ts
+++ b/frontend/src/types/media.ts
@@ -1,3 +1,8 @@
+// This module contains types and interfaces for media items.
+//
+// The source code of this package is parsed to create the media properties
+// documentation by the script `scripts/document-media.js`.
+
import type { SupportedMediaType } from "~/constants/media"
import type { License, LicenseVersion } from "~/constants/license"
import {
@@ -15,8 +20,22 @@ export interface Tag {
* for individual media.
*/
export interface Media {
+ /**
+ * the UUID4 identifier of the media item
+ *
+ * @see {@link https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)|UUID4}
+ */
id: string
+ /**
+ * the name of the creative work; This involves the following kinds of
+ * changes to the original title:
+ *
+ * - remove the file extension
+ * - escape HTML
+ * - handle empty titles
+ */
title: string
+ /** the raw name of the creative work, as returned by the API */
originalTitle: string
creator?: string
@@ -57,7 +76,9 @@ export interface Media {
export interface ImageDetail extends Media {
frontendMediaType: "image"
+ /** the vertical length of the image in pixels */
height?: number
+ /** the horizontal length of the image in pixels */
width?: number
}
@@ -77,8 +98,21 @@ export interface AudioDetail extends Media {
audio_set?: AudioSet
genres?: string[]
length?: string
+ /** the time period of the track in milliseconds */
duration?: number
+ /**
+ * amount of digital audio data transmitted or processed in unit time; This
+ * field holds numbers measured in bits per second.
+ *
+ * @see {@link https://en.wikipedia.org/wiki/Bit_rate#Audio|Wikipedia}
+ */
bit_rate?: number
+ /**
+ * number of samples for digital representation taken in unit time; This field
+ * holds numbers measured in hertz.
+ *
+ * @see {@link https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Audio_sampling|Wikipedia}
+ */
sample_rate?: number
alt_files?: { provider: string; filetype: string }[]
peaks?: number[]