forge
Explore
Log in

Don't you dare go Hollow

dotfiles

Clone
★ 0

0 watching0 forksShellGPL-3.0334.8 KiBb1320e9Tahinli16 days ago105 commits

playerctl_active.sh61 lines, 2.1 KiBHistoryRawDownload
1#!/bin/bash
2# Forward playerctl commands to the player the bar is showing, so clicks hit
3# what song_detail_writer.sh displays instead of the first in `playerctl -l`.
4# Target order:
5# 1. /tmp/song_detail_player (the writer's current player), if still listed
6# 2. pin file line 1 (/tmp/playerctl_pin), if still listed
7# 3. Playing player with the most recent start (/tmp/playerctl_started_*)
8# 4. Paused player with the latest activity (/tmp/playerctl_activity_*)
9#
10# Usage: playerctl_active.sh play-pause|stop|next|previous|status|metadata ...
11
12ACTIVITY_PREFIX="/tmp/playerctl_activity_"
13STARTED_PREFIX="/tmp/playerctl_started_"
14CHOSEN_FILE="/tmp/song_detail_player"
15PIN_FILE="/tmp/playerctl_pin"
16sanitize() { printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_'; }
17
18list=$(playerctl -l 2>/dev/null)
19in_list() { grep -qxF -- "$1" <<< "$list"; }
20
21chosen=""
22if [[ -s "$CHOSEN_FILE" ]]; then
23 cand=$(head -n 1 "$CHOSEN_FILE")
24 [[ -n "$cand" ]] && in_list "$cand" && chosen="$cand"
25fi
26if [[ -z "$chosen" && -f "$PIN_FILE" ]]; then
27 cand=$(head -n 1 "$PIN_FILE")
28 [[ -n "$cand" ]] && in_list "$cand" && chosen="$cand"
29fi
30
31if [[ -z "$chosen" ]]; then
32 best_playing=""
33 best_playing_ts=-1
34 fallback=""
35 fallback_ts=0
36 while IFS= read -r player; do
37 [[ -z "$player" ]] && continue
38 status=$(playerctl -p "$player" status 2>/dev/null) || continue
39 if [[ "$status" == "Playing" ]]; then
40 started=$(cat "${STARTED_PREFIX}$(sanitize "$player")" 2>/dev/null)
41 [[ "$started" =~ ^[0-9]+$ ]] || started=0
42 if (( started > best_playing_ts )); then
43 best_playing_ts="$started"
44 best_playing="$player"
45 fi
46 elif [[ "$status" == "Paused" ]]; then
47 ts=0
48 act_file="${ACTIVITY_PREFIX}$(sanitize "$player")"
49 [[ -f "$act_file" ]] && ts=$(cat "$act_file" 2>/dev/null) && [[ -z "$ts" ]] && ts=0
50 if (( ts > fallback_ts )); then
51 fallback_ts="$ts"
52 fallback="$player"
53 fi
54 fi
55 done <<< "$list"
56 chosen="${best_playing:-$fallback}"
57fi
58
59[[ -z "$chosen" ]] && exit 1
60
61exec playerctl -p "$chosen" "$@"