Drop python 2 compatibility (#107)

This commit is contained in:
Ritiek Malhotra
2017-07-11 20:32:26 +05:30
committed by GitHub
parent b73d0b1049
commit 5add1fd0f8
8 changed files with 47 additions and 101 deletions

View File

@@ -9,22 +9,17 @@ from titlecase import titlecase
from slugify import slugify
import spotipy
import pafy
import urllib.request
import sys
import os
# urllib2 is urllib.request in python3
try:
import urllib2
except ImportError:
import urllib.request as urllib2
def generate_songname(raw_song):
"""Generate a string of the format '[artist] - [song]' for the given song."""
if misc.is_spotify(raw_song):
tags = generate_metadata(raw_song)
raw_song = u'{0} - {1}'.format(tags['artists'][0]['name'], tags['name'])
return misc.fix_encoding(raw_song)
return raw_song
def generate_metadata(raw_song):
@@ -63,7 +58,7 @@ def generate_youtube_url(raw_song):
"""Search for the song on YouTube and generate an URL to its video."""
song = generate_songname(raw_song)
search_url = misc.generate_search_url(song)
item = urllib2.urlopen(search_url).read()
item = urllib.request.urlopen(search_url).read()
# item = unicode(item, 'utf-8')
items_parse = BeautifulSoup(item, "html.parser")
check = 1
@@ -112,7 +107,7 @@ def go_pafy(raw_song):
def get_youtube_title(content, number=None):
"""Get the YouTube video's title."""
title = misc.fix_encoding(content.title)
title = content.title
if number is None:
return title
else:
@@ -131,7 +126,7 @@ def feed_playlist(username):
# is None. Skip these. Also see Issue #91.
if playlist['name'] is not None:
print(u'{0:>5}.| {1:<30} | ({2} tracks)'.format(
check, misc.fix_encoding(playlist['name']),
check, playlist['name'],
playlist['tracks']['total']))
links.append(playlist)
check += 1
@@ -145,11 +140,11 @@ def feed_playlist(username):
results = spotify.user_playlist(
playlist['owner']['id'], playlist['id'], fields='tracks,next')
print('')
file = u'{0}.txt'.format(slugify(playlist['name'], ok='-_()[]{}'))
print(u'Feeding {0} tracks to {1}'.format(playlist['tracks']['total'], file))
text_file = u'{0}.txt'.format(slugify(playlist['name'], ok='-_()[]{}'))
print(u'Feeding {0} tracks to {1}'.format(playlist['tracks']['total'], text_file))
tracks = results['tracks']
with open(file, 'a') as file_out:
with open(text_file, 'a') as file_out:
while True:
for item in tracks['items']:
track = item['track']
@@ -186,21 +181,20 @@ def download_song(content):
def check_exists(music_file, raw_song, islist=True):
"""Check if the input song already exists in the 'Music' folder."""
files = os.listdir('Music')
for file in files:
if file.endswith('.temp'):
os.remove(u'Music/{0}'.format(file))
songs = os.listdir('Music')
for song in songs:
if song.endswith('.temp'):
os.remove(u'Music/{0}'.format(song))
continue
# check if any file with similar name is already present in Music/
dfile = misc.fix_decoding(file)
umfile = misc.fix_decoding(misc.generate_filename(music_file))
if dfile.startswith(umfile):
# check if any song with similar name is already present in Music/
umfile = misc.generate_filename(music_file)
if song.startswith(umfile):
# check if the already downloaded song has correct metadata
already_tagged = metadata.compare(file, generate_metadata(raw_song))
already_tagged = metadata.compare(song, 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/{0}'.format(file))
os.remove('Music/{0}'.format(song))
return False
# do not prompt and skip the current song
@@ -209,22 +203,21 @@ def check_exists(music_file, raw_song, islist=True):
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()
prompt = input('Song with same name has already been downloaded. '
'Re-download? (y/n): ').lower()
if prompt == 'y':
os.remove('Music/{0}'.format(file))
os.remove('Music/{0}'.format(song))
return False
else:
return True
return False
def grab_list(file):
def grab_list(text_file):
"""Download all songs from the list."""
with open(file, 'r') as listed:
with open(text_file, 'r') as listed:
lines = (listed.read()).splitlines()
# ignore blank lines in file (if any)
# ignore blank lines in text_file (if any)
try:
lines.remove('')
except ValueError:
@@ -244,12 +237,12 @@ def grab_list(file):
spotify = spotipy.Spotify(auth=new_token)
grab_single(raw_song, number=number)
# detect network problems
except (urllib2.URLError, TypeError, IOError):
except (urllib.request.URLError, TypeError, IOError):
lines.append(raw_song)
# remove the downloaded song from .txt
misc.trim_song(file)
misc.trim_song(text_file)
# and append it to the last line in .txt
with open(file, 'a') as myfile:
with open(text_file, 'a') as myfile:
myfile.write(raw_song)
print('Failed to download song. Will retry after other songs.')
continue
@@ -257,7 +250,7 @@ def grab_list(file):
misc.grace_quit()
finally:
print('')
misc.trim_song(file)
misc.trim_song(text_file)
number += 1
@@ -276,7 +269,6 @@ def grab_single(raw_song, number=None):
# generate file name of the song to download
music_file = misc.generate_filename(content.title)
music_file = misc.fix_decoding(music_file)
if not check_exists(music_file, raw_song, islist=islist):
if download_song(content):
print('')
@@ -285,7 +277,7 @@ def grab_single(raw_song, number=None):
convert.song(input_song, output_song, avconv=args.avconv,
verbose=args.verbose)
if not args.input_ext == args.output_ext:
os.remove('Music/{0}'.format(misc.fix_encoding(input_song)))
os.remove('Music/{0}'.format(input_song))
meta_tags = generate_metadata(raw_song)
if not args.no_metadata:
metadata.embed(output_song, meta_tags)
@@ -313,6 +305,6 @@ if __name__ == '__main__':
if args.song:
grab_single(raw_song=args.song)
elif args.list:
grab_list(file=args.list)
grab_list(text_file=args.list)
elif args.username:
feed_playlist(username=args.username)