#!/bin/bash # Forward playerctl commands to the player the bar is showing, so clicks hit # what song_detail_writer.sh displays instead of the first in `playerctl -l`. # Target order: # 1. /tmp/song_detail_player (the writer's current player), if still listed # 2. pin file line 1 (/tmp/playerctl_pin), if still listed # 3. Playing player with the most recent start (/tmp/playerctl_started_*) # 4. Paused player with the latest activity (/tmp/playerctl_activity_*) # # Usage: playerctl_active.sh play-pause|stop|next|previous|status|metadata ... ACTIVITY_PREFIX="/tmp/playerctl_activity_" STARTED_PREFIX="/tmp/playerctl_started_" CHOSEN_FILE="/tmp/song_detail_player" PIN_FILE="/tmp/playerctl_pin" sanitize() { printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_'; } list=$(playerctl -l 2>/dev/null) in_list() { grep -qxF -- "$1" <<< "$list"; } chosen="" if [[ -s "$CHOSEN_FILE" ]]; then cand=$(head -n 1 "$CHOSEN_FILE") [[ -n "$cand" ]] && in_list "$cand" && chosen="$cand" fi if [[ -z "$chosen" && -f "$PIN_FILE" ]]; then cand=$(head -n 1 "$PIN_FILE") [[ -n "$cand" ]] && in_list "$cand" && chosen="$cand" fi if [[ -z "$chosen" ]]; then best_playing="" best_playing_ts=-1 fallback="" fallback_ts=0 while IFS= read -r player; do [[ -z "$player" ]] && continue status=$(playerctl -p "$player" status 2>/dev/null) || continue if [[ "$status" == "Playing" ]]; then started=$(cat "${STARTED_PREFIX}$(sanitize "$player")" 2>/dev/null) [[ "$started" =~ ^[0-9]+$ ]] || started=0 if (( started > best_playing_ts )); then best_playing_ts="$started" best_playing="$player" fi elif [[ "$status" == "Paused" ]]; then ts=0 act_file="${ACTIVITY_PREFIX}$(sanitize "$player")" [[ -f "$act_file" ]] && ts=$(cat "$act_file" 2>/dev/null) && [[ -z "$ts" ]] && ts=0 if (( ts > fallback_ts )); then fallback_ts="$ts" fallback="$player" fi fi done <<< "$list" chosen="${best_playing:-$fallback}" fi [[ -z "$chosen" ]] && exit 1 exec playerctl -p "$chosen" "$@"