aboutsummaryrefslogtreecommitdiff
path: root/scripts/music/yt-music.sh
blob: c117972847f23c46cef3f580fd26e6bc2f801179 (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
#!/usr/bin/env sh

set -e -o pipefail

MUSIC_DIR="$HOME/Downloads/music"

yt_download() {
  local url="$1"

  if [ -z "$url" ]; then
    url=$(echo -n "" | dmenu -p "YT music URL :: ")
  fi

  if [ -z "$url" ]; then
    echo "Nothing to download";
    exit 1;
  fi

  if is_downloaded "$url" && [ ! "$FORCE" == "1" ]; then
    echo "== already downloaded =="
    return 0;
  fi

  yt-dlp -x --audio-format flac --audio-quality 8 \
    --embed-metadata --embed-thumbnail \
    --parse-metadata "playlist_index:%(track_number)s" --add-metadata \
    -o "$MUSIC_DIR/%(artist|Others)s/%(album,playlist)s/%(playlist_index)02d - %(title)s.%(ext)s" \
    "$url" \
    && mark_as_done "$url"
}

is_downloaded() { grep "$1" "$MUSIC_DIR/music.lock" > /dev/null 1>&2; }

mark_as_done() {
  echo "$1" >> "$MUSIC_DIR/music.lock"
  sort -u "$MUSIC_DIR/music.lock" -o "$MUSIC_DIR/music.lock"
}

library_data() { jq -r "$1" "$MUSIC_DIR/music.json"; }

sync_library() {
  library_data ".[].url" | while read url; do
    yt_download "$url" || notify-send -u critical "Sync failed for $url"
  done
}

cmd="$1"; shift 1;
case "$cmd" in
  yt)
    yt_download "$@" \
      && notify-send "Music downloaded" \
      || notify-send -u critical "Music download failed"
  ;;
  sync)
    sync_library && notify-send "Sync done"
  ;;
  *) echo "invalid cmd. (yt | sync)"; exit 1 ;;
esac