aboutsummaryrefslogtreecommitdiff
path: root/music/import.sh
blob: 2d5f5e528bb841939a05bff31bfb40c374ec237c (plain) (blame)
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
#!/bin/sh

set -eu -o pipefail

MUSIC_DIR=/nfs/media/music
MP3_BITRATE=320k

# Searches the given argument paths for .flac files, and copies them to
# $MUSIC_DIR with the follow hierarchy:
#
#   flac/${artist}/${album}/${tracknum} ${trackname}.flac
#
# It also transcodes the FLACs to MP3s and stores them in a similar way:
#
#   mp3/${artist}/${album}/${tracknum} ${trackname}.flac
#
# The metadata is taken from the id3 tags in the flac file, santized to contain
# only ASCII characters.

sanitize(){
  echo "$1" | tr -Cd 'A-Za-z0-9 _-'
}

if [ $# -ne 0 ] ; then
  echo 'usage: import.sh PATH...' 1>&2
  exit 1
fi

find "$@" -iname '*.flac' -type f -print | while read -r file; do
  track=$(exiftool -s3 -TrackNumber "$file")
  title=$(exiftool -s3 -Title "$file")
  album=$(exiftool -s3 -Album "$file")
  artist=$(exiftool -s3 -AlbumArtist "$file")
  artist=${artist:-$(exiftool -s3 -Artist "$file")}

  if [ -z "$artist" ]; then
    echo "$file has no artist metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$album" ]; then
    echo "$file has no album metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$title" ]; then
    echo "$file has no title metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$track" ]; then
    echo "$file has no track metadata, skipping" 1>&2
    continue
  fi

  subpath="$(sanitize "$artist")/$(sanitize "$album")"
  basename="$(printf '%03d' "$(expr "$track" + 0)") $(sanitize "$title")"

  # flac
  mkdir -p "${MUSIC_DIR}/flac/${subpath}"

  cp "$file" "${MUSIC_DIR}/flac/${subpath}/${basename}.flac"
  echo "flac :: $artist / $album / $title"

  if ! [ -f "${MUSIC_DIR}/flac/${subpath}/folder.jpg" ]; then
    ffmpeg -y -nostdin -loglevel error -i "$file" -an -c:v copy "${MUSIC_DIR}/flac/${subpath}/folder.jpg"
    echo "aart :: $artist / $album"
  fi

  # mp3
  mkdir -p "${MUSIC_DIR}/mp3/${subpath}"

  ffmpeg -y -nostdin -loglevel error -i "$file" -ab "${MP3_BITRATE}" "${MUSIC_DIR}/mp3/${subpath}/${basename}.mp3"
  echo " mp3 :: $artist / $album / $title"
done