Skip to content

Commit

Permalink
Merge pull request #46 from TeilzeitTaco/main
Browse files Browse the repository at this point in the history
Improve Code Quality
  • Loading branch information
LaurenceRawlings committed Mar 3, 2021
2 parents 2bd5c3c + c6067bb commit a23565e
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 202 deletions.
105 changes: 51 additions & 54 deletions savify/cli.py
Expand Up @@ -42,20 +42,20 @@ class Choices:
GROUPING = "%artist%, %album%, %playlist% separated by /"


def choices(choice):
def choices(choice) -> str:
return ', '.join(choice)


def get_choice():
def get_choice() -> str:
return input('[INPUT]\tEnter choice: ').lower()


def show_banner():
def show_banner() -> None:
click.clear()
click.echo(BANNER)


def validate_group(ctx, param, value):
def validate_group(_ctx, _param, value):
regex = r"^((%artist%|%album%|%playlist%)(\/(%artist%|%album%|%playlist%))*)+$"
if re.search(regex, str(value)) or value is None:
return value
Expand Down Expand Up @@ -86,6 +86,7 @@ def guided_cli(type, quality, format, output, group, path, m3u, artist_albums, s
errors = []
choice = input('[INPUT]\tEnter an option or a search query: ')

# TODO: This is horrendous
if choice == '0':
sys.exit(0)
elif choice == '1':
Expand Down Expand Up @@ -206,7 +207,7 @@ def check_guided():
from .ffmpegdl import FFmpegDL
ffmpeg_dl = FFmpegDL(str(path_holder.data_path))

if not ffmpeg_dl.check():
if not ffmpeg_dl.check_if_file():
logger.error(ex.message)
if silent:
check_guided()
Expand All @@ -221,6 +222,7 @@ def check_guided():
logger.error('Failed to download FFmpeg!')
check_guided()
return 1

logger.info(f'FFmpeg downloaded! [{ffmpeg_location}]')
else:
check_guided()
Expand All @@ -236,10 +238,12 @@ def check_guided():

try:
s.download(query, query_type=query_type, create_m3u=m3u, artist_albums=artist_albums)

except UrlNotSupportedError as ex:
logger.error(ex.message)
check_guided()
return 1

except InternetConnectionError as ex:
logger.error(ex.message)
check_guided()
Expand All @@ -249,58 +253,51 @@ def check_guided():
return 0


def convert_type(query_type):
if query_type.lower() == 'track':
return Type.TRACK
elif query_type.lower() == 'album':
return Type.ALBUM
elif query_type.lower() == 'playlist':
return Type.PLAYLIST
elif query_type.lower() == 'artist':
return Type.ARTIST


def convert_quality(quality):
if quality.lower() == 'best':
return Quality.BEST
elif quality.lower() == '320k':
return Quality.Q320K
elif quality.lower() == '256k':
return Quality.Q256K
elif quality.lower() == '192k':
return Quality.Q192K
elif quality.lower() == '128k':
return Quality.Q128K
elif quality.lower() == '96k':
return Quality.Q96K
elif quality.lower() == '32k':
return Quality.Q32K
elif quality.lower() == 'worst':
return Quality.WORST


def convert_format(output_format):
if output_format.lower() == 'mp3':
return Format.MP3
elif output_format.lower() == 'aac':
return Format.AAC
elif output_format.lower() == 'flac':
return Format.FLAC
elif output_format.lower() == 'M4A':
return Format.M4A
elif output_format.lower() == 'opus':
return Format.OPUS
elif output_format.lower() == 'vorbis':
return Format.VORBIS
elif output_format.lower() == 'wav':
return Format.WAV


def convert_bool(boolean):
def convert_type(query_type: str) -> Type:
mapping = {
'track': Type.TRACK,
'album': Type.ALBUM,
'playlist': Type.PLAYLIST,
"artist": Type.ARTIST,
}

return mapping[query_type.lower()]


def convert_quality(quality: str) -> Quality:
mapping = {
'best': Quality.BEST,
'320k': Quality.Q320K,
'256k': Quality.Q256K,
'192k': Quality.Q192K,
'128k': Quality.Q128K,
'98k': Quality.Q96K,
'32k': Quality.Q32K,
'worst': Quality.WORST,
}

return mapping[quality.lower()]


def convert_format(output_format: str) -> Format:
mapping = {
'mp3': Format.MP3,
'aac': Format.AAC,
'flac': Format.FLAC,
'm4a': Format.M4A,
'opus': Format.OPUS,
'vorbis': Format.VORBIS,
'wav': Format.WAV,
}

return mapping[output_format.lower()]


def convert_bool(boolean) -> bool:
return boolean.lower() == 'true'


def convert_log_level(verbosity: int):
def convert_log_level(verbosity: int) -> int:
if verbosity == 1:
return logging.WARNING
elif verbosity == 2:
Expand Down
39 changes: 21 additions & 18 deletions savify/ffmpegdl.py
Expand Up @@ -2,79 +2,82 @@
from pathlib import Path
from shutil import move, rmtree
from sys import platform
from uuid import uuid1

ffmpeg_static_win = 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip'
ffmpeg_static_linux = 'https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz'
ffmpeg_static_mac = 'https://evermeet.cx/ffmpeg/getrelease/zip'
FFMPEG_STATIC_LINUX = 'https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz'
FFMPEG_STATIC_WIN = 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip'
FFMPEG_STATIC_MAC = 'https://evermeet.cx/ffmpeg/getrelease/zip'


class FFmpegDL:
def __init__(self, data: str):
from uuid import uuid1
def __init__(self, data: str) -> None:
self.data_path = Path(data) / 'ffmpeg'

if platform == 'win32':
self.temp = self.data_path / str(uuid1())
self.download_link = ffmpeg_static_win
self.download_link = FFMPEG_STATIC_WIN
self.final_location = self.data_path / 'bin' / 'ffmpeg.exe'
self.platform_task = self._download_win

elif platform == 'linux':
self.temp = self.data_path / str(uuid1())
self.download_link = ffmpeg_static_linux
self.download_link = FFMPEG_STATIC_LINUX
self.final_location = self.data_path / 'ffmpeg'
self.platform_task = self._download_linux

elif platform == 'darwin':
self.temp = self.data_path / str(uuid1())
self.download_link = ffmpeg_static_mac
self.download_link = FFMPEG_STATIC_MAC
self.final_location = self.data_path / 'ffmpeg'
self.platform_task = self._download_mac

else:
raise RuntimeError(f'Platform not supported! [{platform}]')

self.file = self.temp / self.download_link.split('/')[-1]

def check(self):
def check_if_file(self) -> bool:
return self.final_location.is_file()

def download(self, force=False):
downloaded = self.check()
def download(self, force=False) -> Path:
downloaded = self.check_if_file()
if not downloaded or force:
rmtree(self.data_path)
self._download()
self.platform_task()

return self.final_location

def _download(self):
def _download(self) -> None:
from urllib.request import urlretrieve
self.temp.mkdir(parents=True, exist_ok=True)
urlretrieve(self.download_link, self.file)

def _download_win(self):
def _download_win(self) -> None:
self._unzip()
bin_path = self.temp / os.listdir(self.temp)[0] / 'bin'
self._cleanup(bin_path)

def _download_mac(self):
def _download_mac(self) -> None:
self._unzip()
bin_file = self.temp / 'ffmpeg'
self._cleanup(bin_file)

def _download_linux(self):
def _download_linux(self) -> None:
self._untar()
bin_file = self.temp / os.listdir(self.temp)[0] / 'ffmpeg'
self._cleanup(bin_file)

def _unzip(self):
def _unzip(self) -> None:
from zipfile import ZipFile
with ZipFile(self.file, 'r') as zip_ref:
zip_ref.extractall(self.temp)

def _untar(self):
def _untar(self) -> None:
import tarfile
with tarfile.open(self.file) as tf:
tf.extractall(self.temp)

def _cleanup(self, ffmpeg_files):
def _cleanup(self, ffmpeg_files) -> None:
move(ffmpeg_files, self.data_path)
rmtree(self.temp)
5 changes: 2 additions & 3 deletions savify/logger.py
Expand Up @@ -6,7 +6,7 @@


class Logger:
def __init__(self, log_location: str = '', log_level=logging.INFO):
def __init__(self, log_location: str = '', log_level=logging.INFO) -> None:
self.logger = logging.getLogger('savify')
self.logger.setLevel(logging.DEBUG)

Expand All @@ -27,7 +27,7 @@ def __init__(self, log_location: str = '', log_level=logging.INFO):
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)

def log_traceback(self):
def log_traceback(self) -> None:
self.logger.error('An error occurred!')
self.logger.error(traceback.format_exc())

Expand All @@ -42,4 +42,3 @@ def error(self, message):

def info(self, message):
self.logger.info(message.encode('utf8').decode('utf8'))

0 comments on commit a23565e

Please sign in to comment.