From f7e7918f540c8c3387311495d6e1137f9d6d8b4a Mon Sep 17 00:00:00 2001 From: sascha Date: Sat, 5 Sep 2026 07:59:59 +0200 Subject: [PATCH] feat: archive media handoff orchestrator --- workflows/media-handoff-orchestrator.json | 375 ++++++++++++++++++++++ 1 file changed, 375 insertions(+) create mode 100644 workflows/media-handoff-orchestrator.json diff --git a/workflows/media-handoff-orchestrator.json b/workflows/media-handoff-orchestrator.json new file mode 100644 index 0000000..2882f7c --- /dev/null +++ b/workflows/media-handoff-orchestrator.json @@ -0,0 +1,375 @@ +{ + "name": "🎛️ Media Handoff Orchestrator", + "nodes": [ + { + "parameters": { + "httpMethod": "POST", + "path": "media-handoff", + "responseMode": "lastNode", + "options": {} + }, + "id": "b290b455-c256-4782-8fbd-42c703277737", + "name": "Media Handoff API", + "type": "n8n-nodes-base.webhook", + "typeVersion": 2, + "position": [ + 160, + 160 + ], + "webhookId": "5d8ad588-9a9d-4ae0-9a1d-989fc952d32c" + }, + { + "parameters": { + "jsCode": "const body = $json.body ?? $json;\nconst action = String(body.action ?? '').toLowerCase();\nconst routes = {\n serien4k: { service: 'sonarr', kind: 'episode' },\n serien: { service: 'sonarr1080p', kind: 'episode' },\n video4k: { service: 'radarr', kind: 'movie' },\n video: { service: 'radarr1080p', kind: 'movie' },\n};\nconst now = Date.now();\nconst state = $getWorkflowStaticData('global');\nstate.jobs = state.jobs || {};\nconst jobs = state.jobs;\nconst norm = (v) => String(v ?? '').replace(/\\.nzb$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '');\nconst active = new Set(['registered', 'processing']);\nfor (const [id, job] of Object.entries(jobs)) {\n const terminalAt = Date.parse(job.completedAt || job.failedAt || job.timeoutAt || 0);\n if (!active.has(job.state) && terminalAt && now - terminalAt > 7 * 86400000) delete jobs[id];\n}\nconst fail = (error, extra = {}) => [{ json: { ok: false, error, ...extra } }];\nif (action === 'start') {\n const category = String(body.category ?? '').toLowerCase();\n const route = routes[category];\n const directory = String(body.directory ?? '');\n const release = String(body.release ?? '');\n const cleanName = String(body.cleanName ?? '');\n if (!route) return fail('unsupported_category', { category });\n if (!directory.startsWith('/usenet/complete/' + category + '/')) return fail('invalid_directory');\n if (!release || release.length > 500 || cleanName.length > 500) return fail('invalid_release');\n const dedupeKey = category + ':' + norm(release || cleanName);\n const prior = Object.values(jobs).find(j => active.has(j.state) && j.dedupeKey === dedupeKey);\n if (prior) return [{ json: { ok: true, idempotent: true, jobId: prior.jobId, state: prior.state, service: prior.service } }];\n const jobId = now.toString(36) + '-' + Math.random().toString(36).slice(2, 10);\n jobs[jobId] = {\n jobId, category, service: route.service, kind: route.kind, directory,\n release, cleanName, dedupeKey, state: 'registered',\n startedAt: new Date(now).toISOString(), updatedAt: new Date(now).toISOString(),\n };\n return [{ json: { ok: true, jobId, state: 'registered', service: route.service, kind: route.kind } }];\n}\nconst jobId = String(body.jobId ?? '');\nconst job = jobs[jobId];\nif (!job) return fail('job_not_found', { jobId });\nif (action === 'moved') {\n if (job.state === 'registered') {\n job.state = 'processing'; job.movedAt = new Date(now).toISOString(); job.updatedAt = job.movedAt;\n }\n return [{ json: { ok: true, jobId, state: job.state, service: job.service } }];\n}\nif (action === 'fail') {\n if (active.has(job.state)) {\n job.state = 'failed'; job.reason = String(body.reason ?? 'handoff_failed').slice(0, 300);\n job.failedAt = new Date(now).toISOString(); job.updatedAt = job.failedAt;\n }\n return [{ json: { ok: true, jobId, state: job.state } }];\n}\nif (action === 'status') {\n return [{ json: { ok: true, jobId, state: job.state, category: job.category, service: job.service,\n reason: job.reason ?? null, startedAt: job.startedAt, updatedAt: job.updatedAt } }];\n}\nreturn fail('unsupported_action', { action });" + }, + "id": "81546df2-b2c1-4753-b45c-8f8a6d223cf1", + "name": "Handle API Request", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 420, + 160 + ] + }, + { + "parameters": { + "rule": { + "interval": [ + { + "field": "cronExpression", + "expression": "*/2 * * * *" + } + ] + } + }, + "id": "9fdf3eb8-5e99-49e0-8a4a-ece3612ebbad", + "name": "Every 2 Minutes", + "type": "n8n-nodes-base.scheduleTrigger", + "typeVersion": 1.2, + "position": [ + 120, + 520 + ] + }, + { + "parameters": { + "url": "={{ 'http://10.5.85.2:8888/sonarr/api/v3/history/since?date=' + encodeURIComponent(new Date(Date.now() - 96 * 60 * 60 * 1000).toISOString()) + '&includeSeries=true&includeEpisode=true' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Accept-Encoding", + "value": "none" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + } + } + }, + "id": "93149f52-8d41-46b6-ba12-1a850fc79dad", + "name": "History Sonarr UHD", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 380, + 380 + ], + "credentials": { + "httpHeaderAuth": { + "id": "1y7tu0UBjtoS8UZO", + "name": "Butler API v2" + } + } + }, + { + "parameters": { + "url": "={{ 'http://10.5.85.2:8888/sonarr1080p/api/v3/history/since?date=' + encodeURIComponent(new Date(Date.now() - 96 * 60 * 60 * 1000).toISOString()) + '&includeSeries=true&includeEpisode=true' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Accept-Encoding", + "value": "none" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + } + } + }, + "id": "b6d89a01-80ba-4c6e-8bd1-734a37137df0", + "name": "History Sonarr FHD", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 380, + 480 + ], + "credentials": { + "httpHeaderAuth": { + "id": "1y7tu0UBjtoS8UZO", + "name": "Butler API v2" + } + } + }, + { + "parameters": { + "url": "={{ 'http://10.5.85.2:8888/radarr/api/v3/history/since?date=' + encodeURIComponent(new Date(Date.now() - 96 * 60 * 60 * 1000).toISOString()) + '&includeMovie=true' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Accept-Encoding", + "value": "none" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + } + } + }, + "id": "cf7edda2-9f40-462b-a710-b1158a0295f8", + "name": "History Radarr UHD", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 380, + 580 + ], + "credentials": { + "httpHeaderAuth": { + "id": "1y7tu0UBjtoS8UZO", + "name": "Butler API v2" + } + } + }, + { + "parameters": { + "url": "={{ 'http://10.5.85.2:8888/radarr1080p/api/v3/history/since?date=' + encodeURIComponent(new Date(Date.now() - 96 * 60 * 60 * 1000).toISOString()) + '&includeMovie=true' }}", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Accept-Encoding", + "value": "none" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + } + } + }, + "id": "e15b7f59-d542-467f-bf23-a7fc8c111ba0", + "name": "History Radarr FHD", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 380, + 680 + ], + "credentials": { + "httpHeaderAuth": { + "id": "1y7tu0UBjtoS8UZO", + "name": "Butler API v2" + } + } + }, + { + "parameters": { + "mode": "append" + }, + "id": "dcc19ebf-e267-4c4b-a20f-95e70794cbab", + "name": "Merge Sonarr", + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [ + 650, + 430 + ] + }, + { + "parameters": { + "mode": "append" + }, + "id": "b905342e-3ff4-48c5-ab4c-a42b031af655", + "name": "Merge Radarr", + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [ + 650, + 630 + ] + }, + { + "parameters": { + "mode": "append" + }, + "id": "f260afae-f688-41a5-9492-90db85e79059", + "name": "Merge Histories", + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [ + 880, + 520 + ] + }, + { + "parameters": { + "jsCode": "const state = $getWorkflowStaticData('global');\nstate.jobs = state.jobs || {};\nconst jobs = state.jobs;\nconst now = Date.now();\nconst norm = (v) => String(v ?? '').replace(/\\.nzb$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '');\nconst flatten = (nodeName) => {\n const out = [];\n for (const item of $(nodeName).all()) {\n const value = item.json;\n if (Array.isArray(value)) out.push(...value);\n else if (Array.isArray(value?.records)) out.push(...value.records);\n else if (value?.eventType) out.push(value);\n }\n return out;\n};\nconst sources = {\n sonarr: flatten('History Sonarr UHD'),\n sonarr1080p: flatten('History Sonarr FHD'),\n radarr: flatten('History Radarr UHD'),\n radarr1080p: flatten('History Radarr FHD'),\n};\nconst imported = new Set(['downloadFolderImported']);\nconst failed = new Set(['downloadFailed', 'downloadIgnored']);\nconst changed = [];\nfor (const job of Object.values(jobs)) {\n if (!['registered', 'processing'].includes(job.state)) continue;\n const start = Date.parse(job.startedAt);\n const wanted = new Set([norm(job.release), norm(job.cleanName)].filter(Boolean));\n const events = (sources[job.service] || []).filter(e => {\n const at = Date.parse(e.date || 0);\n return at >= start && wanted.has(norm(e.sourceTitle));\n }).sort((a,b) => Date.parse(a.date) - Date.parse(b.date));\n const terminals = events.filter(e => imported.has(e.eventType) || failed.has(e.eventType));\n const latest = terminals.at(-1);\n if (latest && imported.has(latest.eventType)) {\n job.state = 'success'; job.completedAt = latest.date; job.updatedAt = new Date(now).toISOString();\n job.importEventId = latest.id ?? null; changed.push({ jobId: job.jobId, state: job.state }); continue;\n }\n if (latest && failed.has(latest.eventType)) {\n job.state = 'failed'; job.failedAt = latest.date; job.updatedAt = new Date(now).toISOString();\n job.reason = latest.eventType; changed.push({ jobId: job.jobId, state: job.state }); continue;\n }\n const wasRegistered = job.state === 'registered';\n const maxAge = wasRegistered ? 15 * 60000 : 24 * 3600000;\n if (now - start > maxAge) {\n job.state = 'timeout'; job.timeoutAt = new Date(now).toISOString(); job.updatedAt = job.timeoutAt;\n job.reason = wasRegistered ? 'move_not_confirmed' : 'import_timeout';\n changed.push({ jobId: job.jobId, state: job.state });\n }\n}\nreturn [{ json: { ok: true, activeJobs: Object.values(jobs).filter(j => ['registered','processing'].includes(j.state)).length, changed } }];" + }, + "id": "54c60ec7-6854-4916-a4e3-9a2b7d13b503", + "name": "Reconcile Jobs", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 1120, + 520 + ] + } + ], + "connections": { + "Media Handoff API": { + "main": [ + [ + { + "node": "Handle API Request", + "type": "main", + "index": 0 + } + ] + ] + }, + "Every 2 Minutes": { + "main": [ + [ + { + "node": "History Sonarr UHD", + "type": "main", + "index": 0 + }, + { + "node": "History Sonarr FHD", + "type": "main", + "index": 0 + }, + { + "node": "History Radarr UHD", + "type": "main", + "index": 0 + }, + { + "node": "History Radarr FHD", + "type": "main", + "index": 0 + } + ] + ] + }, + "History Sonarr UHD": { + "main": [ + [ + { + "node": "Merge Sonarr", + "type": "main", + "index": 0 + } + ] + ] + }, + "History Sonarr FHD": { + "main": [ + [ + { + "node": "Merge Sonarr", + "type": "main", + "index": 1 + } + ] + ] + }, + "History Radarr UHD": { + "main": [ + [ + { + "node": "Merge Radarr", + "type": "main", + "index": 0 + } + ] + ] + }, + "History Radarr FHD": { + "main": [ + [ + { + "node": "Merge Radarr", + "type": "main", + "index": 1 + } + ] + ] + }, + "Merge Sonarr": { + "main": [ + [ + { + "node": "Merge Histories", + "type": "main", + "index": 0 + } + ] + ] + }, + "Merge Radarr": { + "main": [ + [ + { + "node": "Merge Histories", + "type": "main", + "index": 1 + } + ] + ] + }, + "Merge Histories": { + "main": [ + [ + { + "node": "Reconcile Jobs", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1", + "errorWorkflow": "AOZA96TZqhB2Dici" + } +} \ No newline at end of file -- 2.49.1