summaryrefslogtreecommitdiff
path: root/ymao.sh
blob: a198cfdafeda795260dfc17f89bc19433eb7b4f1 (plain)
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
#!/bin/bash

# deps: "yt-dlp" "curl" "awk" "sed"

# Vars
music_dir="$MUSIC_DIR"

# Functions
main() {
    read -p "Artist: " artist
    read -p "Album: " album
    final_dir="$music_dir"/"$artist"/"$album"
    artist_query=$(sed 's/[[:punct:]]//g;s/ /+/g' <<< "$artist")
    album_query=$(sed 's/[[:punct:]]//g;s/ /+/g' <<< "$album")
    mkdir "$final_dir"/ 2> /dev/null
    [[ ! -z $i_option ]] && read -p "Playlist's ID: " playlist || search_playlist
    yt-dlp -x --audio-format mp3 --add-metadata -o "$final_dir/%(title)s.%(ext)s" --yes-playlist "https://yewtu.be"/"$playlist"
    [[ ! -z $t_option ]] && get_album_art
    [[ ! -z $c_option ]] && convert_ogg
}

search_playlist() {
    invidious_url="https://yewtu.be/search?q=$artist_query+$album_query+album&page=1&date=none&type=playlist&duration=none&sort=relevance"
    lastfm_url="https://www.last.fm/music/$artist_query/$album_query"
    album_len=$(curl -s "$lastfm_url" | grep -Eo ' [0-9]+ tracks' | awk 'NR==1{print $1 " songs"}')
    playlist=$(curl -s "$invidious_url" | grep -Eoi "playlist\?list=.+[a-zA-Z0-9]|[0-9]+ videos" |
    sed 's/ videos$/ songs/g' | paste - -s -d'\t\n' | grep -E "${album_len}" | awk 'NR==1 {print $1}')
}

get_album_art() {
    album_cover_url="https://itunes.apple.com/search?term=$artist_query+$album_query&media=music&entity=musicTrack"
    curl -o "$final_dir"/AlbumArt.jpg "$(curl -s "$album_cover_url" | grep -o -m1 'https://is.*x30bb.jpg' | sed 's/30x30bb.jpg/600x600bb.jpg/')"
}

convert_ogg() {
	for file in "$final_dir"/*.mp3
    do
	    OUTPUT=${file%.mp3}
	    echo "$OUTPUT"
	    ffmpeg -i "$file" "$OUTPUT.ogg"
    done
    rm -f "$final_dir"/*.mp3
}

check_deps() {
    for dep
    do
        if ! command -v "$dep" >/dev/null ; then
            exit_on_error "\"$dep\" is not installed.\n"
        fi
    done
}

exit_on_error () {
	printf "$*" >&2
	exit 1
}

# Options
while getopts ':cti' opt; do
    case $opt in
        c) c_option=1 ;;
        t) t_option=1 ;;
        i) i_option=1 ;;
        \?) echo "Invalid option: -$OPTARG." >&2 ; exit 1 ;;
    esac
done
shift $((OPTIND-1))

# Check dependencies and start
check_deps "yt-dlp" "curl" "awk" "sed"

main