Skip to content

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

Add sample WordPress REST API script (#223)

Krystle Salazarea31d8109ead
diff --git a/openverse_catalog/dags/provider_api_scripts/wordpress.py b/openverse_catalog/dags/provider_api_scripts/wordpress.py
new file mode 100644
index 000000000..dbef44978
--- /dev/null
+++ b/openverse_catalog/dags/provider_api_scripts/wordpress.py
@@ -0,0 +1,328 @@
+"""
+Content Provider: WordPress Photo Directory
+
+ETL Process: Use the API to identify all openly licensed media.
+
+Output: TSV file containing the media metadata.
+
+Notes: https://wordpress.org/photos/wp-json/wp/v2
+ Provide photos, media, users and more related resources.
+ No rate limit specified.
+"""
+import logging
+from pathlib import Path
+
+import lxml.html as html
+from common.licenses.licenses import get_license_info
+from common.requester import DelayedRequester
+from storage.image import ImageStore
+from util.loader import provider_details as prov
+
+
+logging.basicConfig(
+ format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
+)
+logger = logging.getLogger(__name__)
+
+LIMIT = 100 # number of items per page in API response
+DELAY = 1 # in seconds
+RETRIES = 3
+
+HOST = "wordpress.org"
+ENDPOINT = f"https://{HOST}/photos/wp-json/wp/v2"
+
+PROVIDER = prov.WORDPRESS_DEFAULT_PROVIDER
+
+DEFAULT_QUERY_PARAMS = {
+ "format": "json",
+ "page": 1,
+ "per_page": LIMIT,
+}
+
+delayed_requester = DelayedRequester(DELAY)
+image_store = ImageStore(provider=PROVIDER)
+
+license_url = "https://creativecommons.org/publicdomain/zero/1.0/"
+license_info = get_license_info(license_url=license_url)
+
+IMAGE_RELATED_RESOURCES = {
+ "users": {}, # authors
+ "photo-categories": {},
+ "photo-colors": {},
+ "photo-orientations": {},
+ "photo-tags": {},
+}
+
+
+def main():
+ """
+ This script pulls the data from the WordPress Photo Directory and writes it into a
+ .TSV file to be eventually read into our DB.
+ """
+
+ logger.info("Begin: WordPress Photo Directory script")
+ _prefetch_image_related_data()
+ image_count = _get_images()
+ image_store.commit()
+ logger.info(f"Total images pulled: {image_count}")
+ logger.info("Terminated!")
+
+
+def _prefetch_image_related_data():
+ for resource in IMAGE_RELATED_RESOURCES.keys():
+ collection = _get_resources(resource)
+ IMAGE_RELATED_RESOURCES[resource] = collection
+ logger.info("Prefetch of image-related data completed.")
+
+
+def _get_resources(resource_type):
+ total_pages = page = 1
+ endpoint = f"{ENDPOINT}/{resource_type}"
+ collection = {}
+ while total_pages >= page:
+ query_params = _get_query_params(page=page)
+ batch_data, total_pages = _get_item_page(endpoint, query_params=query_params)
+ if isinstance(batch_data, list) and len(batch_data) > 0:
+ collection_page = _process_resource_batch(resource_type, batch_data)
+ collection = collection | collection_page
+ page += 1
+ return collection
+
+
+def _process_resource_batch(resource_type, batch_data):
+ collected_page = {}
+ for item in batch_data:
+ item_id, name, url = None, None, None
+ try:
+ item_id = item["id"]
+ name = item["name"]
+ if resource_type == "users":
+ # 'url' is the website of the author and 'link' would be their wp.org
+ # profile, so at least the last must always be present
+ url = item["url"] or item["link"]
+ except Exception as e:
+ logger.error(f"Couldn't save resource({resource_type}) info due to {e}")
+ continue
+ if resource_type == "users":
+ collected_page[item_id] = {"name": name, "url": url}
+ else:
+ collected_page[item_id] = name
+ return collected_page
+
+
+def _get_query_params(page=1, default_query_params=None):
+ if default_query_params is None:
+ default_query_params = DEFAULT_QUERY_PARAMS
+ query_params = default_query_params.copy()
+ query_params["page"] = page
+ return query_params
+
+
+def _get_item_page(endpoint, retries=RETRIES, query_params=None):
+ response_json, total_pages = None, None
+ if retries < 0:
+ logger.error("No retries remaining. Returning Nonetypes.")
+ return None, 0
+
+ response = delayed_requester.get(endpoint, query_params, allow_redirects=False)
+
+ if response is not None and response.status_code in [200, 301, 302]:
+ try:
+ response_json = response.json()
+ total_pages = int(response.headers["X-WP-TotalPages"])
+ except Exception as e:
+ logger.warning(f"Response not captured due to {e}")
+ response_json = None
+
+ if response_json is None or total_pages is None:
+ logger.warning(
+ "Retrying:\n_get_item_page(\n"
+ f" {endpoint},\n"
+ f" {query_params},\n"
+ f" retries={retries - 1}"
+ ")"
+ )
+ response_json, total_pages = _get_item_page(endpoint, retries - 1, query_params)
+ return response_json, total_pages
+
+
+def _get_images():
+ item_count = 0
+ total_pages = page = 1
+ endpoint = f"{ENDPOINT}/photos"
+ while total_pages >= page:
+ query_params = _get_query_params(page=page)
+ batch_data, total_pages = _get_item_page(endpoint, query_params=query_params)
+ if isinstance(batch_data, list) and len(batch_data) > 0:
+ item_count = _process_image_batch(batch_data)
+ page += 1
+ return item_count
+
+
+def _process_image_batch(image_batch):
+ for item in image_batch:
+ item_meta_data = _extract_image_data(item)
+ if item_meta_data is None:
+ continue
+ image_store.add_item(**item_meta_data)
+ return image_store.total_items
+
+
+def _get_image_details(media_data):
+ try:
+ url = media_data.get("_links").get("wp:featuredmedia")[0].get("href")
+ response_json = _get_response_json(url, RETRIES, allow_redirects=False)
+ return response_json
+ except (KeyError, AttributeError):
+ return None
+
+
+def _get_response_json(endpoint, retries=0, query_params=None, **kwargs):
+ """
+ Function copied from common.requester.DelayedRequester class to allow responses
+ with status code 301 or 302. It's expected it can be removed once the API is
+ fully ready. This API currently returns a `302` with a JSON body.
+ """
+ response_json = None
+
+ if retries < 0:
+ logger.error("No retries remaining. Failure.")
+ raise Exception("Retries exceeded")
+
+ response = delayed_requester.get(endpoint, params=query_params, **kwargs)
+ if response is not None and response.status_code in [200, 301, 302]:
+ try:
+ response_json = response.json()
+ except Exception as e:
+ logger.warning(f"Could not get response_json.\n{e}")
+ response_json = None
+
+ if response_json is None or response_json.get("error") is not None:
+ logger.warning(f"Bad response_json: {response_json}")
+ logger.warning(
+ "Retrying:\n_get_response_json(\n"
+ f" {endpoint},\n"
+ f" {query_params},\n"
+ f" retries={retries - 1}"
+ ")"
+ )
+ response_json = _get_response_json(
+ endpoint, retries=retries - 1, query_params=query_params, **kwargs
+ )
+
+ return response_json
+
+
+def _extract_image_data(media_data):
+ """
+ Extract data for individual item.
+ """
+ try:
+ foreign_identifier = media_data["slug"]
+ foreign_landing_url = media_data["link"]
+ except (TypeError, KeyError, AttributeError):
+ return None
+ title = _get_title(media_data)
+ image_details = _get_image_details(media_data)
+ if image_details is None:
+ return None
+ image_url, height, width, filetype = _get_file_info(image_details)
+ if image_url is None:
+ return None
+ thumbnail = _get_thumbnail_url(image_details)
+ metadata = _get_metadata(media_data, image_details)
+ creator, creator_url = _get_creator_data(media_data)
+ tags = _get_related_data("tags", media_data)
+
+ return {
+ "title": title,
+ "creator": creator,
+ "creator_url": creator_url,
+ "foreign_identifier": foreign_identifier,
+ "foreign_landing_url": foreign_landing_url,
+ "image_url": image_url,
+ "height": height,
+ "width": width,
+ "thumbnail_url": thumbnail,
+ "filetype": filetype,
+ "license_info": license_info,
+ "meta_data": metadata,
+ "raw_tags": tags,
+ }
+
+
+def _get_file_info(image_details):
+ file_details = (
+ image_details.get("media_details", {}).get("sizes", {}).get("full", {})
+ )
+ image_url = file_details.get("source_url")
+ height = file_details.get("height")
+ width = file_details.get("width")
+ filetype = None
+ if filename := file_details.get("file"):
+ filetype = Path(filename).suffix.replace(".", "")
+ return image_url, height, width, filetype
+
+
+def _get_thumbnail_url(image_details):
+ return (
+ image_details.get("media_details", {})
+ .get("sizes", {})
+ .get("thumbnail", {})
+ .get("source_url")
+ )
+
+
+def _get_creator_data(image):
+ creator, creator_url = None, None
+ if author_id := image.get("author"):
+ creator = IMAGE_RELATED_RESOURCES.get("users").get(author_id, {}).get("name")
+ creator_url = IMAGE_RELATED_RESOURCES.get("users").get(author_id, {}).get("url")
+ return creator, creator_url
+
+
+def _get_title(image):
+ if title := image.get("content", {}).get("rendered"):
+ title = html.fromstring(title).text_content()
+ return title
+
+
+def _get_metadata(image, image_details):
+ raw_metadata = image_details.get("media_details", {}).get("image_meta", {})
+ metadata = {}
+ extras = [
+ "aperture",
+ "camera",
+ "created_timestamp",
+ "focal_length",
+ "iso",
+ "shutter_speed",
+ ]
+ for key in extras:
+ value = raw_metadata.get(key)
+ if value not in [None, ""]:
+ metadata[key] = value
+
+ if published_date := image_details.get("date"):
+ metadata["published_date"] = published_date
+
+ # these fields require looking up additional queried data
+ resource_extras = ["categories", "colors", "orientations"]
+ for resource in resource_extras:
+ metadata[resource] = sorted(_get_related_data(resource, image))
+ return metadata
+
+
+def _get_related_data(resource_type, image):
+ resource_type = f"photo-{resource_type}"
+ ids = image.get(resource_type)
+ resource_names = set()
+ resources_ids = IMAGE_RELATED_RESOURCES[resource_type].keys()
+ for rid in ids:
+ if rid in resources_ids:
+ resource_names.add(IMAGE_RELATED_RESOURCES[resource_type][rid])
+ return list(resource_names)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/openverse_catalog/dags/util/loader/provider_details.py b/openverse_catalog/dags/util/loader/provider_details.py
index e8beced3a..b0581d63d 100644
--- a/openverse_catalog/dags/util/loader/provider_details.py
+++ b/openverse_catalog/dags/util/loader/provider_details.py
@@ -26,6 +26,7 @@ WALTERS_DEFAULT_PROVIDER = "waltersartmuseum"
FINNISH_DEFAULT_PROVIDER = "finnishmuseums"
JAMENDO_DEFAULT_PROVIDER = "jamendo"
STOCKSNAP_DEFAULT_PROVIDER = "stocksnap"
+WORDPRESS_DEFAULT_PROVIDER = "wordpress"
HEALTHCHECK_DEFAULT_PROVIDER = "healthcheck"
# Finnish parameters
diff --git a/openverse_catalog/dags/wordpress_workflow.py b/openverse_catalog/dags/wordpress_workflow.py
new file mode 100644
index 000000000..80ea8e425
--- /dev/null
+++ b/openverse_catalog/dags/wordpress_workflow.py
@@ -0,0 +1,25 @@
+"""
+This file configures the Apache Airflow DAG to (re)ingest WordPress data.
+"""
+import logging
+from datetime import datetime
+
+from provider_api_scripts import wordpress
+from util.dag_factory import create_provider_api_workflow
+
+
+logging.basicConfig(
+ format="%(asctime)s: [%(levelname)s - DAG Loader] %(message)s", level=logging.DEBUG
+)
+logger = logging.getLogger(__name__)
+
+DAG_ID = "wordpress_workflow"
+
+globals()[DAG_ID] = create_provider_api_workflow(
+ DAG_ID,
+ wordpress.main,
+ start_date=datetime(1970, 1, 1),
+ concurrency=1,
+ schedule_string="@monthly",
+ dated=False,
+)
diff --git a/tests/dags/provider_api_scripts/resources/wordpress/full_item.json b/tests/dags/provider_api_scripts/resources/wordpress/full_item.json
new file mode 100644
index 000000000..4dacfacf9
--- /dev/null
+++ b/tests/dags/provider_api_scripts/resources/wordpress/full_item.json
@@ -0,0 +1,116 @@
+{
+ "_links": {
+ "about": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/types/photo"
+ }
+ ],
+ "author": [
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/users/3606"
+ }
+ ],
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos"
+ }
+ ],
+ "curies": [
+ {
+ "href": "https://api.w.org/{rel}",
+ "name": "wp",
+ "templated": true
+ }
+ ],
+ "predecessor-version": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos/43/revisions/45",
+ "id": 45
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos/43"
+ }
+ ],
+ "version-history": [
+ {
+ "count": 1,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos/43/revisions"
+ }
+ ],
+ "wp:attachment": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/media?parent=43"
+ }
+ ],
+ "wp:featuredmedia": [
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/media/44"
+ }
+ ],
+ "wp:term": [
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-categories?post=43",
+ "taxonomy": "photo_category"
+ },
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-colors?post=43",
+ "taxonomy": "photo_color"
+ },
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations?post=43",
+ "taxonomy": "photo_orientation"
+ },
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-tags?post=43",
+ "taxonomy": "photo_tag"
+ }
+ ]
+ },
+ "author": 3606,
+ "content": {
+ "protected": false,
+ "rendered": "<p>Lupinus polyphyllus (aka Washington lupine)</p>\n"
+ },
+ "date": "2021-06-08T07:37:45",
+ "date_gmt": "2021-06-08T07:37:45",
+ "featured_media": 44,
+ "guid": {
+ "rendered": "https://wordpress.org/photos/?post_type=photo&#038;p=43"
+ },
+ "id": 43,
+ "link": "https://wordpress.org/photos/photo/56560bf1d6/",
+ "meta": {
+ "spay_email": ""
+ },
+ "modified": "2021-06-08T07:37:45",
+ "modified_gmt": "2021-06-08T07:37:45",
+ "photo-categories": [
+ 8
+ ],
+ "photo-colors": [
+ 15,
+ 36
+ ],
+ "photo-orientations": [
+ 24
+ ],
+ "photo-tags": [
+ 35,
+ 28
+ ],
+ "slug": "56560bf1d6",
+ "status": "publish",
+ "template": "",
+ "title": {
+ "rendered": "56560bf1d6"
+ },
+ "type": "photo"
+}
diff --git a/tests/dags/provider_api_scripts/resources/wordpress/full_item_details.json b/tests/dags/provider_api_scripts/resources/wordpress/full_item_details.json
new file mode 100644
index 000000000..ecf9c104c
--- /dev/null
+++ b/tests/dags/provider_api_scripts/resources/wordpress/full_item_details.json
@@ -0,0 +1,137 @@
+{
+ "_links": {
+ "about": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/types/attachment"
+ }
+ ],
+ "author": [
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/users/3606"
+ }
+ ],
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/media"
+ }
+ ],
+ "replies": [
+ {
+ "embeddable": true,
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/comments?post=44"
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/media/44"
+ }
+ ]
+ },
+ "alt_text": "",
+ "author": 3606,
+ "caption": {
+ "rendered": "<p>Lupinus polyphyllus (aka Washington lupine)</p>\n"
+ },
+ "comment_status": "open",
+ "date": "2021-06-08T07:34:17",
+ "date_gmt": "2021-06-08T07:34:17",
+ "description": {
+ "rendered": "<p class=\"attachment\"><a href='https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg'><img width=\"225\" height=\"300\" src=\"https://pd.w.org/2021/06/56560bf1d69971f38.94814132-225x300.jpg\" class=\"attachment-medium size-medium\" alt=\"\" loading=\"lazy\" srcset=\"https://storage.googleapis.com/pd.w.org/2021/06/56560bf1d69971f38.94814132-225x300.jpg 225w, https://storage.googleapis.com/pd.w.org/2021/06/56560bf1d69971f38.94814132-768x1024.jpg 768w, https://storage.googleapis.com/pd.w.org/2021/06/56560bf1d69971f38.94814132-1152x1536.jpg 1152w, https://storage.googleapis.com/pd.w.org/2021/06/56560bf1d69971f38.94814132-1536x2048.jpg 1536w\" sizes=\"(max-width: 225px) 100vw, 225px\" /></a></p>\n<p>Lupinus polyphyllus (aka Washington lupine)</p>\n"
+ },
+ "guid": {
+ "rendered": "https://storage.googleapis.com/pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg"
+ },
+ "id": 44,
+ "link": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg",
+ "media_details": {
+ "file": "2021/06/56560bf1d69971f38.94814132.jpg",
+ "gcs_bucket": "pd.w.org",
+ "gcs_name": "2021/06/56560bf1d69971f38.94814132.jpg",
+ "gcs_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg",
+ "height": 4032,
+ "image_meta": {
+ "aperture": "1.8",
+ "camera": "Pixel 2 XL",
+ "caption": "",
+ "copyright": "",
+ "created_timestamp": "1591460495",
+ "credit": "Scott Reilly",
+ "focal_length": "4.459",
+ "iso": "45",
+ "keywords": [],
+ "orientation": "1",
+ "shutter_speed": "0.00171",
+ "title": ""
+ },
+ "sizes": {
+ "1536x1536": {
+ "file": "56560bf1d69971f38.94814132-1152x1536.jpg",
+ "height": 1536,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-1152x1536.jpg",
+ "width": 1152
+ },
+ "2048x2048": {
+ "file": "56560bf1d69971f38.94814132-1536x2048.jpg",
+ "height": 2048,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-1536x2048.jpg",
+ "width": 1536
+ },
+ "full": {
+ "file": "56560bf1d69971f38.94814132.jpg",
+ "height": 4032,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg",
+ "width": 3024
+ },
+ "large": {
+ "file": "56560bf1d69971f38.94814132-768x1024.jpg",
+ "height": 1024,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-768x1024.jpg",
+ "width": 768
+ },
+ "medium": {
+ "file": "56560bf1d69971f38.94814132-225x300.jpg",
+ "height": 300,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-225x300.jpg",
+ "width": 225
+ },
+ "medium_large": {
+ "file": "56560bf1d69971f38.94814132-768x1024.jpg",
+ "height": 1024,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-768x1024.jpg",
+ "width": 768
+ },
+ "thumbnail": {
+ "file": "56560bf1d69971f38.94814132-150x150.jpg",
+ "height": 150,
+ "mime_type": "image/jpeg",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132-150x150.jpg",
+ "width": 150
+ }
+ },
+ "width": 3024
+ },
+ "media_type": "image",
+ "meta": {
+ "spay_email": ""
+ },
+ "mime_type": "image/jpeg",
+ "modified": "2021-09-23T21:56:53",
+ "modified_gmt": "2021-09-23T21:56:53",
+ "ping_status": "closed",
+ "post": 43,
+ "slug": "washington-lupine",
+ "source_url": "https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg",
+ "status": "inherit",
+ "template": "",
+ "title": {
+ "rendered": "washington-lupine"
+ },
+ "type": "attachment"
+}
diff --git a/tests/dags/provider_api_scripts/resources/wordpress/orientations_batch.json b/tests/dags/provider_api_scripts/resources/wordpress/orientations_batch.json
new file mode 100644
index 000000000..5cf4efdb3
--- /dev/null
+++ b/tests/dags/provider_api_scripts/resources/wordpress/orientations_batch.json
@@ -0,0 +1,119 @@
+[
+ {
+ "_links": {
+ "about": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/taxonomies/photo_orientation"
+ }
+ ],
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations"
+ }
+ ],
+ "curies": [
+ {
+ "href": "https://api.w.org/{rel}",
+ "name": "wp",
+ "templated": true
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations/23"
+ }
+ ],
+ "wp:post_type": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos?photo-orientations=23"
+ }
+ ]
+ },
+ "count": 1,
+ "description": "",
+ "id": 23,
+ "link": "https://wordpress.org/photos/orientation/landscape/",
+ "meta": [],
+ "name": "landscape",
+ "slug": "landscape",
+ "taxonomy": "photo_orientation"
+ },
+ {
+ "_links": {
+ "about": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/taxonomies/photo_orientation"
+ }
+ ],
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations"
+ }
+ ],
+ "curies": [
+ {
+ "href": "https://api.w.org/{rel}",
+ "name": "wp",
+ "templated": true
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations/24"
+ }
+ ],
+ "wp:post_type": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos?photo-orientations=24"
+ }
+ ]
+ },
+ "count": 1,
+ "description": "",
+ "id": 24,
+ "link": "https://wordpress.org/photos/orientation/portrait/",
+ "meta": [],
+ "name": "portrait",
+ "slug": "portrait",
+ "taxonomy": "photo_orientation"
+ },
+ {
+ "_links": {
+ "about": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/taxonomies/photo_orientation"
+ }
+ ],
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations"
+ }
+ ],
+ "curies": [
+ {
+ "href": "https://api.w.org/{rel}",
+ "name": "wp",
+ "templated": true
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photo-orientations/25"
+ }
+ ],
+ "wp:post_type": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/photos?photo-orientations=25"
+ }
+ ]
+ },
+ "count": 0,
+ "description": "",
+ "id": 25,
+ "link": "https://wordpress.org/photos/orientation/square/",
+ "meta": [],
+ "name": "square",
+ "slug": "square",
+ "taxonomy": "photo_orientation"
+ }
+]
diff --git a/tests/dags/provider_api_scripts/resources/wordpress/users_batch.json b/tests/dags/provider_api_scripts/resources/wordpress/users_batch.json
new file mode 100644
index 000000000..6b82ce0da
--- /dev/null
+++ b/tests/dags/provider_api_scripts/resources/wordpress/users_batch.json
@@ -0,0 +1,28 @@
+[
+ {
+ "_links": {
+ "collection": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/users"
+ }
+ ],
+ "self": [
+ {
+ "href": "https://wordpress.org/photos/wp-json/wp/v2/users/3606"
+ }
+ ]
+ },
+ "avatar_urls": {
+ "24": "https://secure.gravatar.com/avatar/5af525fba95b93c4e0c8a03b639c9486?s=24&d=mm&r=g",
+ "48": "https://secure.gravatar.com/avatar/5af525fba95b93c4e0c8a03b639c9486?s=48&d=mm&r=g",
+ "96": "https://secure.gravatar.com/avatar/5af525fba95b93c4e0c8a03b639c9486?s=96&d=mm&r=g"
+ },
+ "description": "",
+ "id": 3606,
+ "link": "https://profiles.wordpress.org/coffee2code/",
+ "meta": [],
+ "name": "Scott Reilly",
+ "slug": "coffee2code",
+ "url": "http://coffee2code.com"
+ }
+]
diff --git a/tests/dags/provider_api_scripts/test_wordpress.py b/tests/dags/provider_api_scripts/test_wordpress.py
new file mode 100644
index 000000000..a27304b88
--- /dev/null
+++ b/tests/dags/provider_api_scripts/test_wordpress.py
@@ -0,0 +1,185 @@
+import json
+import logging
+from pathlib import Path
+from unittest.mock import patch
+
+import requests
+import wordpress as wp
+
+
+RESOURCES = Path(__file__).parent / "resources/wordpress"
+SAMPLE_MEDIA_DATA = RESOURCES / "full_item.json"
+SAMPLE_MEDIA_DETAILS = RESOURCES / "full_item_details.json"
+
+logging.basicConfig(
+ format="%(asctime)s - %(name)s - %(levelname)s: %(message)s",
+ level=logging.DEBUG,
+)
+
+
+def test_get_query_params_returns_defaults():
+ expected_result = {
+ "format": "json",
+ "page": 1,
+ "per_page": 100,
+ }
+ actual_result = wp._get_query_params()
+ assert actual_result == expected_result
+
+
+def test_get_query_params_returns_defaults_with_given_page():
+ expected_result = {
+ "format": "json",
+ "page": 3,
+ "per_page": 100,
+ }
+ actual_result = wp._get_query_params(page=3)
+ assert actual_result == expected_result
+
+
+def test_get_item_page_returns_correctly_with_none_response():
+ expected_result = (None, 0)
+ endpoint = "example.com"
+ with patch.object(wp.delayed_requester, "get", return_value=None):
+ actual_result = wp._get_item_page(endpoint)
+ assert actual_result == expected_result
+
+
+def test_get_item_page_returns_correctly_with_no_results():
+ expected_result = (None, 0)
+ endpoint = "example.com"
+ with patch.object(wp.delayed_requester, "get", return_value=requests.Response()):
+ actual_result = wp._get_item_page(endpoint)
+ assert actual_result == expected_result
+
+
+def test_process_resource_batch_with_non_users_resources():
+ # Apply for photo categories, colors and tags too
+ with open(RESOURCES / "orientations_batch.json") as f:
+ batch_data = json.load(f)
+ actual_result = wp._process_resource_batch("photo-orientations", batch_data)
+ expected_result = {23: "landscape", 24: "portrait", 25: "square"}
+ assert actual_result == expected_result
+
+
+def test_process_resource_batch_with_users():
+ with open(RESOURCES / "users_batch.json") as f:
+ batch_data = json.load(f)
+ actual_result = wp._process_resource_batch("users", batch_data)
+ expected_result = {3606: {"name": "Scott Reilly", "url": "http://coffee2code.com"}}
+ assert actual_result == expected_result
+
+
+def test_extract_image_data_returns_none_when_media_data_none():
+ actual_image_info = wp._extract_image_data(None)
+ expected_image_info = None
+ assert actual_image_info is expected_image_info
+
+
+def test_extract_image_data_returns_none_when_no_foreign_id():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ image_data.pop("slug", None)
+ actual_image_info = wp._extract_image_data(image_data)
+ expected_image_info = None
+ assert actual_image_info is expected_image_info
+
+
+def test_extract_image_data_returns_none_when_no_image_details():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ image_data.pop("_links", None)
+ actual_image_info = wp._extract_image_data(image_data)
+ assert actual_image_info is None
+
+
+def test_get_title():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ actual_result = wp._get_title(image_data)
+ expected_result = "Lupinus polyphyllus (aka Washington lupine)"
+ assert actual_result == expected_result
+
+
+def test_get_file_info():
+ with open(SAMPLE_MEDIA_DETAILS) as f:
+ image_details = json.load(f)
+ actual_result = wp._get_file_info(image_details)
+ expected_result = (
+ "https://pd.w.org/2021/06/56560bf1d69971f38.94814132.jpg", # image_url
+ 4032, # height
+ 3024, # width
+ "jpg", # filetype
+ )
+ assert actual_result == expected_result
+
+
+def test_get_creator_data():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ image_related_patch = {
+ "users": {
+ 3606: {"name": "Scott Reilly", "url": "http://coffee2code.com"},
+ }
+ }
+ with patch.object(wp, "IMAGE_RELATED_RESOURCES", image_related_patch):
+ actual_creator, actual_creator_url = wp._get_creator_data(image_data)
+ expected_creator = "Scott Reilly"
+ expected_creator_url = "http://coffee2code.com"
+
+ assert actual_creator == expected_creator
+ assert actual_creator_url == expected_creator_url
+
+
+def test_get_creator_data_handle_no_author():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ image_data.pop("author")
+ image_related_patch = {
+ "users": {
+ 3606: {"name": "Scott Reilly", "url": "http://coffee2code.com"},
+ }
+ }
+ with patch.object(wp, "IMAGE_RELATED_RESOURCES", image_related_patch):
+ actual_creator, actual_creator_url = wp._get_creator_data(image_data)
+ assert actual_creator is None
+ assert actual_creator_url is None
+
+
+def test_get_metadata():
+ with open(SAMPLE_MEDIA_DATA) as f1, open(SAMPLE_MEDIA_DETAILS) as f2:
+ image_data = json.load(f1)
+ image_details = json.load(f2)
+ image_related_patch = {
+ "photo-colors": {15: "green", 36: "purple"},
+ "photo-orientations": {24: "portrait"},
+ "photo-categories": {8: "nature"},
+ }
+ with patch.object(wp, "IMAGE_RELATED_RESOURCES", image_related_patch):
+ actual_metadata = wp._get_metadata(image_data, image_details)
+
+ expected_metadata = {
+ "aperture": "1.8",
+ "camera": "Pixel 2 XL",
+ "created_timestamp": "1591460495",
+ "focal_length": "4.459",
+ "iso": "45",
+ "shutter_speed": "0.00171",
+ "published_date": "2021-06-08T07:34:17",
+ "categories": ["nature"],
+ "colors": ["green", "purple"],
+ "orientations": ["portrait"],
+ }
+ assert len(actual_metadata) == len(expected_metadata)
+ assert actual_metadata == expected_metadata
+
+
+def test_get_related_data_with_tags():
+ with open(SAMPLE_MEDIA_DATA) as f:
+ image_data = json.load(f)
+ prefetched_tags = {"photo-tags": {35: "flower", 28: "plant"}}
+ with patch.object(wp, "IMAGE_RELATED_RESOURCES", prefetched_tags):
+ actual_tags = wp._get_related_data("tags", image_data)
+ expected_tags = ["flower", "plant"]
+ assert len(actual_tags) == len(expected_tags)
+ assert sorted(expected_tags) == sorted(actual_tags)