Formatting

This commit is contained in:
Nathan Thomas 2021-09-16 18:48:27 -07:00
parent 1f3b24e5b7
commit 35c8932ffb
12 changed files with 151 additions and 363 deletions

0
rg Normal file
View File

View File

@ -86,9 +86,7 @@ class DownloadCommand(Command):
if len(core) > 0:
core.download()
elif not urls and path is None:
self.line(
"<error>Must pass arguments. See </><cmd>rip url -h</cmd>."
)
self.line("<error>Must pass arguments. See </><cmd>rip url -h</cmd>.")
update_check.join()
if outdated:
@ -115,16 +113,10 @@ class DownloadCommand(Command):
"https://api.github.com/repos/nathom/streamrip/releases/latest"
).json()["body"]
release_notes = md_header.sub(
r"<header>\1</header>", release_notes
)
release_notes = bullet_point.sub(
r"<options=bold>•</> \1", release_notes
)
release_notes = md_header.sub(r"<header>\1</header>", release_notes)
release_notes = bullet_point.sub(r"<options=bold>•</> \1", release_notes)
release_notes = code.sub(r"<cmd>\1</cmd>", release_notes)
release_notes = issue_reference.sub(
r"<options=bold>\1</>", release_notes
)
release_notes = issue_reference.sub(r"<options=bold>\1</>", release_notes)
self.line(release_notes)
@ -154,9 +146,7 @@ class SearchCommand(Command):
def handle(self):
query = self.argument("query")
source, type = clean_options(
self.option("source"), self.option("type")
)
source, type = clean_options(self.option("source"), self.option("type"))
config = Config()
core = RipCore(config)
@ -219,18 +209,14 @@ class DiscoverCommand(Command):
from streamrip.constants import QOBUZ_FEATURED_KEYS
if chosen_list not in QOBUZ_FEATURED_KEYS:
self.line(
f'<error>Error: list "{chosen_list}" not available</error>'
)
self.line(f'<error>Error: list "{chosen_list}" not available</error>')
self.line(self.help)
return 1
elif source == "deezer":
from streamrip.constants import DEEZER_FEATURED_KEYS
if chosen_list not in DEEZER_FEATURED_KEYS:
self.line(
f'<error>Error: list "{chosen_list}" not available</error>'
)
self.line(f'<error>Error: list "{chosen_list}" not available</error>')
self.line(self.help)
return 1
@ -318,9 +304,7 @@ class ConfigCommand(Command):
self.line(f"<info>{CONFIG_PATH}</info>")
if self.option("open"):
self.line(
f"Opening <url>{CONFIG_PATH}</url> in default application"
)
self.line(f"Opening <url>{CONFIG_PATH}</url> in default application")
launch(CONFIG_PATH)
if self.option("reset"):
@ -367,9 +351,7 @@ class ConfigCommand(Command):
self.line("<b>Sucessfully logged in!</b>")
except AuthenticationError:
self.line(
"<error>Could not log in. Double check your ARL</error>"
)
self.line("<error>Could not log in. Double check your ARL</error>")
if self.option("qobuz"):
import getpass
@ -377,9 +359,7 @@ class ConfigCommand(Command):
self._config.file["qobuz"]["email"] = self.ask("Qobuz email:")
self._config.file["qobuz"]["password"] = hashlib.md5(
getpass.getpass(
"Qobuz password (won't show on screen): "
).encode()
getpass.getpass("Qobuz password (won't show on screen): ").encode()
).hexdigest()
self._config.save()
@ -631,9 +611,7 @@ class Application(BaseApplication):
formatter.set_style("path", Style("green", options=["bold"]))
formatter.set_style("cmd", Style("magenta"))
formatter.set_style("title", Style("yellow", options=["bold"]))
formatter.set_style(
"header", Style("yellow", options=["bold", "underline"])
)
formatter.set_style("header", Style("yellow", options=["bold", "underline"]))
io.output.set_formatter(formatter)
io.error_output.set_formatter(formatter)

View File

