-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
135 lines (111 loc) · 3.77 KB
/
main.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""
Spotify Downloader
"""
from __future__ import unicode_literals
import os
import json
import argparse
import youtube_dl
import spotipy
from youtubesearchpython import SearchVideos
from youtube_dl.utils import DownloadError, ExtractorError
def get_args():
"""
Parse Arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--spotiuri', action='store', help='Playlist\'s Spotify Uri')
parser.add_argument('-p', '--spotiplaylistId', action='store', help='Playlist\'s Spotify id')
parser.add_argument('-i', '--client_id', required=True, action='store', help='Client\'s id')
parser.add_argument('-s', '--client_secret', required=True, action='store', help='Client\'s secret')
parser.add_argument('-d', '--dir_name', required=False, action='store', default="spotify_playlist", help='Directory name')
my_args = parser.parse_args()
if not(my_args.spotiuri or my_args.spotiplaylistId):
parser.error('Need URI or ID')
return my_args
def create_dir(dir_name):
"""
Creates dir if it does not exist
"""
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def download_songs(spotify_info):
"""
Download song
"""
failed = list()
print("\nDownloading songs...\n")
counter = 0
for item in spotify_info["items"]:
song_name = item["track"]["artists"][0]["name"]
song_artist = item["track"]["name"]
wholename = "%s %s" % (song_name, song_artist)
counter += 1
print("%s)\t%s" % (counter, wholename))
track = get_yt_link(song_artist, song_name)
if track:
if not yt_dl(track):
print(f"This track failed: {wholename}")
failed.append(f"{song_artist} {song_name}")
else:
print(f"This track failed: {wholename}")
failed.append(f"{song_artist} {song_name}")
def yt_dl(vid):
"""
Download yt music
"""
ydl_opts = {
'format': 'bestaudio/best',
'quiet': 'True',
'no-playlist': 'True',
'audio-format': 'best',
'extract-audio': 'True',
'addmetadata': 'True',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '320'
}]}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
try:
ydl.download([vid])
except DownloadError as dl_e:
print(f"Couldn't download: {dl_e}")
return False
except ExtractorError as extract_e:
print(f"Couldn't extract: {extract_e}")
return False
return True
def get_yt_link(artist, song):
"""
Return YT Link to download
"""
search = SearchVideos(str(artist + " " + song),
offset=1,
mode="json",
max_results=1)
try:
return search.links[0]
except IndexError as e:
print(f"No videos to download found: {e}")
def main():
"""
main function
"""
args = get_args()
if args.spotiuri:
playlist_id = args.spotiuri.split(":")[len(args.spotiuri.split(":"))-1]
if args.spotiplaylistId:
playlist_id = args.spotiplaylistId
tok = spotipy.oauth2.SpotifyClientCredentials(client_id=args.client_id,
client_secret=args.client_secret)
access_token = tok.get_access_token(as_dict=False)
result = os.popen('curl -s -X GET "https://api.spotify.com/v1/playlists/'
+ playlist_id + '/tracks" -H "Authorization: Bearer '
+ access_token + '"').read()
dir_name = args.dir_name
create_dir(dir_name)
os.chdir(dir_name)
download_songs(json.loads(result))
if __name__ == "__main__":
main()