import-to-music-library (2443B)
1 #!/bin/sh 2 # Meant to be used with mpd and mpc. 3 # Import everything in the current folder to $MUSIC_DIR. Then update the 4 # recently added playlist in $MUSIC_DIR, and run an mpd database update. 5 die() { printf '%s\n' "$1" >&2 && exit 1; } 6 checkdeps() { 7 for com in "$@"; do 8 command -v "$com" >/dev/null 2>&1 \ 9 || { printf '%s required but not found.\n' "$com" >&2 && exit 1; } 10 done 11 } 12 checkdeps rsync mpc 13 14 # Check necessary variables 15 [ -z "$XDG_DATA_HOME" ] && die 'XDG_DATA_HOME not set.' 16 MPD_LOGFILE="$XDG_DATA_HOME"/mpd/mpd.log 17 [ -f "$MPD_LOGFILE" ] || die "$MPD_LOGFILE does not exist or is not a readable file." 18 [ -z "$MUSIC_DIR" ] && die 'MUSIC_DIR not set.' 19 [ -d "$MUSIC_DIR" ] || die "$MUSIC_DIR does not exist or is not a readable directory." 20 21 # Sync current dir into music dir, (u)pdated only, (r)ecursively, (p)reserve 22 # permissions, info about whole transfer, delete originals 23 printf "Moving files into library...\n" 24 rsync -urp --info=progress2 --remove-source-files ./ "$MUSIC_DIR"/ 25 26 # Update the database, waiting for it to finish 27 printf "Updating MPD database...\n" 28 mpc -w update >/dev/null 2>&1 29 30 # Update the recently added playlist: 31 printf "Updating recently added playlist...\n" 32 33 # Create a tempdir for the files 34 tempdir="$(mktemp -d)" 35 trap 'rm -r "$tempdir"' INT TERM EXIT 36 37 # MPD logs all additions to the library, so extract from that. 38 # Sort for use in comm (1) 39 tac ~/.local/share/mpd/mpd.log \ 40 | awk -F 'added ' '/update: added/ { print $2 }' \ 41 | sort > "$tempdir"/sorted_newly_added.log 42 43 # Get the current contents of the recently added playlist, without M3U metadata 44 # Sort for use in comm (1) 45 grep -v '^#' "$MUSIC_DIR"/recently-added.m3u > "$tempdir"/current_recently_added.m3u 46 sort "$tempdir"/current_recently_added.m3u > "$tempdir"/sorted_recently_added.m3u 47 48 # Find the lines that have been logged by MPD as added but are not yet in the recently added playlist 49 # via comm (1), excluding lines present only in file 2 (MPD logfile) and in both. 50 # Then, add an M3U header, and concatenate with the current recently added playlist. 51 # The result is: [M3U header, newly added tracks, rest of current recently added playlist] 52 cat - "$tempdir"/current_recently_added.m3u \ 53 > "$MUSIC_DIR"/recently-added.m3u \ 54 <<PLAYLIST_END 55 #EXTM3U 56 #PLAYLIST:Recently Added 57 $(comm -23 "$tempdir"/sorted_newly_added.log "$tempdir"/sorted_recently_added.m3u) 58 PLAYLIST_END 59 60 # Untrap 61 trap - INT TERM EXIT 62 63 printf "Done!\n"