@ -31,9 +31,7 @@ class Config:
values.
"""
default_config_path = os.path.join(
os.path.dirname(__file__), "config.toml"
)
default_config_path = os.path.join(os.path.dirname(__file__), "config.toml")
with open(default_config_path) as cfg:
defaults: Dict[str, Any] = tomlkit.parse(cfg.read().strip())
@ -57,10 +55,7 @@ class Config:
if os.path.isfile(self._path):
self.load()
if (
self.file["misc"]["version"]
!= self.defaults["misc"]["version"]
):
if self.file["misc"]["version"] != self.defaults["misc"]["version"]:
secho(
"Updating config file to new version. Some settings may be lost.",
fg="yellow",

View File

@ -112,18 +112,14 @@ class RipCore(list):
else:
self.config = config
if (
theme := self.config.file["theme"]["progress_bar"]
) != TQDM_DEFAULT_THEME:
if (theme := self.config.file["theme"]["progress_bar"]) != TQDM_DEFAULT_THEME:
set_progress_bar_theme(theme.lower())
def get_db(db_type: str) -> db.Database:
db_settings = self.config.session["database"]
db_class = db.CLASS_MAP[db_type]
if db_settings[db_type]["enabled"] and db_settings.get(
"enabled", True
):
if db_settings[db_type]["enabled"] and db_settings.get("enabled", True):
default_db_path = DB_PATH_MAP[db_type]
path = db_settings[db_type]["path"]
@ -218,8 +214,7 @@ class RipCore(list):
logger.debug(session)
# So that the dictionary isn't searched for the same keys multiple times
artwork, conversion, filepaths, metadata = (
session[key]
for key in ("artwork", "conversion", "filepaths", "metadata")
session[key] for key in ("artwork", "conversion", "filepaths", "metadata")
)
concurrency = session["downloads"]["concurrency"]
return {
@ -265,9 +260,7 @@ class RipCore(list):
)
exit()
for counter, (source, media_type, item_id) in enumerate(
self.failed_db
):
for counter, (source, media_type, item_id) in enumerate(self.failed_db):
if counter >= max_items:
break
@ -290,9 +283,7 @@ class RipCore(list):
logger.debug("Arguments from config: %s", arguments)
source_subdirs = self.config.session["downloads"][
"source_subdirectories"
]
source_subdirs = self.config.session["downloads"]["source_subdirectories"]
for item in self:
# Item already checked in database in handle_urls
if source_subdirs:
@ -304,26 +295,20 @@ class RipCore(list):
item.download(**arguments)
continue
arguments["quality"] = self.config.session[item.client.source][
"quality"
]
arguments["quality"] = self.config.session[item.client.source]["quality"]
if isinstance(item, Artist):
filters_ = tuple(
k for k, v in self.config.session["filters"].items() if v
)
arguments["filters"] = filters_
logger.debug(
"Added filter argument for artist/label: %s", filters_
)
logger.debug("Added filter argument for artist/label: %s", filters_)
if not isinstance(item, Tracklist) or not item.loaded:
logger.debug("Loading metadata")
try:
item.load_meta(**arguments)
except NonStreamable:
self.failed_db.add(
(item.client.source, item.type, item.id)
)
self.failed_db.add((item.client.source, item.type, item.id))
secho(f"{item!s} is not available, skipping.", fg="red")
continue
@ -360,9 +345,7 @@ class RipCore(list):
:param featured_list: The name of the list. See `rip discover --help`.
:type featured_list: str
"""
self.extend(
self.search("qobuz", featured_list, "featured", limit=max_items)
)
self.extend(self.search("qobuz", featured_list, "featured", limit=max_items))
def get_client(self, source: str) -> Client:
"""Get a client given the source and log in.
@ -427,6 +410,17 @@ class RipCore(list):
self.config.file["qobuz"]["secrets"],
) = client.get_tokens()
self.config.save()
elif (
client.source == "soundcloud"
and not creds.get("client_id")
and not creds.get("app_version")
):
(
self.config.file["soundcloud"]["client_id"],
self.config.file["soundcloud"]["app_version"],
) = client.get_tokens()
self.config.save()
elif client.source == "tidal":
self.config.file["tidal"].update(client.get_tokens())
self.config.save() # only for the expiry stamp
@ -435,14 +429,14 @@ class RipCore(list):
"""Return the type of the url and the id.
Compatible with urls of the form:
https://www.qobuz.com/us-en/{type}/{name}/{id}
https://open.qobuz.com/{type}/{id}
https://play.qobuz.com/{type}/{id}
https://www.qobuz.com/us-en/type/name/id
https://open.qobuz.com/type/id
https://play.qobuz.com/type/id
https://www.deezer.com/us/{type}/{id}
https://tidal.com/browse/{type}/{id}
https://www.deezer.com/us/type/id
https://tidal.com/browse/type/id
:raises exceptions.ParsingError
:raises exceptions.ParsingError:
"""
parsed: List[Tuple[str, str, str]] = []
@ -468,20 +462,25 @@ class RipCore(list):
fg="yellow",
)
parsed.extend(
("deezer", *extract_deezer_dynamic_link(url))
for url in dynamic_urls
("deezer", *extract_deezer_dynamic_link(url)) for url in dynamic_urls
)
parsed.extend(URL_REGEX.findall(url)) # Qobuz, Tidal, Dezer
parsed.extend(URL_REGEX.findall(url)) # Qobuz, Tidal, Deezer
soundcloud_urls = SOUNDCLOUD_URL_REGEX.findall(url)
soundcloud_items = [
self.clients["soundcloud"].get(u) for u in soundcloud_urls
]
parsed.extend(
("soundcloud", item["kind"], url)
for item, url in zip(soundcloud_items, soundcloud_urls)
)
if soundcloud_urls:
soundcloud_client = self.get_client("soundcloud")
assert isinstance(soundcloud_client, SoundCloudClient) # for typing
# TODO: Make this async
soundcloud_items = (
soundcloud_client.resolve_url(u) for u in soundcloud_urls
)
parsed.extend(
("soundcloud", item["kind"], str(item["id"]))
for item in soundcloud_items
)
logger.debug("Parsed urls: %s", parsed)
@ -507,15 +506,11 @@ class RipCore(list):
# For testing:
# https://www.last.fm/user/nathan3895/playlists/12058911
user_regex = re.compile(
r"https://www\.last\.fm/user/([^/]+)/playlists/\d+"
)
user_regex = re.compile(r"https://www\.last\.fm/user/([^/]+)/playlists/\d+")
lastfm_urls = LASTFM_URL_REGEX.findall(urls)
try:
lastfm_source = self.config.session["lastfm"]["source"]
lastfm_fallback_source = self.config.session["lastfm"][
"fallback_source"
]
lastfm_fallback_source = self.config.session["lastfm"]["fallback_source"]
except KeyError:
self._config_updating_message()
self.config.update()
@ -549,16 +544,12 @@ class RipCore(list):
)
query_is_clean = banned_words_plain.search(query) is None
search_results = self.search(
source, query, media_type="track"
)
search_results = self.search(source, query, media_type="track")
track = next(search_results)
if query_is_clean:
while banned_words.search(track["title"]) is not None:
logger.debug(
"Track title banned for query=%s", query
)
logger.debug("Track title banned for query=%s", query)
track = next(search_results)
# Because the track is searched as a single we need to set
@ -568,9 +559,7 @@ class RipCore(list):
except (NoResultsFound, StopIteration):
return None
track = try_search(lastfm_source) or try_search(
lastfm_fallback_source
)
track = try_search(lastfm_source) or try_search(lastfm_fallback_source)
if track is None:
return False
@ -594,9 +583,7 @@ class RipCore(list):
pl.creator = creator_match.group(1)
tracks_not_found = 0
with concurrent.futures.ThreadPoolExecutor(
max_workers=15
) as executor:
with concurrent.futures.ThreadPoolExecutor(max_workers=15) as executor:
futures = [
executor.submit(search_query, title, artist, pl)
for title, artist in queries
@ -725,9 +712,7 @@ class RipCore(list):
raise NotImplementedError
fields = (fname for _, fname, _, _ in Formatter().parse(fmt) if fname)
ret = fmt.format(
**{k: media.get(k, default="Unknown") for k in fields}
)
ret = fmt.format(**{k: media.get(k, default="Unknown") for k in fields})
return ret
def interactive_search(
@ -865,9 +850,7 @@ class RipCore(list):
playlist_title = html.unescape(playlist_title_match.group(1))
if remaining_tracks > 0:
with concurrent.futures.ThreadPoolExecutor(
max_workers=15
) as executor:
with concurrent.futures.ThreadPoolExecutor(max_workers=15) as executor:
last_page = int(remaining_tracks // 50) + int(
remaining_tracks % 50 != 0
)
@ -922,9 +905,7 @@ class RipCore(list):
fg="blue",
)
self.config.file["deezer"]["arl"] = input(
style("ARL: ", fg="green")
)
self.config.file["deezer"]["arl"] = input(style("ARL: ", fg="green"))
self.config.save()
secho(
f'Credentials saved to config file at "{self.config._path}"',

View File

@ -71,15 +71,11 @@ class Database:
with sqlite3.connect(self.path) as conn:
conditions = " AND ".join(f"{key}=?" for key in items.keys())
command = (
f"SELECT EXISTS(SELECT 1 FROM {self.name} WHERE {conditions})"
)
command = f"SELECT EXISTS(SELECT 1 FROM {self.name} WHERE {conditions})"
logger.debug("Executing %s", command)
return bool(
conn.execute(command, tuple(items.values())).fetchone()[0]
)
return bool(conn.execute(command, tuple(items.values())).fetchone()[0])
def __contains__(self, keys: Union[str, dict]) -> bool:
"""Check whether a key-value pair exists in the database.
@ -123,9 +119,7 @@ class Database:
params = ", ".join(self.structure.keys())
question_marks = ", ".join("?" for _ in items)
command = (
f"INSERT INTO {self.name} ({params}) VALUES ({question_marks})"
)
command = f"INSERT INTO {self.name} ({params}) VALUES ({question_marks})"
logger.debug("Executing %s", command)
logger.debug("Items to add: %s", items)

