diff --git a/Media/upgrade_webhook_handler.sh b/Media/upgrade_webhook_handler.sh new file mode 100755 index 0000000..241acf9 --- /dev/null +++ b/Media/upgrade_webhook_handler.sh @@ -0,0 +1,134 @@ +#!/bin/bash +# ============================================================================================== +# ========================= Upgrade Webhook Handler ============================================ +# ============================================================================================== +# +# PURPOSE +# ───────────────────────────────────────────────────────────────────────────── +# Triggered by Sonarr/Radarr/Lidarr OnUpgrade webhook (via webhook.php). +# Pushes the upgraded item folder to every other mesh node immediately, then +# triggers a library rescan on each remote arr so it accepts the new file as +# ground truth without initiating a redundant quality search. +# +# Closes the propagation window: without this, a remote node that already has +# the 720p copy will see the 1080p tagged in arr_sync but not on disk and +# begin searching — a search it will never win because we already have it. +# +# ============================================================================================== +# USAGE +# ============================================================================================== +# +# upgrade_webhook_handler.sh +# +# arr_type — sonarr | radarr | lidarr +# item_path — absolute path to the series/movie/artist folder on local disk +# (series.path from Sonarr, movie.folderPath from Radarr, +# artist.path from Lidarr) +# +# Called by webhook.php — not intended for direct invocation outside testing. +# +# ============================================================================================== + +set -uo pipefail + +ARR_TYPE="${1:-}" +ITEM_PATH="${2:-}" + +[[ -z "$ARR_TYPE" || -z "$ITEM_PATH" ]] && { + echo "Usage: upgrade_webhook_handler.sh " >&2 + exit 1 +} + +[[ -d "$ITEM_PATH" ]] || { echo "Path not found: $ITEM_PATH" >&2; exit 1; } + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/../load_config.sh" +detect_hosts + +# ── Arr type → API port / version / rescan command ─────────────────────────────────────────── +case "$ARR_TYPE" in + sonarr) PORT=8989; API_VER="v3"; RESCAN_CMD="RefreshSeries" ;; + radarr) PORT=7878; API_VER="v3"; RESCAN_CMD="RefreshMovie" ;; + lidarr) PORT=8686; API_VER="v1"; RESCAN_CMD="RefreshArtist" ;; + *) echo "Unknown arr type: $ARR_TYPE" >&2; exit 1 ;; +esac + +# ── Remote node list ────────────────────────────────────────────────────────────────────────── +declare -a REMOTE_NODES=() +for _hv in HOST1 HOST2 HOST3 HOST4 HOST5 HOST6 HOST7 HOST8; do + [[ "$_hv" == "$MY_ID" ]] && continue + [[ -z "${!_hv:-}" ]] && continue + REMOTE_NODES+=("$_hv") +done +unset _hv + +if [[ "${#REMOTE_NODES[@]}" -eq 0 ]]; then + echo "No remote nodes configured — nothing to push" + exit 0 +fi + +ENCODED=$(printf '{"name":"%s"}' "$RESCAN_CMD" | base64 -w0) +ITEM_NAME=$(basename "$ITEM_PATH") + +echo "[$(date '+%H:%M:%S')] Upgrade push: ${ARR_TYPE} — ${ITEM_NAME}" +echo " Path: $ITEM_PATH" +echo " Targets: ${REMOTE_NODES[*]}" + +# ── Push and rescan each remote ─────────────────────────────────────────────────────────────── +for node_id in "${REMOTE_NODES[@]}"; do + node_name="${!node_id}" + node_ip=$(resolve_tailscale_ip "$node_name") || { + echo " [${node_name}] Cannot resolve Tailscale IP — skipping" + continue + } + + # ── Targeted rsync — push only this item, no delete ────────────────────────────────────── + echo " [${node_name}] rsync ${ITEM_NAME}..." + rsync_out=$(rsync -av --no-delete \ + -e "ssh -i $SSH_KEY -T -o Compression=no -o IPQoS=throughput -o StrictHostKeyChecking=no" \ + "${ITEM_PATH}/" \ + "root@${node_ip}:${ITEM_PATH}/" 2>&1) + rsync_exit=$? + transferred=$(echo "$rsync_out" | awk '/Total transferred file size:/{gsub(/,/,"",$NF); gsub(/[^0-9]/,"",$NF); print $NF+0}') + + if [[ "$rsync_exit" -ne 0 ]]; then + echo " [${node_name}] rsync failed (exit ${rsync_exit}) — skipping rescan" + continue + fi + echo " [${node_name}] rsync done (${transferred:-0} bytes)" + + # ── Trigger arr rescan on remote — cache-first, SSH fallback ───────────────────────────── + _kvar="${node_id}_${ARR_TYPE^^}_API_KEY" + cached_key="${!_kvar:-}" + + if [[ -n "$cached_key" ]]; then + body=$(printf '%s' "$ENCODED" | base64 -d) + http_code=$(curl -sf -o /dev/null -w '%{http_code}' -X POST \ + -H "X-Api-Key: $cached_key" \ + -H "Content-Type: application/json" \ + -d "$body" \ + "http://${node_ip}:${PORT}/api/${API_VER}/command" 2>/dev/null) + else + config_xml="${DOCKER_APPDATA_BASE}/${ARR_TYPE^}/config.xml" + http_code=$(ssh -i "$SSH_KEY" -o ConnectTimeout="$ARR_SYNC_CONNECT_TIMEOUT" \ + root@"$node_ip" bash </dev/null +KEY=\$(grep -oP '(?<=)[^<]+' '${config_xml}' 2>/dev/null) +[[ -z "\$KEY" ]] && exit 1 +BODY=\$(printf '%s' '${ENCODED}' | base64 -d) +curl -sf -o /dev/null -w '%{http_code}' -X POST \ + -H "X-Api-Key: \$KEY" \ + -H 'Content-Type: application/json' \ + -d "\$BODY" \ + "http://localhost:${PORT}/api/${API_VER}/command" +REMOTE + ) + fi + + if [[ "$http_code" == "201" || "$http_code" == "200" ]]; then + echo " [${node_name}] ${RESCAN_CMD} triggered ✅" + else + echo " [${node_name}] ${RESCAN_CMD} failed (HTTP ${http_code:-timeout})" + fi +done + +echo "[$(date '+%H:%M:%S')] Done — ${ITEM_NAME}" diff --git a/Plugin/unraid/api/webhook.php b/Plugin/unraid/api/webhook.php new file mode 100644 index 0000000..e590008 --- /dev/null +++ b/Plugin/unraid/api/webhook.php @@ -0,0 +1,76 @@ + false, 'error' => 'POST only']); + exit; +} + +$payload = json_decode(file_get_contents('php://input'), true); +if (!$payload) { + http_response_code(400); + echo json_encode(['ok' => false, 'error' => 'Invalid JSON']); + exit; +} + +$event = $payload['eventType'] ?? ''; + +if ($event === 'Test') { + echo json_encode(['ok' => true, 'message' => 'Webhook connected — configure On Upgrade to use this URL']); + exit; +} + +// Sonarr/Radarr/Lidarr fire eventType "Download" with isUpgrade=true for upgrades. +// A plain Download (no upgrade) is not our concern — the original quality is fine. +$is_upgrade = $payload['isUpgrade'] ?? false; +if ($event !== 'Download' || !$is_upgrade) { + echo json_encode(['ok' => true, 'skipped' => $event]); + exit; +} + +// Detect arr type and item folder from payload structure +if (isset($payload['series']['path'])) { + $arr_type = 'sonarr'; + $path = $payload['series']['path']; +} elseif (isset($payload['movie']['folderPath'])) { + $arr_type = 'radarr'; + $path = $payload['movie']['folderPath']; +} elseif (isset($payload['artist']['path'])) { + $arr_type = 'lidarr'; + $path = $payload['artist']['path']; +} else { + http_response_code(400); + echo json_encode(['ok' => false, 'error' => 'Unrecognised payload structure']); + exit; +} + +if (!$path) { + http_response_code(400); + echo json_encode(['ok' => false, 'error' => 'Empty path in payload']); + exit; +} + +// Basic path sanity — must be absolute, no traversal +if (!str_starts_with($path, '/') || str_contains($path, '..') || preg_match('/[\x00\n\r]/', $path)) { + http_response_code(400); + echo json_encode(['ok' => false, 'error' => 'Unsafe path']); + exit; +} + +$handler = SCRIPTS_DIR . '/Media/upgrade_webhook_handler.sh'; +if (!file_exists($handler)) { + http_response_code(500); + echo json_encode(['ok' => false, 'error' => 'upgrade_webhook_handler.sh not found']); + exit; +} + +exec('bash ' . escapeshellarg($handler) + . ' ' . escapeshellarg($arr_type) + . ' ' . escapeshellarg($path) + . ' >> /var/log/varaverk/upgrade_webhook.log 2>&1 &'); + +echo json_encode(['ok' => true, 'arr' => $arr_type, 'path' => $path]);