Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions streamrip/client/tidal.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
import aiohttp

from ..config import Config
from ..exceptions import NonStreamableError
from ..exceptions import (
AuthenticationError,
MissingCredentialsError,
NonStreamableError,
)
from .client import Client
from .downloadable import TidalDownloadable

Expand Down Expand Up @@ -55,7 +59,9 @@ async def login(self):
)
c = self.config
if not c.access_token:
raise Exception("Access token not found in config.")
raise MissingCredentialsError(
"No Tidal access token in config -- Tidal has not been set up yet."
)

self.token_expiry = float(c.token_expiry)
self.refresh_token = c.refresh_token
Expand Down Expand Up @@ -300,7 +306,13 @@ async def _refresh_access_token(self):
resp = await self._api_post(f"{AUTH_URL}/token", data, AUTH)

if resp.get("status", 200) != 200:
raise Exception("Refresh failed")
# The refresh token itself has lapsed or been revoked, so there is
# nothing left to refresh from and only a fresh device login will
# help. Typed so the caller can offer that instead of dying with a
# traceback.
raise AuthenticationError(
"Tidal refresh token has expired or been revoked."
)

c = self.config
c.access_token = resp["access_token"]
Expand Down
38 changes: 35 additions & 3 deletions streamrip/rip/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
import json
import logging
import platform
import sys

import aiofiles
from rich.prompt import Confirm

from .. import db
from ..client import Client, DeezerClient, QobuzClient, SoundcloudClient, TidalClient
from ..config import Config
from ..console import console
from ..exceptions import AuthenticationError, MissingCredentialsError
from ..media import (
Media,
Pending,
Expand Down Expand Up @@ -145,13 +148,42 @@ async def get_logged_in_client(self, source: str):
await prompter.prompt_and_login()
prompter.save()
else:
with console.status(f"[cyan]Logging into {source}", spinner="dots"):
# Log into client using credentials from config
await client.login()
try:
with console.status(
f"[cyan]Logging into {source}", spinner="dots"
):
# Log into client using credentials from config
await client.login()
except (AuthenticationError, MissingCredentialsError) as e:
# has_creds() only checks that something is *stored*, not
# that it still works. Saved tokens expire, so the usual
# way to discover a lapsed login is a failure here -- which
# used to be a bare traceback, even though the prompter
# that fixes it is already built and sitting right there.
await self._reauthenticate(source, prompter, e)

assert client.logged_in
return client

async def _reauthenticate(self, source: str, prompter, cause: Exception):
"""Offer a fresh login after stored credentials stop working."""
console.print(f"[yellow]{source.title()} login failed: {cause}")

# Never block on a prompt nobody is there to answer: rip is run from
# cron and from scripts, where a hidden y/n means hanging forever
# rather than failing.
if not sys.stdin.isatty():
raise AuthenticationError(
f"{source} needs authorising again. Re-run this from an "
f"interactive terminal and you will be prompted to log in."
) from cause

if not Confirm.ask(f"Log into {source} again now?"):
raise cause

await prompter.prompt_and_login()
prompter.save()

async def resolve(self):
"""Resolve all currently pending items."""
with console.status("Resolving URLs...", spinner="dots"):
Expand Down
74 changes: 74 additions & 0 deletions tests/test_reauth_prompt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Stored credentials that stop working should offer a fresh login.

`has_creds()` only checks that something is *stored*, not that it still works,
so an expired token passes that check and the failure surfaces from `login()`.
Before this was handled, that meant a traceback -- even though the prompter
that fixes it was already built.
"""

from contextlib import ExitStack
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from streamrip.exceptions import AuthenticationError
from streamrip.rip.main import Main


def _main_with_expired_token():
main = Main.__new__(Main)
client = MagicMock()
client.logged_in = False
client.login = AsyncMock(
side_effect=AuthenticationError("Tidal refresh token has expired.")
)
main.clients = {"tidal": client}
main.config = MagicMock()

prompter = MagicMock()
prompter.has_creds.return_value = True
prompter.prompt_and_login = AsyncMock(
side_effect=lambda: setattr(client, "logged_in", True)
)
return main, client, prompter


def _patches(prompter, *, isatty: bool, confirm: bool):
stack = ExitStack()
stack.enter_context(
patch("streamrip.rip.main.get_prompter", return_value=prompter)
)
stack.enter_context(patch("sys.stdin.isatty", return_value=isatty))
stack.enter_context(
patch("streamrip.rip.main.Confirm.ask", return_value=confirm)
)
return stack


@pytest.mark.asyncio
async def test_prompts_and_recovers_when_user_agrees():
main, client, prompter = _main_with_expired_token()
with _patches(prompter, isatty=True, confirm=True):
result = await main.get_logged_in_client("tidal")
prompter.prompt_and_login.assert_awaited_once()
prompter.save.assert_called_once()
assert result is client


@pytest.mark.asyncio
async def test_propagates_when_user_declines():
main, _, prompter = _main_with_expired_token()
with _patches(prompter, isatty=True, confirm=False):
with pytest.raises(AuthenticationError, match="refresh token has expired"):
await main.get_logged_in_client("tidal")
prompter.prompt_and_login.assert_not_awaited()


@pytest.mark.asyncio
async def test_never_prompts_without_a_terminal():
"""rip runs from cron and from scripts, where a hidden y/n hangs forever."""
main, _, prompter = _main_with_expired_token()
with _patches(prompter, isatty=False, confirm=True):
with pytest.raises(AuthenticationError, match="interactive terminal"):
await main.get_logged_in_client("tidal")
prompter.prompt_and_login.assert_not_awaited()