mirror of
https://github.com/KevinMidboe/spotify-downloader.git
synced 2025-12-08 20:39:08 +00:00
Apply most best practices of PEP 8
This refactoring includes:
- Two empty lines before each global function
- Using '{0} {1}'.format(str1, str2) instead of str1 + ' ' + str2
Sometimes this will make lines longer, sometimes shorter.
- Starting all comments with # + space + comment
- Make lines not longer than 80 characters in most cases
- Renaming some variables to make more sense
- Add some missing code like returns and Exceptions
Not included, but follows:
- Make some comments docstrings
- Rename all 'file' variables, only for Python 2
- Remove some way too verbose comments ;)
This commit is contained in:
100
spotdl.py
100
spotdl.py
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
from core import metadata
|
||||
@@ -19,13 +18,15 @@ try:
|
||||
except ImportError:
|
||||
import urllib.request as urllib2
|
||||
|
||||
|
||||
# "[artist] - [song]"
|
||||
def generate_songname(raw_song):
|
||||
if misc.is_spotify(raw_song):
|
||||
tags = generate_metadata(raw_song)
|
||||
raw_song = tags['artists'][0]['name'] + ' - ' + tags['name']
|
||||
raw_song = '{0} - {1}'.format(tags['artists'][0]['name'], tags['name'])
|
||||
return misc.fix_encoding(raw_song)
|
||||
|
||||
|
||||
# fetch song's metadata from spotify
|
||||
def generate_metadata(raw_song):
|
||||
if misc.is_spotify(raw_song):
|
||||
@@ -52,18 +53,19 @@ def generate_metadata(raw_song):
|
||||
meta_tags[u'release_date'] = album['release_date']
|
||||
meta_tags[u'publisher'] = album['label']
|
||||
meta_tags[u'total_tracks'] = album['tracks']['total']
|
||||
#import pprint
|
||||
#pprint.pprint(meta_tags)
|
||||
#pprint.pprint(spotify.album(meta_tags['album']['id']))
|
||||
# import pprint
|
||||
# pprint.pprint(meta_tags)
|
||||
# pprint.pprint(spotify.album(meta_tags['album']['id']))
|
||||
return meta_tags
|
||||
|
||||
|
||||
def generate_youtube_url(raw_song):
|
||||
# decode spotify http link to "[artist] - [song]"
|
||||
song = generate_songname(raw_song)
|
||||
# generate direct search YouTube URL
|
||||
search_url = misc.generate_search_url(song)
|
||||
item = urllib2.urlopen(search_url).read()
|
||||
#item = unicode(item, 'utf-8')
|
||||
# item = unicode(item, 'utf-8')
|
||||
items_parse = BeautifulSoup(item, "html.parser")
|
||||
check = 1
|
||||
if args.manual:
|
||||
@@ -75,7 +77,7 @@ def generate_youtube_url(raw_song):
|
||||
for x in items_parse.find_all('h3', {'class': 'yt-lockup-title'}):
|
||||
# confirm the video result is not an advertisement
|
||||
if not x.find('channel') == -1 or not x.find('googleads') == -1:
|
||||
print(str(check) + '. ' + x.get_text())
|
||||
print('{0}. {1}'.format(check, x.get_text()))
|
||||
links.append(x.find('a')['href'])
|
||||
check += 1
|
||||
print('')
|
||||
@@ -85,15 +87,20 @@ def generate_youtube_url(raw_song):
|
||||
return None
|
||||
else:
|
||||
# get video link of the first YouTube result
|
||||
result = items_parse.find_all(attrs={'class': 'yt-uix-tile-link'})[0]['href']
|
||||
result = items_parse.find_all(
|
||||
attrs={'class': 'yt-uix-tile-link'})[0]['href']
|
||||
|
||||
# confirm the video result is not an advertisement
|
||||
# otherwise keep iterating until it is not
|
||||
while not result.find('channel') == -1 or not result.find('googleads') == -1:
|
||||
result = items_parse.find_all(attrs={'class': 'yt-uix-tile-link'})[check]['href']
|
||||
while result.find('channel') < 0 or result.find('googleads') < 0:
|
||||
result = items_parse.find_all(
|
||||
attrs={'class': 'yt-uix-tile-link'})[check]['href']
|
||||
check += 1
|
||||
full_link = "youtube.com" + result
|
||||
|
||||
full_link = "youtube.com{0}'.format(result)
|
||||
return full_link
|
||||
|
||||
|
||||
# parse track from YouTube
|
||||
def go_pafy(raw_song):
|
||||
# video link of the video to extract audio from
|
||||
@@ -104,13 +111,15 @@ def go_pafy(raw_song):
|
||||
# parse the YouTube video
|
||||
return pafy.new(track_url)
|
||||
|
||||
|
||||
# title of the YouTube video
|
||||
def get_youtube_title(content, number=None):
|
||||
title = misc.fix_encoding(content.title)
|
||||
if number is None:
|
||||
return title
|
||||
else:
|
||||
return str(number) + '. ' + title
|
||||
return '{0}. {1}'.format(number, title)
|
||||
|
||||
|
||||
# fetch user playlists when using -u option
|
||||
def feed_playlist(username):
|
||||
@@ -118,13 +127,16 @@ def feed_playlist(username):
|
||||
playlists = spotify.user_playlists(username)
|
||||
links = []
|
||||
check = 1
|
||||
|
||||
# iterate over user playlists
|
||||
while True:
|
||||
for playlist in playlists['items']:
|
||||
# In rare cases, playlists may not be found, so playlists['next'] is
|
||||
# None. Skip these. Also see Issue #91.
|
||||
# in rare cases, playlists may not be found, so playlists['next']
|
||||
# is None. Skip these. Also see Issue #91.
|
||||
if playlist['name'] is not None:
|
||||
print(str(check) + '. ' + misc.fix_encoding(playlist['name']) + ' (' + str(playlist['tracks']['total']) + ' tracks)')
|
||||
print('{0}. {1} ({2} tracks)'.format(
|
||||
check, misc.fix_encoding(playlist['name'])),
|
||||
playlist['tracks']['total'])
|
||||
links.append(playlist)
|
||||
check += 1
|
||||
if playlists['next']:
|
||||
@@ -136,22 +148,23 @@ def feed_playlist(username):
|
||||
# let user select playlist
|
||||
playlist = misc.input_link(links)
|
||||
# fetch detailed information for playlist
|
||||
results = spotify.user_playlist(playlist['owner']['id'], playlist['id'], fields="tracks,next")
|
||||
results = spotify.user_playlist(
|
||||
playlist['owner']['id'], playlist['id'], fields='tracks,next')
|
||||
print('')
|
||||
# slugify removes any special characters
|
||||
file = slugify(playlist['name'], ok='-_()[]{}') + '.txt'
|
||||
print('Feeding ' + str(playlist['tracks']['total']) + ' tracks to ' + file)
|
||||
file = '{0}.txt'.format(slugify(playlist['name'], ok='-_()[]{}'))
|
||||
print('Feeding {0} tracks to {1}'.format(playlist['tracks']['total'], file))
|
||||
|
||||
tracks = results['tracks']
|
||||
with open(file, 'a') as fout:
|
||||
with open(file, 'a') as file_out:
|
||||
while True:
|
||||
for item in tracks['items']:
|
||||
track = item['track']
|
||||
try:
|
||||
fout.write(track['external_urls']['spotify'] + '\n')
|
||||
file_out.write(track['external_urls']['spotify'] + '\n')
|
||||
except KeyError:
|
||||
title = track['name'] + ' by '+ track['artists'][0]['name']
|
||||
print('Skipping track ' + title + ' (local only?)')
|
||||
print('Skipping track {0} by {1} (local only?)'.format(
|
||||
track['name'], track['artists'][0]['name']))
|
||||
# 1 page = 50 results
|
||||
# check if there are more pages
|
||||
if tracks['next']:
|
||||
@@ -159,6 +172,7 @@ def feed_playlist(username):
|
||||
else:
|
||||
break
|
||||
|
||||
|
||||
def download_song(content):
|
||||
if args.input_ext == '.webm':
|
||||
# best available audio in .webm
|
||||
@@ -174,15 +188,17 @@ def download_song(content):
|
||||
else:
|
||||
music_file = misc.generate_filename(content.title)
|
||||
# download link
|
||||
link.download(filepath='Music/' + music_file + args.input_ext)
|
||||
link.download(
|
||||
filepath='Music/{0}{1}'.format(music_file, args.input_ext))
|
||||
return True
|
||||
|
||||
|
||||
# check if input song already exists in Music folder
|
||||
def check_exists(music_file, raw_song, islist=True):
|
||||
files = os.listdir("Music")
|
||||
files = os.listdir('Music')
|
||||
for file in files:
|
||||
if file.endswith(".temp"):
|
||||
os.remove("Music/" + file)
|
||||
if file.endswith('.temp'):
|
||||
os.remove('Music/{0}'.format(file))
|
||||
continue
|
||||
# check if any file with similar name is already present in Music/
|
||||
dfile = misc.fix_decoding(file)
|
||||
@@ -190,23 +206,29 @@ def check_exists(music_file, raw_song, islist=True):
|
||||
if dfile.startswith(umfile):
|
||||
# check if the already downloaded song has correct metadata
|
||||
already_tagged = metadata.compare(file, generate_metadata(raw_song))
|
||||
|
||||
# if not, remove it and download again without prompt
|
||||
if misc.is_spotify(raw_song) and not already_tagged:
|
||||
os.remove("Music/" + file)
|
||||
os.remove('Music/{0}'.format(file))
|
||||
return False
|
||||
# do not prompt and skip the current song if already downloaded when using list
|
||||
|
||||
# do not prompt and skip the current song
|
||||
# if already downloaded when using list
|
||||
if islist:
|
||||
return True
|
||||
# if downloading only single song, prompt to re-download
|
||||
else:
|
||||
prompt = misc.user_input('Song with same name has already been downloaded. Re-download? (y/n): ').lower()
|
||||
if prompt == "y":
|
||||
os.remove("Music/" + file)
|
||||
prompt = misc.user_input(
|
||||
'Song with same name has already been downloaded. '
|
||||
'Re-download? (y/n): ').lower()
|
||||
if prompt == 'y':
|
||||
os.remove('Music/{0}'.format(file))
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# download songs from list
|
||||
def grab_list(file):
|
||||
with open(file, 'r') as listed:
|
||||
@@ -216,7 +238,7 @@ def grab_list(file):
|
||||
lines.remove('')
|
||||
except ValueError:
|
||||
pass
|
||||
print('Total songs in list = ' + str(len(lines)) + ' songs')
|
||||
print('Total songs in list: {0} songs'.format(len(lines)))
|
||||
print('')
|
||||
# nth input song
|
||||
number = 1
|
||||
@@ -226,9 +248,9 @@ def grab_list(file):
|
||||
# token expires after 1 hour
|
||||
except spotipy.oauth2.SpotifyOauthError:
|
||||
# refresh token when it expires
|
||||
token = misc.generate_token()
|
||||
new_token = misc.generate_token()
|
||||
global spotify
|
||||
spotify = spotipy.Spotify(auth=token)
|
||||
spotify = spotipy.Spotify(auth=new_token)
|
||||
grab_single(raw_song, number=number)
|
||||
# detect network problems
|
||||
except (urllib2.URLError, TypeError, IOError):
|
||||
@@ -247,6 +269,7 @@ def grab_list(file):
|
||||
misc.trim_song(file)
|
||||
number += 1
|
||||
|
||||
|
||||
# logic behind downloading some song
|
||||
def grab_single(raw_song, number=None):
|
||||
# check if song is being downloaded from list
|
||||
@@ -257,8 +280,8 @@ def grab_single(raw_song, number=None):
|
||||
content = go_pafy(raw_song)
|
||||
if content is None:
|
||||
return
|
||||
# print "[number]. [artist] - [song]" if downloading from list
|
||||
# otherwise print "[artist] - [song]"
|
||||
# print '[number]. [artist] - [song]' if downloading from list
|
||||
# otherwise print '[artist] - [song]'
|
||||
print(get_youtube_title(content, number))
|
||||
# generate file name of the song to download
|
||||
music_file = misc.generate_filename(content.title)
|
||||
@@ -272,13 +295,14 @@ def grab_single(raw_song, number=None):
|
||||
output_song,
|
||||
avconv=args.avconv,
|
||||
verbose=args.verbose)
|
||||
os.remove('Music/' + input_song)
|
||||
os.remove('Music/{0}'.format(file))
|
||||
meta_tags = generate_metadata(raw_song)
|
||||
if not args.no_metadata:
|
||||
metadata.embed(output_song, meta_tags)
|
||||
else:
|
||||
print('No audio streams available')
|
||||
|
||||
|
||||
class Args(object):
|
||||
manual = False
|
||||
input_ext = '.m4a'
|
||||
@@ -293,9 +317,7 @@ spotify = spotipy.Spotify(auth=token)
|
||||
misc.filter_path('Music')
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
os.chdir(sys.path[0])
|
||||
|
||||
args = misc.get_arguments()
|
||||
|
||||
if args.song:
|
||||
|
||||
Reference in New Issue
Block a user