Skip to content

Commit

Permalink
clean code; fix time format
Browse files Browse the repository at this point in the history
  • Loading branch information
vitiko98 committed Oct 17, 2020
1 parent a6ad33a commit 68caf02
Show file tree
Hide file tree
Showing 8 changed files with 236 additions and 203 deletions.
104 changes: 60 additions & 44 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,46 @@
from qo_utils.search import Search
from qo_utils import downloader
from pick import pick
import argparse
import itertools
import re
import json
import os
import re
import sys
import json

from pick import pick

import qopy
from qo_utils import downloader
from qo_utils.search import Search


def getArgs():
parser = argparse.ArgumentParser(prog='python3 main.py')
parser.add_argument("-a", action="store_true",
help="enable albums-only search")
parser.add_argument("-i", action="store_true",
help="run Qo-Dl-curses on URL input mode")
parser.add_argument("-q", metavar="int", default=6,
help="quality (5, 6, 7, 27) (default: 6)")
parser.add_argument("-l", metavar="int", default=10,
help="limit of search results by type (default: 10)")
parser.add_argument("-d", metavar="PATH", default='Qobuz Downloads',
help="custom directory for downloads")
parser = argparse.ArgumentParser(prog="python3 main.py")
parser.add_argument("-a", action="store_true", help="enable albums-only search")
parser.add_argument(
"-i", action="store_true", help="run Qo-Dl-curses on URL input mode"
)
parser.add_argument(
"-q", metavar="int", default=6, help="quality (5, 6, 7, 27) (default: 6)"
)
parser.add_argument(
"-l",
metavar="int",
default=10,
help="limit of search results by type (default: 10)",
)
parser.add_argument(
"-d",
metavar="PATH",
default="Qobuz Downloads",
help="custom directory for downloads",
)
return parser.parse_args()


def getSession():
print('Logging...')
with open('config.json') as f:
print("Logging...")
with open("config.json") as f:
config = json.load(f)
return qopy.Client(config['email'], config['password'])
return qopy.Client(config["email"], config["password"])


def musicDir(dir):
Expand All @@ -40,13 +51,16 @@ def musicDir(dir):


def get_id(url):
return re.match(r'https?://(?:w{0,3}|play|open)\.qobuz\.com/(?:(?'
':album|track)/|[a-z]{2}-[a-z]{2}/album/-?\w+(?:-\w+)'
'*-?/|user/library/favorites/)(\w+)', url).group(1)
return re.match(
r"https?://(?:w{0,3}|play|open)\.qobuz\.com/(?:(?"
":album|track)/|[a-z]{2}-[a-z]{2}/album/-?\w+(?:-\w+)"
"*-?/|user/library/favorites/)(\w+)",
url,
).group(1)


def searchSelected(Qz, path, albums, ids, types, quality):
q = ['5', '6', '7', '27']
q = ["5", "6", "7", "27"]
quality = q[quality[1]]
for alb, id_, type_ in zip(albums, ids, types):
for al in alb:
Expand All @@ -57,7 +71,7 @@ def searchSelected(Qz, path, albums, ids, types, quality):


def fromUrl(Qz, path, link, quality):
if '/track/' in link:
if "/track/" in link:
id = get_id(link)
downloader.iterateIDs(Qz, id, path, quality, False)
else:
Expand All @@ -71,32 +85,37 @@ def interactive(Qz, path, limit, tracks=True):
try:
while True:
query = input("\nEnter your search: [Ctrl + c to quit]\n- ")
print('Searching...')
print("Searching...")
start = Search(Qz, query, limit)
start.getResults(tracks)
Types.append(start.Types)
IDs.append(start.IDs)

title = ('Select [space] the item(s) you want to download '
'(one or more)\nPress Ctrl + c to quit\n')
Selected = pick(start.Total, title,
multiselect=True, min_selection_count=1)
title = (
"Select [space] the item(s) you want to download "
"(one or more)\nPress Ctrl + c to quit\n"
)
Selected = pick(
start.Total, title, multiselect=True, min_selection_count=1
)
Albums.append(Selected)

y_n = pick(['Yes', 'No'], 'Items were added to queue to '
'be downloaded. Keep searching?')
if y_n[0][0] == 'N':
y_n = pick(
["Yes", "No"],
"Items were added to queue to be downloaded. Keep searching?",
)
if y_n[0][0] == "N":
break
else:
pass

desc = ('Select [intro] the quality (the quality will be automat'
'ically\ndowngraded if the selected is not found)')
Qualits = ['320', 'Lossless', 'Hi-res =< 96kHz', 'Hi-Res > 96 kHz']
desc = (
"Select [intro] the quality (the quality will be automat"
"ically\ndowngraded if the selected is not found)"
)
Qualits = ["320", "Lossless", "Hi-res =< 96kHz", "Hi-Res > 96 kHz"]
quality = pick(Qualits, desc)
searchSelected(Qz, path, Albums, IDs, Types, quality)
except KeyboardInterrupt:
sys.exit('\nBye')
sys.exit("\nBye")


def inputMode(Qz, path, quality):
Expand All @@ -105,18 +124,15 @@ def inputMode(Qz, path, quality):
link = input("\nAlbum/track URL: [Ctrl + c to quit]\n- ")
fromUrl(Qz, path, link, quality)
except KeyboardInterrupt:
sys.exit('\nBye')
sys.exit("\nBye")


