Skip to content

Commit

Permalink
update: Added logger for better handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
deepjyoti30 committed Nov 9, 2019
1 parent 311dcf2 commit f50a5d1
Show file tree
Hide file tree
Showing 3 changed files with 164 additions and 56 deletions.
98 changes: 43 additions & 55 deletions bin/ytmdl
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,24 @@ import sys
from colorama import init
from colorama import Fore, Style
import argparse
from ytmdl import (dir, song, yt, defaults, prepend, setupConfig, cache, utility,
metadata)
from ytmdl import (
dir,
song,
yt,
defaults,
prepend,
setupConfig,
cache,
utility,
metadata,
logger
)

# init colorama for windows
init()

logger = logger.Logger('ytmdl')


def arguments():
"""Parse the arguments."""
Expand Down Expand Up @@ -72,10 +84,8 @@ def main(args):

# After this part song name is required
if song_name is None:
prepend.PREPEND(2)
print("Please pass a song name. This is necessary",
"to search metadata.")
exit(1)
logger.critical("Please pass a song name. This is necessary\
to search metadata.")

if not args.nolocal:
# Search for the song locally
Expand All @@ -99,24 +109,20 @@ def main(args):
choice = 0
else:
if is_quiet:
prepend.PREPEND(1)
print('Quiet is enabled')
logger.info('Quiet is enabled')

prepend.PREPEND(1)
print('Searching Youtube for ', end='')
print(Fore.LIGHTYELLOW_EX, end='')
print(song_name, end='')
print(Style.RESET_ALL)
logger.info('Searching Youtube for {}{}{}'.format(
Fore.LIGHTYELLOW_EX,
song_name,
Style.RESET_ALL
))

data, urls = yt.search(song_name, not args.disable_metaadd,
kw=[args.artist, args.album])

# Handle the exception if urls has len 0
if len(urls) == 0:
prepend.PREPEND(2)
print("No song found. Please try again with a different keyword.")
print(Style.RESET_ALL, end='')
exit()
logger.critical("No song found. Please try again with a different keyword.")

if len(data) > 1 and not is_quiet:
# Ask for a choice
Expand All @@ -129,37 +135,29 @@ def main(args):
# Declare a var to store the name of the yt video
yt_title = data[choice]['title']

prepend.PREPEND(1)
print('Downloading ', end='')
print(Fore.LIGHTMAGENTA_EX, end='')
print(yt_title, end=' ')
print(Style.RESET_ALL, end='')
print('in', end=' ')
print(Fore.LIGHTYELLOW_EX, end='')
print(defaults.DEFAULT.SONG_QUALITY + 'kbps', end='')
print(Style.RESET_ALL)
logger.info('Downloading {}{}{} in {}{}kbps{}'.format(
Fore.LIGHTMAGENTA_EX,
yt_title,
Style.RESET_ALL,
Fore.LIGHTYELLOW_EX,
defaults.DEFAULT.SONG_QUALITY,
Style.RESET_ALL
))
path = yt.dw(link, yt_title)

if not path:
prepend.PREPEND(2)
print('Something went wrong while downloading!\a')
sys.exit(0)
logger.critical("ERROR: {}".format(path))
else:
prepend.PREPEND(1)
print('Downloaded!')
logger.info('Downloaded!')

prepend.PREPEND(1)
print('Converting to mp3...')
logger.info('Converting to mp3...')

conv_name = utility.convert_to_mp3(path)

if not conv_name:
prepend.PREPEND(2)
print('Something went wrong while converting!\a')
exit(-1)
logger.critical('Something went wrong while converting!\a')

prepend.PREPEND(1)
print('Getting song data...')
logger.info('Getting song data...')

# TRACK_INFO = song.getData(song_name)
TRACK_INFO = metadata.SEARCH_SONG(song_name, filters=[args.artist, args.album])
Expand All @@ -173,33 +171,25 @@ def main(args):
# exit(0)
pass
elif len(TRACK_INFO) == 0:
prepend.PREPEND(2)
print('No data was found!\a')
sys.exit(0)
logger.critical('No data was found!\a')
else:
prepend.PREPEND(1)
print('Setting data...')

option = song.setData(TRACK_INFO, is_quiet, conv_name)

