Skip to content

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

Add DAG to report reported media pending review (#513)

Staci Cooper909808259c67
diff --git a/env.template b/env.template
index f50bbf02e..75717e79a 100644
--- a/env.template
+++ b/env.template
@@ -43,18 +43,23 @@ AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgr
# Remote logging connection ID
# Replace "access_key" and "secret+key" with the real values. Secret key must be URL-encoded
AIRFLOW_CONN_AWS_DEFAULT=aws://test_key:test_secret@?region_name=us-east-1&host=http://s3:5000
-# Change the following line in prod to use the appropriate DB
+
+# Catalog DB connection. Change the following line in prod to use the appropriate DB
AIRFLOW_CONN_POSTGRES_OPENLEDGER_UPSTREAM=postgres://deploy:deploy@postgres:5432/openledger
AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING=postgres://deploy:deploy@postgres:5432/openledger
+OPENLEDGER_CONN_ID=postgres_openledger_upstream
+TEST_CONN_ID=postgres_openledger_testing
+
+# API DB connection. Change the following line in prod to use the appropriate DB
+AIRFLOW_CONN_POSTGRES_OPENLEDGER_API=postgres://deploy:[email protected]:5432/openledger
+OPENLEDGER_API_CONN_ID=postgres_openledger_api
+
# Slack webhook connection info (note that these values are modified by the Docker entrypoint)
# A distinction is made here between "notifications" and "alerts", the former being
# useful updates and the latter being alarms or actionable errors.
AIRFLOW_CONN_SLACK_NOTIFICATIONS=https://slack
AIRFLOW_CONN_SLACK_ALERTS=https://slack
-OPENLEDGER_CONN_ID=postgres_openledger_upstream
-TEST_CONN_ID=postgres_openledger_testing
-
S3_LOCAL_ENDPOINT=http://s3:5000
AWS_CONN_ID=aws_default
@@ -68,6 +73,9 @@ EMR_TEST_CONN_ID=emr_test
# connect to your locally running ingestion server.
AIRFLOW_CONN_DATA_REFRESH=http://172.17.0.1:8001
+# Django Admin url. Change the following line to use the appropriate environment.
+DJANGO_ADMIN_URL="https://localhost:8000/admin"
+
########################################################################################
# Other config
diff --git a/openverse_catalog/dags/common/slack.py b/openverse_catalog/dags/common/slack.py
index c919d954e..ee9e9a18f 100644
--- a/openverse_catalog/dags/common/slack.py
+++ b/openverse_catalog/dags/common/slack.py
@@ -253,6 +253,21 @@ def should_send_message(http_conn_id=SLACK_NOTIFICATIONS_CONN_ID):
return environment == "prod" or force_message
+def send_alert(
+ text: str,
+ username: str = "Airflow Alert",
+ icon_emoji: str = ":airflow:",
+ markdown: bool = True,
+):
+ """
+ Wrapper for send_message that allows sending a message to the configured alerts
+ channel instead of the default notification channel.
+ """
+ send_message(
+ text, username, icon_emoji, markdown, http_conn_id=SLACK_ALERTS_CONN_ID
+ )
+
+
def on_failure_callback(context: dict) -> None:
"""
Send an alert out regarding a failure to Slack.
diff --git a/openverse_catalog/dags/database/report_pending_reported_media.py b/openverse_catalog/dags/database/report_pending_reported_media.py
new file mode 100644
index 000000000..089254026
--- /dev/null
+++ b/openverse_catalog/dags/database/report_pending_reported_media.py
@@ -0,0 +1,168 @@
+"""
+# Report Pending Reported Media DAG
+This DAG checks for any user-reported media pending manual review, and alerts
+via Slack.
+
+Media may be reported for mature content or copyright infringement, for
+example. Once reported, these require manual review through the Django Admin to
+determine whether further action (such as deindexing the record) needs to be
+taken. If a record has been reported multiple times, it only needs to be
+reviewed once and so is only counted once in the reporting by this DAG.
+"""
+import logging
+import os
+from textwrap import dedent
+from urllib.parse import urljoin
+
+from airflow import DAG
+from airflow.exceptions import AirflowException
+from airflow.models import TaskInstance
+from airflow.operators.python import PythonOperator
+from airflow.providers.postgres.hooks.postgres import PostgresHook
+from common import slack
+from common.constants import DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMPLATE
+
+
+logger = logging.getLogger(__name__)
+
+DAG_ID = "report_pending_reported_media"
+DB_CONN_ID = os.getenv("OPENLEDGER_API_CONN_ID", "postgres_openledger_api")
+ADMIN_URL = os.getenv("DJANGO_ADMIN_URL", "http://localhost:8000/admin")
+
+REPORTS_TABLES = {
+ "image": "nsfw_reports",
+ "audio": "nsfw_reports_audio",
+}
+
+# Column name constants
+URL = "identifier"
+STATUS = "status"
+REASON = "reason"
+
+ReportCountsByReason = dict[str, int]
+MediaTypeReportCounts = dict[str, ReportCountsByReason]
+
+
+def get_pending_report_counts(
+ db_conn_id: str, media_type: str, ti: TaskInstance
+) -> ReportCountsByReason:
+ """
+ For the given media type, builds a dict of pending report counts grouped by
+ report reason.
+
+ Required Arguments:
+
+ db_conn_id: Connection ID for the API database
+ media_type: Media type for which to look up reports
+ ti: Running task instance
+ """
+ postgres = PostgresHook(postgres_conn_id=db_conn_id)
+ report_counts_by_reason = {}
+
+ if media_type not in REPORTS_TABLES:
+ raise AirflowException(f"{media_type} has no Reports table configured.")
+
+ query = dedent(
+ f"""
+ SELECT
+ COUNT(DISTINCT {URL}), {REASON}
+ FROM {REPORTS_TABLES[media_type]}
+ WHERE {STATUS}='pending_review'
+ GROUP BY {REASON}
+ """
+ )
+ for count, reason in postgres.get_records(query):
+ report_counts_by_reason[reason] = count
+
+ logger.info(f"{report_counts_by_reason} records require manual review")
+
+ return report_counts_by_reason
+
+
+def report_actionable_records(
+ report_counts_by_media_type: MediaTypeReportCounts,
+) -> None:
+ """
+ Build a report detailing pending reports for all media types, and alert to Slack.
+
+ Required Arguments:
+
+ report_counts_by_media_type: dict containing report counts per media type, per
+ report reason
+ """
+ if all(len(reports) == 0 for reports in report_counts_by_media_type.values()):
+ slack.send_message(
+ "No records require review at this time :tada:",
+ username="Reported Media Check-In",
+ )
+ return
+
+ media_type_reports = ""
+ for media_type, distinct_report_counts in report_counts_by_media_type.items():
+ if not distinct_report_counts:
+ continue
+
+ admin_review_link = urljoin(
+ ADMIN_URL, f"api/{media_type}report/?status__exact=pending_review"
+ )
+ total_report_count = 0
+ counts_by_reason = []
+
+ for reason, count in distinct_report_counts.items():
+ total_report_count += count
+ counts_by_reason.append(f"{count} {reason}")
+
+ media_type_reports += (
+ f" - *<{admin_review_link}|{media_type}: {total_report_count}>*"
+ )
+ media_type_reports += f" _({', '.join(counts_by_reason)})_"
+ media_type_reports += "\n"
+
+ message = f"""
+The following media have been reported and require manual review:
+{media_type_reports}
+"""
+
+ logger.info(message)
+ slack.send_alert(message, username="Reported Media Requires Review")
+
+
+def create_dag():
+ dag = DAG(
+ dag_id=DAG_ID,
+ default_args=DAG_DEFAULT_ARGS,
+ schedule_interval="@weekly",
+ catchup=False,
+ tags=["database"],
+ doc_md=__doc__,
+ render_template_as_native_obj=True,
+ )
+
+ with dag:
+ get_reports_tasks = []
+ report_counts_by_media_type = {}
+
+ for media_type in MEDIA_TYPES:
+ get_reports = PythonOperator(
+ task_id=f"get_pending_{media_type}_reports",
+ python_callable=get_pending_report_counts,
+ op_kwargs={"db_conn_id": DB_CONN_ID, "media_type": media_type},
+ )
+
+ report_counts_by_media_type[media_type] = XCOM_PULL_TEMPLATE.format(
+ get_reports.task_id, "return_value"
+ )
+ get_reports_tasks.append(get_reports)
+
+ report_pending_reports = PythonOperator(
+ task_id="report_pending_media_reports",
+ python_callable=report_actionable_records,
+ op_kwargs={"report_counts_by_media_type": report_counts_by_media_type},
+ )
+
+ get_reports_tasks >> report_pending_reports
+
+ return dag
+
+
+globals()[DAG_ID] = create_dag()
diff --git a/tests/dags/common/test_slack.py b/tests/dags/common/test_slack.py
index c11311a24..62882ef81 100644
--- a/tests/dags/common/test_slack.py
+++ b/tests/dags/common/test_slack.py
@@ -4,8 +4,10 @@ from unittest import mock
import pytest
from airflow.exceptions import AirflowNotFoundException
from common.slack import (
+ SLACK_ALERTS_CONN_ID,
SlackMessage,
on_failure_callback,
+ send_alert,
send_message,
should_send_message,
)
@@ -328,6 +330,18 @@ def test_send_message_does_not_send_if_checks_fail(http_hook_mock):
http_hook_mock.run.assert_not_called()
+def test_send_alert():
+ with mock.patch("common.slack.send_message") as send_message_mock:
+ send_alert("Sample text", username="DifferentUser")
+ send_message_mock.assert_called_with(
+ "Sample text",
+ "DifferentUser",
+ ":airflow:",
+ True,
+ http_conn_id=SLACK_ALERTS_CONN_ID,
+ )
+
+
@pytest.mark.parametrize(
"exception, environment, slack_message_override, call_expected",
[
diff --git a/tests/dags/database/__init__.py b/tests/dags/database/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/dags/database/test_report_pending_reported_media.py b/tests/dags/database/test_report_pending_reported_media.py
new file mode 100644
index 000000000..55941efbc
--- /dev/null
+++ b/tests/dags/database/test_report_pending_reported_media.py
@@ -0,0 +1,60 @@
+from unittest import mock
+
+import pytest
+from database.report_pending_reported_media import report_actionable_records
+
+
+def _make_reported_records_data(media_type: str):
+ return [
+ (
+ {"dmca": 1, "mature": 2, "other": 3},
+ [
+ f"{media_type}: 6",
+ "_(1 dmca, 2 mature, 3 other)_",
+ ],
+ ),
+ (
+ {"dmca": 1, "mature": 2},
+ [
+ f"{media_type}: 3",
+ "_(1 dmca, 2 mature)_",
+ ],
+ ),
+ (
+ {"other": 7},
+ [
+ f"{media_type}: 7",
+ "_(7 other)_",
+ ],
+ ),
+ ]
+
+
+ "audio_counts, audio_expected_messages", _make_reported_records_data("audio")
+)
+ "image_counts, image_expected_messages", _make_reported_records_data("image")
+)
+def test_report_actionable_records(
+ audio_counts, audio_expected_messages, image_counts, image_expected_messages
+):
+ with mock.patch("common.slack.send_alert") as send_alert_mock:
+ report_counts_by_media_type = {"audio": audio_counts, "image": image_counts}
+ report_actionable_records(report_counts_by_media_type)
+
+ for message in audio_expected_messages + image_expected_messages:
+ assert (
+ message in send_alert_mock.call_args.args[0]
+ ), "Completion message doesn't contain expected text"
+
+
+def test_report_actionable_records_no_data_message():
+ with mock.patch("common.slack.send_message") as send_message_mock:
+ report_counts_by_media_type = {"audio": {}, "image": {}}
+ report_actionable_records(report_counts_by_media_type)
+
+ assert (
+ "No records require review at this time"
+ in send_message_mock.call_args.args[0]
+ )