| 1 | #!/bin/sh |
| 2 | # mpd-add: fuzzy-pick a track from the MPD library and play it right away. |
| 3 | # Works in a terminal (fzf) or launched from a menu (aurora-run). |
| 4 | # |
| 5 | # Usage: mpd-add [-q] |
| 6 | # -q queue the track right after the current one, but don't jump to it |
| 7 | |
| 8 | QUEUE_ONLY=0 |
| 9 | [ "${1:-}" = "-q" ] && QUEUE_ONLY=1 |
| 10 | |
| 11 | # Notifications replace each other instead of stacking (dunst/mako/swaync). |
| 12 | notify() { # notify [-u urgency] <title> <body> |
| 13 | urgency=normal |
| 14 | if [ "$1" = "-u" ]; then urgency=$2; shift 2; fi |
| 15 | echo "$1: $2" >&2 |
| 16 | command -v notify-send >/dev/null 2>&1 || return 0 |
| 17 | notify-send -a mpd-add -u "$urgency" \ |
| 18 | -h string:x-canonical-private-synchronous:mpd-add \ |
| 19 | -h string:x-dunst-stack-tag:mpd-add \ |
| 20 | "$1" "$2" |
| 21 | } |
| 22 | |
| 23 | if ! mpc status >/dev/null 2>&1; then |
| 24 | notify -u critical "MPD unreachable" "Is mpd running?" |
| 25 | exit 1 |
| 26 | fi |
| 27 | |
| 28 | library=$(mpc listall) |
| 29 | if [ -z "$library" ]; then |
| 30 | notify -u critical "MPD library is empty" "Try: mpc update" |
| 31 | exit 1 |
| 32 | fi |
| 33 | |
| 34 | if [ -t 0 ]; then |
| 35 | filename=$(printf '%s\n' "$library" | fzf) |
| 36 | else |
| 37 | filename=$(printf '%s\n' "$library" | aurora-run -d -l 30 -p 'play: ') |
| 38 | fi |
| 39 | |
| 40 | # Cancelled (Esc): nothing to do. |
| 41 | [ -z "$filename" ] && exit 0 |
| 42 | |
| 43 | # Position of the current song (1-based); empty if nothing is playing/paused. |
| 44 | cur=$(mpc -f '%position%' current) |
| 45 | |
| 46 | if ! mpc insert "$filename" >/dev/null; then |
| 47 | notify -u critical "Couldn't add track" "$filename" |
| 48 | exit 1 |
| 49 | fi |
| 50 | |
| 51 | if [ "$QUEUE_ONLY" -eq 1 ]; then |
| 52 | notify "Queued next" "$filename" |
| 53 | exit 0 |
| 54 | fi |
| 55 | |
| 56 | # Jump straight to the song we just inserted. It lands right after the current |
| 57 | # song, or at the end of the queue when nothing is playing. Using an explicit |
| 58 | # position avoids `mpc next`, which misbehaves when stopped or paused. |
| 59 | if [ -n "$cur" ]; then |
| 60 | target=$((cur + 1)) |
| 61 | else |
| 62 | target=$(mpc playlist | wc -l) |
| 63 | fi |
| 64 | |
| 65 | if mpc play $target >/dev/null; then |
| 66 | now=$(mpc current) |
| 67 | notify "Now playing" "${now:-$filename}" |
| 68 | else |
| 69 | notify -u critical "Couldn't start playback" "$filename" |
| 70 | exit 1 |
| 71 | fi |