#!/bin/bash
# Never let Plex background analysis (loudness, analyze/deep analysis, chapter thumbs, intro/credits) run while someone is playing.
# Installed in the `plex` LXD container as /usr/sbin/plex-playback-guard (package ctg-plex-guard), run every minute by /etc/cron.d/plex-playback-guard
# Killed jobs are retried by Plex in its next Butler window (see README.md).
P="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"
TOKEN=$(grep -o 'PlexOnlineToken="[^"]*' "$P" | cut -d'"' -f2)
PAT='Plex Transcoder.*loudnorm|Plex Media Scanner.*(--analyze|--generate|--credits|--intro|--chapter)'
pgrep -f "$PAT" >/dev/null || exit 0
N=$(curl -s -m 5 -H "X-Plex-Token: $TOKEN" -H Accept:application/json http://127.0.0.1:32400/status/sessions | python3 -c 'import sys,json;print(len([m for m in json.load(sys.stdin)["MediaContainer"].get("Metadata",[]) if m["Player"]["state"] in ("playing","buffering")]))' 2>/dev/null)
[ "${N:-0}" -gt 0 ] || exit 0
curl -s -m 5 -X DELETE -H "X-Plex-Token: $TOKEN" http://127.0.0.1:32400/butler >/dev/null
pkill -TERM -f "$PAT"
echo "$(date -u +%FT%TZ) playback active ($N): stopped butler + analysis jobs" >> /var/log/plex-playback-guard.log
