Script to submit TSV from Rockbox lastfm_scrobbler

This script takes a TSV file as generated by the Rockbox lastfm_scrobbler as its only argument, and submits the listening data to ListenBrainz.

There’s currently an issue with lastfm_scrobbler where the timezone is 10hrs in the future so I’ve added a workaround for that.

The script assumes tracks are already tagged with MBID. The script also wipes the scrobble file clean, so use at your own risk.

#!/bin/sh

api_host=https://api.listenbrainz.org
api_path=/1/submit-listens
api_url="$api_host$api_path"
token=$(cat $HOME/.keys/listenbrainz)
tz_offset=$(date +%z)

# print_json_payload(time, artist, album, title, mbid)
# returns: JSON
print_json_single() {
	cat <<EOF
{
	"listened_at": "$1",
	"track_metadata": {
		"artist_name": "$2",
		"release_name": "$3",
		"track_name": "$4",
		"additional_info": {
			"recording_mbid": "$5",
			"media_player": "rockbox",
			"submission_client": "scrobble_tsv",
			"submission_client_version": "0.1.0"
		}
	}
},
EOF
}

# print_json(paylod)
# returns: JSON
print_json() {
	cat <<EOF
{
	"listen_type": "import",
	"payload": [
		$(cat)
	]
}
EOF
}

scrobble() {
	curl -sX POST \
		 -H "Authorization: Token $token" \
		 -H "Content-Type: application/json" \
		 -d "@-" \
		 "$api_url" >> $HOME/.cache/scrobble_tsv.log
}

# main(file)
main() {
	file=$(readlink -f "$1")
	[ -f "$file" ] || exit 1

	sed '/^#/d' < "$file" | while read -r row; do
		echo "$row" | while IFS='	' read -r artist album title tracknum \
							   length rating time mbid; do
			if [ -n "$mbid" ]; then
				offset=$(( 60 * 60 * tz_offset * -1 / 100 ))
				time=$(( time + offset ))
				print_json_single "$time" "$artist" "$album" "$title" "$mbid"
			fi
		done
	done | sed '$ s/,$//' | print_json | scrobble

	cp "$file" "$file~"
	grep ^# < "$file~" > "$file"
}

main "$@"
1 Like