This commit is contained in:
Kepoor Hampond 2017-03-15 20:14:05 -07:00
commit 4a1d34db0b
7 changed files with 210 additions and 140 deletions

View file

@ -5,7 +5,7 @@ Ironic Redistribution System
[![License: GNU](https://img.shields.io/badge/license-gnu-yellow.svg?style=flat-square)](http://www.gnu.org/licenses/gpl.html) [![License: GNU](https://img.shields.io/badge/license-gnu-yellow.svg?style=flat-square)](http://www.gnu.org/licenses/gpl.html)
[![Stars](https://img.shields.io/github/stars/kepoorhampond/irs.svg?style=flat-square)](https://github.com/kepoorhampond/irs/stargazers) [![Stars](https://img.shields.io/github/stars/kepoorhampond/irs.svg?style=flat-square)](https://github.com/kepoorhampond/irs/stargazers)
[![Build Status](https://img.shields.io/travis/kepoorhampond/irs/master.svg?style=flat-square)](https://travis-ci.org/karma-runner/karma-coverage) [![Build Status](https://img.shields.io/travis/kepoorhampond/irs/master.svg?style=flat-square)](https://travis-ci.org/kepoorhampond/irs)
[![Say Thanks](https://img.shields.io/badge/say-thanks-ff69b4.svg?style=flat-square)](https://saythanks.io/to/kepoorhampond) [![Say Thanks](https://img.shields.io/badge/say-thanks-ff69b4.svg?style=flat-square)](https://saythanks.io/to/kepoorhampond)
[![Coverage Status](http://img.shields.io/coveralls/kepoorhampond/irs.svg?style=flat-square)](https://coveralls.io/github/kepoorhampond/irs?branch=master&style=flat-square) [![Coverage Status](http://img.shields.io/coveralls/kepoorhampond/irs.svg?style=flat-square)](https://coveralls.io/github/kepoorhampond/irs?branch=master&style=flat-square)
[![PyPI](https://img.shields.io/badge/pypi-irs-blue.svg?style=flat-square)](https://pypi.python.org/pypi/irs) [![PyPI](https://img.shields.io/badge/pypi-irs-blue.svg?style=flat-square)](https://pypi.python.org/pypi/irs)
@ -42,6 +42,7 @@ optional arguments:
-l LOCATION, --location LOCATION -l LOCATION, --location LOCATION
Specify a directory to place files in. Specify a directory to place files in.
-o, --organize Organize downloaded files. -o, --organize Organize downloaded files.
-c, --config Display path to config file.
``` ```
So all of these are valid commands: So all of these are valid commands:
``` ```

View file

@ -7,7 +7,8 @@ import os
# Powered by: # Powered by:
from .ripper import Ripper from .ripper import Ripper
from .utils import console, remove_none_values from .utils import console, parse_default_flags
from .config import CONFIG
def main(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -27,12 +28,21 @@ def main():
parser.add_argument("-l", "--location", dest="location", help="Specify a directory to place files in.") parser.add_argument("-l", "--location", dest="location", help="Specify a directory to place files in.")
parser.add_argument("-o", "--organize", dest="organize", action="store_true", help="Organize downloaded files.") parser.add_argument("-o", "--organize", dest="organize", action="store_true", help="Organize downloaded files.")
# Config
parser.add_argument("-c", "--config", dest="config", action="store_true", help="Display path to config file.")
args = parser.parse_args(parse_default_flags())
if args.config:
import irs
print (os.path.dirname(irs.__file__) + "/config.py")
sys.exit()
args = parser.parse_args()
ripper_args = { ripper_args = {
"post_processors": { "post_processors": {
"location": args.location, "custom_directory": args.location,
"organize": args.organize, "organize": args.organize,
} }
} }
@ -46,7 +56,7 @@ def main():
elif args.username and args.playlist: elif args.username and args.playlist:
ripper.spotify_list("playlist", args.playlist, args.username) ripper.spotify_list("playlist", args.playlist, args.username)
else: else:
console(Ripper()) console(ripper)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -1,29 +1,22 @@
from os.path import expanduser
CONFIG = dict( CONFIG = dict(
# To autostart rhythmbox with a new song: default_flags = ['-o'],
# default_flags = '-c rhythmbox %(loc)s', # For default flags. Right now, it organizes your files into an
# To make choosing of links default: # artist/album/song structure.
# default_flags = '-l', # To add a flag or argument, add an element to the index:
# To place all playlist songs into one folder: # default_flags = ['-o', '-l', '~/Music']
# default_flags = '-of',
default_flags = '',
SPOTIFY_CLIENT_ID = '',
# These are necessary to download Spotify playlists SPOTIFY_CLIENT_SECRET = '',
client_id = '', # You can either specify Spotify keys here, or in environment variables.
client_secret = '',
additional_search_terms = 'lyrics', additional_search_terms = 'lyrics',
# For a custom directory. Note that `~` will not work as a shortcut in a organize = True,
# plain text manner. # True always forces organization.
directory = str(expanduser("~")) + "/Music", # False always forces non-organization.
# None allows options and flags to determine if the files will be organized.
# If you want numbered file names custom_directory = "",
numbered_file_names = True, # Defaults to '~/Music'
# Downloaded file names
download_file_names = False,
) )

View file

@ -74,5 +74,3 @@ def parse_genre(genres):
return genres[0].title() return genres[0].title()
else: else:
return "" return ""
#Metadata("Da Frame 2R.mp3").add_album_art("https://i.scdn.co/image/c8931dc7eb717531de93ae0d4626362875c51ba9")

View file

@ -30,28 +30,39 @@ class Ripper:
self.locations = [] self.locations = []
self.type = None self.type = None
try: try:
client_credentials_manager = SpotifyClientCredentials(os.environ["SPOTIFY_CLIENT_ID"], os.environ["SPOTIFY_CLIENT_SECRET"]) CLIENT_ID, CLIENT_SECRET = parse_spotify_creds(self)
client_credentials_manager = SpotifyClientCredentials(CLIENT_ID, CLIENT_SECRET)
self.spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager) self.spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
self.authorized = True self.authorized = True
except spotipy.oauth2.SpotifyOauthError: except Exception as e:
self.spotify = spotipy.Spotify() self.spotify = spotipy.Spotify()
self.authorized = False self.authorized = False
def post_processing(self, locations): def post_processing(self, locations):
post_processors = self.args.get("post_processors") post_processors = self.args.get("post_processors")
if post_processors: if post_processors:
if type(post_processors.get("location")) is str: if parse_directory(self) != None:
for index, loc in enumerate(locations): for index, loc in enumerate(locations):
new_file_name = post_processors["location"] + "/" + loc new_file_name = parse_directory(self) + "/" + loc
os.rename(loc, new_file_name) os.rename(loc, new_file_name)
locations[index] = new_file_name locations[index] = new_file_name
if post_processors.get("organize") == True: # I'd just go on believing that code this terrible doesn't exist.
if self.type == "album": # You can just close your eyes and scroll by. I'd encourage it.
# It's okay if you need to cry though.
# The rest of the code is here for you.
# It's like loving someone,
# Everyone has some flaws, but you still appreciate and embrace
# those flaws for being exclusive to them.
# And if those flaws are really enough to turn you off of them, then
# you *probably* don't really want to be with them anyways.
# Either way, it's up to you.
if parse_organize(self):
if self.type in ("album", "song"):
for index, loc in enumerate(locations): for index, loc in enumerate(locations):
mp3 = Metadata(loc) mp3 = Metadata(loc)
new_loc = "" new_loc = ""
if len(loc.split("/")) > 1: if len(loc.split("/")) >= 2:
new_loc = "/".join(loc.split("/")[0:-1]) new_loc = "/".join(loc.split("/")[0:-1]) + "/"
file_name = loc.split("/")[-1] file_name = loc.split("/")[-1]
else: else:
file_name = loc file_name = loc
@ -66,6 +77,7 @@ class Ripper:
new_loc = new_loc.replace("//", "/") new_loc = new_loc.replace("//", "/")
os.rename(loc, new_loc) os.rename(loc, new_loc)
locations[index] = new_loc locations[index] = new_loc
print (new_loc)
elif self.type == "playlist": elif self.type == "playlist":
for index, loc in enumerate(locations): for index, loc in enumerate(locations):
new_loc = "" new_loc = ""
@ -83,16 +95,16 @@ class Ripper:
return locations return locations
def find_yt_url(self, song=None, artist=None, additional_search="lyrics"): def find_yt_url(self, song=None, artist=None, additional_search=None):
if additional_search == None:
additional_search = parse_search_terms(self)
try: try:
if not song: song = self.args["song_title"] if not song: song = self.args["song_title"]
if not artist: artist = self.args["artist"] if not artist: artist = self.args["artist"]
except KeyError: except KeyError:
raise ValueError("Must specify song_title/artist in `args` with init, or in method arguments.") raise ValueError("Must specify song_title/artist in `args` with init, or in method arguments.")
clear_line() print ("Finding Youtube Link ...")
sys.stdout.write("Finding Youtube Link ...\r")
sys.stdout.flush()
search_terms = song + " " + artist + " " + additional_search search_terms = song + " " + artist + " " + additional_search
query_string = urlencode({"search_query" : (search_terms)}) query_string = urlencode({"search_query" : (search_terms)})
@ -178,8 +190,7 @@ class Ripper:
break break
if the_list != None: if the_list != None:
clear_line() clear_line()
sys.stdout.write(type.title() + ': "%s" by "%s"\r' % (the_list["name"], the_list["artists"][0]["name"])) print (type.title() + ': "%s" by "%s"' % (the_list["name"], the_list["artists"][0]["name"]))
sys.stdout.flush()
compilation = "" compilation = ""
if type == "album": if type == "album":
tmp_artists = [] tmp_artists = []
@ -285,9 +296,7 @@ class Ripper:
video_url, video_title = self.find_yt_url(song, artist) video_url, video_title = self.find_yt_url(song, artist)
clear_line() print ('Downloading "%s" by "%s" ...' % (song, artist))
sys.stdout.write('Downloading "%s" by "%s" ...\r' % (song, artist))
sys.stdout.flush()
file_name = str(data["file_prefix"] + blank(song, False) + ".mp3") file_name = str(data["file_prefix"] + blank(song, False) + ".mp3")

View file

@ -21,9 +21,7 @@ class MyLogger(object):
def my_hook(d): def my_hook(d):
if d['status'] == 'finished': if d['status'] == 'finished':
clear_line() # TODO: Make this into a method. print ("Converting to mp3 ...")
sys.stdout.write("Converting to mp3 ...\r")
sys.stdout.flush()
#================================= #=================================
@ -280,3 +278,64 @@ def console(ripper):
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(0) sys.exit(0)
#======================
# Config File and Flags
#======================
from .config import CONFIG
def check_sources(ripper, key, default=None, environment=False, where=None):
if where != None:
tmp_args = ripper.args.get(where)
else:
tmp_args = ripper.args
if tmp_args.get(key):
return tmp_args.get(key)
#============
# CONFIG FILE
#============
from .config import CONFIG
def check_sources(ripper, key, default=None, environment=False):
if ripper.args.get(key):
return ripper.args.get(key)
elif CONFIG.get(key):
return CONFIG.get(key)
elif os.environ.get(key) and environment == True:
return os.environ.get(key)
else:
return default
def parse_spotify_creds(ripper):
CLIENT_ID = check_sources(ripper, "SPOTIFY_CLIENT_ID", environment=True)
CLIENT_SECRET = check_sources(ripper, "SPOTIFY_CLIENT_SECRET", environment=True)
return CLIENT_ID, CLIENT_SECRET
def parse_search_terms(ripper):
search_terms = check_sources(ripper, "additional_search_terms", "lyrics")
return search_terms
def parse_directory(ripper):
directory = check_sources(ripper, "custom_directory", where="post_processors")
if directory == None:
directory = check_sources(ripper, "custom_directory", "~/Music")
return directory.replace("~", os.path.expanduser("~"))
def parse_default_flags(default=""):
if CONFIG.get("default_flags"):
args = sys.argv[1:] + CONFIG.get("default_flags")
else:
args = default
return args
def parse_organize(ripper):
organize = check_sources(ripper, "organize")
if organize == None:
return check_sources(ripper, "organize", False, where="post_processors")
else:
return True
def parse_search_terms(ripper):
search_terms = check_sources(ripper, "additional_search_terms", "lyrics")
return search_terms

View file

@ -7,14 +7,14 @@ if not os.path.exists("test_dir"):
os.makedirs("test_dir") os.makedirs("test_dir")
Ripper({ Ripper({
"post_processors": { "post_processors": {
"location": "test_dir/", "custom_directory": "test_dir/",
"organize": True, "organize": True,
} }
}).album("Da Frame 2R / Matador") }).album("Da Frame 2R / Matador")
Ripper({ Ripper({
"post_processors": { "post_processors": {
"location": "test_dir/", "custom_directory": "test_dir/",
"organize": True, "organize": True,
} }
}).playlist("IRS Testing", "prakkillian") }).playlist("IRS Testing", "prakkillian")