#!/bin/bash # Media picker (rofi): choose which MPRIS player the waybar music module follows. # Auto (no pin file) follows the latest player; picking a player writes # /tmp/playerctl_pin (line 1 bus name, 2 url host, 3 base name, 4 timestamp). # Bound to middle-click on custom/music. PIN=/tmp/playerctl_pin notify() { notify-send "$@" 2>/dev/null || true } # host of an http(s) url, empty otherwise host_of() { local url=$1 [[ $url =~ ^https?:// ]] || return 0 sed -E 's#^[a-z]+://([^/]+).*#\1#' <<<"$url" } # --- collect players ---------------------------------------------------------- players=() while IFS= read -r p; do [[ -n $p ]] && players+=("$p") done < <(playerctl -l 2>/dev/null) if (( ${#players[@]} == 0 )); then notify "No media players" exit 0 fi pinned="" if [[ -f $PIN ]]; then pinned=$(sed -n 1p "$PIN" 2>/dev/null) fi # parallel arrays, index-aligned with players[] titles=() labels=() places=() entries=() if [[ -z $pinned ]]; then entries+=("📌 Auto (follow latest)") else entries+=("Auto (follow latest)") fi for p in "${players[@]}"; do status=$(playerctl -p "$p" status 2>/dev/null) artist=$(playerctl -p "$p" metadata artist 2>/dev/null) title=$(playerctl -p "$p" metadata title 2>/dev/null) url=$(playerctl -p "$p" metadata xesam:url 2>/dev/null) case "$status" in Playing) icon="▶" ;; Paused) icon="⏸" ;; *) icon="⏹" ;; esac if [[ -n $artist && -n $title ]]; then label="$artist - $title" elif [[ -n $title ]]; then label=$title else label="(no title)" fi host=$(host_of "$url") base=${p%%.*} place=${host:-$base} titles+=("${title:-(no title)}") labels+=("$label") places+=("$place") prefix="" [[ $p == "$pinned" ]] && prefix="📌 " entries+=("${prefix}${icon} ${label} — ${place} [${p}]") done # --- menu ------------------------------------------------------------------- idx=$(printf '%s\n' "${entries[@]}" | rofi -dmenu -i -p "Media" -format i) [[ -z $idx ]] && exit 0 [[ $idx =~ ^[0-9]+$ ]] || exit 0 if (( idx == 0 )); then rm -f "$PIN" notify "Media: auto" exit 0 fi (( idx <= ${#players[@]} )) || exit 0 i=$((idx - 1)) player=${players[i]} tmp=$(mktemp /tmp/playerctl_pin.XXXXXX) || exit 1 host=$(host_of "$(playerctl -p "$player" metadata xesam:url 2>/dev/null)") printf '%s\n%s\n%s\n%s\n' "$player" "$host" "${player%%.*}" "$(date +%s)" > "$tmp" mv -f "$tmp" "$PIN" notify "Media pinned" "${titles[i]} — ${places[i]}"