Skip to content

Commit

Permalink
✨ add logging names
Browse files Browse the repository at this point in the history
  • Loading branch information
oskvr37 committed Jul 30, 2024
1 parent 4dfd15e commit 5c39fe0
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 30 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="tiddl",
version="1.0.0",
version="1.1.0",
description="TIDDL (Tidal Downloader) is a Python CLI application that allows downloading Tidal tracks.",
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
Expand Down
39 changes: 22 additions & 17 deletions tiddl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,37 @@
def main():
args = parser.parse_args()

logger = logging.getLogger("TIDDL")
stream_handler = logging.StreamHandler()
function_log = ""

if args.silent:
log_level = logging.ERROR
elif args.verbose:
log_level = logging.DEBUG
function_log = " %(funcName)s"
else:
log_level = logging.INFO

stream_handler = logging.StreamHandler()
stream_handler.setLevel(log_level)
stream_handler.setFormatter(
logging.Formatter(
"\033[1;34m%(levelname)s\033[0m \033[1;95m%(module)s\033[0m %(message)s"
)
)

if args.no_color:
stream_handler.setFormatter(
logging.Formatter("[ %(levelname)s %(module)s ] %(message)s")
logging.Formatter(
f"[ %(levelname)s ] (%(name)s){function_log} - %(message)s"
)
)
else:
stream_handler.setFormatter(
logging.Formatter(
f"\033[1;34m%(levelname)s\033[0m \033[1;95m%(name)s{function_log}\033[0m %(message)s"
)
)

file_handler = logging.FileHandler("tiddl.log", "w", "utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(
logging.Formatter(
"%(levelname)s\t%(name)s.%(module)s.%(funcName)s :: %(message)s"
)
logging.Formatter("%(levelname)s\t%(name)s.%(funcName)s :: %(message)s")
)

logging.basicConfig(
Expand All @@ -64,7 +69,7 @@ def main():
}
).get("settings")

logging.info(f"saved settings to {config.config_path}")
logger.info(f"saved settings to {config.config_path}")

# TODO: pretty print settings ✨
if settings:
Expand All @@ -90,7 +95,7 @@ def main():
},
}
)
logging.info(f"authenticated!")
logger.info(f"authenticated!")

t_now = int(time.time())
token_expired = t_now > config["token_expires_at"]
Expand All @@ -103,20 +108,20 @@ def main():
"token_expires_at": int(time.time()) + token["expires_in"],
}
)
logging.info(f"refreshed token!")
logger.info(f"refreshed token!")

time_to_expire = config["token_expires_at"] - t_now
days, hours = time_to_expire // (24 * 3600), time_to_expire % (24 * 3600) // 3600
days_text = f" {days} {'day' if days == 1 else 'days'}" if days else ""
hours_text = f" {hours} {'hour' if hours == 1 else 'hours'}" if hours else ""
logging.info(f"token expires in{days_text}{hours_text}")
logger.info(f"token expires in{days_text}{hours_text}")

# TODO: parse input type ✨
# it can be track, album, playlist or artist
track_id: str = args.input

if not track_id:
logging.warning("no ID nor URL provided")
logger.warning("no ID nor URL provided")
return

api = TidalApi(
Expand All @@ -135,7 +140,7 @@ def main():
else:
details = quality["details"]

logging.info(f"{quality['name']} Quality - {details}")
logger.info(f"{quality['name']} Quality - {details}")

file_name: str = args.file_name or track_id
track_path = downloadTrack(
Expand All @@ -145,7 +150,7 @@ def main():
track["manifestMimeType"],
)

logging.info(f"track saved in {track_path}")
logger.info(f"track saved in {track_path}")


if __name__ == "__main__":
Expand Down
13 changes: 7 additions & 6 deletions tiddl/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,24 @@ def __init__(self, token: str, user_id: str, country_code: str) -> None:
self.user_id = user_id
self.country_code = country_code

self.session = Session()
self.session.headers = {"authorization": f"Bearer {token}"}
self._session = Session()
self._session.headers = {"authorization": f"Bearer {token}"}
self._logger = logging.getLogger("TidalApi")

def getSession(self) -> SessionResponse:
return self.session.get(
return self._session.get(
f"{API_URL}/sessions",
).json()

def getPlaylists(self) -> PlaylistResponse:
return self.session.get(
return self._session.get(
f"{API_URL}/users/{self.user_id}/playlists",
params={"countryCode": self.country_code},
).json()

def getTrack(self, id: int, quality: TrackQuality) -> TrackResponse:
logging.debug((id, quality))
return self.session.get(
self._logger.debug((id, quality))
return self._session.get(
f"{API_URL}/tracks/{id}/playbackinfo",
params={
"audioquality": quality,
Expand Down
9 changes: 5 additions & 4 deletions tiddl/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,21 @@ class Config:
def __init__(self, config_path=DEFAULT_PATH) -> None:
self.config_path = config_path
self._config: ConfigData = DEFAULT_CONFIG
self._logger = logging.getLogger("Config")

try:
with open(self.config_path, "r") as f:
logging.debug("loading from config file")
self._logger.debug("loading from file")
loaded_config = json.load(f)
self.update(loaded_config)
except FileNotFoundError:
logging.debug("creating new config file")
self._logger.debug("creating new file")
self._save() # save default config if file does not exist

def _save(self) -> None:
with open(self.config_path, "w") as f:
json.dump(self._config, f, indent=2)
logging.debug("saved config")
self._logger.debug("saved")

def __getitem__(self, key: str) -> Any:
return self._config[key]
Expand All @@ -62,6 +63,6 @@ def __str__(self) -> str:

def update(self, data: ConfigData) -> ConfigData:
self._config.update(data)
logging.debug("updated config")
self._logger.debug("updated")
self._save()
return self._config.copy()
7 changes: 5 additions & 2 deletions tiddl/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
from .types import ManifestMimeType


logger = logging.getLogger("download")


def decodeManifest(manifest: str):
return b64decode(manifest).decode()

Expand Down Expand Up @@ -82,7 +85,7 @@ def threadDownload(urls: list[str]) -> bytes:
def downloadTrack(
path: str, file_name: str, encoded_manifest: str, mime_type: ManifestMimeType
):
logging.debug(mime_type)
logger.debug(mime_type)
manifest = decodeManifest(encoded_manifest)

match mime_type:
Expand All @@ -96,7 +99,7 @@ def downloadTrack(

track_data = threadDownload(track_urls)

logging.debug(codecs)
logger.debug(codecs)

"""
known codecs
Expand Down

0 comments on commit 5c39fe0

Please sign in to comment.