View File

@ -21,12 +21,9 @@ from .constants import (
DEEZER_BASE,
DEEZER_DL,
DEEZER_FORMATS,
DEEZER_MAX_Q,
QOBUZ_BASE,
QOBUZ_FEATURED_KEYS,
SOUNDCLOUD_APP_VERSION,
SOUNDCLOUD_BASE,
SOUNDCLOUD_CLIENT_ID,
SOUNDCLOUD_USER_ID,
TIDAL_AUTH_URL,
TIDAL_BASE,
@ -240,9 +237,7 @@ class QobuzClient(Client):
:rtype: dict
"""
page, status_code = self._api_request(epoint, params)
logger.debug(
"Keys returned from _gen_pages: %s", ", ".join(page.keys())
)
logger.debug("Keys returned from _gen_pages: %s", ", ".join(page.keys()))
key = epoint.split("/")[0] + "s"
total = page.get(key, {})
total = total.get("total") or total.get("items")
@ -265,8 +260,7 @@ class QobuzClient(Client):
"""Check if the secrets are usable."""
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [
executor.submit(self._test_secret, secret)
for secret in self.secrets
executor.submit(self._test_secret, secret) for secret in self.secrets
]
for future in concurrent.futures.as_completed(futures):
@ -309,15 +303,11 @@ class QobuzClient(Client):
response, status_code = self._api_request(epoint, params)
if status_code != 200:
raise Exception(
f'Error fetching metadata. "{response["message"]}"'
)
raise Exception(f'Error fetching metadata. "{response["message"]}"')
return response
def _api_search(
self, query: str, media_type: str, limit: int = 500
) -> Generator:
def _api_search(self, query: str, media_type: str, limit: int = 500) -> Generator:
"""Send a search request to the API.
:param query:
@ -369,9 +359,7 @@ class QobuzClient(Client):
resp, status_code = self._api_request(epoint, params)
if status_code == 401:
raise AuthenticationError(
f"Invalid credentials from params {params}"
)
raise AuthenticationError(f"Invalid credentials from params {params}")
elif status_code == 400:
logger.debug(resp)
raise InvalidAppIdError(f"Invalid app id from params {params}")
@ -379,9 +367,7 @@ class QobuzClient(Client):
logger.info("Logged in to Qobuz")
if not resp["user"]["credential"]["parameters"]:
raise IneligibleError(
"Free accounts are not eligible to download tracks."
)
raise IneligibleError("Free accounts are not eligible to download tracks.")
self.uat = resp["user_auth_token"]
self.session.headers.update({"X-User-Auth-Token": self.uat})
@ -430,9 +416,7 @@ class QobuzClient(Client):
}
response, status_code = self._api_request("track/getFileUrl", params)
if status_code == 400:
raise InvalidAppSecretError(
"Invalid app secret from params %s" % params
)
raise InvalidAppSecretError("Invalid app secret from params %s" % params)
return response
@ -451,9 +435,7 @@ class QobuzClient(Client):
logger.debug(r.text)
return r.json(), r.status_code
except Exception:
logger.error(
"Problem getting JSON. Status code: %s", r.status_code
)
logger.error("Problem getting JSON. Status code: %s", r.status_code)
raise
def _test_secret(self, secret: str) -> Optional[str]:
@ -485,9 +467,7 @@ class DeezerClient(Client):
# no login required
self.logged_in = False
def search(
self, query: str, media_type: str = "album", limit: int = 200
) -> dict:
def search(self, query: str, media_type: str = "album", limit: int = 200) -> dict:
"""Search API for query.
:param query:
@ -501,16 +481,12 @@ class DeezerClient(Client):
try:
if media_type == "featured":
if query:
search_function = getattr(
self.client.api, f"get_editorial_{query}"
)
search_function = getattr(self.client.api, f"get_editorial_{query}")
else:
search_function = self.client.api.get_editorial_releases
else:
search_function = getattr(
self.client.api, f"search_{media_type}"
)
search_function = getattr(self.client.api, f"search_{media_type}")
except AttributeError:
raise Exception
@ -584,9 +560,9 @@ class DeezerClient(Client):
format_no, format_str = format_info
dl_info["size_to_quality"] = {
int(
track_info.get(f"FILESIZE_{format}")
): self._quality_id_from_filetype(format)
int(track_info.get(f"FILESIZE_{format}")): self._quality_id_from_filetype(
format
)
for format in DEEZER_FORMATS
}
@ -627,9 +603,7 @@ class DeezerClient(Client):
logger.debug("Info bytes: %s", info_bytes)
path = self._gen_url_path(info_bytes)
logger.debug(path)
return (
f"https://e-cdns-proxy-{track_hash[0]}.dzcdn.net/mobile/1/{path}"
)
return f"https://e-cdns-proxy-{track_hash[0]}.dzcdn.net/mobile/1/{path}"
def _gen_url_path(self, data):
return binascii.hexlify(
@ -659,9 +633,7 @@ class DeezloaderClient(Client):
# no login required
self.logged_in = True
def search(
self, query: str, media_type: str = "album", limit: int = 200
) -> dict:
def search(self, query: str, media_type: str = "album", limit: int = 200) -> dict:
"""Search API for query.
:param query:
@ -698,9 +670,7 @@ class DeezloaderClient(Client):
url = f"{DEEZER_BASE}/{media_type}/{meta_id}"
item = self.session.get(url).json()
if media_type in ("album", "playlist"):
tracks = self.session.get(
f"{url}/tracks", params={"limit": 1000}
).json()
tracks = self.session.get(f"{url}/tracks", params={"limit": 1000}).json()
item["tracks"] = tracks["data"]
item["track_total"] = len(tracks["data"])
elif media_type == "artist":
@ -796,9 +766,7 @@ class TidalClient(Client):
logger.debug(resp)
return resp
def search(
self, query: str, media_type: str = "album", limit: int = 100
) -> dict:
def search(self, query: str, media_type: str = "album", limit: int = 100) -> dict:
"""Search for a query.
:param query:
@ -827,19 +795,13 @@ class TidalClient(Client):
return self._get_video_stream_url(track_id)
params = {
"audioquality": get_quality(
min(quality, TIDAL_MAX_Q), self.source
),
"audioquality": get_quality(min(quality, TIDAL_MAX_Q), self.source),
"playbackmode": "STREAM",
"assetpresentation": "FULL",
}
resp = self._api_request(
f"tracks/{track_id}/playbackinfopostpaywall", params
)
resp = self._api_request(f"tracks/{track_id}/playbackinfopostpaywall", params)
try:
manifest = json.loads(
base64.b64decode(resp["manifest"]).decode("utf-8")
)
manifest = json.loads(base64.b64decode(resp["manifest"]).decode("utf-8"))
except KeyError:
raise Exception(resp["userMessage"])
@ -1044,9 +1006,7 @@ class TidalClient(Client):
offset += 100
tracks_left -= 100
resp["items"].extend(
self._api_request(f"{url}/items", {"offset": offset})[
"items"
]
self._api_request(f"{url}/items", {"offset": offset})["items"]
)
item["tracks"] = [item["item"] for item in resp["items"]]
@ -1096,9 +1056,7 @@ class TidalClient(Client):
resp = self._api_request(
f"videos/{video_id}/playbackinfopostpaywall", params=params
)
manifest = json.loads(
base64.b64decode(resp["manifest"]).decode("utf-8")
)
manifest = json.loads(base64.b64decode(resp["manifest"]).decode("utf-8"))
available_urls = self.session.get(manifest["urls"][0])
available_urls.encoding = "utf-8"

View File

@ -52,9 +52,7 @@ class Converter:
self.filename = filename
self.final_fn = f"{os.path.splitext(filename)[0]}.{self.container}"
self.tempfile = os.path.join(
gettempdir(), os.path.basename(self.final_fn)
)
self.tempfile = os.path.join(gettempdir(), os.path.basename(self.final_fn))
self.remove_source = remove_source
self.sampling_rate = sampling_rate
self.bit_depth = bit_depth
@ -119,13 +117,9 @@ class Converter:
if self.lossless:
if isinstance(self.sampling_rate, int):
sampling_rates = "|".join(
str(rate)
for rate in SAMPLING_RATES
if rate <= self.sampling_rate
)
command.extend(
["-af", f"aformat=sample_rates={sampling_rates}"]
str(rate) for rate in SAMPLING_RATES if rate <= self.sampling_rate
)
command.extend(["-af", f"aformat=sample_rates={sampling_rates}"])
elif self.sampling_rate is not None:
raise TypeError(
@ -140,9 +134,7 @@ class Converter:
else:
raise ValueError("Bit depth must be 16, 24, or 32")
elif self.bit_depth is not None:
raise TypeError(
f"Bit depth must be int, not {type(self.bit_depth)}"
)
raise TypeError(f"Bit depth must be int, not {type(self.bit_depth)}")
# automatically overwrite
command.extend(["-y", self.tempfile])
@ -207,9 +199,7 @@ class Vorbis(Converter):
codec_name = "vorbis"
codec_lib = "libvorbis"
container = "ogg"
default_ffmpeg_arg = (
"-q:a 6" # 160, aka the "high" quality profile from Spotify
)
default_ffmpeg_arg = "-q:a 6" # 160, aka the "high" quality profile from Spotify
class OPUS(Converter):

View File

@ -74,9 +74,7 @@ class DownloadStream:
info = self.request.json()
try:
# Usually happens with deezloader downloads
raise NonStreamable(
f"{info['error']} -- {info['message']}"
)
raise NonStreamable(f"{info['error']} - {info['message']}")
except KeyError:
raise NonStreamable(info)
@ -88,10 +86,7 @@ class DownloadStream:
:rtype: Iterator
"""
if (
self.source == "deezer"
and self.is_encrypted.search(self.url) is not None
):
if self.source == "deezer" and self.is_encrypted.search(self.url) is not None:
assert isinstance(self.id, str), self.id
blowfish_key = self._generate_blowfish_key(self.id)
@ -99,10 +94,7 @@ class DownloadStream:
CHUNK_SIZE = 2048 * 3
return (
# (decryptor.decrypt(chunk[:2048]) + chunk[2048:])
(
self._decrypt_chunk(blowfish_key, chunk[:2048])
+ chunk[2048:]
)
(self._decrypt_chunk(blowfish_key, chunk[:2048]) + chunk[2048:])
if len(chunk) >= 2048
else chunk
for chunk in self.request.iter_content(CHUNK_SIZE)
@ -123,9 +115,7 @@ class DownloadStream:
return self.file_size
def _create_deezer_decryptor(self, key) -> Blowfish:
return Blowfish.new(
key, Blowfish.MODE_CBC, b"\x00\x01\x02\x03\x04\x05\x06\x07"
)
return Blowfish.new(key, Blowfish.MODE_CBC, b"\x00\x01\x02\x03\x04\x05\x06\x07")
@staticmethod
def _generate_blowfish_key(track_id: str):
@ -178,9 +168,7 @@ class DownloadPool:
self.tempdir = tempdir
async def getfn(self, url):
path = os.path.join(
self.tempdir, f"__streamrip_partial_{abs(hash(url))}"
)
path = os.path.join(self.tempdir, f"__streamrip_partial_{abs(hash(url))}")
self._paths[url] = path
return path
@ -195,9 +183,7 @@ class DownloadPool:
async def _download_url(self, session, url):
filename = await self.getfn(url)
logger.debug("Downloading %s", url)
async with session.get(url) as response, aiofiles.open(
filename, "wb"
) as f:
async with session.get(url) as response, aiofiles.open(filename, "wb") as f:
# without aiofiles 3.6632679780000004s
# with aiofiles 2.504482839s
await f.write(await response.content.read())
@ -215,9 +201,7 @@ class DownloadPool:
def files(self):
if len(self._paths) != len(self.urls):
# Not all of them have downloaded
raise Exception(
"Must run DownloadPool.download() before accessing files"
)
raise Exception("Must run DownloadPool.download() before accessing files")
return [
os.path.join(self.tempdir, self._paths[self.urls[i]])

View File

@ -68,9 +68,7 @@ logger = logging.getLogger("streamrip")
TYPE_REGEXES = {
"remaster": re.compile(r"(?i)(re)?master(ed)?"),
"extra": re.compile(
r"(?i)(anniversary|deluxe|live|collector|demo|expanded)"
),
"extra": re.compile(r"(?i)(anniversary|deluxe|live|collector|demo|expanded)"),
}
@ -270,9 +268,7 @@ class Track(Media):
except ItemExists as e:
logger.debug(e)
self.path = os.path.join(
gettempdir(), f"{hash(self.id)}_{self.quality}.tmp"
)
self.path = os.path.join(gettempdir(), f"{hash(self.id)}_{self.quality}.tmp")
def download( # noqa
self,
@ -327,14 +323,9 @@ class Track(Media):
except KeyError as e:
if restrictions := dl_info["restrictions"]:
# Turn CamelCase code into a readable sentence
words = re.findall(
r"([A-Z][a-z]+)", restrictions[0]["code"]
)
words = re.findall(r"([A-Z][a-z]+)", restrictions[0]["code"])
raise NonStreamable(
words[0]
+ " "
+ " ".join(map(str.lower, words[1:]))
+ "."
words[0] + " " + " ".join(map(str.lower, words[1:])) + "."
)
secho(f"Panic: {e} dl_info = {dl_info}", fg="red")
@ -343,9 +334,7 @@ class Track(Media):
_quick_download(download_url, self.path, desc=self._progress_desc)
elif isinstance(self.client, DeezloaderClient):
_quick_download(
dl_info["url"], self.path, desc=self._progress_desc
)
_quick_download(dl_info["url"], self.path, desc=self._progress_desc)
elif self.client.source == "deezer":
# We can only find out if the requested quality is available
@ -457,13 +446,9 @@ class Track(Media):
parsed_m3u = m3u8.loads(requests.get(dl_info["url"]).text)
self.path += ".mp3"
with DownloadPool(
segment.uri for segment in parsed_m3u.segments
) as pool:
with DownloadPool(segment.uri for segment in parsed_m3u.segments) as pool:
bar = get_tqdm_bar(
len(pool), desc=self._progress_desc, unit="Chunk"
)
bar = get_tqdm_bar(len(pool), desc=self._progress_desc, unit="Chunk")
def update_tqdm_bar():
bar.update(1)
@ -483,9 +468,7 @@ class Track(Media):
)
elif dl_info["type"] == "original":
_quick_download(
dl_info["url"], self.path, desc=self._progress_desc
)
_quick_download(dl_info["url"], self.path, desc=self._progress_desc)
# if a wav is returned, convert to flac
engine = converter.FLAC(self.path)
@ -513,9 +496,7 @@ class Track(Media):
def download_cover(self, width=999999, height=999999):
"""Download the cover art, if cover_url is given."""
self.cover_path = os.path.join(
gettempdir(), f"cover{hash(self.cover_url)}.jpg"
)
self.cover_path = os.path.join(gettempdir(), f"cover{hash(self.cover_url)}.jpg")
logger.debug("Downloading cover from %s", self.cover_url)
if not os.path.exists(self.cover_path):
@ -535,9 +516,9 @@ class Track(Media):
formatter = self.meta.get_formatter(max_quality=self.quality)
logger.debug("Track meta formatter %s", formatter)
filename = clean_format(self.file_format, formatter, restrict=restrict)
self.final_path = os.path.join(self.folder, filename)[
:250
].strip() + ext(self.quality, self.client.source)
self.final_path = os.path.join(self.folder, filename)[:250].strip() + ext(
self.quality, self.client.source
)
logger.debug("Formatted path: %s", self.final_path)
@ -550,9 +531,7 @@ class Track(Media):
return self.final_path
@classmethod
def from_album_meta(
cls, album: TrackMetadata, track: dict, client: Client
):
def from_album_meta(cls, album: TrackMetadata, track: dict, client: Client):
"""Return a new Track object initialized with info.
:param album: album metadata returned by API
@ -562,9 +541,7 @@ class Track(Media):
:raises: IndexError
"""
meta = TrackMetadata(album=album, track=track, source=client.source)
return cls(
client=client, meta=meta, id=track["id"], part_of_tracklist=True
)
return cls(client=client, meta=meta, id=track["id"], part_of_tracklist=True)
@classmethod
def from_api(cls, item: dict, client: Client):
@ -624,9 +601,7 @@ class Track(Media):
:param embed_cover: Embed cover art into file
:type embed_cover: bool
"""
assert isinstance(
self.meta, TrackMetadata
), "meta must be TrackMetadata"
assert isinstance(self.meta, TrackMetadata), "meta must be TrackMetadata"
if not self.downloaded:
logger.info(
"Track %s not tagged because it was not downloaded",
@ -750,9 +725,7 @@ class Track(Media):
self.format_final_path(kwargs.get("restrict_filenames", False))
if not os.path.isfile(self.path):
logger.info(
"File %s does not exist. Skipping conversion.", self.path
)
logger.info("File %s does not exist. Skipping conversion.", self.path)
secho(f"{self!s} does not exist. Skipping conversion.", fg="red")
return
@ -892,12 +865,8 @@ class Video(Media):
parsed_m3u = m3u8.loads(requests.get(url).text)
# Asynchronously download the streams
with DownloadPool(
segment.uri for segment in parsed_m3u.segments
) as pool:
bar = get_tqdm_bar(
len(pool), desc=self._progress_desc, unit="Chunk"
)
with DownloadPool(segment.uri for segment in parsed_m3u.segments) as pool:
bar = get_tqdm_bar(len(pool), desc=self._progress_desc, unit="Chunk")
def update_tqdm_bar():
bar.update(1)
@ -906,9 +875,7 @@ class Video(Media):
# Put the filenames in a tempfile that ffmpeg
# can read from
file_list_path = os.path.join(
gettempdir(), "__streamrip_video_files"
)
file_list_path = os.path.join(gettempdir(), "__streamrip_video_files")
with open(file_list_path, "w") as file_list:
text = "\n".join(f"file '{path}'" for path in pool.files)
file_list.write(text)
@ -1149,9 +1116,7 @@ class Booklet:
:type parent_folder: str
:param kwargs:
"""
fn = clean_filename(
self.description, restrict=kwargs.get("restrict_filenames")
)
fn = clean_filename(self.description, restrict=kwargs.get("restrict_filenames"))
filepath = os.path.join(parent_folder, f"{fn}.pdf")
_quick_download(self.url, filepath, "Booklet")
@ -1206,8 +1171,7 @@ class Tracklist(list):
kwargs.get("max_connections", 3)
) as executor:
future_map = {
executor.submit(target, item, **kwargs): item
for item in self
executor.submit(target, item, **kwargs): item for item in self
}
try:
concurrent.futures.wait(future_map.keys())
@ -1238,9 +1202,7 @@ class Tracklist(list):
secho(f"{item!s} exists. Skipping.", fg="yellow")
except NonStreamable as e:
e.print(item)
failed_downloads.append(
(item.client.source, item.type, item.id)
)
failed_downloads.append((item.client.source, item.type, item.id))
self.downloaded = True
@ -1596,9 +1558,7 @@ class Album(Tracklist, Media):
and isinstance(item, Track)
and kwargs.get("folder_format")
):
disc_folder = os.path.join(
self.folder, f"Disc {item.meta.discnumber}"
)
disc_folder = os.path.join(self.folder, f"Disc {item.meta.discnumber}")
kwargs["parent_folder"] = disc_folder
else:
kwargs["parent_folder"] = self.folder
@ -1684,9 +1644,7 @@ class Album(Tracklist, Media):
logger.debug("Formatter: %s", fmt)
return fmt
def _get_formatted_folder(
self, parent_folder: str, restrict: bool = False
) -> str:
def _get_formatted_folder(self, parent_folder: str, restrict: bool = False) -> str:
"""Generate the folder name for this album.
:param parent_folder:
@ -1818,9 +1776,7 @@ class Playlist(Tracklist, Media):
if self.client.source == "qobuz":
self.name = self.meta["name"]
self.image = self.meta["images"]
self.creator = safe_get(
self.meta, "owner", "name", default="Qobuz"
)
self.creator = safe_get(self.meta, "owner", "name", default="Qobuz")
tracklist = self.meta["tracks"]["items"]
@ -1830,9 +1786,7 @@ class Playlist(Tracklist, Media):
elif self.client.source == "tidal":
self.name = self.meta["title"]
self.image = tidal_cover_url(self.meta["image"], 640)
self.creator = safe_get(
self.meta, "creator", "name", default="TIDAL"
)
self.creator = safe_get(self.meta, "creator", "name", default="TIDAL")
tracklist = self.meta["tracks"]
@ -1845,9 +1799,7 @@ class Playlist(Tracklist, Media):
elif self.client.source == "deezer":
self.name = self.meta["title"]
self.image = self.meta["picture_big"]
self.creator = safe_get(
self.meta, "creator", "name", default="Deezer"
)
self.creator = safe_get(self.meta, "creator", "name", default="Deezer")
tracklist = self.meta["tracks"]
@ -1888,13 +1840,9 @@ class Playlist(Tracklist, Media):
logger.debug("Loaded %d tracks from playlist %s", len(self), self.name)
def _prepare_download(
self, parent_folder: str = "StreamripDownloads", **kwargs
):
def _prepare_download(self, parent_folder: str = "StreamripDownloads", **kwargs):
if kwargs.get("folder_format"):
fname = clean_filename(
self.name, kwargs.get("restrict_filenames", False)
)
fname = clean_filename(self.name, kwargs.get("restrict_filenames", False))
self.folder = os.path.join(parent_folder, fname)
else:
self.folder = parent_folder
@ -2091,9 +2039,7 @@ class Artist(Tracklist, Media):
:rtype: Iterable
"""
if kwargs.get("folder_format"):
folder = clean_filename(
self.name, kwargs.get("restrict_filenames", False)
)
folder = clean_filename(self.name, kwargs.get("restrict_filenames", False))
self.folder = os.path.join(parent_folder, folder)
else:
self.folder = parent_folder
@ -2110,9 +2056,7 @@ class Artist(Tracklist, Media):
final = self
if isinstance(filters, tuple) and self.client.source == "qobuz":
filter_funcs = (
getattr(self, f"_{filter_}") for filter_ in filters
)
filter_funcs = (getattr(self, f"_{filter_}") for filter_ in filters)
for func in filter_funcs:
final = filter(func, final)
@ -2225,10 +2169,7 @@ class Artist(Tracklist, Media):
best_bd = bit_depth(a["bit_depth"] for a in group)
best_sr = sampling_rate(a["sampling_rate"] for a in group)
for album in group:
if (
album["bit_depth"] == best_bd
and album["sampling_rate"] == best_sr
):
if album["bit_depth"] == best_bd and album["sampling_rate"] == best_sr:
yield album
break

