-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshellsonic
More file actions
executable file
·317 lines (277 loc) · 10.6 KB
/
Copy pathshellsonic
File metadata and controls
executable file
·317 lines (277 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/bin/sh
#######
# UI #
#######
help() {
case $1 in
search*)
name="search_play"
args='"search_query"'
description="this function first searches the $args, then opens the menu(fzf,[d|be]menu,[t|r|w]ofi) with the results,then calls the play function to play the music"
;;
loop)
name="loop"
args='"print"'
description="this function runs in a loop to play the next music if the current music is successfully finished
this function should be put as background process
passing print argument will show the progress to stdout"
;;
play*)
name="play_next"
args='"menu"'
description="immediately plays the next song stored in $tmpdir/next file in mpv if argument is empty
passing $args argument will show the $args(fzf,[d|be]menu,[t|r|w]ofi) for selecting what should be played"
;;
*)
name="[ <function_name> ]"
args="[ <function_arg> ]"
description="
<function_name> <function_arg> <function_description>
search_play search_query searches first then plays the music in mpv
play_next menu(optional) plays the next music in $tmpdir/next file
loop print(optional) plays the next music after the current is finished (run it as background process)
tip:
type ${0##*/} help <function_name> to get individual help
"
;;
esac
while read -r line; do
printf "%s\n" "$line"
done <<-EOF
Usage :
${0##*/} $name $args
Description :
$description
EOF
exit 0
}
info() {
#shellcheck disable=SC2059
printf "\033[2K\r\033[1;${2:-36}m${1}\033[0m"
}
success() {
info "$1" "32"
}
ask() {
info "$1" "33"
}
err() {
info "$1\n" "31"
}
menu() {
if command -v bemenu >/dev/null; then
bemenu -R 20 $3 --accept-single --fn 'IBM Plex Sans 15' -i -c -W 0.5 -B 2 -p "$1" -l 26 -I "${2:-0}" -P ">>" --bdr="#$GLOBAL_ACCENT" --tf="#$GLOBAL_ACCENT" --hf="#$GLOBAL_ACCENT"
else
fzf --prompt="$1" --height=25 --reverse --border=horizontal --header="${2:-0}" --marker=">>"
fi
}
cleanup_shit() {
pgrep -f "$socket" >/dev/null && pkill -f "$socket"
rm -rdf "$tmpdir"
exit 0
}
##########
# CONFIG #
##########
# create/update the variable value
save_config() {
grep -q "^$1=" "$config_file" && sed -i "s|$1=.*|$1=$2|g" "$config_file" >/dev/null 2>&1 || printf "%s=%s\n" "$1" "$2" >>"$config_file"
[ -z "$3" ] && success "$1 Saved in config, to override config values pass it as environment variable\n"
}
# checks the variable existance, if it's filled
# if either or both are false, it ask the user to submit them.
ensure_config() {
grep -qE "$1=(.+)" "$config_file" && return 0
ask "$2"
read -r query
save_config "$1" "$query"
unset query
}
# checks the config, does the auth and check if config is correct
# if not, then present the user to re-configure it.
setup() {
info "Checking Config.."
[ -f "$config_file" ] || : >"$config_file"
ensure_config "SS_URL" "Where is Subsonic Server hosted? : "
ensure_config "SS_USER" "Please type the username : "
ensure_config "SS_PASS" "Please type the password : "
# shellcheck source=/dev/null
. "$config_file"
info "Checking Auth..."
case "$(subsonic_api "getUser" "username=$SS_USER")" in
*'"status":"ok"'*)
info ""
return 0
;;
*'"code":40'* | *'"message":"Wrong username or password"'*)
err "Wrong username or password."
save_config "SS_USER" "" "noprint"
save_config "SS_PASS" "" "noprint"
unset SS_USER SS_PASS
exit 1
;;
*)
err "Unable to connect to server."
exit 1
;;
esac
}
###########
# NETWORK #
###########
# generates a random token with salt to maximize security.
prepare_token() {
SALT="$(tr -dc '[:alnum:]' </dev/urandom | head -c16)"
TOKEN="$(printf '%s%s' "$SS_PASS" "$SALT" | md5sum | cut -d' ' -f1)"
}
# all the api calls are done by this function
subsonic_api() {
prepare_token
curl -s -A "$AGENT" "$SS_URL/rest/${1}?u=$SS_USER&t=$TOKEN&s=$SALT&v=$API_VERSION&c=${0##*/}&f=json&${2}" -G
}
# fetches the track list and present it in usable format for code
get_list() {
subsonic_api "$1" "$2" | sed 's/movements/\n/g' | sed -nE 's|.*\{"id":"([^"]*)",.*"title":"([^"]*)","album":".*","artist":"([^"]*)".*"coverArt":"([^"]*)",.*|\2 BY \3\t\1\t\4|p' | sed "s/\\\u0026/and/g;s/'/-/g;/^$/d"
}
# get next songs basec on current song, to make a playlist to continue playing.
get_music_list() {
artist_id=$(subsonic_api "getSong" "id=$1" | sed -nE 's|.*"artistId":"([^"]*)",.*|\1|p')
similarsongs2=$(get_list "getSimilarSongs2" "id=$artist_id&count=25")
#shellcheck disable=SC1091,SC2094
[ -n "$similarsongs2" ] && printf '%s\n' "$similarsongs2" | sed -e "$(cut -f2 "$tmpdir/next" | sed 's|^|/|g;s|$|/d|g')" >>"$tmpdir/next"
similarsongs=$(get_list "getSimilarSongs" "id=$1&count=25")
#shellcheck disable=SC1091,SC2094
[ -n "$similarsongs" ] && printf '%s\n' "$similarsongs" | sed -e "$(cut -f2 "$tmpdir/next" | sed 's|^|/|g;s|$|/d|g')" >>"$tmpdir/next"
#shellcheck disable=SC1091,SC2094
[ -z "$similarsongs" ] && [ -z "$similarsongs2" ] && get_list "getRandomSongs" "count=25" | sed -e "$(cut -f2 "$tmpdir/next" | sed 's|^|/|g;s|$|/d|g')" >>"$tmpdir/next"
}
get_lyrics() {
subsonic_api "getLyricsBySongId" "id=$1" | sed 's|[\{\}]|\n|g' | sed -nE 's|.*"start":([0-9]*),"value":"(.*)"$|\1\t\2|p' | sed 's/\(\(\w\+\W\+\)\{10\}\)/\1\\n/g' >"$tmpdir/lyrics"
}
#############
# FUNCTIONS #
#############
#this function does exactly what it says, it should run in the background
#it plays next song after the current song get played completely
#it does nothing until u run the search_play function for first track and then this code kicks in
loop() {
trap cleanup_shit INT HUP TERM
socat -U - "UNIX-CONNECT:$socket" | while read -r event; do
#look for eof event
if printf "%s" "$event" | grep -q "end-file.*eof"; then
i=$(cat "$tmpdir/counter")
: $((i += 1))
subsonic_api "scrobble" "submission=true&id=$(sed -nE 's/^ID="([^"]*)"/\1/p' "$tmpdir/current")"
pgrep -f "$socket" >/dev/null || continue
next=$(sed -n "${i}p" "$tmpdir/next")
[ -z "$next" ] && break
play "$next" "$1"
printf '%s' "$i" >"$tmpdir/counter"
[ -f "$tmpdir/playlist-mode" ] && continue
currentsongID=$(printf '%s' "$next" | cut -f2)
[ -n "$currentsongID" ] && tail -1 "$tmpdir/next" | grep -q "$currentsongID" && get_music_list "$currentsongID"
fi
done
cleanup_shit
}
#run this if u want to listen to songs and start playlist
#call this by script-name search_play [ search_query ]
search_play() {
[ -z "$1" ] && query=$(: | menu "SS-music [Search]:") || query="$1"
[ -z "$query" ] && notify-send -e "Err.. Search query empty" -u critical -h "string:x-canonical-private-synchronous:${0##*/}" && return 1
case "$query" in
playlist)
playlist=$(subsonic_api "getPlaylists" | sed 's/readonly/\n/g' | sed -nE 's|.*"id":"([^"]*)","name":"([^"]*)","songCount":([0-9]*),.*|\2 (\3)\t\1|p' | menu "SS-music [Playlist]:" "" "--ifne")
[ -z "$playlist" ] && notify-send -e "Err.. No playlist selected" -u critical -h "string:x-canonical-private-synchronous:${0##*/}" && return 1
playlist_id=$(printf '%s' "$playlist" | cut -f2)
playlist_name=$(printf '%s' "$playlist" | cut -f1)
playlist_data=$(get_list "getPlaylist" "id=$playlist_id&size=-1" | shuf | tee "$tmpdir/next")
[ -z "$playlist_data" ] && notify-send -e "Err.. Playlist $playlist_name empty" -u critical -h "string:x-canonical-private-synchronous:${0##*/}" && return 1
song=$(printf '%s' "$playlist_data" | head -1)
[ -z "$song" ] && return 1
play "$song" "verbose"
touch "$tmpdir/playlist-mode"
;;
*)
song=$(get_list "search3" "query=$(printf '%s' "$query" | tr ' ' '+')" | menu "SS-music [Play]:" "" "--ifne")
[ -z "$song" ] && return 1
printf "%s\n" "$song" >"$tmpdir/next"
play "$song" "verbose" "1"
rm -f "$tmpdir/playlist-mode"
;;
esac
printf "1" >"$tmpdir/counter"
pgrep -f "${0##*/} loop" >/dev/null || setsid -f "$0" loop
}
#this function does all the heavy lifting
#it uses the track id to generate stream url and pass to mpv
#then generates playlist, fetches lyrics, scrobble now-playing the current track
play() {
title=$(printf '%s' "$1" | cut -f1)
id=$(printf '%s' "$1" | cut -f2)
coverId=$(printf '%s' "$1" | cut -f3)
[ -z "$id" ] && err "[ opensubsonic ] Invalid Id" && exit 1
prepare_token
stream_url="$SS_URL/rest/stream?id=$id&u=$SS_USER&t=$TOKEN&s=$SALT&v=$API_VERSION&c=${0##*/}"
[ -n "$2" ] && success "Playing $title on mpv\n"
curl -s "$SS_URL/rest/getCoverArt?id=$coverId&u=$SS_USER&t=$TOKEN&s=$SALT&v=$API_VERSION&c=${0##*/}&size=300" -o "$tmpdir/default.jpg" && notify-send -e -h "string:x-canonical-private-synchronous:${0##*/}" -i "$tmpdir/default.jpg" "Now Playing" "$title" -t 5000
pgrep -f "$socket" >/dev/null || setsid -f mpv --really-quiet --input-ipc-server="$socket" --idle --quiet --no-audio-display >/dev/null
while [ ! -S "$socket" ]; do sleep 1; done
printf '{"command":["loadfile","%s","replace"]}\n' "$stream_url" | socat -u - "$socket"
song_title="${title%% BY *}"
artist="${title#* BY }"
printf 'SONG="%s"\nARTIST="%s"\nID="%s"' "$song_title" "$artist" "$id" >"$tmpdir/current"
# run complementary functions to make listening more fun...
get_lyrics "$id" &
[ -n "$3" ] && get_music_list "$id" &
subsonic_api "scrobble" "id=$id&submission=false" &
}
#call this by script-name "play_next" for playing next song immediately
#or add "menu" after "play_next" to show menu for selecting and playing next song immediately
#like this script-name "play_next" "menu"
play_next() {
pgrep -f "$socket" || return 0
i=$(cat "$tmpdir/counter")
if [ -z "$1" ]; then
: $((i += 1))
play "$(sed -n "${i}p" "$tmpdir/next")"
else
#shellcheck source=/dev/null
#shellcheck disable=SC1091
[ -f "$tmpdir/current" ] && . "$tmpdir/current"
notify-send -e -h "string:x-canonical-private-synchronous:${0##*/}" -i "$tmpdir/default.jpg" "Listening @ $(basename "$0")" "$SONG BY $ARTIST"
next=$(nl -n'ln' "$tmpdir/next" | sed "s/^$i /*& /" | menu "SS-music [play-next]: " "$((i - 1))")
[ -z "$next" ] && return 0
i=$(printf '%s' "$next" | sed 's/^*//g' | cut -f1 | tr -d ' ')
play "$(printf '%s' "$next" | cut -f2-)" "verbose"
fi
printf '%s' "$i" >"$tmpdir/counter"
currentsongID=$(sed -nE 's/^ID="([^"]*)"/\1/p' "$tmpdir/current")
[ -n "$currentsongID" ] && tail -1 "$tmpdir/next" | grep -q "$currentsongID" && get_music_list "$currentsongID"
}
#############
# VARIABLES #
#############
API_VERSION="1.16.1"
AGENT="${0##*/} 1.0.1"
tmpdir="/tmp/${0##*/}"
socket="$tmpdir/${0##*/}-mpvsocket"
config_file="${XDG_STATE_HOME:-$HOME/.local/state}/${0##*/}-config"
########
# MAIN #
########
if [ -z "$1" ] || [ "$1" = "help" ]; then
help "$2"
fi
setup
mkdir -p "$tmpdir"
case "$1" in
search_play) search_play "$2" "$3" ;;
play_next) play_next "$2" ;;
play) play "$2" ;;
loop) loop "$2" ;;
*)
err "Function does not exist!"
help
;;
esac