mirror of
https://github.com/KevinMidboe/spotify-downloader.git
synced 2025-10-29 18:00:15 +00:00
@@ -2,21 +2,25 @@ import subprocess
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
def song(input_song, output_song, avconv=False, verbose=False):
|
def song(input_song, output_song, avconv=False, verbose=False):
|
||||||
|
"""Do the audio format conversion."""
|
||||||
if not input_song == output_song:
|
if not input_song == output_song:
|
||||||
if sys.version_info < (3, 0):
|
if sys.version_info < (3, 0):
|
||||||
input_song = input_song.encode('utf-8')
|
input_song = input_song.encode('utf-8')
|
||||||
output_song = output_song.encode('utf-8')
|
output_song = output_song.encode('utf-8')
|
||||||
print('Converting ' + input_song + ' to ' + output_song.split('.')[-1])
|
print('Converting {0} to {1}'.format(
|
||||||
|
input_song, output_song.split('.')[-1]))
|
||||||
if avconv:
|
if avconv:
|
||||||
exit_code = convert_with_avconv(input_song, output_song, verbose)
|
exit_code = convert_with_avconv(input_song, output_song, verbose)
|
||||||
else:
|
else:
|
||||||
exit_code = convert_with_FFmpeg(input_song, output_song, verbose)
|
exit_code = convert_with_ffmpeg(input_song, output_song, verbose)
|
||||||
return exit_code
|
return exit_code
|
||||||
return None
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def convert_with_avconv(input_song, output_song, verbose):
|
def convert_with_avconv(input_song, output_song, verbose):
|
||||||
# different path for windows
|
"""Convert the audio file using avconv."""
|
||||||
if os.name == 'nt':
|
if os.name == 'nt':
|
||||||
avconv_path = 'Scripts\\avconv.exe'
|
avconv_path = 'Scripts\\avconv.exe'
|
||||||
else:
|
else:
|
||||||
@@ -33,17 +37,20 @@ def convert_with_avconv(input_song, output_song, verbose):
|
|||||||
'-ab', '192k',
|
'-ab', '192k',
|
||||||
'Music/' + output_song]
|
'Music/' + output_song]
|
||||||
|
|
||||||
subprocess.call(command)
|
return subprocess.call(command)
|
||||||
|
|
||||||
|
|
||||||
def convert_with_FFmpeg(input_song, output_song, verbose):
|
def convert_with_ffmpeg(input_song, output_song, verbose):
|
||||||
# What are the differences and similarities between ffmpeg, libav, and avconv?
|
"""Convert the audio file using FFMpeg.
|
||||||
# https://stackoverflow.com/questions/9477115
|
|
||||||
# ffmeg encoders high to lower quality
|
What are the differences and similarities between ffmpeg, libav, and avconv?
|
||||||
# libopus > libvorbis >= libfdk_aac > aac > libmp3lame
|
https://stackoverflow.com/questions/9477115
|
||||||
# libfdk_aac due to copyrights needs to be compiled by end user
|
ffmeg encoders high to lower quality
|
||||||
# on MacOS brew install ffmpeg --with-fdk-aac will do just that. Other OS?
|
libopus > libvorbis >= libfdk_aac > aac > libmp3lame
|
||||||
# https://trac.ffmpeg.org/wiki/Encode/AAC
|
libfdk_aac due to copyrights needs to be compiled by end user
|
||||||
|
on MacOS brew install ffmpeg --with-fdk-aac will do just that. Other OS?
|
||||||
|
https://trac.ffmpeg.org/wiki/Encode/AAC
|
||||||
|
"""
|
||||||
|
|
||||||
if os.name == "nt":
|
if os.name == "nt":
|
||||||
ffmpeg_pre = 'Scripts\\ffmpeg.exe '
|
ffmpeg_pre = 'Scripts\\ffmpeg.exe '
|
||||||
@@ -54,6 +61,7 @@ def convert_with_FFmpeg(input_song, output_song, verbose):
|
|||||||
if not verbose:
|
if not verbose:
|
||||||
ffmpeg_pre += '-hide_banner -nostats -v panic '
|
ffmpeg_pre += '-hide_banner -nostats -v panic '
|
||||||
|
|
||||||
|
ffmpeg_params = ''
|
||||||
input_ext = input_song.split('.')[-1]
|
input_ext = input_song.split('.')[-1]
|
||||||
output_ext = output_song.split('.')[-1]
|
output_ext = output_song.split('.')[-1]
|
||||||
|
|
||||||
@@ -69,10 +77,7 @@ def convert_with_FFmpeg(input_song, output_song, verbose):
|
|||||||
elif output_ext == 'm4a':
|
elif output_ext == 'm4a':
|
||||||
ffmpeg_params = '-cutoff 20000 -c:a libfdk_aac -b:a 192k -vn '
|
ffmpeg_params = '-cutoff 20000 -c:a libfdk_aac -b:a 192k -vn '
|
||||||
|
|
||||||
command = (ffmpeg_pre +
|
command = '{0}-i Music/{1} {2}Music/{3}'.format(
|
||||||
'-i Music/' + input_song + ' ' +
|
ffmpeg_pre, input_song, ffmpeg_params, output_song).split(' ')
|
||||||
ffmpeg_params +
|
|
||||||
'Music/' + output_song + '').split(' ')
|
|
||||||
|
|
||||||
subprocess.call(command)
|
|
||||||
|
|
||||||
|
return subprocess.call(command)
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
import urllib.request as urllib2
|
import urllib.request as urllib2
|
||||||
|
|
||||||
# check if input file title matches with expected title
|
|
||||||
def compare(file, metadata):
|
def compare(file, metadata):
|
||||||
|
"""Check if the input file title matches the expected title."""
|
||||||
|
already_tagged = False
|
||||||
try:
|
try:
|
||||||
if file.endswith('.mp3'):
|
if file.endswith('.mp3'):
|
||||||
audiofile = EasyID3('Music/' + file)
|
audiofile = EasyID3('Music/' + file)
|
||||||
@@ -22,10 +24,12 @@ def compare(file, metadata):
|
|||||||
# fetch track title metadata
|
# fetch track title metadata
|
||||||
already_tagged = audiofile[tags['title']] == metadata['name']
|
already_tagged = audiofile[tags['title']] == metadata['name']
|
||||||
except KeyError:
|
except KeyError:
|
||||||
already_tagged = False
|
pass
|
||||||
return already_tagged
|
return already_tagged
|
||||||
|
|
||||||
|
|
||||||
def embed(music_file, meta_tags):
|
def embed(music_file, meta_tags):
|
||||||
|
"""Embed metadata."""
|
||||||
if sys.version_info < (3, 0):
|
if sys.version_info < (3, 0):
|
||||||
music_file = music_file.encode('utf-8')
|
music_file = music_file.encode('utf-8')
|
||||||
if meta_tags is None:
|
if meta_tags is None:
|
||||||
@@ -41,14 +45,17 @@ def embed(music_file, meta_tags):
|
|||||||
print('Cannot embed meta-tags into given output extension')
|
print('Cannot embed meta-tags into given output extension')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def embed_mp3(music_file, meta_tags):
|
def embed_mp3(music_file, meta_tags):
|
||||||
|
"""Embed metadata to MP3 files."""
|
||||||
# EasyID3 is fun to use ;)
|
# EasyID3 is fun to use ;)
|
||||||
audiofile = EasyID3('Music/' + music_file)
|
audiofile = EasyID3('Music/' + music_file)
|
||||||
audiofile['artist'] = meta_tags['artists'][0]['name']
|
audiofile['artist'] = meta_tags['artists'][0]['name']
|
||||||
audiofile['albumartist'] = meta_tags['artists'][0]['name']
|
audiofile['albumartist'] = meta_tags['artists'][0]['name']
|
||||||
audiofile['album'] = meta_tags['album']['name']
|
audiofile['album'] = meta_tags['album']['name']
|
||||||
audiofile['title'] = meta_tags['name']
|
audiofile['title'] = meta_tags['name']
|
||||||
audiofile['tracknumber'] = [meta_tags['track_number'], meta_tags['total_tracks']]
|
audiofile['tracknumber'] = [meta_tags['track_number'],
|
||||||
|
meta_tags['total_tracks']]
|
||||||
audiofile['discnumber'] = [meta_tags['disc_number'], 0]
|
audiofile['discnumber'] = [meta_tags['disc_number'], 0]
|
||||||
audiofile['date'] = meta_tags['release_date']
|
audiofile['date'] = meta_tags['release_date']
|
||||||
audiofile['originaldate'] = meta_tags['release_date']
|
audiofile['originaldate'] = meta_tags['release_date']
|
||||||
@@ -68,12 +75,15 @@ def embed_mp3(music_file, meta_tags):
|
|||||||
audiofile.save(v2_version=3)
|
audiofile.save(v2_version=3)
|
||||||
audiofile = ID3('Music/' + music_file)
|
audiofile = ID3('Music/' + music_file)
|
||||||
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
||||||
audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=albumart.read())
|
audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3,
|
||||||
|
desc=u'Cover', data=albumart.read())
|
||||||
albumart.close()
|
albumart.close()
|
||||||
audiofile.save(v2_version=3)
|
audiofile.save(v2_version=3)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def embed_m4a(music_file, meta_tags):
|
def embed_m4a(music_file, meta_tags):
|
||||||
|
"""Embed metadata to M4A files."""
|
||||||
# Apple has specific tags - see mutagen docs -
|
# Apple has specific tags - see mutagen docs -
|
||||||
# http://mutagen.readthedocs.io/en/latest/api/mp4.html
|
# http://mutagen.readthedocs.io/en/latest/api/mp4.html
|
||||||
tags = {'album': '\xa9alb',
|
tags = {'album': '\xa9alb',
|
||||||
@@ -98,7 +108,8 @@ def embed_m4a(music_file, meta_tags):
|
|||||||
audiofile[tags['albumartist']] = meta_tags['artists'][0]['name']
|
audiofile[tags['albumartist']] = meta_tags['artists'][0]['name']
|
||||||
audiofile[tags['album']] = meta_tags['album']['name']
|
audiofile[tags['album']] = meta_tags['album']['name']
|
||||||
audiofile[tags['title']] = meta_tags['name']
|
audiofile[tags['title']] = meta_tags['name']
|
||||||
audiofile[tags['tracknumber']] = [(meta_tags['track_number'], meta_tags['total_tracks'])]
|
audiofile[tags['tracknumber']] = [(meta_tags['track_number'],
|
||||||
|
meta_tags['total_tracks'])]
|
||||||
audiofile[tags['disknumber']] = [(meta_tags['disc_number'], 0)]
|
audiofile[tags['disknumber']] = [(meta_tags['disc_number'], 0)]
|
||||||
audiofile[tags['date']] = meta_tags['release_date']
|
audiofile[tags['date']] = meta_tags['release_date']
|
||||||
audiofile[tags['originaldate']] = meta_tags['release_date']
|
audiofile[tags['originaldate']] = meta_tags['release_date']
|
||||||
@@ -107,7 +118,8 @@ def embed_m4a(music_file, meta_tags):
|
|||||||
if meta_tags['copyright']:
|
if meta_tags['copyright']:
|
||||||
audiofile[tags['copyright']] = meta_tags['copyright']
|
audiofile[tags['copyright']] = meta_tags['copyright']
|
||||||
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
||||||
audiofile[tags['albumart']] = [ MP4Cover(albumart.read(), imageformat=MP4Cover.FORMAT_JPEG) ]
|
audiofile[tags['albumart']] = [MP4Cover(
|
||||||
|
albumart.read(), imageformat=MP4Cover.FORMAT_JPEG)]
|
||||||
albumart.close()
|
albumart.close()
|
||||||
audiofile.save()
|
audiofile.save()
|
||||||
return True
|
return True
|
||||||
|
|||||||
108
core/misc.py
108
core/misc.py
@@ -6,15 +6,16 @@ import spotipy.oauth2 as oauth2
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
from urllib2 import quote
|
from urllib2 import quote
|
||||||
except:
|
except ImportError:
|
||||||
from urllib.request import quote
|
from urllib.request import quote
|
||||||
|
|
||||||
# method to input (user playlists) and (track when using manual mode)
|
|
||||||
def input_link(links):
|
def input_link(links):
|
||||||
|
"""Let the user input a number."""
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
the_chosen_one = int(user_input('>> Choose your number: '))
|
the_chosen_one = int(user_input('>> Choose your number: '))
|
||||||
if the_chosen_one >= 1 and the_chosen_one <= len(links):
|
if 1 <= the_chosen_one <= len(links):
|
||||||
return links[the_chosen_one - 1]
|
return links[the_chosen_one - 1]
|
||||||
elif the_chosen_one == 0:
|
elif the_chosen_one == 0:
|
||||||
return None
|
return None
|
||||||
@@ -23,99 +24,120 @@ def input_link(links):
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
print('Choose a valid number!')
|
print('Choose a valid number!')
|
||||||
|
|
||||||
# take input correctly for both python2 & 3
|
|
||||||
def user_input(string=''):
|
def user_input(string=''):
|
||||||
|
"""Take input correctly for both Python 2 & 3."""
|
||||||
if sys.version_info > (3, 0):
|
if sys.version_info > (3, 0):
|
||||||
return input(string)
|
return input(string)
|
||||||
else:
|
else:
|
||||||
return raw_input(string)
|
return raw_input(string)
|
||||||
|
|
||||||
# remove first song from .txt
|
|
||||||
def trim_song(file):
|
def trim_song(file):
|
||||||
with open(file, 'r') as fin:
|
"""Remove the first song from file."""
|
||||||
data = fin.read().splitlines(True)
|
with open(file, 'r') as file_in:
|
||||||
with open(file, 'w') as fout:
|
data = file_in.read().splitlines(True)
|
||||||
fout.writelines(data[1:])
|
with open(file, 'w') as file_out:
|
||||||
|
file_out.writelines(data[1:])
|
||||||
|
|
||||||
|
|
||||||
def get_arguments():
|
def get_arguments():
|
||||||
parser = argparse.ArgumentParser(description='Download and convert songs \
|
parser = argparse.ArgumentParser(
|
||||||
from Spotify, Youtube etc.',
|
description='Download and convert songs from Spotify, Youtube etc.',
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||||
group = parser.add_mutually_exclusive_group(required=True)
|
group = parser.add_mutually_exclusive_group(required=True)
|
||||||
|
|
||||||
group.add_argument('-s', '--song',
|
group.add_argument(
|
||||||
help='download song by spotify link or name')
|
'-s', '--song', help='download song by spotify link or name')
|
||||||
group.add_argument('-l', '--list',
|
group.add_argument(
|
||||||
help='download songs from a file')
|
'-l', '--list', help='download songs from a file')
|
||||||
group.add_argument('-u', '--username',
|
group.add_argument(
|
||||||
help="load user's playlists into <playlist_name>.txt")
|
'-u', '--username',
|
||||||
parser.add_argument('-m', '--manual', default=False,
|
help="load user's playlists into <playlist_name>.txt")
|
||||||
help='choose the song to download manually', action='store_true')
|
parser.add_argument(
|
||||||
parser.add_argument('-nm', '--no-metadata', default=False,
|
'-m', '--manual', default=False,
|
||||||
help='do not embed metadata in songs', action='store_true')
|
help='choose the song to download manually', action='store_true')
|
||||||
parser.add_argument('-a', '--avconv', default=False,
|
parser.add_argument(
|
||||||
help='Use avconv for conversion otherwise set defaults to ffmpeg',
|
'-nm', '--no-metadata', default=False,
|
||||||
action='store_true')
|
help='do not embed metadata in songs', action='store_true')
|
||||||
parser.add_argument('-v', '--verbose', default=False,
|
parser.add_argument(
|
||||||
help='show debug output', action='store_true')
|
'-a', '--avconv', default=False,
|
||||||
parser.add_argument('-i', '--input_ext', default='.m4a',
|
help='Use avconv for conversion otherwise set defaults to ffmpeg',
|
||||||
help='prefered input format .m4a or .webm (Opus)')
|
action='store_true')
|
||||||
parser.add_argument('-o', '--output_ext', default='.mp3',
|
parser.add_argument(
|
||||||
help='prefered output extension .mp3 or .m4a (AAC)')
|
'-v', '--verbose', default=False, help='show debug output',
|
||||||
|
action='store_true')
|
||||||
|
parser.add_argument(
|
||||||
|
'-i', '--input_ext', default='.m4a',
|
||||||
|
help='prefered input format .m4a or .webm (Opus)')
|
||||||
|
parser.add_argument(
|
||||||
|
'-o', '--output_ext', default='.mp3',
|
||||||
|
help='prefered output extension .mp3 or .m4a (AAC)')
|
||||||
|
|
||||||
return parser.parse_args()
|
return parser.parse_args()
|
||||||
|
|
||||||
# check if input song is spotify link
|
|
||||||
def is_spotify(raw_song):
|
def is_spotify(raw_song):
|
||||||
if (len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1):
|
"""Check if the input song is a Spotify link."""
|
||||||
|
if (len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or \
|
||||||
|
(raw_song.find('spotify') > -1):
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# generate filename of the song to be downloaded
|
|
||||||
def generate_filename(title):
|
def generate_filename(title):
|
||||||
|
"""Generate filename of the song to be downloaded."""
|
||||||
# IMO python2 sucks dealing with unicode
|
# IMO python2 sucks dealing with unicode
|
||||||
title = fix_encoding(title)
|
title = fix_encoding(title)
|
||||||
title = fix_decoding(title)
|
title = fix_decoding(title)
|
||||||
title = title.replace(' ', '_')
|
title = title.replace(' ', '_')
|
||||||
|
|
||||||
# slugify removes any special characters
|
# slugify removes any special characters
|
||||||
filename = slugify(title, ok='-_()[]{}', lower=False)
|
filename = slugify(title, ok='-_()[]{}', lower=False)
|
||||||
return fix_encoding(filename)
|
return fix_encoding(filename)
|
||||||
|
|
||||||
# please respect these credentials :)
|
|
||||||
def generate_token():
|
def generate_token():
|
||||||
creds = oauth2.SpotifyClientCredentials(
|
"""Generate the token. Please respect these credentials :)"""
|
||||||
|
credentials = oauth2.SpotifyClientCredentials(
|
||||||
client_id='4fe3fecfe5334023a1472516cc99d805',
|
client_id='4fe3fecfe5334023a1472516cc99d805',
|
||||||
client_secret='0f02b7c483c04257984695007a4a8d5c')
|
client_secret='0f02b7c483c04257984695007a4a8d5c')
|
||||||
token = creds.get_access_token()
|
token = credentials.get_access_token()
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
def generate_search_url(song):
|
def generate_search_url(song):
|
||||||
|
"""Generate YouTube search URL for the given song."""
|
||||||
# urllib2.quote() encodes URL with special characters
|
# urllib2.quote() encodes URL with special characters
|
||||||
url = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + quote(song)
|
url = u"https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q={0}".format(
|
||||||
|
quote(song))
|
||||||
return url
|
return url
|
||||||
|
|
||||||
# fix encoding issues in python2
|
|
||||||
def fix_encoding(query):
|
def fix_encoding(query):
|
||||||
|
"""Fix encoding issues in Python 2."""
|
||||||
if sys.version_info < (3, 0):
|
if sys.version_info < (3, 0):
|
||||||
query = query.encode('utf-8')
|
query = query.encode('utf-8')
|
||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
def fix_decoding(query):
|
def fix_decoding(query):
|
||||||
|
"""Fix decoding issues in Python 2."""
|
||||||
if sys.version_info < (3, 0):
|
if sys.version_info < (3, 0):
|
||||||
query = query.decode('utf-8')
|
query = query.decode('utf-8')
|
||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
def filter_path(path):
|
def filter_path(path):
|
||||||
os.chdir(sys.path[0])
|
os.chdir(sys.path[0])
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
os.makedirs(path)
|
os.makedirs(path)
|
||||||
for temp in os.listdir(path):
|
for temp in os.listdir(path):
|
||||||
if temp.endswith('.temp'):
|
if temp.endswith('.temp'):
|
||||||
os.remove(path + '/' + temp)
|
os.remove('{0}/{1}'.format(path, temp))
|
||||||
|
|
||||||
|
|
||||||
def grace_quit():
|
def grace_quit():
|
||||||
print('')
|
print('\n\nExiting.')
|
||||||
print('')
|
|
||||||
print('Exitting..')
|
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|||||||
138
spotdl.py
138
spotdl.py
@@ -1,5 +1,4 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
# -*- coding: UTF-8 -*-
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
from core import metadata
|
from core import metadata
|
||||||
@@ -19,15 +18,17 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
import urllib.request as urllib2
|
import urllib.request as urllib2
|
||||||
|
|
||||||
# "[artist] - [song]"
|
|
||||||
def generate_songname(raw_song):
|
def generate_songname(raw_song):
|
||||||
|
"""Generate a string of the format '[artist] - [song]' for the given song."""
|
||||||
if misc.is_spotify(raw_song):
|
if misc.is_spotify(raw_song):
|
||||||
tags = generate_metadata(raw_song)
|
tags = generate_metadata(raw_song)
|
||||||
raw_song = tags['artists'][0]['name'] + ' - ' + tags['name']
|
raw_song = u'{0} - {1}'.format(tags['artists'][0]['name'], tags['name'])
|
||||||
return misc.fix_encoding(raw_song)
|
return misc.fix_encoding(raw_song)
|
||||||
|
|
||||||
# fetch song's metadata from spotify
|
|
||||||
def generate_metadata(raw_song):
|
def generate_metadata(raw_song):
|
||||||
|
"""Fetch a song's metadata from Spotify."""
|
||||||
if misc.is_spotify(raw_song):
|
if misc.is_spotify(raw_song):
|
||||||
# fetch track information directly if it is spotify link
|
# fetch track information directly if it is spotify link
|
||||||
meta_tags = spotify.track(raw_song)
|
meta_tags = spotify.track(raw_song)
|
||||||
@@ -52,18 +53,18 @@ def generate_metadata(raw_song):
|
|||||||
meta_tags[u'release_date'] = album['release_date']
|
meta_tags[u'release_date'] = album['release_date']
|
||||||
meta_tags[u'publisher'] = album['label']
|
meta_tags[u'publisher'] = album['label']
|
||||||
meta_tags[u'total_tracks'] = album['tracks']['total']
|
meta_tags[u'total_tracks'] = album['tracks']['total']
|
||||||
#import pprint
|
# import pprint
|
||||||
#pprint.pprint(meta_tags)
|
# pprint.pprint(meta_tags)
|
||||||
#pprint.pprint(spotify.album(meta_tags['album']['id']))
|
# pprint.pprint(spotify.album(meta_tags['album']['id']))
|
||||||
return meta_tags
|
return meta_tags
|
||||||
|
|
||||||
|
|
||||||
def generate_youtube_url(raw_song):
|
def generate_youtube_url(raw_song):
|
||||||
# decode spotify http link to "[artist] - [song]"
|
"""Search for the song on YouTube and generate an URL to its video."""
|
||||||
song = generate_songname(raw_song)
|
song = generate_songname(raw_song)
|
||||||
# generate direct search YouTube URL
|
|
||||||
search_url = misc.generate_search_url(song)
|
search_url = misc.generate_search_url(song)
|
||||||
item = urllib2.urlopen(search_url).read()
|
item = urllib2.urlopen(search_url).read()
|
||||||
#item = unicode(item, 'utf-8')
|
# item = unicode(item, 'utf-8')
|
||||||
items_parse = BeautifulSoup(item, "html.parser")
|
items_parse = BeautifulSoup(item, "html.parser")
|
||||||
check = 1
|
check = 1
|
||||||
if args.manual:
|
if args.manual:
|
||||||
@@ -74,8 +75,8 @@ def generate_youtube_url(raw_song):
|
|||||||
# fetch all video links on first page on YouTube
|
# fetch all video links on first page on YouTube
|
||||||
for x in items_parse.find_all('h3', {'class': 'yt-lockup-title'}):
|
for x in items_parse.find_all('h3', {'class': 'yt-lockup-title'}):
|
||||||
# confirm the video result is not an advertisement
|
# confirm the video result is not an advertisement
|
||||||
if not x.find('channel') == -1 or not x.find('googleads') == -1:
|
if x.find('channel') is None and x.find('googleads') is None:
|
||||||
print(str(check) + '. ' + x.get_text())
|
print(u'{0}. {1}'.format(check, x.get_text()))
|
||||||
links.append(x.find('a')['href'])
|
links.append(x.find('a')['href'])
|
||||||
check += 1
|
check += 1
|
||||||
print('')
|
print('')
|
||||||
@@ -85,46 +86,52 @@ def generate_youtube_url(raw_song):
|
|||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
# get video link of the first YouTube result
|
# 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
|
# confirm the video result is not an advertisement
|
||||||
# otherwise keep iterating until it is not
|
# otherwise keep iterating until it is not
|
||||||
while not result.find('channel') == -1 or not result.find('googleads') == -1:
|
while result.find('channel') > -1 or result.find('googleads') > -1:
|
||||||
result = items_parse.find_all(attrs={'class': 'yt-uix-tile-link'})[check]['href']
|
result = items_parse.find_all(
|
||||||
|
attrs={'class': 'yt-uix-tile-link'})[check]['href']
|
||||||
check += 1
|
check += 1
|
||||||
full_link = "youtube.com" + result
|
|
||||||
|
full_link = u'youtube.com{0}'.format(result)
|
||||||
return full_link
|
return full_link
|
||||||
|
|
||||||
# parse track from YouTube
|
|
||||||
def go_pafy(raw_song):
|
def go_pafy(raw_song):
|
||||||
# video link of the video to extract audio from
|
"""Parse track from YouTube."""
|
||||||
track_url = generate_youtube_url(raw_song)
|
track_url = generate_youtube_url(raw_song)
|
||||||
if track_url is None:
|
if track_url is None:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
# parse the YouTube video
|
|
||||||
return pafy.new(track_url)
|
return pafy.new(track_url)
|
||||||
|
|
||||||
# title of the YouTube video
|
|
||||||
def get_youtube_title(content, number=None):
|
def get_youtube_title(content, number=None):
|
||||||
|
"""Get the YouTube video's title."""
|
||||||
title = misc.fix_encoding(content.title)
|
title = misc.fix_encoding(content.title)
|
||||||
if number is None:
|
if number is None:
|
||||||
return title
|
return title
|
||||||
else:
|
else:
|
||||||
return str(number) + '. ' + title
|
return '{0}. {1}'.format(number, title)
|
||||||
|
|
||||||
|
|
||||||
# fetch user playlists when using -u option
|
|
||||||
def feed_playlist(username):
|
def feed_playlist(username):
|
||||||
# fetch all user playlists
|
"""Fetch user playlists when using the -u option."""
|
||||||
playlists = spotify.user_playlists(username)
|
playlists = spotify.user_playlists(username)
|
||||||
links = []
|
links = []
|
||||||
check = 1
|
check = 1
|
||||||
# iterate over user playlists
|
|
||||||
while True:
|
while True:
|
||||||
for playlist in playlists['items']:
|
for playlist in playlists['items']:
|
||||||
# In rare cases, playlists may not be found, so playlists['next'] is
|
# in rare cases, playlists may not be found, so playlists['next']
|
||||||
# None. Skip these. Also see Issue #91.
|
# is None. Skip these. Also see Issue #91.
|
||||||
if playlist['name'] is not None:
|
if playlist['name'] is not None:
|
||||||
print(str(check) + '. ' + misc.fix_encoding(playlist['name']) + ' (' + str(playlist['tracks']['total']) + ' tracks)')
|
print(u'{0}. {1} ({2} tracks)'.format(
|
||||||
|
check, misc.fix_encoding(playlist['name']),
|
||||||
|
playlist['tracks']['total']))
|
||||||
links.append(playlist)
|
links.append(playlist)
|
||||||
check += 1
|
check += 1
|
||||||
if playlists['next']:
|
if playlists['next']:
|
||||||
@@ -133,25 +140,23 @@ def feed_playlist(username):
|
|||||||
break
|
break
|
||||||
|
|
||||||
print('')
|
print('')
|
||||||
# let user select playlist
|
|
||||||
playlist = misc.input_link(links)
|
playlist = misc.input_link(links)
|
||||||
# fetch detailed information for playlist
|
results = spotify.user_playlist(
|
||||||
results = spotify.user_playlist(playlist['owner']['id'], playlist['id'], fields="tracks,next")
|
playlist['owner']['id'], playlist['id'], fields='tracks,next')
|
||||||
print('')
|
print('')
|
||||||
# slugify removes any special characters
|
file = u'{0}.txt'.format(slugify(playlist['name'], ok='-_()[]{}'))
|
||||||
file = slugify(playlist['name'], ok='-_()[]{}') + '.txt'
|
print(u'Feeding {0} tracks to {1}'.format(playlist['tracks']['total'], file))
|
||||||
print('Feeding ' + str(playlist['tracks']['total']) + ' tracks to ' + file)
|
|
||||||
|
|
||||||
tracks = results['tracks']
|
tracks = results['tracks']
|
||||||
with open(file, 'a') as fout:
|
with open(file, 'a') as file_out:
|
||||||
while True:
|
while True:
|
||||||
for item in tracks['items']:
|
for item in tracks['items']:
|
||||||
track = item['track']
|
track = item['track']
|
||||||
try:
|
try:
|
||||||
fout.write(track['external_urls']['spotify'] + '\n')
|
file_out.write(track['external_urls']['spotify'] + '\n')
|
||||||
except KeyError:
|
except KeyError:
|
||||||
title = track['name'] + ' by '+ track['artists'][0]['name']
|
print(u'Skipping track {0} by {1} (local only?)'.format(
|
||||||
print('Skipping track ' + title + ' (local only?)')
|
track['name'], track['artists'][0]['name']))
|
||||||
# 1 page = 50 results
|
# 1 page = 50 results
|
||||||
# check if there are more pages
|
# check if there are more pages
|
||||||
if tracks['next']:
|
if tracks['next']:
|
||||||
@@ -159,12 +164,12 @@ def feed_playlist(username):
|
|||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
||||||
def download_song(content):
|
def download_song(content):
|
||||||
|
"""Download the audio file from YouTube."""
|
||||||
if args.input_ext == '.webm':
|
if args.input_ext == '.webm':
|
||||||
# best available audio in .webm
|
|
||||||
link = content.getbestaudio(preftype='webm')
|
link = content.getbestaudio(preftype='webm')
|
||||||
elif args.input_ext == '.m4a':
|
elif args.input_ext == '.m4a':
|
||||||
# best available audio in .webm
|
|
||||||
link = content.getbestaudio(preftype='m4a')
|
link = content.getbestaudio(preftype='m4a')
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
@@ -173,16 +178,17 @@ def download_song(content):
|
|||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
music_file = misc.generate_filename(content.title)
|
music_file = misc.generate_filename(content.title)
|
||||||
# download link
|
link.download(
|
||||||
link.download(filepath='Music/' + music_file + args.input_ext)
|
filepath='Music/{0}{1}'.format(music_file, args.input_ext))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# check if input song already exists in Music folder
|
|
||||||
def check_exists(music_file, raw_song, islist=True):
|
def check_exists(music_file, raw_song, islist=True):
|
||||||
files = os.listdir("Music")
|
"""Check if the input song already exists in the 'Music' folder."""
|
||||||
|
files = os.listdir('Music')
|
||||||
for file in files:
|
for file in files:
|
||||||
if file.endswith(".temp"):
|
if file.endswith('.temp'):
|
||||||
os.remove("Music/" + file)
|
os.remove(u'Music/{0}'.format(file))
|
||||||
continue
|
continue
|
||||||
# check if any file with similar name is already present in Music/
|
# check if any file with similar name is already present in Music/
|
||||||
dfile = misc.fix_decoding(file)
|
dfile = misc.fix_decoding(file)
|
||||||
@@ -190,25 +196,31 @@ def check_exists(music_file, raw_song, islist=True):
|
|||||||
if dfile.startswith(umfile):
|
if dfile.startswith(umfile):
|
||||||
# check if the already downloaded song has correct metadata
|
# check if the already downloaded song has correct metadata
|
||||||
already_tagged = metadata.compare(file, generate_metadata(raw_song))
|
already_tagged = metadata.compare(file, generate_metadata(raw_song))
|
||||||
|
|
||||||
# if not, remove it and download again without prompt
|
# if not, remove it and download again without prompt
|
||||||
if misc.is_spotify(raw_song) and not already_tagged:
|
if misc.is_spotify(raw_song) and not already_tagged:
|
||||||
os.remove("Music/" + file)
|
os.remove('Music/{0}'.format(file))
|
||||||
return False
|
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:
|
if islist:
|
||||||
return True
|
return True
|
||||||
# if downloading only single song, prompt to re-download
|
# if downloading only single song, prompt to re-download
|
||||||
else:
|
else:
|
||||||
prompt = misc.user_input('Song with same name has already been downloaded. Re-download? (y/n): ').lower()
|
prompt = misc.user_input(
|
||||||
if prompt == "y":
|
'Song with same name has already been downloaded. '
|
||||||
os.remove("Music/" + file)
|
'Re-download? (y/n): ').lower()
|
||||||
|
if prompt == 'y':
|
||||||
|
os.remove('Music/{0}'.format(file))
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# download songs from list
|
|
||||||
def grab_list(file):
|
def grab_list(file):
|
||||||
|
"""Download all songs from the list."""
|
||||||
with open(file, 'r') as listed:
|
with open(file, 'r') as listed:
|
||||||
lines = (listed.read()).splitlines()
|
lines = (listed.read()).splitlines()
|
||||||
# ignore blank lines in file (if any)
|
# ignore blank lines in file (if any)
|
||||||
@@ -216,7 +228,7 @@ def grab_list(file):
|
|||||||
lines.remove('')
|
lines.remove('')
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
print('Total songs in list = ' + str(len(lines)) + ' songs')
|
print(u'Total songs in list: {0} songs'.format(len(lines)))
|
||||||
print('')
|
print('')
|
||||||
# nth input song
|
# nth input song
|
||||||
number = 1
|
number = 1
|
||||||
@@ -226,9 +238,9 @@ def grab_list(file):
|
|||||||
# token expires after 1 hour
|
# token expires after 1 hour
|
||||||
except spotipy.oauth2.SpotifyOauthError:
|
except spotipy.oauth2.SpotifyOauthError:
|
||||||
# refresh token when it expires
|
# refresh token when it expires
|
||||||
token = misc.generate_token()
|
new_token = misc.generate_token()
|
||||||
global spotify
|
global spotify
|
||||||
spotify = spotipy.Spotify(auth=token)
|
spotify = spotipy.Spotify(auth=new_token)
|
||||||
grab_single(raw_song, number=number)
|
grab_single(raw_song, number=number)
|
||||||
# detect network problems
|
# detect network problems
|
||||||
except (urllib2.URLError, TypeError, IOError):
|
except (urllib2.URLError, TypeError, IOError):
|
||||||
@@ -247,9 +259,9 @@ def grab_list(file):
|
|||||||
misc.trim_song(file)
|
misc.trim_song(file)
|
||||||
number += 1
|
number += 1
|
||||||
|
|
||||||
# logic behind downloading some song
|
|
||||||
def grab_single(raw_song, number=None):
|
def grab_single(raw_song, number=None):
|
||||||
# check if song is being downloaded from list
|
"""Logic behind downloading a song."""
|
||||||
if number:
|
if number:
|
||||||
islist = True
|
islist = True
|
||||||
else:
|
else:
|
||||||
@@ -257,9 +269,10 @@ def grab_single(raw_song, number=None):
|
|||||||
content = go_pafy(raw_song)
|
content = go_pafy(raw_song)
|
||||||
if content is None:
|
if content is None:
|
||||||
return
|
return
|
||||||
# print "[number]. [artist] - [song]" if downloading from list
|
# print '[number]. [artist] - [song]' if downloading from list
|
||||||
# otherwise print "[artist] - [song]"
|
# otherwise print '[artist] - [song]'
|
||||||
print(get_youtube_title(content, number))
|
print(get_youtube_title(content, number))
|
||||||
|
|
||||||
# generate file name of the song to download
|
# generate file name of the song to download
|
||||||
music_file = misc.generate_filename(content.title)
|
music_file = misc.generate_filename(content.title)
|
||||||
music_file = misc.fix_decoding(music_file)
|
music_file = misc.fix_decoding(music_file)
|
||||||
@@ -268,17 +281,16 @@ def grab_single(raw_song, number=None):
|
|||||||
print('')
|
print('')
|
||||||
input_song = music_file + args.input_ext
|
input_song = music_file + args.input_ext
|
||||||
output_song = music_file + args.output_ext
|
output_song = music_file + args.output_ext
|
||||||
convert.song(input_song,
|
convert.song(input_song, output_song, avconv=args.avconv,
|
||||||
output_song,
|
|
||||||
avconv=args.avconv,
|
|
||||||
verbose=args.verbose)
|
verbose=args.verbose)
|
||||||
os.remove('Music/' + input_song)
|
os.remove('Music/{0}'.format(misc.fix_encoding(input_song)))
|
||||||
meta_tags = generate_metadata(raw_song)
|
meta_tags = generate_metadata(raw_song)
|
||||||
if not args.no_metadata:
|
if not args.no_metadata:
|
||||||
metadata.embed(output_song, meta_tags)
|
metadata.embed(output_song, meta_tags)
|
||||||
else:
|
else:
|
||||||
print('No audio streams available')
|
print('No audio streams available')
|
||||||
|
|
||||||
|
|
||||||
class Args(object):
|
class Args(object):
|
||||||
manual = False
|
manual = False
|
||||||
input_ext = '.m4a'
|
input_ext = '.m4a'
|
||||||
@@ -293,9 +305,7 @@ spotify = spotipy.Spotify(auth=token)
|
|||||||
misc.filter_path('Music')
|
misc.filter_path('Music')
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
||||||
os.chdir(sys.path[0])
|
os.chdir(sys.path[0])
|
||||||
|
|
||||||
args = misc.get_arguments()
|
args = misc.get_arguments()
|
||||||
|
|
||||||
if args.song:
|
if args.song:
|
||||||
|
|||||||
@@ -4,22 +4,26 @@ import spotdl
|
|||||||
|
|
||||||
raw_song = 'http://open.spotify.com/track/0JlS7BXXD07hRmevDnbPDU'
|
raw_song = 'http://open.spotify.com/track/0JlS7BXXD07hRmevDnbPDU'
|
||||||
|
|
||||||
|
|
||||||
def test_spotify_title():
|
def test_spotify_title():
|
||||||
expect_title = 'David André Østby - Intro'
|
expect_title = 'David André Østby - Intro'
|
||||||
title = spotdl.generate_songname(raw_song)
|
title = spotdl.generate_songname(raw_song)
|
||||||
assert title == expect_title
|
assert title == expect_title
|
||||||
|
|
||||||
|
|
||||||
def test_youtube_url():
|
def test_youtube_url():
|
||||||
expect_url = 'youtube.com/watch?v=rg1wfcty0BA'
|
expect_url = 'youtube.com/watch?v=rg1wfcty0BA'
|
||||||
url = spotdl.generate_youtube_url(raw_song)
|
url = spotdl.generate_youtube_url(raw_song)
|
||||||
assert url == expect_url
|
assert url == expect_url
|
||||||
|
|
||||||
|
|
||||||
def test_youtube_title():
|
def test_youtube_title():
|
||||||
expect_title = 'Intro - David André Østby'
|
expect_title = 'Intro - David André Østby'
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
title = spotdl.get_youtube_title(content)
|
title = spotdl.get_youtube_title(content)
|
||||||
assert title == expect_title
|
assert title == expect_title
|
||||||
|
|
||||||
|
|
||||||
def test_check_exists():
|
def test_check_exists():
|
||||||
expect_check = False
|
expect_check = False
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
@@ -28,15 +32,17 @@ def test_check_exists():
|
|||||||
check = spotdl.check_exists(music_file, raw_song)
|
check = spotdl.check_exists(music_file, raw_song)
|
||||||
assert check == expect_check
|
assert check == expect_check
|
||||||
|
|
||||||
|
|
||||||
def test_download():
|
def test_download():
|
||||||
expect_download = True
|
expect_download = True
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
download = spotdl.download_song(content)
|
download = spotdl.download_song(content)
|
||||||
assert download == expect_download
|
assert download == expect_download
|
||||||
|
|
||||||
|
|
||||||
def test_convert():
|
def test_convert():
|
||||||
# exit code None = success
|
# exit code 0 = success
|
||||||
expect_convert = None
|
expect_convert = 0
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
music_file = spotdl.misc.generate_filename(content.title)
|
music_file = spotdl.misc.generate_filename(content.title)
|
||||||
music_file = spotdl.misc.fix_decoding(music_file)
|
music_file = spotdl.misc.fix_decoding(music_file)
|
||||||
@@ -45,6 +51,7 @@ def test_convert():
|
|||||||
convert = spotdl.convert.song(input_song, output_song)
|
convert = spotdl.convert.song(input_song, output_song)
|
||||||
assert convert == expect_convert
|
assert convert == expect_convert
|
||||||
|
|
||||||
|
|
||||||
def test_metadata():
|
def test_metadata():
|
||||||
expect_metadata = True
|
expect_metadata = True
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
@@ -60,6 +67,7 @@ def test_metadata():
|
|||||||
|
|
||||||
assert metadata_output == (metadata_input == expect_metadata)
|
assert metadata_output == (metadata_input == expect_metadata)
|
||||||
|
|
||||||
|
|
||||||
def check_exists2():
|
def check_exists2():
|
||||||
expect_check = True
|
expect_check = True
|
||||||
content = spotdl.go_pafy(raw_song)
|
content = spotdl.go_pafy(raw_song)
|
||||||
|
|||||||
@@ -4,22 +4,26 @@ import spotdl
|
|||||||
|
|
||||||
username = 'alex'
|
username = 'alex'
|
||||||
|
|
||||||
|
|
||||||
def test_user():
|
def test_user():
|
||||||
expect_playlists = 7
|
expect_playlists = 7
|
||||||
playlists = spotdl.spotify.user_playlists(username)
|
playlists = spotdl.spotify.user_playlists(username)
|
||||||
playlists = len(playlists['items'])
|
playlists = len(playlists['items'])
|
||||||
assert playlists == expect_playlists
|
assert playlists == expect_playlists
|
||||||
|
|
||||||
|
|
||||||
def test_playlist():
|
def test_playlist():
|
||||||
expect_tracks = 14
|
expect_tracks = 14
|
||||||
playlist = spotdl.spotify.user_playlists(username)['items'][0]
|
playlist = spotdl.spotify.user_playlists(username)['items'][0]
|
||||||
tracks = playlist['tracks']['total']
|
tracks = playlist['tracks']['total']
|
||||||
assert tracks == expect_tracks
|
assert tracks == expect_tracks
|
||||||
|
|
||||||
|
|
||||||
def test_tracks():
|
def test_tracks():
|
||||||
playlist = spotdl.spotify.user_playlists(username)['items'][0]
|
playlist = spotdl.spotify.user_playlists(username)['items'][0]
|
||||||
expect_lines = playlist['tracks']['total']
|
expect_lines = playlist['tracks']['total']
|
||||||
result = spotdl.spotify.user_playlist(playlist['owner']['id'], playlist['id'], fields='tracks,next')
|
result = spotdl.spotify.user_playlist(
|
||||||
|
playlist['owner']['id'], playlist['id'], fields='tracks,next')
|
||||||
tracks = result['tracks']
|
tracks = result['tracks']
|
||||||
|
|
||||||
with open('list.txt', 'a') as fout:
|
with open('list.txt', 'a') as fout:
|
||||||
|
|||||||
Reference in New Issue
Block a user