View File

@ -132,9 +132,7 @@ class TrackMetadata:
self.album = resp.get("title", "Unknown Album")
self.tracktotal = resp.get("tracks_count", 1)
self.genre = resp.get("genres_list") or resp.get("genre") or []
self.date = resp.get("release_date_original") or resp.get(
"release_date"
)
self.date = resp.get("release_date_original") or resp.get("release_date")
self.copyright = resp.get("copyright")
if artists := resp.get("artists"):
@ -148,9 +146,7 @@ class TrackMetadata:
self.disctotal = (
max(
track.get("media_number", 1)
for track in safe_get(
resp, "tracks", "items", default=[{}]
)
for track in safe_get(resp, "tracks", "items", default=[{}])
)
or 1
)
@ -191,22 +187,14 @@ class TrackMetadata:
self.streamable = resp.get("allowStreaming", False)
self.id = resp.get("id")
if q := resp.get(
"audioQuality"
): # for album entries in single tracks
if q := resp.get("audioQuality"): # for album entries in single tracks
self._get_tidal_quality(q)
elif self.__source == "deezer":
self.album = resp.get("title", "Unknown Album")
self.tracktotal = resp.get("track_total", 0) or resp.get(
"nb_tracks", 0
)
self.tracktotal = resp.get("track_total", 0) or resp.get("nb_tracks", 0)
self.disctotal = (
max(
track.get("disk_number")
for track in resp.get("tracks", [{}])
)
or 1
max(track.get("disk_number") for track in resp.get("tracks", [{}])) or 1
)
self.genre = safe_get(resp, "genres", "data")
self.date = resp.get("release_date")
@ -365,9 +353,7 @@ class TrackMetadata:
if isinstance(self._genres, list):
if self.__source == "qobuz":
genres: Iterable = re.findall(
r"([^\u2192\/]+)", "/".join(self._genres)
)
genres: Iterable = re.findall(r"([^\u2192\/]+)", "/".join(self._genres))
genres = set(genres)
elif self.__source == "deezer":
genres = (g["name"] for g in self._genres)
@ -401,9 +387,7 @@ class TrackMetadata:
if hasattr(self, "_copyright"):
if self._copyright is None:
return None
copyright: str = re.sub(
r"(?i)\(P\)", PHON_COPYRIGHT, self._copyright
)
copyright: str = re.sub(r"(?i)\(P\)", PHON_COPYRIGHT, self._copyright)
copyright = re.sub(r"(?i)\(C\)", COPYRIGHT, copyright)
return copyright
@ -463,9 +447,7 @@ class TrackMetadata:
formatter["sampling_rate"] /= 1000
return formatter
def tags(
self, container: str = "flac", exclude: Optional[set] = None
) -> Generator:
def tags(self, container: str = "flac", exclude: Optional[set] = None) -> Generator:
"""Create a generator of key, value pairs for use with mutagen.
The *_KEY dicts are organized in the format:
@ -623,9 +605,7 @@ class TrackMetadata:
:rtype: int
"""
return sum(
hash(v) for v in self.asdict().values() if isinstance(v, Hashable)
)
return sum(hash(v) for v in self.asdict().values() if isinstance(v, Hashable))
def __repr__(self) -> str:
"""Return the string representation of the metadata object.

View File

@ -84,9 +84,7 @@ __QUALITY_MAP: Dict[str, Dict[int, Union[int, str, Tuple[int, str]]]] = {
}
def get_quality(
quality_id: int, source: str
) -> Union[str, int, Tuple[int, str]]:
def get_quality(quality_id: int, source: str) -> Union[str, int, Tuple[int, str]]:
"""Get the source-specific quality id.
:param quality_id: the universal quality id (0, 1, 2, 4)
@ -156,9 +154,7 @@ def clean_format(formatter: str, format_info, restrict: bool = False):
clean_dict = dict()
for key in fmt_keys:
if isinstance(format_info.get(key), (str, float)):
clean_dict[key] = clean_filename(
str(format_info[key]), restrict=restrict
)
clean_dict[key] = clean_filename(str(format_info[key]), restrict=restrict)
elif isinstance(format_info.get(key), int): # track/discnumber
clean_dict[key] = f"{format_info[key]:02}"
else:
@ -176,9 +172,7 @@ def tidal_cover_url(uuid, size):
possibles = (80, 160, 320, 640, 1280)
assert size in possibles, f"size must be in {possibles}"
return TIDAL_COVER_URL.format(
uuid=uuid.replace("-", "/"), height=size, width=size
)
return TIDAL_COVER_URL.format(uuid=uuid.replace("-", "/"), height=size, width=size)
def init_log(path: Optional[str] = None, level: str = "DEBUG"):
@ -280,9 +274,7 @@ def gen_threadsafe_session(
headers = {}
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
pool_connections=100, pool_maxsize=100
)
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100)
session.mount("https://", adapter)
session.headers.update(headers)
return session
@ -350,9 +342,7 @@ def get_cover_urls(resp: dict, source: str) -> dict:
"picture_xl",
)
cover_urls = {
sk: resp.get(
rk, resp.get(rkf)
) # size key, resp key, resp key fallback
sk: resp.get(rk, resp.get(rkf)) # size key, resp key, resp key fallback
for sk, rk, rkf in zip(
COVER_SIZES,
resp_keys,
@ -367,9 +357,9 @@ def get_cover_urls(resp: dict, source: str) -> dict:
return cover_urls
if source == "soundcloud":
cover_url = (
resp["artwork_url"] or resp["user"].get("avatar_url")
).replace("large", "t500x500")
cover_url = (resp["artwork_url"] or resp["user"].get("avatar_url")).replace(
"large", "t500x500"
)
cover_urls = {"large": cover_url}

View File

@ -8,10 +8,7 @@ from streamrip.downloadtools import DownloadPool
def test_downloadpool(tmpdir):
start = time.perf_counter()
with DownloadPool(
(
f"https://pokeapi.co/api/v2/pokemon/{number}"
for number in range(1, 151)
),
(f"https://pokeapi.co/api/v2/pokemon/{number}" for number in range(1, 151)),
tempdir=tmpdir,
) as pool:
pool.download()