Merge pull request #10 from kepoorhampond/config-file

Added a feature for config file.
This commit is contained in:
Kepoor Hampond 2017-03-15 20:05:58 -07:00 committed by GitHub
commit 3696710e63
7 changed files with 210 additions and 140 deletions

View file

@ -4,7 +4,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)
[![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)
[![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)
@ -41,6 +41,7 @@ optional arguments:
-l LOCATION, --location LOCATION
Specify a directory to place files in.
-o, --organize Organize downloaded files.
-c, --config Display path to config file.
```
So all of these are valid commands:
```

View file

@ -7,7 +7,8 @@ import os
# Powered by:
from .ripper import Ripper
from .utils import console, remove_none_values
from .utils import console, parse_default_flags
from .config import CONFIG
def main():
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("-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 = {
"post_processors": {
"location": args.location,
"custom_directory": args.location,
"organize": args.organize,
}
}
@ -46,7 +56,7 @@ def main():
elif args.username and args.playlist:
ripper.spotify_list("playlist", args.playlist, args.username)
else:
console(Ripper())
console(ripper)
if __name__ == "__main__":
main()

View file

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

View file

@ -74,5 +74,3 @@ def parse_genre(genres):
return genres[0].title()
else:
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.type = None
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.authorized = True
except spotipy.oauth2.SpotifyOauthError:
except Exception as e:
self.spotify = spotipy.Spotify()
self.authorized = False
def post_processing(self, locations):
post_processors = self.args.get("post_processors")
if post_processors:
if type(post_processors.get("location")) is str:
if parse_directory(self) != None:
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)
locations[index] = new_file_name
if post_processors.get("organize") == True:
if self.type == "album":
# I'd just go on believing that code this terrible doesn't exist.
# 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):
mp3 = Metadata(loc)
new_loc = ""
if len(loc.split("/")) > 1:
new_loc = "/".join(loc.split("/")[0:-1])
if len(loc.split("/")) >= 2:
new_loc = "/".join(loc.split("/")[0:-1]) + "/"
file_name = loc.split("/")[-1]
else:
file_name = loc
@ -66,6 +77,7 @@ class Ripper:
new_loc = new_loc.replace("//", "/")
os.rename(loc, new_loc)
locations[index] = new_loc
print (new_loc)
elif self.type == "playlist":
for index, loc in enumerate(locations):
new_loc = ""
@ -83,16 +95,16 @@ class Ripper:
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:
if not song: song = self.args["song_title"]
if not artist: artist = self.args["artist"]
except KeyError:
raise ValueError("Must specify song_title/artist in `args` with init, or in method arguments.")
clear_line()
sys.stdout.write("Finding Youtube Link ...\r")
sys.stdout.flush()
print ("Finding Youtube Link ...")
search_terms = song + " " + artist + " " + additional_search
query_string = urlencode({"search_query" : (search_terms)})
@ -178,8 +190,7 @@ class Ripper:
break
if the_list != None:
clear_line()
sys.stdout.write(type.title() + ': "%s" by "%s"\r' % (the_list["name"], the_list["artists"][0]["name"]))
sys.stdout.flush()
print (type.title() + ': "%s" by "%s"' % (the_list["name"], the_list["artists"][0]["name"]))
compilation = ""
if type == "album":
tmp_artists = []
@ -285,9 +296,7 @@ class Ripper:
video_url, video_title = self.find_yt_url(song, artist)
clear_line()
sys.stdout.write('Downloading "%s" by "%s" ...\r' % (song, artist))
sys.stdout.flush()
print ('Downloading "%s" by "%s" ...' % (song, artist))
file_name = str(data["file_prefix"] + blank(song, False) + ".mp3")

View file

@ -21,9 +21,7 @@ class MyLogger(object):
def my_hook(d):
if d['status'] == 'finished':
clear_line() # TODO: Make this into a method.
sys.stdout.write("Converting to mp3 ...\r")
sys.stdout.flush()
print ("Converting to mp3 ...")
#=================================
@ -280,3 +278,64 @@ def console(ripper):
except KeyboardInterrupt:
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")
Ripper({
"post_processors": {
"location": "test_dir/",
"custom_directory": "test_dir/",
"organize": True,
}
}).album("Da Frame 2R / Matador")
Ripper({
"post_processors": {
"location": "test_dir/",
"custom_directory": "test_dir/",
"organize": True,
}
}).playlist("IRS Testing", "prakkillian")