if type(option) is not int:
prepend.PREPEND(2)
print('Something went wrong while writing data!\a')
sys.exit(0)
logger.critical('Something went wrong while writing data!\a')

# Get the directory where song is moved

DIR = dir.cleanup(TRACK_INFO, option)
prepend.PREPEND(1)
print('Moving to {}...'.format(DIR))
logger.info('Moving to {}...'.format(DIR))

if not DIR:
prepend.PREPEND(2)
print('Something went wrong while moving!\a')
sys.exit(0)
logger.critical('Something went wrong while moving!\a')
else:
prepend.PREPEND(1)
print('Done')
logger.info('Done')


def extract_data():
Expand All @@ -209,14 +199,12 @@ def extract_data():
if args.list is not None:
songs = utility.get_songs(args.list)
if len(songs) != 0:
prepend.PREPEND(1)
print("Downloading songs in {}".format(args.list))
logger.info("Downloading songs in {}".format(args.list))
for song_name in songs:
args.SONG_NAME = song_name
main(args)
else:
prepend.PREPEND(2)
print("{}: is empty".format(args.list))
logger.info("{}: is empty".format(args.list))
else:
main(args)

Expand Down
4 changes: 3 additions & 1 deletion ytmdl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@
'utility',
'gaana',
'metadata',
'download']
'download',
'logger'
]
118 changes: 118 additions & 0 deletions ytmdl/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@

from pathlib import Path
import datetime
import os
from ytmdl.prepend import PREPEND


class Logger:
"""
Custom logger that meets the requirements of using multiple logging setup.
"""

def __init__(self, name='', level='INFO'):
self.name = name
self._file_format = ''
self._console_format = ''
self._log_file = Path('~/.cache/ytmdl/logs/log.cat').expanduser()
self._check_logfile()
self._level_number = {
'DEBUG': 0,
'INFO': 1,
'WARNING': 2,
'ERROR': 3,
'CRITICAL': 4
}
self.level = self._level_number[level]

def _check_logfile(self):
"""
Check if the passed logfile path is present.
If not present then create it.
"""
if not self._log_file.exists():
if not self._log_file.parent.exists():
os.makedirs(self._log_file.parent)
f = open(self._log_file, 'w')
f.close()

def _write(self, message, LEVEL_NUMBER):
"""
Write the logs.
LEVEL_NUMBER is the levelnumber of the level that is calling the
_write function.
"""
if LEVEL_NUMBER >= self.level:
self._make_format(message)
with open(self._log_file, 'a') as f:
# The file log is to be written to the _log_file file
f = open(self._log_file, 'a')
f.write(self._file_format)
print(self._console_format)

def _make_format(self, message):
"""
Make the format of the string that is to be written.
"""
t = datetime.datetime.now()
DATETIME_FORMAT = '{}-{}-{} {}:{}:{}'.format(
t.year,
t.month,
t.day,
t.hour,
t.minute,
t.second
)
self._console_format = '{}'.format(message)
self._file_format = '[{}]-[{}]: {}\n'.format(self.name, DATETIME_FORMAT, message)

def hold(self):
"""
Hold the screen by using input()
"""
LEVEL_NUMBER = 0

if LEVEL_NUMBER >= self.level:
input("Screen hold! Press any key to continue")

def debug(self, message):
"""
Add the message if the level is debug.
"""
LEVEL_NUMBER = 0
PREPEND(1)
self._write(message, LEVEL_NUMBER)

def info(self, message):
"""
Add the message if the level is info or less.
"""
LEVEL_NUMBER = 1
PREPEND(1)
self._write(message, LEVEL_NUMBER)

def warning(self, message):
"""
Add the message if the level is warning or less.
"""
LEVEL_NUMBER = 2
PREPEND(2)
self._write(message, LEVEL_NUMBER)

def error(self, message):
"""
Add the message if the level is error or less.
"""
LEVEL_NUMBER = 3
PREPEND(2)
self._write(message, LEVEL_NUMBER)

def critical(self, message):
"""
Add the message if the level is critical or less.
"""
LEVEL_NUMBER = 4
PREPEND(2)
self._write(message, LEVEL_NUMBER)
exit()

0 comments on commit f50a5d1

Please sign in to comment.