From 8871e4794a1a81d76e3eb2bb82b252b5162d2717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Mon, 10 Aug 2026 13:10:13 +0200 Subject: [PATCH] feat: stream originals with download accounting --- drizzle/0003_stream_delivery.sql | 1 + drizzle/meta/0003_snapshot.json | 1524 +++++++++++++++++ drizzle/meta/_journal.json | 7 + .../api/download-intents/intent-handler.ts | 124 ++ src/app/api/download-intents/route.test.ts | 140 ++ src/app/api/download-intents/route.ts | 3 + .../[downloadId]/file/download-handler.ts | 162 ++ .../downloads/[downloadId]/file/route.test.ts | 228 +++ .../api/downloads/[downloadId]/file/route.ts | 3 + src/app/globals.css | 305 ++++ src/app/redaktion/alben/[albumId]/page.tsx | 8 +- src/app/redaktion/nutzungen/page.test.tsx | 84 + src/app/redaktion/nutzungen/page.tsx | 40 + .../nutzungen/usage-history-content.tsx | 120 ++ src/components/download/usage-dialog.test.tsx | 137 ++ src/components/download/usage-dialog.tsx | 224 +++ src/components/layout/portal-shell.tsx | 1 + src/db/schema/usages.ts | 2 +- src/modules/albums/catalog-content.test.tsx | 46 +- src/modules/albums/catalog-content.tsx | 13 + src/modules/downloads/service.ts | 3 +- src/modules/downloads/stream.test.ts | 223 +++ src/modules/downloads/stream.ts | 510 ++++++ src/modules/usages/service.ts | 3 +- src/modules/usages/types.ts | 2 +- .../download-delivery-migration-sql.test.ts | 14 + tests/db/download-delivery.test.ts | 152 ++ tests/db/postgres.ts | 10 +- 28 files changed, 4081 insertions(+), 8 deletions(-) create mode 100644 drizzle/0003_stream_delivery.sql create mode 100644 drizzle/meta/0003_snapshot.json create mode 100644 src/app/api/download-intents/intent-handler.ts create mode 100644 src/app/api/download-intents/route.test.ts create mode 100644 src/app/api/download-intents/route.ts create mode 100644 src/app/api/downloads/[downloadId]/file/download-handler.ts create mode 100644 src/app/api/downloads/[downloadId]/file/route.test.ts create mode 100644 src/app/api/downloads/[downloadId]/file/route.ts create mode 100644 src/app/redaktion/nutzungen/page.test.tsx create mode 100644 src/app/redaktion/nutzungen/page.tsx create mode 100644 src/app/redaktion/nutzungen/usage-history-content.tsx create mode 100644 src/components/download/usage-dialog.test.tsx create mode 100644 src/components/download/usage-dialog.tsx create mode 100644 src/modules/downloads/stream.test.ts create mode 100644 src/modules/downloads/stream.ts create mode 100644 tests/db/download-delivery-migration-sql.test.ts create mode 100644 tests/db/download-delivery.test.ts diff --git a/drizzle/0003_stream_delivery.sql b/drizzle/0003_stream_delivery.sql new file mode 100644 index 0000000..358dae5 --- /dev/null +++ b/drizzle/0003_stream_delivery.sql @@ -0,0 +1 @@ +ALTER TYPE "public"."usage_billing_status" ADD VALUE 'voided'; \ No newline at end of file diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..af23c8e --- /dev/null +++ b/drizzle/meta/0003_snapshot.json @@ -0,0 +1,1524 @@ +{ + "id": "090a698a-550f-4283-8632-f9c3d22d236d", + "prevId": "8944c4e7-b3ab-47b5-a05b-91be6fb5c915", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album_grants": { + "name": "album_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_album_id": { + "name": "immich_album_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "granted_by_user_id": { + "name": "granted_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_grants_editorial_account_id_idx": { + "name": "album_grants_editorial_account_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_immich_album_id_idx": { + "name": "album_grants_immich_album_id_idx", + "columns": [ + { + "expression": "immich_album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_editorial_active_album_unique": { + "name": "album_grants_editorial_active_album_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"immich_album_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"album_grants\".\"revoked_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_grants_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_grants_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_grants", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_grants_granted_by_user_id_user_id_fk": { + "name": "album_grants_granted_by_user_id_user_id_fk", + "tableFrom": "album_grants", + "tableTo": "user", + "columnsFrom": [ + "granted_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "album_grants_immich_album_id_uuid_check": { + "name": "album_grants_immich_album_id_uuid_check", + "value": "\"album_grants\".\"immich_album_id\" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + }, + "public.audit_events": { + "name": "audit_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "previous_values": { + "name": "previous_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "new_values": { + "name": "new_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "audit_events_actor_user_id_user_id_fk": { + "name": "audit_events_actor_user_id_user_id_fk", + "tableFrom": "audit_events", + "tableTo": "user", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "portal_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'EDITORIAL'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_report_items": { + "name": "billing_report_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id_snapshot": { + "name": "immich_asset_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose_snapshot": { + "name": "purpose_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference_snapshot": { + "name": "internal_reference_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "billing_report_items_report_usage_unique": { + "name": "billing_report_items_report_usage_unique", + "columns": [ + { + "expression": "billing_report_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_report_items_billing_report_id_billing_reports_id_fk": { + "name": "billing_report_items_billing_report_id_billing_reports_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_report_items_usage_id_usages_id_fk": { + "name": "billing_report_items_usage_id_usages_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_reports": { + "name": "billing_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "report_number": { + "name": "report_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "period_starts_at": { + "name": "period_starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "period_ends_at": { + "name": "period_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "billing_address_snapshot": { + "name": "billing_address_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "invoice_number": { + "name": "invoice_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "net_total_cents": { + "name": "net_total_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "pdf": { + "name": "pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "pdf_sha256": { + "name": "pdf_sha256", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finalized_at": { + "name": "finalized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_reason": { + "name": "cancellation_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cancelled_by_user_id": { + "name": "cancelled_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "billing_reports_report_number_unique": { + "name": "billing_reports_report_number_unique", + "columns": [ + { + "expression": "report_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "billing_reports_invoice_number_unique": { + "name": "billing_reports_invoice_number_unique", + "columns": [ + { + "expression": "invoice_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_reports_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_reports_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_reports", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_created_by_user_id_user_id_fk": { + "name": "billing_reports_created_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_cancelled_by_user_id_user_id_fk": { + "name": "billing_reports_cancelled_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "cancelled_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "billing_reports_pdf_sha256_hex_check": { + "name": "billing_reports_pdf_sha256_hex_check", + "value": "\"billing_reports\".\"pdf_sha256\" ~ '^[0-9a-f]{64}$'" + }, + "billing_reports_final_pdf_check": { + "name": "billing_reports_final_pdf_check", + "value": "\"billing_reports\".\"status\" <> 'final' OR (\"billing_reports\".\"pdf\" IS NOT NULL AND \"billing_reports\".\"pdf_sha256\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.billing_address_versions": { + "name": "billing_address_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_1": { + "name": "address_line_1", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_2": { + "name": "address_line_2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "postal_code": { + "name": "postal_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "city": { + "name": "city", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "country_code": { + "name": "country_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "superseded_by_id": { + "name": "superseded_by_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "billing_address_versions_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_address_versions_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_superseded_by_id_billing_address_versions_id_fk": { + "name": "billing_address_versions_superseded_by_id_billing_address_versions_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "superseded_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_created_by_user_id_user_id_fk": { + "name": "billing_address_versions_created_by_user_id_user_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.editorial_accounts": { + "name": "editorial_accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "login_email": { + "name": "login_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "account_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending_email'" + }, + "current_price_cents": { + "name": "current_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "approval_notice_status": { + "name": "approval_notice_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'not_requested'" + }, + "current_billing_address_version_id": { + "name": "current_billing_address_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_version": { + "name": "accepted_terms_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_at": { + "name": "accepted_terms_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "privacy_acknowledged_at": { + "name": "privacy_acknowledged_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "editorial_accounts_user_id_user_id_fk": { + "name": "editorial_accounts_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk": { + "name": "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "current_billing_address_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "editorial_accounts_user_id_unique": { + "name": "editorial_accounts_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + }, + "editorial_accounts_login_email_unique": { + "name": "editorial_accounts_login_email_unique", + "nullsNotDistinct": false, + "columns": [ + "login_email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.download_events": { + "name": "download_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorized_at": { + "name": "authorized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "download_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'authorized'" + }, + "transferred_bytes": { + "name": "transferred_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "repeat_download_note": { + "name": "repeat_download_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "intent_kind": { + "name": "intent_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new_usage'" + }, + "request_fingerprint": { + "name": "request_fingerprint", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "legacy_intent": { + "name": "legacy_intent", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "download_events_editorial_idempotency_key_unique": { + "name": "download_events_editorial_idempotency_key_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "download_events_editorial_account_id_editorial_accounts_id_fk": { + "name": "download_events_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "download_events", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "download_events_usage_id_usages_id_fk": { + "name": "download_events_usage_id_usages_id_fk", + "tableFrom": "download_events", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "download_events_intent_kind_check": { + "name": "download_events_intent_kind_check", + "value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')" + }, + "download_events_request_fingerprint_hex_check": { + "name": "download_events_request_fingerprint_hex_check", + "value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'" + }, + "download_events_canonical_idempotency_key_check": { + "name": "download_events_canonical_idempotency_key_check", + "value": "\"download_events\".\"legacy_intent\" OR \"download_events\".\"idempotency_key\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + }, + "download_events_canonical_immich_asset_id_check": { + "name": "download_events_canonical_immich_asset_id_check", + "value": "\"download_events\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + }, + "public.usages": { + "name": "usages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "immich_album_id_snapshot": { + "name": "immich_album_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference": { + "name": "internal_reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "billing_status": { + "name": "billing_status", + "type": "usage_billing_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "usages_editorial_account_id_editorial_accounts_id_fk": { + "name": "usages_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "usages", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "usages_billing_report_id_billing_reports_id_fk": { + "name": "usages_billing_report_id_billing_reports_id_fk", + "tableFrom": "usages", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usages_canonical_immich_asset_id_check": { + "name": "usages_canonical_immich_asset_id_check", + "value": "\"usages\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + }, + "usages_canonical_immich_album_id_check": { + "name": "usages_canonical_immich_album_id_check", + "value": "\"usages\".\"immich_album_id_snapshot\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" + } + }, + "isRLSEnabled": false + } + }, + "enums": { + "public.portal_role": { + "name": "portal_role", + "schema": "public", + "values": [ + "ADMIN", + "EDITORIAL" + ] + }, + "public.report_status": { + "name": "report_status", + "schema": "public", + "values": [ + "draft", + "final", + "cancelled" + ] + }, + "public.account_status": { + "name": "account_status", + "schema": "public", + "values": [ + "pending_email", + "pending_approval", + "active", + "suspended", + "rejected" + ] + }, + "public.download_status": { + "name": "download_status", + "schema": "public", + "values": [ + "authorized", + "streaming", + "completed", + "failed_before_delivery", + "interrupted" + ] + }, + "public.usage_billing_status": { + "name": "usage_billing_status", + "schema": "public", + "values": [ + "open", + "billed", + "reopened", + "voided" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index c9e805a..c2f8c87 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1786354215684, "tag": "0002_accounting_intents", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1786358492749, + "tag": "0003_stream_delivery", + "breakpoints": true } ] } diff --git a/src/app/api/download-intents/intent-handler.ts b/src/app/api/download-intents/intent-handler.ts new file mode 100644 index 0000000..526d459 --- /dev/null +++ b/src/app/api/download-intents/intent-handler.ts @@ -0,0 +1,124 @@ +import { z } from "zod"; + +import { createRepeatDownload } from "@/modules/downloads/service"; +import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { createNewUsage } from "@/modules/usages/service"; +import { UsageAccountingError } from "@/modules/usages/types"; + +const newUsagePayload = z + .object({ + kind: z.literal("new_usage"), + assetId: z.string(), + albumId: z.string(), + purpose: z.string(), + reference: z.string().optional(), + idempotencyKey: z.string(), + }) + .strict(); + +const repeatDownloadPayload = z + .object({ + kind: z.literal("repeat_download"), + usageId: z.string(), + note: z.string().optional(), + idempotencyKey: z.string(), + }) + .strict(); + +const intentPayload = z.discriminatedUnion("kind", [newUsagePayload, repeatDownloadPayload]); + +type IntentHandlerDependencies = { + requireActiveEditorial: typeof requireActiveEditorial; + createNewUsage: typeof createNewUsage; + createRepeatDownload: typeof createRepeatDownload; +}; + +export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) { + return async function POST(request: Request): Promise { + try { + const principal = await dependencies.requireActiveEditorial(request.headers); + const payload = intentPayload.safeParse(await readJson(request)); + if (!payload.success) return errorResponse(400, "INVALID_REQUEST"); + + const intent = + payload.data.kind === "new_usage" + ? await dependencies.createNewUsage({ + editorialId: principal.editorialId, + assetId: payload.data.assetId, + albumId: payload.data.albumId, + purpose: payload.data.purpose, + ...(payload.data.reference === undefined + ? {} + : { reference: payload.data.reference }), + idempotencyKey: payload.data.idempotencyKey, + }) + : await dependencies.createRepeatDownload({ + editorialId: principal.editorialId, + usageId: payload.data.usageId, + ...(payload.data.note === undefined ? {} : { note: payload.data.note }), + idempotencyKey: payload.data.idempotencyKey, + }); + + return Response.json( + { + downloadId: intent.id, + fileUrl: `/api/downloads/${encodeURIComponent(intent.id)}/file`, + priceCents: intent.priceCents, + billable: intent.billable, + }, + { status: 201, headers: { "cache-control": "private, no-store" } }, + ); + } catch (error) { + return mappedError(error); + } + }; +} + +async function readJson(request: Request): Promise { + try { + return await request.json(); + } catch { + return null; + } +} + +function mappedError(error: unknown): Response { + if (error instanceof PrincipalAuthorizationError) { + return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); + } + if (error instanceof UsageAccountingError) { + switch (error.code) { + case "INVALID_INPUT": + return errorResponse(400, "INVALID_REQUEST"); + case "IDEMPOTENCY_CONFLICT": + return errorResponse(409, "IDEMPOTENCY_CONFLICT"); + case "ALBUM_NOT_GRANTED": + case "ASSET_NOT_FOUND": + case "ASSET_NOT_IN_ALBUM": + case "USAGE_NOT_FOUND": + return errorResponse(404, "NOT_FOUND"); + case "IMMICH_UNAVAILABLE": + return errorResponse(503, "UPSTREAM_UNAVAILABLE"); + case "ASSET_NOT_IMAGE": + return errorResponse(422, "INVALID_ASSET"); + case "EDITORIAL_NOT_ACTIVE": + return errorResponse(403, "FORBIDDEN"); + case "INVALID_PRICE": + return errorResponse(409, "ACCOUNTING_UNAVAILABLE"); + } + } + return errorResponse(500, "REQUEST_FAILED"); +} + +function errorResponse(status: number, code: string): Response { + return Response.json( + { code }, + { status, headers: { "cache-control": "private, no-store" } }, + ); +} + +export const authorizedDownloadIntentHandler = createDownloadIntentHandler({ + requireActiveEditorial, + createNewUsage, + createRepeatDownload, +}); diff --git a/src/app/api/download-intents/route.test.ts b/src/app/api/download-intents/route.test.ts new file mode 100644 index 0000000..2402017 --- /dev/null +++ b/src/app/api/download-intents/route.test.ts @@ -0,0 +1,140 @@ +import { expect, test, vi } from "vitest"; + +import { createDownloadIntentHandler } from "./intent-handler"; + +const editorialId = "11111111-1111-4111-8111-111111111111"; +const assetId = "22222222-2222-4222-8222-222222222222"; +const albumId = "33333333-3333-4333-8333-333333333333"; +const usageId = "44444444-4444-4444-8444-444444444444"; +const idempotencyKey = "55555555-5555-4555-8555-555555555555"; +const downloadId = "66666666-6666-4666-8666-666666666666"; + +function dependencies() { + return { + requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }), + createNewUsage: vi.fn().mockResolvedValue({ + id: downloadId, + usageId, + assetId, + priceCents: 1_500, + billable: true, + status: "authorized", + authorizedAt: new Date("2026-08-10T10:00:00.000Z"), + }), + createRepeatDownload: vi.fn().mockResolvedValue({ + id: downloadId, + usageId, + assetId, + priceCents: 0, + billable: false, + status: "authorized", + authorizedAt: new Date("2026-08-10T10:00:00.000Z"), + }), + }; +} + +function post(handler: ReturnType, body: unknown) { + return handler( + new Request("http://portal.test/api/download-intents", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); +} + +test("derives editorial scope and billable price exclusively on the server", async () => { + const deps = dependencies(); + const response = await post(createDownloadIntentHandler(deps), { + kind: "new_usage", + assetId, + albumId, + purpose: "Titelgeschichte", + idempotencyKey, + }); + + expect(response.status).toBe(201); + await expect(response.json()).resolves.toEqual({ + downloadId, + fileUrl: `/api/downloads/${downloadId}/file`, + priceCents: 1_500, + billable: true, + }); + expect(deps.createNewUsage).toHaveBeenCalledWith({ + editorialId, + assetId, + albumId, + purpose: "Titelgeschichte", + idempotencyKey, + }); +}); + +test("creates a zero-cost repeat intent scoped to the authenticated editorial", async () => { + const deps = dependencies(); + const response = await post(createDownloadIntentHandler(deps), { + kind: "repeat_download", + usageId, + note: "erneuter Abruf", + idempotencyKey, + }); + + expect(response.status).toBe(201); + expect(deps.createRepeatDownload).toHaveBeenCalledWith({ + editorialId, + usageId, + note: "erneuter Abruf", + idempotencyKey, + }); + await expect(response.json()).resolves.toMatchObject({ priceCents: 0, billable: false }); +}); + +test.each([ + { field: "editorialId", value: "77777777-7777-4777-8777-777777777777" }, + { field: "priceCents", value: 1 }, +])("rejects a client-controlled $field before any accounting side effect", async ({ field, value }) => { + const deps = dependencies(); + const response = await post(createDownloadIntentHandler(deps), { + kind: "new_usage", + assetId, + albumId, + purpose: "Titelgeschichte", + idempotencyKey, + [field]: value, + }); + + expect(response.status).toBe(400); + expect(deps.createNewUsage).not.toHaveBeenCalled(); + expect(deps.createRepeatDownload).not.toHaveBeenCalled(); +}); + +test("rejects mixed new and repeat fields as an invalid discriminated payload", async () => { + const deps = dependencies(); + const response = await post(createDownloadIntentHandler(deps), { + kind: "repeat_download", + usageId, + assetId, + idempotencyKey, + }); + + expect(response.status).toBe(400); + expect(deps.createRepeatDownload).not.toHaveBeenCalled(); +}); + +test("passes one submitted idempotency key through unchanged", async () => { + const deps = dependencies(); + const handler = createDownloadIntentHandler(deps); + const body = { + kind: "new_usage", + assetId, + albumId, + purpose: "Titelgeschichte", + idempotencyKey, + }; + + const [first, retry] = await Promise.all([post(handler, body), post(handler, body)]); + + expect(first.status).toBe(201); + expect(retry.status).toBe(201); + expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey })); + expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey })); +}); diff --git a/src/app/api/download-intents/route.ts b/src/app/api/download-intents/route.ts new file mode 100644 index 0000000..dca3d5b --- /dev/null +++ b/src/app/api/download-intents/route.ts @@ -0,0 +1,3 @@ +import { authorizedDownloadIntentHandler } from "./intent-handler"; + +export const POST = authorizedDownloadIntentHandler; diff --git a/src/app/api/downloads/[downloadId]/file/download-handler.ts b/src/app/api/downloads/[downloadId]/file/download-handler.ts new file mode 100644 index 0000000..d1cfb31 --- /dev/null +++ b/src/app/api/downloads/[downloadId]/file/download-handler.ts @@ -0,0 +1,162 @@ +import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream"; +import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { immichClient } from "@/modules/immich/client"; +import type { ImmichBinary } from "@/modules/immich/types"; +import { normalizeUuid } from "@/modules/usages/types"; + +type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string }> }>; + +type DownloadFileHandlerDependencies = { + requireActiveEditorial: typeof requireActiveEditorial; + repository: typeof downloadDeliveryRepository; + immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise }; +}; + +export function createDownloadFileHandler(dependencies: DownloadFileHandlerDependencies) { + return async function GET( + request: Request, + context: DownloadFileRouteContext, + ): Promise { + try { + const principal = await dependencies.requireActiveEditorial(request.headers); + const downloadId = safeDownloadId((await context.params).downloadId); + if (!downloadId) return genericNotFound(); + + const claim = await dependencies.repository.claimAuthorized( + principal.editorialId, + downloadId, + ); + if (claim.outcome === "not_found") return genericNotFound(); + if (claim.outcome === "not_authorized") { + return jsonError(409, "DOWNLOAD_NOT_AVAILABLE"); + } + + let original: ImmichBinary; + try { + original = await dependencies.immich.getOriginal( + claim.download.assetId, + request.signal, + ); + } catch { + await failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind); + return jsonError(503, "DOWNLOAD_UNAVAILABLE"); + } + + try { + const body = streamWithAccounting({ + downloadId, + upstream: original.body, + voidNewUsageOnFailure: claim.download.intentKind === "new_usage", + repository: dependencies.repository, + }); + return new Response(body, { + headers: downloadHeaders(original, claim.download.filename), + }); + } catch { + const cancellation = Promise.resolve().then(() => original.body.cancel()); + await Promise.allSettled([ + cancellation, + failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind), + ]); + return jsonError(503, "DOWNLOAD_UNAVAILABLE"); + } + } catch (error) { + if (error instanceof PrincipalAuthorizationError) { + return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); + } + return jsonError(503, "DOWNLOAD_UNAVAILABLE"); + } + }; +} + +async function failClaimBeforeDelivery( + dependencies: DownloadFileHandlerDependencies, + downloadId: string, + intentKind: "new_usage" | "repeat_download" | "legacy", +) { + await dependencies.repository + .failBeforeDelivery(downloadId, { voidNewUsage: intentKind === "new_usage" }) + .catch(() => undefined); +} + +function safeDownloadId(value: string): string | null { + try { + return normalizeUuid(value); + } catch { + return null; + } +} + +function downloadHeaders(original: ImmichBinary, snapshotFilename: string): Headers { + const headers = new Headers({ + "cache-control": "private, no-store", + "content-disposition": contentDisposition(original.filename || snapshotFilename), + "content-type": safeContentType(original.contentType), + "x-content-type-options": "nosniff", + }); + if ( + original.contentLength !== null && + Number.isSafeInteger(original.contentLength) && + original.contentLength >= 0 + ) { + headers.set("content-length", String(original.contentLength)); + } + return headers; +} + +export function contentDisposition(filename: string): string { + const cleaned = cleanFilename(filename); + const fallback = asciiFilename(cleaned); + const encoded = encodeURIComponent(cleaned).replace(/[!'()*]/g, (character) => + `%${character.charCodeAt(0).toString(16).toUpperCase()}`, + ); + return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`; +} + +function cleanFilename(filename: string): string { + const cleaned = [...filename.normalize("NFC").replace(/[\uD800-\uDFFF]/gu, "_")] + .slice(0, 180) + .join("") + .replace(/[\\/]/g, "_") + .replace(/[\u0000-\u001f\u007f-\u009f]/g, "") + .trim(); + return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "download"; +} + +function asciiFilename(filename: string): string { + const fallback = filename + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^A-Za-z0-9._ ()+-]/g, "_") + .replace(/[";]/g, "_") + .trim(); + return fallback && fallback !== "." && fallback !== ".." ? fallback : "download"; +} + +function safeContentType(value: string): string { + return /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:[ \t]*;[ \t]*[A-Za-z0-9!#$&^_.+-]+=[A-Za-z0-9!#$&^_.+"'()-]+)*$/.test( + value, + ) + ? value + : "application/octet-stream"; +} + +function genericNotFound(): Response { + return new Response(null, { + status: 404, + headers: { "cache-control": "private, no-store" }, + }); +} + +function jsonError(status: number, code: string): Response { + return Response.json( + { code }, + { status, headers: { "cache-control": "private, no-store" } }, + ); +} + +export const authorizedDownloadFileHandler = createDownloadFileHandler({ + requireActiveEditorial, + repository: downloadDeliveryRepository, + immich: immichClient, +}); diff --git a/src/app/api/downloads/[downloadId]/file/route.test.ts b/src/app/api/downloads/[downloadId]/file/route.test.ts new file mode 100644 index 0000000..2a4c2cb --- /dev/null +++ b/src/app/api/downloads/[downloadId]/file/route.test.ts @@ -0,0 +1,228 @@ +import { expect, test, vi } from "vitest"; + +import { PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { contentDisposition, createDownloadFileHandler } from "./download-handler"; + +const editorialId = "11111111-1111-4111-8111-111111111111"; +const otherEditorialId = "22222222-2222-4222-8222-222222222222"; +const downloadId = "33333333-3333-4333-8333-333333333333"; +const usageId = "44444444-4444-4444-8444-444444444444"; +const assetId = "55555555-5555-4555-8555-555555555555"; + +function binary(overrides: Partial<{ + body: ReadableStream; + contentType: string; + contentLength: number | null; + filename: string; +}> = {}) { + return { + body: new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])); + controller.close(); + }, + }), + contentType: "image/jpeg", + contentLength: 3, + filename: "heimspiel.jpg", + ...overrides, + }; +} + +function dependencies(options: { + claim?: "claimed" | "not_found" | "not_authorized"; + editorialError?: Error; + original?: ReturnType; + originalError?: Error; + intentKind?: "new_usage" | "repeat_download"; +} = {}) { + const repository = { + claimAuthorized: vi.fn().mockResolvedValue( + options.claim === "not_found" + ? { outcome: "not_found" } + : options.claim === "not_authorized" + ? { outcome: "not_authorized" } + : { + outcome: "claimed", + download: { + id: downloadId, + usageId, + assetId, + filename: "snapshot.jpg", + intentKind: options.intentKind ?? "new_usage", + }, + }, + ), + failBeforeDelivery: vi.fn().mockResolvedValue(true), + markCompleted: vi.fn().mockResolvedValue(true), + markInterrupted: vi.fn().mockResolvedValue(true), + }; + const values = { + requireActiveEditorial: vi.fn().mockImplementation(async () => { + if (options.editorialError) throw options.editorialError; + return { editorialId }; + }), + repository, + immich: { + getOriginal: vi.fn().mockImplementation(async () => { + if (options.originalError) throw options.originalError; + return options.original ?? binary(); + }), + }, + }; + return values; +} + +function call( + handler: ReturnType, + id = downloadId, + signal?: AbortSignal, +) { + return handler(new Request(`http://portal.test/api/downloads/${id}/file`, { signal }), { + params: Promise.resolve({ downloadId: id }), + }); +} + +test("claims an owned authorized event before requesting and streaming the original", async () => { + const deps = dependencies(); + const handler = createDownloadFileHandler(deps); + + const response = await call(handler); + + expect(response.status).toBe(200); + expect(deps.repository.claimAuthorized).toHaveBeenCalledWith(editorialId, downloadId); + expect(deps.immich.getOriginal).toHaveBeenCalledWith(assetId, expect.any(AbortSignal)); + expect(await response.arrayBuffer()).toEqual(new Uint8Array([1, 2, 3]).buffer); + expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3); +}); + +test("returns the same generic 404 for an invalid id, missing event, and another editorial's event", async () => { + const invalid = dependencies(); + const missing = dependencies({ claim: "not_found" }); + const foreign = dependencies({ claim: "not_found" }); + foreign.requireActiveEditorial.mockResolvedValue({ editorialId: otherEditorialId }); + + const responses = await Promise.all([ + call(createDownloadFileHandler(invalid), "not-a-uuid"), + call(createDownloadFileHandler(missing)), + call(createDownloadFileHandler(foreign)), + ]); + const results = await Promise.all( + responses.map(async (response) => ({ status: response.status, body: await response.text() })), + ); + + expect(results[1]).toEqual(results[0]); + expect(results[2]).toEqual(results[0]); + expect(invalid.repository.claimAuthorized).not.toHaveBeenCalled(); + expect(foreign.immich.getOriginal).not.toHaveBeenCalled(); +}); + +test.each(["streaming", "completed", "interrupted", "failed_before_delivery"])( + "denies reuse of a %s attempt before reaching Immich", + async () => { + const deps = dependencies({ claim: "not_authorized" }); + const response = await call(createDownloadFileHandler(deps)); + + expect(response.status).toBe(409); + await expect(response.json()).resolves.toEqual({ code: "DOWNLOAD_NOT_AVAILABLE" }); + expect(deps.immich.getOriginal).not.toHaveBeenCalled(); + }, +); + +test("marks a pre-response Immich failure failed and voids a new usage", async () => { + const deps = dependencies({ originalError: new Error("IMMICH_UNAVAILABLE") }); + + const response = await call(createDownloadFileHandler(deps)); + + expect(response.status).toBe(503); + expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { + voidNewUsage: true, + }); +}); + +test("a repeat pre-response failure retains the original usage", async () => { + const deps = dependencies({ + originalError: new Error("IMMICH_UNAVAILABLE"), + intentKind: "repeat_download", + }); + + await call(createDownloadFileHandler(deps)); + + expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { + voidNewUsage: false, + }); +}); + +test("accounts for a claimed attempt when the upstream body cannot be consumed", async () => { + const original = binary(); + const lock = original.body.getReader(); + const deps = dependencies({ original }); + + const response = await call(createDownloadFileHandler(deps)); + + expect(response.status).toBe(503); + expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, { + voidNewUsage: true, + }); + lock.releaseLock(); +}); + +test("emits only safe download headers for an injected Unicode filename", async () => { + const deps = dependencies({ + original: binary({ + filename: "../München\r\nX-Internal: secret\\final.jpg", + contentType: "image/jpeg", + contentLength: 3, + }), + }); + + const response = await call(createDownloadFileHandler(deps)); + const disposition = response.headers.get("content-disposition") ?? ""; + + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(response.headers.get("content-type")).toBe("image/jpeg"); + expect(response.headers.get("content-length")).toBe("3"); + expect(response.headers.has("x-api-key")).toBe(false); + expect(disposition).not.toMatch(/[\r\n\\/]/); + expect(disposition).toContain("filename*=UTF-8''"); + expect(disposition).toContain("M%C3%BCnchen"); +}); + +test("falls back from an untrustworthy media type and length without forwarding header injection", async () => { + const deps = dependencies({ + original: binary({ + contentType: "image/jpeg;\r\nx-api-key=secret", + contentLength: -1, + }), + }); + + const response = await call(createDownloadFileHandler(deps)); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/octet-stream"); + expect(response.headers.has("content-length")).toBe(false); + expect(response.headers.has("x-api-key")).toBe(false); +}); + +test("builds a standards-safe disposition for malformed Unicode", () => { + expect(() => contentDisposition("foto-\ud800.jpg")).not.toThrow(); + expect(contentDisposition("foto-\ud800.jpg")).toContain("filename*=UTF-8''foto-_.jpg"); +}); + +test("returns stable authentication semantics without exposing guard details", async () => { + const unauthenticated = dependencies({ + editorialError: new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"), + }); + const inactive = dependencies({ + editorialError: new PrincipalAuthorizationError("ACCOUNT_SUSPENDED"), + }); + + const [first, second] = await Promise.all([ + call(createDownloadFileHandler(unauthenticated)), + call(createDownloadFileHandler(inactive)), + ]); + + expect(first.status).toBe(401); + expect(second.status).toBe(403); + expect(await second.text()).not.toContain("SUSPENDED"); +}); diff --git a/src/app/api/downloads/[downloadId]/file/route.ts b/src/app/api/downloads/[downloadId]/file/route.ts new file mode 100644 index 0000000..2fee8e1 --- /dev/null +++ b/src/app/api/downloads/[downloadId]/file/route.ts @@ -0,0 +1,3 @@ +import { authorizedDownloadFileHandler } from "./download-handler"; + +export const GET = authorizedDownloadFileHandler; diff --git a/src/app/globals.css b/src/app/globals.css index 814ba9e..de83a9d 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -621,3 +621,308 @@ a { transition: none; } } + +.download-trigger { + width: 100%; + min-height: 2.45rem; + border: 0; + border-top: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + cursor: pointer; + font: inherit; + font-size: 0.7rem; + font-weight: 750; + letter-spacing: 0.07em; + text-transform: uppercase; +} + +.download-trigger:hover { + background: var(--ink); + color: var(--paper); +} + +.usage-dialog { + width: min(calc(100% - 2rem), 46rem); + max-height: calc(100vh - 2rem); + padding: 0; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); +} + +.usage-dialog::backdrop { + background: rgb(0 0 0 / 70%); +} + +.usage-dialog form { + display: grid; + gap: 1.5rem; + padding: clamp(1.25rem, 4vw, 2.5rem); +} + +.usage-dialog-heading { + padding-bottom: 1.25rem; + border-bottom: 1px solid var(--ink); +} + +.usage-dialog-heading h2 { + margin: 0; + font-size: clamp(2rem, 6vw, 4rem); + font-weight: 600; + letter-spacing: -0.055em; + line-height: 0.95; +} + +.usage-dialog-heading > p:last-child { + max-width: 38rem; + margin: 1rem 0 0; + color: var(--graphite); + line-height: 1.5; +} + +.usage-options { + display: grid; + gap: 0; + margin: 0; + padding: 0; + border: 0; +} + +.usage-options legend, +.usage-purpose { + margin-bottom: 0.6rem; + font-size: 0.7rem; + font-weight: 750; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.usage-option { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 0.9rem; + padding: 0.9rem 0; + border-top: 1px solid var(--line); + cursor: pointer; +} + +.usage-option:last-child { + border-bottom: 1px solid var(--line); +} + +.usage-option input { + width: 1.05rem; + height: 1.05rem; + accent-color: var(--ink); +} + +.usage-option span { + display: grid; + gap: 0.2rem; + min-width: 0; +} + +.usage-option strong, +.usage-option b { + font-size: 0.875rem; +} + +.usage-option small { + overflow: hidden; + color: var(--metadata); + font-size: 0.7rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.usage-purpose { + display: grid; + gap: 0.5rem; + margin: 0; +} + +.usage-purpose textarea { + width: 100%; + resize: vertical; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + font: inherit; + padding: 0.75rem; +} + +.usage-purpose textarea:disabled { + border-color: var(--line); + background: var(--soft); +} + +.usage-dialog [role="alert"] { + margin: 0; + color: #8d1010; + font-size: 0.875rem; +} + +.usage-dialog-actions { + display: flex; + justify-content: flex-end; + gap: 0.75rem; +} + +.usage-dialog-actions button { + min-height: 2.8rem; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + cursor: pointer; + font: inherit; + font-size: 0.8rem; + font-weight: 700; + padding-inline: 1rem; +} + +.usage-dialog-actions .download-confirm { + background: var(--ink); + color: var(--paper); +} + +.usage-dialog-actions button:disabled { + cursor: wait; + opacity: 0.55; +} + +.usage-history-empty { + max-width: 38rem; +} + +.usage-history-empty p { + color: var(--graphite); + line-height: 1.55; +} + +.usage-ledger, +.usage-attempts { + margin: 0; + padding: 0; + list-style: none; +} + +.usage-ledger { + display: grid; + gap: 2.5rem; +} + +.usage-ledger-entry { + border-top: 2px solid var(--ink); +} + +.usage-ledger-entry > header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 1rem; + padding: 0.8rem 0; + border-bottom: 1px solid var(--line); +} + +.usage-ledger-entry > header p { + margin: 0; + color: var(--metadata); + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 0.65rem; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.usage-ledger-entry h2 { + overflow-wrap: anywhere; + margin: 0; + font-size: clamp(1.35rem, 3vw, 2.25rem); + font-weight: 600; + letter-spacing: -0.035em; +} + +.usage-snapshot { + display: grid !important; + grid-template-columns: repeat(3, minmax(0, 1fr)) !important; + gap: 1rem !important; + max-width: none !important; + margin: 0 !important; + padding: 1rem 0 !important; + border-top: 0 !important; +} + +.usage-snapshot div { + min-width: 0; +} + +.usage-snapshot dd { + overflow-wrap: anywhere; + margin-top: 0.25rem; +} + +.usage-attempts { + border-top: 1px solid var(--ink); +} + +.usage-attempts li { + display: grid; + grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr; + gap: 1rem; + align-items: baseline; + padding: 0.7rem 0; + border-bottom: 1px solid var(--line); + font-size: 0.75rem; +} + +.usage-attempts time, +.usage-attempts span { + color: var(--metadata); +} + +.usage-attempts b { + text-align: right; +} + +.usage-attempt-empty { + margin: 0; + padding: 1rem 0; + border-top: 1px solid var(--line); + color: var(--metadata); + font-size: 0.8rem; +} + +@media (max-width: 52rem) { + .usage-snapshot { + grid-template-columns: 1fr !important; + } + + .usage-attempts li { + grid-template-columns: 1fr auto; + } + + .usage-attempts li > :nth-child(3), + .usage-attempts li > :nth-child(4) { + display: none; + } +} + +@media (max-width: 40rem) { + .usage-dialog-actions { + flex-direction: column-reverse; + } + + .usage-dialog-actions button { + width: 100%; + } + + .usage-ledger-entry > header { + align-items: flex-start; + flex-direction: column-reverse; + } +} diff --git a/src/app/redaktion/alben/[albumId]/page.tsx b/src/app/redaktion/alben/[albumId]/page.tsx index c138973..bc054ca 100644 --- a/src/app/redaktion/alben/[albumId]/page.tsx +++ b/src/app/redaktion/alben/[albumId]/page.tsx @@ -3,6 +3,7 @@ import { notFound } from "next/navigation"; import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog"; import { PhotoContactSheet } from "@/modules/albums/catalog-content"; +import { loadEditorialDownloadOptions } from "@/modules/downloads/stream"; import { requireEditorial } from "../../access"; @@ -44,6 +45,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps @@ -73,7 +75,11 @@ async function loadAlbumPage({ description: query, page, }); - return { album, page: results, unavailable: false as const }; + const downloadOptions = await loadEditorialDownloadOptions( + editorialId, + results.items.map((asset) => asset.id), + ); + return { album, page: results, downloadOptions, unavailable: false as const }; } catch (error) { if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") { return { album: null, page: null, unavailable: true as const }; diff --git a/src/app/redaktion/nutzungen/page.test.tsx b/src/app/redaktion/nutzungen/page.test.tsx new file mode 100644 index 0000000..5e3952d --- /dev/null +++ b/src/app/redaktion/nutzungen/page.test.tsx @@ -0,0 +1,84 @@ +// @vitest-environment jsdom + +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, expect, test } from "vitest"; + +import { UsageHistoryContent } from "./usage-history-content"; + +afterEach(cleanup); + +test("renders every terminal attempt with its immutable usage snapshot", () => { + render( + , + ); + + expect(screen.getByRole("heading", { name: /tor-des-monats\.jpg/i })).not.toBeNull(); + expect(screen.getByText("Heimspiel gegen Nord")).not.toBeNull(); + expect(screen.getByText("Titelgeschichte")).not.toBeNull(); + expect(screen.getByText("Abgeschlossen")).not.toBeNull(); + expect(screen.getByText("Unterbrochen")).not.toBeNull(); + expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull(); + expect(screen.getByText(/15,00\s*€/)).not.toBeNull(); + expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2); + expect(screen.getByRole("link", { name: /nächste seite/i }).getAttribute("href")).toBe( + "/redaktion/nutzungen?page=2", + ); +}); + +test("renders a directional empty state", () => { + render( + , + ); + + expect(screen.getByText(/noch keine nutzungen/i)).not.toBeNull(); + expect(screen.getByRole("link", { name: /zu den alben/i })).not.toBeNull(); +}); diff --git a/src/app/redaktion/nutzungen/page.tsx b/src/app/redaktion/nutzungen/page.tsx new file mode 100644 index 0000000..82cad2e --- /dev/null +++ b/src/app/redaktion/nutzungen/page.tsx @@ -0,0 +1,40 @@ +import { listEditorialUsageHistory } from "@/modules/downloads/stream"; + +import { requireEditorial } from "../access"; +import { UsageHistoryContent } from "./usage-history-content"; + +type UsageHistoryPageProps = Readonly<{ + searchParams: Promise<{ page?: string | string[] }>; +}>; + +export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) { + const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]); + const result = await loadHistory(principal.editorialId, singleValue(parameters.page)); + if (result.unavailable) return ; + return ; +} + +async function loadHistory(editorialId: string, page: string | undefined) { + try { + return { + history: await listEditorialUsageHistory(editorialId, page), + unavailable: false as const, + }; + } catch { + return { history: null, unavailable: true as const }; + } +} + +function HistoryUnavailable() { + return ( +
+

Abrechnung

+

Nutzungen momentan nicht erreichbar

+

Bitte laden Sie diese Seite in wenigen Minuten erneut.

+
+ ); +} + +function singleValue(value: string | string[] | undefined): string | undefined { + return typeof value === "string" ? value : undefined; +} diff --git a/src/app/redaktion/nutzungen/usage-history-content.tsx b/src/app/redaktion/nutzungen/usage-history-content.tsx new file mode 100644 index 0000000..539aff9 --- /dev/null +++ b/src/app/redaktion/nutzungen/usage-history-content.tsx @@ -0,0 +1,120 @@ +import Link from "next/link"; + +import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream"; + +const dateTimeFormatter = new Intl.DateTimeFormat("de-DE", { + dateStyle: "medium", + timeStyle: "short", +}); +const priceFormatter = new Intl.NumberFormat("de-DE", { + style: "currency", + currency: "EUR", +}); +const byteFormatter = new Intl.NumberFormat("de-DE", { + style: "unit", + unit: "byte", + unitDisplay: "short", + maximumFractionDigits: 0, +}); + +export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) { + return ( +
+

Abrechnung · Downloadprotokoll

+
+

Ihre Nutzungen

+

Verwendungszwecke, Kosten und Auslieferungsversuche Ihrer Redaktion.

+
+ + {history.items.length === 0 ? ( +
+

Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.

+ + Zu den Alben + +
+ ) : ( +
    + {history.items.map((usage) => ( +
  1. +
    +
    +

    {formatDateTime(usage.createdAt)}

    +

    {usage.filename}

    +
    +
    +
    +
    Album
    +
    {usage.albumName}
    +
    +
    +
    Verwendungszweck
    +
    {usage.purpose}
    +
    + {usage.reference ? ( +
    +
    Interne Referenz
    +
    {usage.reference}
    +
    + ) : null} +
    + {usage.attempts.length === 0 ? ( +

    Noch kein abgeschlossener Auslieferungsversuch.

    + ) : ( +
      + {usage.attempts.map((attempt) => ( + + ))} +
    + )} +
    +
  2. + ))} +
+ )} + + +
+ ); +} + +function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) { + return ( +
  • + + {statusLabel(attempt.status)} + {attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} + {byteFormatter.format(attempt.transferredBytes)} + {priceFormatter.format(attempt.billableCents / 100)} +
  • + ); +} + +function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) { + if (history.page === 1 && !history.hasNext) return null; + return ( + + ); +} + +function statusLabel(status: UsageHistoryAttempt["status"]): string { + const labels: Record = { + completed: "Abgeschlossen", + interrupted: "Unterbrochen", + failed_before_delivery: "Vor Auslieferung fehlgeschlagen", + }; + return labels[status]; +} + +function formatDateTime(value: Date): string { + return dateTimeFormatter.format(value); +} diff --git a/src/components/download/usage-dialog.test.tsx b/src/components/download/usage-dialog.test.tsx new file mode 100644 index 0000000..76e194a --- /dev/null +++ b/src/components/download/usage-dialog.test.tsx @@ -0,0 +1,137 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { UsageDialog } from "./usage-dialog"; + +const idempotencyKey = "55555555-5555-4555-8555-555555555555"; + +beforeEach(() => { + Object.defineProperty(HTMLDialogElement.prototype, "showModal", { + configurable: true, + value() { + this.setAttribute("open", ""); + }, + }); + Object.defineProperty(HTMLDialogElement.prototype, "close", { + configurable: true, + value() { + this.removeAttribute("open"); + this.dispatchEvent(new Event("close")); + }, + }); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +function renderDialog() { + return render( + , + ); +} + +test("offers an existing free use and a new server-priced use with required purpose", () => { + renderDialog(); + fireEvent.click(screen.getByRole("button", { name: /original laden/i })); + + expect(screen.getByRole("dialog", { name: /nutzung auswählen/i })).not.toBeNull(); + expect( + (screen.getByRole("radio", { + name: /online-nachbericht.*0,00\s*€/i, + }) as HTMLInputElement).checked, + ).toBe(true); + expect( + (screen.getByRole("radio", { name: /neue nutzung.*15,00\s*€/i }) as HTMLInputElement) + .checked, + ).toBe(false); + expect( + (screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement) + .disabled, + ).toBe(true); + + fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i })); + expect( + (screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement) + .required, + ).toBe(true); +}); + +test("reuses one idempotency key when the same failed submission is retried", async () => { + const randomUUID = vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey); + const fetch = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 503 })) + .mockResolvedValueOnce( + Response.json({ + downloadId: "66666666-6666-4666-8666-666666666666", + fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file", + priceCents: 1_500, + billable: true, + }), + ); + vi.stubGlobal("fetch", fetch); + const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); + renderDialog(); + fireEvent.click(screen.getByRole("button", { name: /original laden/i })); + fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i })); + fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), { + target: { value: "Titelgeschichte" }, + }); + + fireEvent.click(screen.getByRole("button", { name: /download anfordern/i })); + await screen.findByRole("alert"); + fireEvent.click(screen.getByRole("button", { name: /download erneut anfordern/i })); + + await waitFor(() => expect(anchorClick).toHaveBeenCalledOnce()); + expect(randomUUID).toHaveBeenCalledOnce(); + expect(fetch).toHaveBeenCalledTimes(2); + for (const [, init] of fetch.mock.calls) { + expect(JSON.parse(String(init?.body))).toMatchObject({ idempotencyKey }); + } +}); + +test("suppresses double-click submission while one request is pending", async () => { + vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey); + let resolveRequest: ((response: Response) => void) | undefined; + const fetch = vi.fn().mockReturnValue( + new Promise((resolve) => { + resolveRequest = resolve; + }), + ); + vi.stubGlobal("fetch", fetch); + vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); + renderDialog(); + fireEvent.click(screen.getByRole("button", { name: /original laden/i })); + const submit = screen.getByRole("button", { name: /download anfordern/i }); + + fireEvent.click(submit); + fireEvent.click(submit); + + expect(fetch).toHaveBeenCalledOnce(); + resolveRequest?.( + Response.json({ + downloadId: "66666666-6666-4666-8666-666666666666", + fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file", + priceCents: 0, + billable: false, + }), + ); + await waitFor(() => expect((submit as HTMLButtonElement).disabled).toBe(false)); +}); diff --git a/src/components/download/usage-dialog.tsx b/src/components/download/usage-dialog.tsx new file mode 100644 index 0000000..8346b5d --- /dev/null +++ b/src/components/download/usage-dialog.tsx @@ -0,0 +1,224 @@ +"use client"; + +import { useRef, useState, type FormEvent } from "react"; + +import type { DownloadDialogUsage } from "@/modules/downloads/stream"; + +type UsageDialogProps = Readonly<{ + albumId: string; + assetId: string; + filename: string; + newUsagePriceCents: number; + priorUsages: DownloadDialogUsage[]; +}>; + +type IntentResponse = { + downloadId: string; + fileUrl: string; + priceCents: number; + billable: boolean; +}; + +const priceFormatter = new Intl.NumberFormat("de-DE", { + style: "currency", + currency: "EUR", +}); +const dateFormatter = new Intl.DateTimeFormat("de-DE", { + dateStyle: "medium", +}); + +export function UsageDialog({ + albumId, + assetId, + filename, + newUsagePriceCents, + priorUsages, +}: UsageDialogProps) { + const dialogRef = useRef(null); + const firstChoiceRef = useRef(null); + const idempotencyKeyRef = useRef(null); + const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage"; + const [choice, setChoice] = useState(initialChoice); + const [purpose, setPurpose] = useState(""); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + + function openDialog() { + setChoice(initialChoice); + setPurpose(""); + setPending(false); + setError(null); + idempotencyKeyRef.current = null; + dialogRef.current?.showModal(); + requestAnimationFrame(() => firstChoiceRef.current?.focus()); + } + + function closeDialog() { + if (!pending) dialogRef.current?.close(); + } + + function resetSubmission() { + idempotencyKeyRef.current = null; + setError(null); + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (pending) return; + setPending(true); + setError(null); + idempotencyKeyRef.current ??= crypto.randomUUID(); + + const payload = choice.startsWith("repeat:") + ? { + kind: "repeat_download" as const, + usageId: choice.slice("repeat:".length), + idempotencyKey: idempotencyKeyRef.current, + } + : { + kind: "new_usage" as const, + assetId, + albumId, + purpose, + idempotencyKey: idempotencyKeyRef.current, + }; + + try { + const response = await fetch("/api/download-intents", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(payload), + }); + if (!response.ok) throw new Error("intent failed"); + const intent = (await response.json()) as IntentResponse; + if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) { + throw new Error("invalid download url"); + } + const link = document.createElement("a"); + link.href = intent.fileUrl; + link.download = filename; + link.click(); + dialogRef.current?.close(); + idempotencyKeyRef.current = null; + } catch { + setError( + "Der Download konnte nicht vorbereitet werden. Versuchen Sie dieselbe Anfrage erneut.", + ); + } finally { + setPending(false); + } + } + + const isNewUsage = choice === "new_usage"; + + return ( + <> + + { + if (pending) event.preventDefault(); + }} + onClose={() => { + setError(null); + idempotencyKeyRef.current = null; + }} + ref={dialogRef} + > +
    +
    +

    Download · {filename}

    +

    Nutzung auswählen

    +

    Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.

    +
    + +
    + Abrechnung + {priorUsages.map((usage, index) => ( + + ))} + +
    + +