def main():
arguments = getArgs()
directory = musicDir(arguments.d) + '/'
directory = musicDir(arguments.d) + "/"
Qz = getSession()
if not arguments.i:
if arguments.a:
interactive(Qz, directory, arguments.l, False)
else:
interactive(Qz, directory, arguments.l, True)
interactive(Qz, directory, arguments.l, not arguments.a)
else:
inputMode(Qz, directory, arguments.q)

Expand Down
91 changes: 45 additions & 46 deletions qo_utils/downloader.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import os

import requests
from qo_utils import metadata
from pathvalidate import sanitize_filename
from tqdm import tqdm

from qo_utils import metadata


def req_tqdm(url, fname, track_name):
r = requests.get(url, allow_redirects=True, stream=True)
total = int(r.headers.get('content-length', 0))
with open(fname, 'wb') as file, tqdm(
total = int(r.headers.get("content-length", 0))
with open(fname, "wb") as file, tqdm(
total=total,
unit='iB',
unit="iB",
unit_scale=True,
unit_divisor=1024,
desc=track_name,
bar_format='{n_fmt}/{total_fmt} /// {desc}',
bar_format="{n_fmt}/{total_fmt} /// {desc}",
) as bar:
for data in r.iter_content(chunk_size=1024):
size = file.write(data)
Expand All @@ -25,25 +27,25 @@ def mkDir(dirn):
try:
os.mkdir(dirn)
except FileExistsError:
print('Warning: folder already exists. Overwriting...')
print("Warning: folder already exists. Overwriting...")


def getDesc(u, mt):
return '{} [{}/{}]'.format(mt['title'], u['bit_depth'], u['sampling_rate'])
return "{} [{}/{}]".format(mt["title"], u["bit_depth"], u["sampling_rate"])


def getCover(i, dirn):
req_tqdm(i, dirn + '/cover.jpg', 'Downloading cover art')
req_tqdm(i, dirn + "/cover.jpg", "Downloading cover art")


# Download and tag a file
def downloadItem(dirn, count, parse, meta, album, url, is_track, mp3):
if mp3:
fname = '{}/{:02}.mp3'.format(dirn, count)
func = metadata.tag_mp3
else:
fname = '{}/{:02}.flac'.format(dirn, count)
func = metadata.tag_flac
fname = (
"{}/{:02}.mp3".format(dirn, count)
if mp3
else "{}/{:02}.flac".format(dirn, count)
)
func = metadata.tag_mp3 if mp3 else metadata.tag_flac
desc = getDesc(parse, meta)
req_tqdm(url, fname, desc)
func(fname, dirn, meta, album, is_track)
Expand All @@ -55,46 +57,43 @@ def iterateIDs(client, id, path, quality, album=False):

if album:
meta = client.get_album_meta(id)
print('\nDownloading: {}\n'.format(meta['title']))
dirT = (meta['artist']['name'],
meta['title'],
meta['release_date_original'].split('-')[0])
sanitized_title = sanitize_filename('{} - {} [{}]'.format(*dirT))
print("\nDownloading: {}\n".format(meta["title"]))
dirT = (
meta["artist"]["name"],
meta["title"],
meta["release_date_original"].split("-")[0],
)
sanitized_title = sanitize_filename("{} - {} [{}]".format(*dirT))
dirn = path + sanitized_title
mkDir(dirn)
getCover(meta['image']['large'], dirn)
for i in meta['tracks']['items']:
parse = client.get_track_url(i['id'], quality)
url = parse['url']

if 'sample' not in parse:
if int(quality) == 5:
downloadItem(dirn, count, parse, i, meta, url, False, True)
else:
downloadItem(dirn, count, parse, i, meta, url, False, False)
getCover(meta["image"]["large"], dirn)
for i in meta["tracks"]["items"]:
parse = client.get_track_url(i["id"], quality)
url = parse["url"]
if "sample" not in parse:
is_mp3 = True if int(quality) == 5 else False
downloadItem(dirn, count, parse, i, meta, url, False, is_mp3)
else:
print('Demo. Skipping')

print("Demo. Skipping")
count = count + 1
else:
parse = client.get_track_url(id, quality)
url = parse['url']
url = parse["url"]

if 'sample' not in parse:
if "sample" not in parse:
meta = client.get_track_meta(id)
print('\nDownloading: {}\n'.format(meta['title']))
dirT = (meta['album']['artist']['name'],
meta['title'],
meta['album']['release_date_original'].split('-')[0])
sanitized_title = sanitize_filename('{} - {} [{}]'.format(*dirT))
print("\nDownloading: {}\n".format(meta["title"]))
dirT = (
meta["album"]["artist"]["name"],
meta["title"],
meta["album"]["release_date_original"].split("-")[0],
)
sanitized_title = sanitize_filename("{} - {} [{}]".format(*dirT))
dirn = path + sanitized_title
mkDir(dirn)
getCover(meta['album']['image']['large'], dirn)
if int(quality) == 5:
downloadItem(dirn, count, parse, meta, meta, url, True, True)
else:
downloadItem(dirn, count, parse, meta, meta, url, True, False)
getCover(meta["album"]["image"]["large"], dirn)
is_mp3 = True if int(quality) == 5 else False
downloadItem(dirn, count, parse, meta, meta, url, True, is_mp3)
else:
print('Demo. Skipping')

print('\nCompleted\n')
print("Demo. Skipping")
print("\nCompleted\n")
Loading

0 comments on commit 68caf02

Please sign in to comment.