summaryrefslogtreecommitdiff
path: root/spotify-scrobble.sh
blob: 83b3f9f61eb1620d4526732cdf5b3d05534f0088 (plain)
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
#!/bin/sh
#
# Get currently played song from Spotify and scrobble with
# moc-scrobbler (https://github.com/pachanka/moc-scrobbler)
#

DBUS_ARGS="--print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:org.mpris.MediaPlayer2.Player"

scrobble() {
	artist=$1
	title=$2
	album=$3
	duration=$4

	moc-scrobbler --artist="$1" --track="$2" --album="$3" --duration="$4"
}

while true
do
	status=`dbus-send $DBUS_ARGS string:PlaybackStatus 2>/dev/null`
	if [ $? -gt 0 ]; then
		echo "Spotify is not running."
		exit
	fi

	if [ "`echo "$status" | tail -n1 | cut -d '"' -f 2`" != "Playing" ]; then
		# currently nothing is playing; keep checking
		sleep 5
		continue
	fi

	metadata=`dbus-send $DBUS_ARGS string:Metadata`

	artist=`echo "$metadata" | grep -A2 "\<artist\>" | tail -n1 | cut -d '"' -f 2`
	title=`echo "$metadata" | grep -A1 "\<title\>" | tail -n1 | sed 's/.*string \"\(.*\)\"$/\1/g'`
	album=`echo "$metadata" | grep -A1 "\<album\>" | tail -n1 | sed 's/.*string \"\(.*\)\"$/\1/g'`
	duration=`echo "$metadata" | grep -A1 "\<length\>" | tail -n1 | awk '{ print $3 }'`
	[ -n "$duration" ] && duration=`expr $duration / 1000000`

	if [ -z "$artist" -o -z "$title" -o -z "$album" -o -z "$duration" ]; then
		echo "Invalid data, not scrobbling. [$artist] [$title] [$album] [$duration]"
		sleep 5
		continue
	fi

	if [ "$old_artist" = "$artist" -a "$old_title" = "$title" ]; then
		# don't scrobble same song as in last iteration
		sleep 5
		continue
	fi

	scrobble "$artist" "$title" "$album" "$duration"

	old_artist=$artist
	old_title=$title
	old_album=$album
	old_duration=$duration

	sleep 5
done