commit b7a62ae3affaf3f99a1d8a9cb59288d885934276
parent 2f7cbc76b62a6f8c87da9e8ca2740f9b9710a5c8
Author: Alex Balgavy <alex@balgavy.eu>
Date: Mon, 30 Aug 2021 10:56:34 +0200
import-to-music-library script
Import files in current directory to $MUSIC_DIR && run an MPD database
update && update the recently added m3u playlist.
Diffstat:
1 file changed, 60 insertions(+), 0 deletions(-)
diff --git a/scripts/import-to-music-library b/scripts/import-to-music-library
@@ -0,0 +1,60 @@
+#!/bin/sh
+die() { printf '%s\n' "$1" >&2 && exit 1; }
+checkdeps() {
+ for com in "$@"; do
+ command -v "$com" >/dev/null 2>&1 \
+ || { printf '%s required but not found.\n' "$com" >&2 && exit 1; }
+ done
+}
+checkdeps rsync mpc
+
+# Check necessary variables
+[ -z "$XDG_DATA_HOME" ] && die 'XDG_DATA_HOME not set.'
+MPD_LOGFILE="$XDG_DATA_HOME"/mpd/mpd.log
+[ -f "$MPD_LOGFILE" ] || die "$MPD_LOGFILE does not exist or is not a readable file."
+[ -z "$MUSIC_DIR" ] && die 'MUSIC_DIR not set.'
+[ -d "$MUSIC_DIR" ] || die "$MUSIC_DIR does not exist or is not a readable directory."
+
+# Sync current dir into music dir, (u)pdated only, (r)ecursively, (p)reserve
+# permissions, info about whole transfer, delete originals
+printf "Moving files into library...\n"
+rsync -urp --info=progress2 --remove-source-files ./ "$MUSIC_DIR"/
+
+# Update the database, waiting for it to finish
+printf "Updating MPD database...\n"
+mpc -w update >/dev/null 2>&1
+
+# Update the recently added playlist:
+printf "Updating recently added playlist...\n"
+
+# Create a tempdir for the files
+tempdir="$(mktemp -d)"
+trap 'rm -r "$tempdir"' INT TERM EXIT
+
+# MPD logs all additions to the library, so extract from that.
+# Sort for use in comm (1)
+tac ~/.local/share/mpd/mpd.log \
+ | awk -F 'added ' '/update: added/ { print $2 }' \
+ | sort > "$tempdir"/sorted_newly_added.log
+
+# Get the current contents of the recently added playlist, without M3U metadata
+# Sort for use in comm (1)
+grep -v '^#' "$MUSIC_DIR"/recently-added.m3u > "$tempdir"/current_recently_added.m3u
+sort "$tempdir"/current_recently_added.m3u > "$tempdir"/sorted_recently_added.m3u
+
+# Find the lines that have been logged by MPD as added but are not yet in the recently added playlist
+# via comm (1), excluding lines present only in file 2 (MPD logfile) and in both.
+# Then, add an M3U header, and concatenate with the current recently added playlist.
+# The result is: [M3U header, newly added tracks, rest of current recently added playlist]
+cat - "$tempdir"/current_recently_added.m3u \
+ > "$MUSIC_DIR"/recently-added.m3u \
+ <<PLAYLIST_END
+#EXTM3U
+#PLAYLIST:Recently Added
+$(comm -23 "$tempdir"/sorted_newly_added.log "$tempdir"/sorted_recently_added.m3u)
+PLAYLIST_END
+
+# Untrap
+trap - INT TERM EXIT
+
+printf "Done!\n"