From 733b51dd334300c1b90b401bafbfcccf873b921e Mon Sep 17 00:00:00 2001 From: oskvr37 Date: Sun, 9 Feb 2025 17:44:05 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20automatically=20refresh=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tiddl/cli/__init__.py | 4 ++++ tiddl/cli/auth.py | 49 +++++++++++++++++++++++++++---------------- 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/tiddl/cli/__init__.py b/tiddl/cli/__init__.py index 54882cb..92b6980 100644 --- a/tiddl/cli/__init__.py +++ b/tiddl/cli/__init__.py @@ -10,6 +10,8 @@ from .config import ConfigCommand from tiddl.config import HOME_PATH +from .auth import refresh + @click.group() @passContext @@ -51,6 +53,8 @@ def cli(ctx: Context, verbose: bool, quiet: bool, no_cache: bool): logging.getLogger("urllib3").setLevel(logging.ERROR) + refresh(ctx) + cli.add_command(ConfigCommand) cli.add_command(AuthGroup) diff --git a/tiddl/cli/auth.py b/tiddl/cli/auth.py index 1286086..6810c51 100644 --- a/tiddl/cli/auth.py +++ b/tiddl/cli/auth.py @@ -4,8 +4,15 @@ import logging from click import style from time import sleep, time -from tiddl.auth import getDeviceAuth, getToken, refreshToken, removeToken, AuthError from tiddl.config import AuthConfig +from tiddl.auth import ( + getDeviceAuth, + getToken, + refreshToken, + removeToken, + AuthError, +) + from .ctx import passContext, Context @@ -17,27 +24,31 @@ def AuthGroup(): """Manage Tidal token.""" +def refresh(ctx: Context): + """Refresh auth token when is expired""" + + auth = ctx.obj.config.auth + + if auth.refresh_token and time() > auth.expires: + click.echo(style("Refreshing token...", fg="yellow")) + token = refreshToken(auth.refresh_token) + + ctx.obj.config.auth.expires = token.expires_in + int(time()) + ctx.obj.config.auth.token = token.access_token + + ctx.obj.config.save() + + click.echo(style("Refreshed auth token!", fg="green")) + + @AuthGroup.command("login") @passContext def login(ctx: Context): """Add token to the config""" - # TODO: refresh token automatically. - # we can just invoke this command - - auth = ctx.obj.config.auth - - if auth.token: - if auth.refresh_token and time() > auth.expires: - click.echo(style("Refreshing token...", fg="yellow")) - token = refreshToken(auth.refresh_token) - - ctx.obj.config.auth.expires = token.expires_in + int(time()) - ctx.obj.config.auth.token = token.access_token - - ctx.obj.config.save() - - click.echo(style("Authenticated!", fg="green")) + if ctx.obj.config.auth.token: + click.echo(style("Already logged in.", fg="green")) + refresh(ctx) return auth = getDeviceAuth() @@ -58,7 +69,9 @@ def login(ctx: Context): time_left = auth_end_at - time() minutes, seconds = time_left // 60, int(time_left % 60) - click.echo(f"\rTime left: {minutes:.0f}:{seconds:02d}", nl=False) + click.echo( + f"\rTime left: {minutes:.0f}:{seconds:02d}", nl=False + ) continue if e.error == "expired_token":