{ writeShellScriptBin , coreutils , findutils , gnugrep , iproute2 , systemd }: # jellyfin-mpv-shim keeps a persistent socket to the Jellyfin server. When the # machine drops off the network that socket dies, but the process stays alive # and the unit stays "active" — running yet deaf to cast requests, the "up but # not working, restart it by hand" case. systemd can't see this: nothing # crashes and the shim speaks no health protocol, so we probe the real thing — # is its MainPID still holding a live (established, non-loopback) connection? # # check (default) one tick, run by a 60s timer: restart if online but # not connected, rate-limited to one restart per 5 min # wait-online block until a real address exists; used as ExecStartPre so the # unit only starts once online writeShellScriptBin "jellyfin-mpv-shim-watchdog" '' set -u service="jellyfin-mpv-shim.service" stamp="''${XDG_RUNTIME_DIR:-/run/user/$(${coreutils}/bin/id -u)}/jellyfin-mpv-shim-watchdog.stamp" # A global-scope address on a non-loopback interface — true for a LAN IP too, # so this needs no server URL and works whether Jellyfin is local or remote. network_up() { ${iproute2}/bin/ip -o addr show scope global up 2>/dev/null | ${gnugrep}/bin/grep -q .; } if [ "''${1:-check}" = wait-online ]; then while ! network_up; do ${coreutils}/bin/sleep 5; done exit 0 fi # Healthy: MainPID owns an established socket to something other than loopback. pid="$(${systemd}/bin/systemctl --user show -p MainPID --value "$service" 2>/dev/null)" if [ "''${pid:-0}" != 0 ] && ${iproute2}/bin/ss -tnpH state established 2>/dev/null \ | ${gnugrep}/bin/grep "pid=$pid," \ | ${gnugrep}/bin/grep -qv -e '127\.0\.0\.1' -e '\[::1\]'; then exit 0 fi # Not connected: only worth restarting once the network is actually back... network_up || exit 0 # ...and not if we already restarted within the last 5 minutes. [ -e "$stamp" ] && [ -n "$(${findutils}/bin/find "$stamp" -mmin -5 2>/dev/null)" ] && exit 0 : > "$stamp" echo "jellyfin-mpv-shim-watchdog: online but no live connection -> restarting $service" ${systemd}/bin/systemctl --user restart "$service" ''