feat: Yandex sign-in with device code, keychain storage and account status

- ym-api wraps yamuse: device-code flow, token refresh, account status,
  and its own Error type that the UI acts on (expired, denied, network)
- Credentials live in the system keychain, never print their tokens, and
  refresh when within a week of expiry; a rejected token is forgotten
- Sign-in screen with code, QR, copy/open-in-browser, countdown and a
  pasted-token fallback; restoring/unreachable screens on startup
- Sidebar account chip and Settings account card with Plus status and
  sign-out; Settings re-reads the account when opened
- Live device-code test behind --ignored
This commit is contained in:
Yuriy Panov committed 2026-10-15 14:25:45 +06:00
1 parent c4928ae7fe
commit 43e8f86a5d
17 files changed
+2811 -127

No files matched your search

+6 -3
View File
@@ -8,13 +8,16 @@ publish.workspace = true
[dependencies]
ym-api = { path = "../ym-api" }
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced"] }
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code"] }
keyring = "4.2.0"
open = "5.4.4"
serde_json = "1"
tokio = { version = "1", features = ["time", "rt"] }
png = { version = "0.18.1", optional = true }
tokio = { version = "1", features = ["time"], optional = true }
[features]
# `MUSYX_SNAPSHOT=out.png cargo run --features snapshot` renders one screen to a PNG and exits.
snapshot = ["dep:png", "dep:tokio"]
snapshot = ["dep:png"]
[lints]
workspace = true
+139 -16
View File
@@ -3,18 +3,33 @@
use iced::theme::Mode;
use iced::widget::{column, container, row, scrollable, space};
use iced::{Element, Fill, Subscription, Task, Theme};
use ym_api::auth::Credentials;
use ym_api::{Account, Error, YmClient};
use crate::route::{Navigator, Route};
use crate::screens;
use crate::screens::{self, sign_in};
use crate::session::{self, Restored};
use crate::ui::theme::{self, shell};
use crate::widgets::drawer::{self, Panel};
use crate::widgets::player_bar::{self, PlayerUi};
use crate::widgets::{sidebar, topbar};
/// Where sign-in stands. Everything but `SignedIn` takes the whole window.
pub enum Session {
/// Reading the keychain and checking the stored token.
Restoring,
SignedOut(Box<sign_in::SignIn>),
/// Fresh credentials are being checked. `pasted` picks the error wording if they fail.
Connecting { pasted: bool },
Unreachable,
SignedIn { client: YmClient, account: Account },
}
pub struct App {
theme: Theme,
/// Set by a snapshot run so the system appearance can't override it.
forced_mode: Option<Mode>,
session: Session,
nav: Navigator,
search: String,
drawer: Option<Panel>,
@@ -24,6 +39,13 @@ pub struct App {
#[derive(Debug, Clone)]
pub enum Message {
ThemeChanged(Mode),
Restore,
Restored(Restored),
SignIn(sign_in::Msg),
Connected(Result<(YmClient, Account), Error>),
AccountRefreshed(Result<Account, Error>),
SignOut,
SignedOut,
Navigate(Route),
Back,
SearchChanged(String),
@@ -38,16 +60,18 @@ impl App {
let app = Self {
theme: theme::for_mode(Mode::Dark),
forced_mode: None,
session: Session::Restoring,
nav: Navigator::new(Route::Home),
search: String::new(),
drawer: None,
player: PlayerUi::default(),
};
let boot = iced::system::theme().map(Message::ThemeChanged);
let appearance = iced::system::theme().map(Message::ThemeChanged);
#[cfg(feature = "snapshot")]
if let Some(config) = crate::snapshot::Config::from_env() {
let mut app = app;
app.session = config.session();
if let Some(route) = config.route {
app.nav = Navigator::new(route);
}
@@ -56,16 +80,18 @@ impl App {
if let Some(mode) = config.mode {
app.theme = theme::for_mode(mode);
}
return (app, Task::batch([boot, config.capture()]));
return (app, Task::batch([appearance, config.capture()]));
}
(app, boot)
(app, Task::batch([appearance, restore()]))
}
pub fn title(&self) -> String {
match self.nav.current() {
Route::Home => "Musyx".into(),
route => format!("{} · Musyx", route.label()),
match (&self.session, self.nav.current()) {
(Session::SignedIn { .. }, route) if route != Route::Home => {
format!("{} · Musyx", route.label())
}
_ => "Musyx".into(),
}
}
@@ -74,7 +100,13 @@ impl App {
}
pub fn subscription(&self) -> Subscription<Message> {
iced::system::theme_changes().map(Message::ThemeChanged)
let appearance = iced::system::theme_changes().map(Message::ThemeChanged);
match &self.session {
Session::SignedOut(sign_in) => {
Subscription::batch([appearance, sign_in.subscription().map(Message::SignIn)])
}
_ => appearance,
}
}
pub fn update(&mut self, message: Message) -> Task<Message> {
@@ -82,7 +114,77 @@ impl App {
Message::ThemeChanged(mode) => {
self.theme = theme::for_mode(self.forced_mode.unwrap_or(mode));
}
Message::Navigate(route) => self.nav.go(route),
Message::Restore => {
self.session = Session::Restoring;
return restore();
}
Message::Restored(restored) => {
self.session = match restored {
Restored::SignedIn(client, account) => Session::SignedIn { client, account },
Restored::SignedOut => Session::SignedOut(Box::default()),
Restored::Unreachable => Session::Unreachable,
};
}
Message::SignIn(msg) => {
let Session::SignedOut(sign_in) = &mut self.session else {
return Task::none();
};
match sign_in.update(msg) {
sign_in::Outcome::Continue(task) => return task.map(Message::SignIn),
sign_in::Outcome::Granted(credentials) => {
let pasted = credentials.refresh_token.is_none();
self.session = Session::Connecting { pasted };
return connect(credentials);
}
}
}
Message::Connected(Ok((client, account))) => {
self.nav = Navigator::new(Route::Home);
self.session = Session::SignedIn { client, account };
}
Message::Connected(Err(e)) => {
eprintln!("sign-in: {e}");
let pasted = matches!(self.session, Session::Connecting { pasted: true });
self.session = Session::SignedOut(Box::new(match &e {
Error::Unauthorized(_) if pasted => sign_in::SignIn::rejected_token(),
_ => sign_in::SignIn::with_error(&e),
}));
// Don't keep credentials that just failed.
return Task::future(session::clear()).discard();
}
Message::SignOut => {
return Task::future(session::clear()).map(|result| {
if let Err(e) = result {
eprintln!("keychain: {e}");
}
Message::SignedOut
});
}
Message::SignedOut => {
self.session = Session::SignedOut(Box::default());
self.nav = Navigator::new(Route::Home);
self.drawer = None;
self.player = PlayerUi::default();
}
Message::Navigate(route) => {
self.nav.go(route);
// Settings shows the subscription, which can change outside the app.
if let (Route::Settings, Session::SignedIn { client, .. }) = (route, &self.session) {
let client = client.clone();
return Task::future(async move { client.account().await })
.map(Message::AccountRefreshed);
}
}
Message::AccountRefreshed(Ok(fresh)) => {
if let Session::SignedIn { account, .. } = &mut self.session {
*account = fresh;
}
}
Message::AccountRefreshed(Err(Error::Unauthorized(e))) => {
eprintln!("token rejected: {e}");
return self.update(Message::SignOut);
}
Message::AccountRefreshed(Err(e)) => eprintln!("account refresh: {e}"),
Message::Back => self.nav.back(),
Message::SearchChanged(query) => self.search = query,
Message::SearchSubmitted => self.nav.go(Route::Search),
@@ -97,23 +199,29 @@ impl App {
pub fn view(&self) -> Element<'_, Message> {
let t = theme::tokens(&self.theme);
let page = match &self.session {
Session::Restoring => screens::connecting(t, "Checking your sign-in…"),
Session::Connecting { .. } => screens::connecting(t, "Signing in…"),
Session::Unreachable => screens::unreachable(t),
Session::SignedOut(sign_in) => sign_in.view(t).map(Message::SignIn),
Session::SignedIn { account, .. } => return self.shell(t, account),
};
container(page).width(Fill).height(Fill).style(theme::app).into()
}
fn shell<'a>(&'a self, t: &'static theme::Tokens, account: &'a Account) -> Element<'a, Message> {
let route = self.nav.current();
let content = column![
topbar::view(t, self.nav.can_go_back(), &self.search),
scrollable(screens::view(t, route, &self.search))
scrollable(screens::view(t, route, &self.search, account))
.height(Fill)
.style(theme::scroll),
]
.width(Fill)
.height(Fill);
let mut body = row![
sidebar::view(t, route),
vline(),
content,
]
.height(Fill);
let mut body = row![sidebar::view(t, route, account), vline(), content].height(Fill);
if let Some(panel) = self.drawer {
body = body.push(vline()).push(drawer::view(t, panel));
@@ -131,6 +239,21 @@ impl App {
}
}
fn restore() -> Task<Message> {
Task::future(session::restore()).map(Message::Restored)
}
/// Save first so a crash right after sign-in doesn't lose it, then check the token.
fn connect(credentials: Credentials) -> Task<Message> {
Task::future(async move {
if let Err(e) = session::save(credentials.clone()).await {
eprintln!("keychain: {e}");
}
YmClient::connect(&credentials).await
})
.map(Message::Connected)
}
fn vline<'a>() -> Element<'a, Message> {
container(space()).width(1).height(Fill).style(theme::divider).into()
}
+1
View File
@@ -1,6 +1,7 @@
mod app;
mod route;
mod screens;
mod session;
#[cfg(feature = "snapshot")]
mod snapshot;
mod ui;
-3
View File
@@ -11,7 +11,6 @@ pub enum Route {
Collection,
Podcasts,
Settings,
SignIn,
}
impl Route {
@@ -27,7 +26,6 @@ impl Route {
Route::Collection => "Collection",
Route::Podcasts => "Podcasts",
Route::Settings => "Settings",
Route::SignIn => "Sign in",
}
}
@@ -39,7 +37,6 @@ impl Route {
Route::Collection => Icon::Library,
Route::Podcasts => Icon::Podcast,
Route::Settings => Icon::Settings,
Route::SignIn => Icon::LogOut,
}
}
}
+125 -77
View File
@@ -1,34 +1,27 @@
//! Content for each route. Until sign-in exists every screen shows its
//! signed-out state, which is also what a signed-out user will see later.
//! Content for each route, plus the full-window screens shown outside a session.
pub mod sign_in;
use iced::widget::{Column, button, column, container, row, space};
use iced::{Alignment, Element, Fill, Padding};
use ym_api::Account;
use crate::app::Message;
use crate::route::Route;
use crate::ui::icons::{Icon, icon, sized};
use crate::ui::theme::{self, Tokens, radius, size, space as sp};
use crate::ui::{line, para};
use crate::widgets::sidebar;
pub fn view<'a>(t: &'static Tokens, route: Route, query: &str) -> Element<'a, Message> {
pub fn view<'a>(t: &'static Tokens, route: Route, query: &str, me: &'a Account) -> Element<'a, Message> {
let content: Column<'a, Message> = match route {
Route::Home => column![
wave_hero(t),
signed_out(
t,
Icon::Library,
"Your music, picked for you",
"Sign in to see your daily playlists, the chart and albums picked from what you play.",
),
upcoming(t, Icon::Library, "Made for you", "Daily playlists, the chart and albums picked from what you play."),
],
Route::Wave => column![
title(t, "My Wave"),
signed_out(
t,
Icon::Wave,
"An endless stream that learns from you",
"Sign in to start My Wave. Every like, skip and full listen steers what comes next.",
),
upcoming(t, Icon::Wave, "An endless stream that learns from you", "Every like, skip and full listen steers what comes next."),
],
Route::Search => column![
title(t, if query.trim().is_empty() {
@@ -36,41 +29,17 @@ pub fn view<'a>(t: &'static Tokens, route: Route, query: &str) -> Element<'a, Me
} else {
format!("Results for “{}”", query.trim())
}),
signed_out(
t,
Icon::Search,
"Search the whole catalogue",
"Sign in to search tracks, albums, artists, playlists and podcasts.",
),
upcoming(t, Icon::Search, "Search the whole catalogue", "Tracks, albums, artists, playlists and podcasts."),
],
Route::Collection => column![
title(t, "Collection"),
signed_out(
t,
Icon::HeartFilled,
"Everything you've liked",
"Your liked tracks, albums, artists and playlists appear here after you sign in.",
),
upcoming(t, Icon::HeartFilled, "Everything you've liked", "Liked tracks, albums, artists and playlists."),
],
Route::Podcasts => column![
title(t, "Podcasts and books"),
signed_out(
t,
Icon::Podcast,
"Pick up where you left off",
"Podcasts and audiobooks you follow appear here after you sign in.",
),
upcoming(t, Icon::Podcast, "Pick up where you left off", "Podcasts and audiobooks you follow."),
],
Route::Settings => column![
title(t, "Settings"),
signed_out(
t,
Icon::Settings,
"Account and playback",
"Sign in to choose streaming quality and manage your Yandex account.",
),
],
Route::SignIn => column![sign_in(t)],
Route::Settings => column![title(t, "Settings"), account_card(t, me)],
};
content
@@ -84,24 +53,17 @@ fn title<'a>(t: &'static Tokens, text: impl Into<String>) -> Element<'a, Message
line(text.into(), theme::DISPLAY, size::DISPLAY_S, t.fg).into()
}
fn signed_out<'a>(
t: &'static Tokens,
glyph: Icon,
heading: &'a str,
body: &'a str,
) -> Element<'a, Message> {
/// A section whose content arrives in a later build.
fn upcoming<'a>(t: &'static Tokens, glyph: Icon, heading: &'a str, body: &'a str) -> Element<'a, Message> {
container(
column![
sized(glyph, 28.0, t.accent),
column![
line(heading, theme::SEMIBOLD, size::SECTION, t.fg),
container(para(body, size::BODY, t.muted)).max_width(460),
line("Arrives in the next Musyx update.", theme::MEDIUM, size::META, t.muted),
]
.spacing(6),
button(line("Sign in", theme::SEMIBOLD, size::BODY, t.accent_ink))
.padding([11, 18])
.style(theme::primary)
.on_press(Message::Navigate(Route::SignIn)),
]
.spacing(18),
)
@@ -111,6 +73,60 @@ fn signed_out<'a>(
.into()
}
fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> {
let avatar = container(line(me.initial().to_string(), theme::SEMIBOLD, 22.0, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
.center(56)
.style(theme::avatar);
let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) {
(true, Some(end)) => format!("Yandex Plus until {end}"),
(true, None) => "Yandex Plus".to_owned(),
(false, _) => "No Plus subscription. Tracks play as 30-second previews.".to_owned(),
};
container(
row![
avatar,
column![
line(&me.name, theme::SEMIBOLD, size::SECTION, t.fg),
line(&me.login, theme::BODY, size::BODY, t.muted),
line(plan, theme::MEDIUM, size::META, if me.has_plus { t.ok } else { t.muted }),
]
.spacing(4)
.width(Fill),
button(
row![icon(Icon::LogOut, t.fg), line("Sign out", theme::MEDIUM, size::BODY, t.fg)]
.spacing(8)
.align_y(Alignment::Center),
)
.padding([9, 16])
.style(theme::ghost)
.on_press(Message::SignOut),
]
.spacing(18)
.align_y(Alignment::Center),
)
.padding(24)
.width(Fill)
.style(theme::card)
.into()
}
/// `2027-01-05T00:00:00+03:00` → `5 January 2027`.
pub fn human_date(iso: &str) -> Option<String> {
const MONTHS: [&str; 12] = [
"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December",
];
let date = iso.get(..10)?;
let mut parts = date.split('-');
let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?);
let month = MONTHS.get(m.parse::<usize>().ok()?.checked_sub(1)?)?;
let day: u32 = d.parse().ok()?;
y.parse::<u32>().ok()?;
Some(format!("{day} {month} {y}"))
}
/// Static version of the My Wave hero; the animated wave arrives with playback.
fn wave_hero<'a>(t: &'static Tokens) -> Element<'a, Message> {
container(
@@ -153,29 +169,61 @@ fn wave_hero<'a>(t: &'static Tokens) -> Element<'a, Message> {
.into()
}
fn sign_in<'a>(t: &'static Tokens) -> Element<'a, Message> {
column![
container(line("Sign in with your Yandex account", theme::DISPLAY, size::DISPLAY_M, t.fg)),
container(para(
"Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in \
on Yandex's own page, so your password never passes through this app.",
15.0,
t.muted,
))
.max_width(520),
button(line("Get sign-in code", theme::SEMIBOLD, size::BODY, t.muted))
.padding([11, 18])
.style(theme::primary),
space().height(8),
container(para(
"Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token \
is kept in the system keychain.",
size::SMALL,
t.muted,
))
.max_width(520),
]
.spacing(22)
.padding(Padding::default().top(24))
/// Full-window holding screen while the stored session is checked or a new one connects.
pub fn connecting<'a>(t: &'static Tokens, label: &'a str) -> Element<'a, Message> {
container(
column![
sidebar::wordmark(t),
line(label, theme::BODY, size::BODY, t.muted),
]
.spacing(14)
.align_x(Alignment::Center),
)
.center(Fill)
.into()
}
/// Full-window screen when stored credentials exist but Yandex can't be reached.
pub fn unreachable<'a>(t: &'static Tokens) -> Element<'a, Message> {
container(
column![
sidebar::wordmark(t),
line("Can't reach Yandex Music", theme::DISPLAY, size::DISPLAY_S, t.fg),
container(para(
"You're still signed in. Check your internet connection, then try again.",
15.0,
t.muted,
))
.max_width(440),
row![
button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink))
.padding([11, 18])
.style(theme::primary)
.on_press(Message::Restore),
button(line("Sign out", theme::MEDIUM, size::BODY, t.fg))
.padding([11, 18])
.style(theme::ghost)
.on_press(Message::SignOut),
]
.spacing(10),
space().height(40),
]
.spacing(18)
.align_x(Alignment::Center),
)
.center(Fill)
.into()
}
#[cfg(test)]
mod tests {
use super::human_date;
#[test]
fn dates_read_naturally() {
assert_eq!(human_date("2027-01-05T00:00:00+03:00").as_deref(), Some("5 January 2027"));
assert_eq!(human_date("2026-12-31").as_deref(), Some("31 December 2026"));
assert_eq!(human_date("2026-13-01"), None);
assert_eq!(human_date("soon"), None);
}
}
+500
View File
@@ -0,0 +1,500 @@
//! Device-code sign-in: get a code, the user confirms it on Yandex's page
//! (or scans the QR), we poll until a token arrives. A pasted token is the
//! fallback for people who already have one.
use std::time::{Duration, Instant};
use iced::widget::{button, column, container, qr_code, row, space, text_input};
use iced::{Alignment, Element, Fill, Length, Padding, Subscription, Task};
use ym_api::Error;
use ym_api::auth::{Auth, Credentials, DeviceCode, Poll};
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para};
use crate::widgets::sidebar;
#[derive(Debug, Clone)]
pub enum Msg {
GetCode,
CodeReady(Result<DeviceCode, Error>),
Tick(Instant),
Polled(Result<Poll, Error>),
CopyCode,
OpenPage,
ToggleToken,
TokenChanged(String),
UseToken,
Cancel,
}
enum Stage {
Idle,
Requesting,
Waiting(Box<Waiting>),
}
struct Waiting {
code: DeviceCode,
qr: Option<qr_code::Data>,
started: Instant,
now: Instant,
next_poll: Instant,
polling: bool,
copied_at: Option<Instant>,
}
impl Waiting {
fn remaining(&self) -> Duration {
self.code.expires_in.saturating_sub(self.now.duration_since(self.started))
}
}
pub struct SignIn {
stage: Stage,
error: Option<String>,
token_open: bool,
token: String,
}
impl Default for SignIn {
fn default() -> Self {
Self { stage: Stage::Idle, error: None, token_open: false, token: String::new() }
}
}
/// What the app should do after a sign-in message.
pub enum Outcome {
Continue(Task<Msg>),
/// Credentials from Yandex (or pasted); the app saves them and connects.
Granted(Credentials),
}
impl SignIn {
/// Shown after a pasted token turned out to be invalid.
pub fn rejected_token() -> Self {
Self {
error: Some("Yandex didn't accept that token. Check it and paste it again.".into()),
token_open: true,
..Self::default()
}
}
/// Shown when connecting with fresh credentials failed.
pub fn with_error(error: &Error) -> Self {
Self { error: Some(describe(error).into()), ..Self::default() }
}
pub fn update(&mut self, msg: Msg) -> Outcome {
match msg {
Msg::GetCode => {
self.error = None;
self.stage = Stage::Requesting;
return Outcome::Continue(Task::future(async {
match Auth::new() {
Ok(auth) => auth.request_code().await,
Err(e) => Err(e),
}
}).map(Msg::CodeReady));
}
Msg::CodeReady(Ok(code)) => {
let now = Instant::now();
let qr = qr_code::Data::new(code.verification_url.as_bytes()).ok();
self.stage = Stage::Waiting(Box::new(Waiting {
next_poll: now + code.interval,
code,
qr,
started: now,
now,
polling: false,
copied_at: None,
}));
}
Msg::CodeReady(Err(e)) => self.fail(&e),
Msg::Tick(now) => {
let Stage::Waiting(w) = &mut self.stage else {
return Outcome::Continue(Task::none());
};
w.now = now;
if w.remaining().is_zero() {
self.fail(&Error::CodeExpired);
} else if !w.polling && now >= w.next_poll {
w.polling = true;
let code = w.code.clone();
return Outcome::Continue(
Task::future(async move {
match Auth::new() {
Ok(auth) => auth.poll(&code).await,
Err(e) => Err(e),
}
})
.map(Msg::Polled),
);
}
}
Msg::Polled(result) => {
let Stage::Waiting(w) = &mut self.stage else {
return Outcome::Continue(Task::none());
};
w.polling = false;
match result {
Ok(Poll::Pending) => w.next_poll = Instant::now() + w.code.interval,
// A dropped poll isn't fatal: try again next interval.
Err(e) if e.is_retryable() => w.next_poll = Instant::now() + w.code.interval,
Ok(Poll::Granted(credentials)) => {
self.stage = Stage::Idle;
return Outcome::Granted(credentials);
}
Err(e) => self.fail(&e),
}
}
Msg::CopyCode => {
if let Stage::Waiting(w) = &mut self.stage {
w.copied_at = Some(w.now);
return Outcome::Continue(iced::clipboard::write(w.code.user_code.clone()));
}
}
Msg::OpenPage => {
if let Stage::Waiting(w) = &self.stage
&& open::that_detached(&w.code.verification_url).is_err()
{
self.error = Some(format!(
"Couldn't open your browser. Go to {} yourself.",
w.code.verification_url
));
}
}
Msg::ToggleToken => self.token_open = !self.token_open,
Msg::TokenChanged(token) => self.token = token,
Msg::UseToken => {
let credentials = Credentials::from_token(&self.token);
if !credentials.access_token.is_empty() {
self.token.clear();
self.stage = Stage::Idle;
return Outcome::Granted(credentials);
}
}
Msg::Cancel => {
self.stage = Stage::Idle;
self.error = None;
}
}
Outcome::Continue(Task::none())
}
fn fail(&mut self, error: &Error) {
self.stage = Stage::Idle;
self.error = Some(describe(error).into());
}
/// Ticks once a second while a code is on screen: drives the countdown and polling.
pub fn subscription(&self) -> Subscription<Msg> {
match self.stage {
Stage::Waiting(_) => iced::time::every(Duration::from_secs(1)).map(Msg::Tick),
_ => Subscription::none(),
}
}
pub fn view<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let left = column![
sidebar::wordmark(t),
container(
iced::widget::text("Sign in with your Yandex account")
.font(theme::DISPLAY)
.size(size::DISPLAY_M)
.line_height(1.12)
.color(t.fg),
)
.max_width(520),
container(para(
"Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in \
on Yandex's own page, so your password never passes through this app.",
15.0,
t.muted,
))
.max_width(500),
self.body(t),
self.token_fallback(t),
space().height(Fill),
container(para(
"Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in \
token is kept in the system keychain.",
size::SMALL,
t.muted,
))
.max_width(520),
]
.spacing(26)
.padding(Padding::from([44, 56]))
.width(Length::FillPortion(21))
.clip(true)
.height(Fill);
let right = container(self.qr_card(t))
.center(Fill)
.width(Length::FillPortion(20))
.style(move |th| {
let mut s = theme::panel(th);
s.background = Some(iced::Background::Gradient(
iced::gradient::Linear::new(0.4)
.add_stop(0.0, t.panel)
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.14))
.into(),
));
s
});
row![left, container(space()).width(1).height(Fill).style(theme::divider), right]
.height(Fill)
.into()
}
fn body<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let error = self.error.as_deref().map(|e| {
container(para(e, size::BODY, t.like)).max_width(500)
});
let content: Element<'a, Msg> = match &self.stage {
Stage::Idle => column![
primary(t, "Get sign-in code", Some(Msg::GetCode)),
]
.into(),
Stage::Requesting => column![primary(t, "Getting a code…", None)].into(),
Stage::Waiting(w) => self.steps(t, w),
};
column![content].push(error).spacing(16).into()
}
fn steps<'a>(&'a self, t: &'static Tokens, w: &'a Waiting) -> Element<'a, Msg> {
let host = w
.code
.verification_url
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_end_matches('/')
.to_owned();
let copied = w.copied_at.is_some_and(|at| w.now.duration_since(at) < Duration::from_secs(2));
let code_box = row![
container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
.padding([14, 18])
.style(theme::card),
ghost(t, Icon::Copy, if copied { "Copied" } else { "Copy code" }, Msg::CopyCode),
]
.spacing(14)
.align_y(Alignment::Center);
let remaining = w.remaining().as_secs();
let status = row![
container(space()).width(9).height(9).style(theme::accent_dot),
line(
format!("Waiting for confirmation · code expires in {}:{:02}", remaining / 60, remaining % 60),
theme::BODY,
13.5,
t.muted,
),
space().width(12),
button(line("Cancel", theme::MEDIUM, 13.5, t.muted))
.padding(0)
.style(theme::tab(false))
.on_press(Msg::Cancel),
]
.spacing(10)
.align_y(Alignment::Center);
column![
step(t, 1, column![
line(format!("Open {host}"), theme::MEDIUM, size::BODY, t.fg),
para("On this computer or your phone. You can also scan the QR code.", 13.5, t.muted),
ghost(t, Icon::Globe, "Open in browser", Msg::OpenPage),
].spacing(6)),
step(t, 2, column![
line("Enter this code", theme::MEDIUM, size::BODY, t.fg),
code_box,
].spacing(10)),
step(t, 3, column![
line("Come back here", theme::MEDIUM, size::BODY, t.fg),
para("Musyx signs you in as soon as you allow access.", 13.5, t.muted),
].spacing(4)),
status,
]
.spacing(20)
.into()
}
fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let toggle = button(line(
if self.token_open { "Hide token sign-in" } else { "Sign in with an existing token instead" },
theme::BODY,
13.5,
t.muted,
))
.padding(0)
.style(theme::tab(false))
.on_press(Msg::ToggleToken);
if !self.token_open {
return toggle.into();
}
let can_submit = !self.token.trim().is_empty();
column![
toggle,
row![
text_input("Paste OAuth token", &self.token)
.id("token")
.secure(true)
.on_input(Msg::TokenChanged)
.on_submit_maybe(can_submit.then_some(Msg::UseToken))
.padding([10, 14])
.width(320)
.style(theme::search_field),
button(line("Sign in", theme::MEDIUM, size::BODY, t.fg))
.padding([10, 18])
.style(theme::ghost)
.on_press_maybe(can_submit.then_some(Msg::UseToken)),
]
.spacing(8)
.align_y(Alignment::Center),
]
.spacing(10)
.into()
}
fn qr_card<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let qr = match &self.stage {
Stage::Waiting(w) => w.qr.as_ref(),
_ => None,
};
let (code, caption): (Element<'a, Msg>, &str) = match qr {
Some(data) => (
qr_code(data)
.total_size(200)
.style(|_| qr_code::Style {
cell: iced::Color::from_rgb8(0x1C, 0x1A, 0x22),
background: iced::Color::WHITE,
})
.into(),
"Scan to open the sign-in page",
),
None => (
container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78)))
.center(200)
.into(),
"A QR code appears with your sign-in code",
),
};
container(
column![
code,
line(caption, theme::BODY, size::SMALL, iced::Color::from_rgb8(0x4A, 0x44, 0x58)),
]
.spacing(10)
.align_x(Alignment::Center),
)
.padding(18)
.style(move |_| iced::widget::container::Style {
background: Some(iced::Color::WHITE.into()),
border: iced::Border { radius: radius::HERO.into(), ..Default::default() },
shadow: iced::Shadow {
color: iced::Color::BLACK.scale_alpha(if t == &theme::DARK { 0.45 } else { 0.14 }),
offset: iced::Vector::new(0.0, 18.0),
blur_radius: 50.0,
},
..Default::default()
})
.into()
}
}
/// The user's next step for each failure. Never shows the raw error.
fn describe(error: &Error) -> &'static str {
match error {
Error::CodeExpired => "The code expired before it was confirmed. Get a new code to try again.",
Error::Denied => "Access was declined on Yandex's page. Get a new code if that was a mistake.",
Error::Network(_) => "Can't reach Yandex. Check your connection and try again.",
Error::Unauthorized(_) => "Yandex didn't accept the sign-in. Get a new code to try again.",
Error::Api(_) => "Yandex sent an unexpected answer. Try again in a moment.",
}
}
/// `ABCD1234` → `ABCD 1234` for easier reading; codes that already have separators stay as they are.
fn spaced(code: &str) -> String {
if code.len() == 8 && code.chars().all(|c| c.is_ascii_alphanumeric()) {
format!("{} {}", &code[..4], &code[4..])
} else {
code.to_owned()
}
}
fn step<'a>(t: &'static Tokens, n: u8, content: impl Into<Element<'a, Msg>>) -> Element<'a, Msg> {
let badge = container(line(n.to_string(), theme::SEMIBOLD, size::BODY, t.muted))
.center(30)
.style(move |_| iced::widget::container::Style {
border: iced::Border { color: t.line, width: 1.0, radius: radius::PILL.into() },
..Default::default()
});
row![badge, container(content).padding(Padding::default().top(4))]
.spacing(14)
.into()
}
fn primary<'a>(t: &'static Tokens, label: &'a str, msg: Option<Msg>) -> Element<'a, Msg> {
let ink = if msg.is_some() { t.accent_ink } else { t.muted };
button(line(label, theme::SEMIBOLD, size::BODY, ink))
.padding([11, 18])
.style(theme::primary)
.on_press_maybe(msg)
.into()
}
fn ghost<'a>(t: &'static Tokens, glyph: Icon, label: &'a str, msg: Msg) -> Element<'a, Msg> {
button(
row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::BODY, t.fg)]
.spacing(8)
.align_y(Alignment::Center),
)
.padding([9, 16])
.style(theme::ghost)
.on_press(msg)
.into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_are_split_for_reading() {
assert_eq!(spaced("QX7K29PM"), "QX7K 29PM");
assert_eq!(spaced("QX7-K29"), "QX7-K29");
assert_eq!(spaced("1234567"), "1234567");
}
#[test]
fn pasted_token_is_trimmed_and_granted() {
let mut s = SignIn::default();
let _ = s.update(Msg::TokenChanged(" y0_token \n".into()));
match s.update(Msg::UseToken) {
Outcome::Granted(c) => assert_eq!(c.access_token, "y0_token"),
Outcome::Continue(_) => panic!("expected credentials"),
}
assert!(s.token.is_empty(), "token must not linger in UI state");
}
#[test]
fn blank_token_is_ignored() {
let mut s = SignIn::default();
let _ = s.update(Msg::TokenChanged(" ".into()));
assert!(matches!(s.update(Msg::UseToken), Outcome::Continue(_)));
}
#[test]
fn failures_leave_an_actionable_message() {
let mut s = SignIn::default();
let _ = s.update(Msg::CodeReady(Err(Error::Network("dns".into()))));
assert!(matches!(s.stage, Stage::Idle));
assert!(s.error.as_deref().unwrap().contains("connection"));
}
}
+110
View File
@@ -0,0 +1,110 @@
//! Keeping the user signed in: credentials live in the system keychain, and
//! startup turns them back into a connected client.
use std::time::SystemTime;
use ym_api::auth::{Auth, Credentials};
use ym_api::{Account, Error, YmClient};
const SERVICE: &str = "musyx";
const ACCOUNT: &str = "yandex-music";
/// What startup found.
#[derive(Debug, Clone)]
pub enum Restored {
SignedIn(YmClient, Account),
/// Nothing stored, or the stored token was rejected (and has been removed).
SignedOut,
/// Credentials are stored but Yandex couldn't be reached; they're kept for a retry.
Unreachable,
}
/// Keychain access is blocking (and may show a system prompt), so it runs off the UI thread.
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
tokio::task::spawn_blocking(f).await.expect("keychain task panicked")
}
fn entry() -> Result<keyring::Entry, String> {
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| e.to_string())
}
pub async fn load() -> Result<Option<Credentials>, String> {
blocking(|| {
let raw = match entry()?.get_password() {
Ok(raw) => raw,
Err(keyring::Error::NoEntry) => return Ok(None),
Err(e) => return Err(e.to_string()),
};
// An unreadable entry is treated as absent; the next sign-in overwrites it.
Ok(serde_json::from_str(&raw).ok())
})
.await
}
pub async fn save(credentials: Credentials) -> Result<(), String> {
blocking(move || {
let json = serde_json::to_string(&credentials).map_err(|e| e.to_string())?;
entry()?.set_password(&json).map_err(|e| e.to_string())
})
.await
}
pub async fn clear() -> Result<(), String> {
blocking(|| match entry()?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
})
.await
}
/// Load stored credentials, refresh them if they're close to expiring, connect.
pub async fn restore() -> Restored {
let credentials = match load().await {
Ok(Some(c)) => c,
Ok(None) => return Restored::SignedOut,
Err(e) => {
eprintln!("keychain: {e}");
return Restored::SignedOut;
}
};
let credentials = if credentials.needs_refresh(SystemTime::now()) {
match refresh(&credentials).await {
Some(fresh) => fresh,
None => credentials,
}
} else {
credentials
};
match YmClient::connect(&credentials).await {
Ok((client, account)) => Restored::SignedIn(client, account),
Err(Error::Unauthorized(_)) => match refresh(&credentials).await {
Some(fresh) => match YmClient::connect(&fresh).await {
Ok((client, account)) => Restored::SignedIn(client, account),
Err(e) => forget(e).await,
},
None => forget(Error::Unauthorized("refresh failed".into())).await,
},
Err(e) if e.is_retryable() => Restored::Unreachable,
Err(e) => forget(e).await,
}
}
/// Refresh and persist; `None` when there is nothing to refresh with or Yandex said no.
async fn refresh(credentials: &Credentials) -> Option<Credentials> {
credentials.refresh_token.as_ref()?;
let fresh = Auth::new().ok()?.refresh(credentials).await.ok()?;
if let Err(e) = save(fresh.clone()).await {
eprintln!("keychain: {e}");
}
Some(fresh)
}
async fn forget(reason: Error) -> Restored {
eprintln!("stored sign-in rejected: {reason}");
if let Err(e) = clear().await {
eprintln!("keychain: {e}");
}
Restored::SignedOut
}
+24 -2
View File
@@ -13,12 +13,17 @@ use iced::Task;
use iced::theme::Mode;
use iced::window;
use ym_api::{Account, YmClient};
use crate::app::Session;
use crate::route::Route;
use crate::widgets::drawer::Panel;
#[derive(Debug, Clone)]
pub struct Config {
pub out: PathBuf,
/// `MUSYX_SNAPSHOT_ROUTE=signin` shows the sign-in page instead of a signed-in shell.
pub signed_out: bool,
pub route: Option<Route>,
pub drawer: Option<Panel>,
pub mode: Option<Mode>,
@@ -28,6 +33,7 @@ impl Config {
pub fn from_env() -> Option<Self> {
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
let var = |k: &str| std::env::var(k).ok().map(|v| v.to_ascii_lowercase());
let signed_out = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("signin");
let route = var("MUSYX_SNAPSHOT_ROUTE").and_then(|r| {
Some(match r.as_str() {
"home" => Route::Home,
@@ -36,7 +42,6 @@ impl Config {
"collection" => Route::Collection,
"podcasts" => Route::Podcasts,
"settings" => Route::Settings,
"signin" => Route::SignIn,
_ => return None,
})
});
@@ -50,7 +55,24 @@ impl Config {
"dark" => Some(Mode::Dark),
_ => None,
});
Some(Self { out, route, drawer, mode })
Some(Self { out, signed_out, route, drawer, mode })
}
/// A made-up account so the shell renders without a network or keychain.
pub fn session(&self) -> Session {
if self.signed_out {
return Session::SignedOut(Box::default());
}
Session::SignedIn {
client: YmClient::unauthenticated().expect("client"),
account: Account {
uid: 1,
login: "sample.listener".into(),
name: "Sample Listener".into(),
has_plus: true,
subscription_end: Some("2027-01-05T00:00:00+03:00".into()),
},
}
}
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
+20 -19
View File
@@ -3,13 +3,15 @@
use iced::widget::{Column, button, column, container, row, space};
use iced::{Alignment, Element, Fill, Padding};
use ym_api::Account;
use crate::app::Message;
use crate::route::Route;
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, shell, size};
use crate::ui::theme::{self, Tokens, shell, size};
use crate::ui::{line, para};
pub fn view<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
pub fn view<'a>(t: &'static Tokens, current: Route, me: &'a Account) -> Element<'a, Message> {
let nav = Column::with_children(Route::NAV.map(|route| nav_item(t, route, route == current)))
.spacing(2);
@@ -24,7 +26,7 @@ pub fn view<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
.padding(Padding::default().left(10).right(2));
let playlists = container(para(
"Your playlists appear here after you sign in.",
"Your playlists will be listed here.",
size::META,
t.muted,
))
@@ -35,7 +37,7 @@ pub fn view<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
nav,
column![playlists_head, playlists].spacing(6),
space().height(Fill),
account(t, current),
account(t, current, me),
]
.spacing(22)
.padding(Padding::default().top(18).bottom(12).left(12).right(12))
@@ -44,7 +46,7 @@ pub fn view<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
.into()
}
pub fn wordmark<'a>(t: &'static Tokens) -> Element<'a, Message> {
pub fn wordmark<'a, M: 'a>(t: &'static Tokens) -> Element<'a, M> {
row![
line("musyx", theme::DISPLAY, size::WORDMARK, t.fg),
container(space()).width(7).height(7).style(theme::accent_dot),
@@ -72,15 +74,16 @@ fn nav_item<'a>(t: &'static Tokens, route: Route, active: bool) -> Element<'a, M
.into()
}
/// Signed-out state; becomes the avatar, login and subscription once sign-in lands.
fn account<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
let avatar = container(line("?", theme::SEMIBOLD, size::BODY, t.muted))
fn account<'a>(t: &'static Tokens, current: Route, account: &'a Account) -> Element<'a, Message> {
let avatar = container(line(account.initial().to_string(), theme::SEMIBOLD, size::BODY, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
.center(32)
.style(move |_| iced::widget::container::Style {
background: Some(t.raised.into()),
border: iced::Border { radius: radius::PILL.into(), ..Default::default() },
..Default::default()
});
.style(theme::avatar);
let (plan, plan_colour) = if account.has_plus {
("Plus subscription", t.ok)
} else {
("No Plus: 30-second previews", t.muted)
};
let settings_active = current == Route::Settings;
column![
@@ -88,14 +91,12 @@ fn account<'a>(t: &'static Tokens, current: Route) -> Element<'a, Message> {
row![
avatar,
column![
line("Not signed in", theme::MEDIUM, 13.5, t.fg),
button(line("Sign in", theme::MEDIUM, size::SMALL, t.accent))
.padding(0)
.style(theme::tab(false))
.on_press(Message::Navigate(Route::SignIn)),
line(&account.name, theme::MEDIUM, 13.5, t.fg),
line(plan, theme::BODY, 12.0, plan_colour),
]
.spacing(1)
.width(Fill),
.width(Fill)
.clip(true),
button(icon(Icon::Settings, if settings_active { t.accent } else { t.muted }))
.padding(8)
.style(theme::icon_button(None))
+7
View File
@@ -7,6 +7,13 @@ license.workspace = true
publish.workspace = true
[dependencies]
yamuse = "0.3.2"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
[dev-dependencies]
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
[lints]
workspace = true
+207
View File
@@ -0,0 +1,207 @@
//! Yandex OAuth device flow: show a code, the user confirms it on Yandex's
//! page, poll until a token arrives.
//!
//! Uses the official Android app's public client id (via `yamuse`), because
//! third parties can't register an app for the music API.
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::{Error, Result};
/// Shown on Yandex's list of signed-in devices.
const DEVICE_NAME: &str = "Musyx";
/// Yandex rate-limits polling; faster than this turns a pending login into a rejected one.
const MIN_POLL: Duration = Duration::from_secs(3);
/// Refresh once less than this much lifetime is left.
const REFRESH_MARGIN: Duration = Duration::from_secs(7 * 24 * 3600);
/// A pending sign-in: what to show the user and what to poll with.
#[derive(Clone, PartialEq, Eq)]
pub struct DeviceCode {
pub user_code: String,
pub verification_url: String,
pub expires_in: Duration,
pub interval: Duration,
device_code: String,
}
impl std::fmt::Debug for DeviceCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DeviceCode")
.field("user_code", &self.user_code)
.field("verification_url", &self.verification_url)
.field("expires_in", &self.expires_in)
.field("interval", &self.interval)
.finish_non_exhaustive()
}
}
/// What the keychain stores. `Debug` never prints the tokens.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Credentials {
pub access_token: String,
#[serde(default)]
pub refresh_token: Option<String>,
/// Unix seconds; `None` when Yandex didn't say (pasted tokens).
#[serde(default)]
pub expires_at: Option<u64>,
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Credentials")
.field("access_token", &"<redacted>")
.field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
.field("expires_at", &self.expires_at)
.finish()
}
}
impl Credentials {
/// A token the user pasted. Its lifetime is unknown, so it is never refreshed.
pub fn from_token(token: impl Into<String>) -> Self {
Self { access_token: token.into().trim().to_owned(), refresh_token: None, expires_at: None }
}
/// True when the token expires within a week and can be refreshed.
pub fn needs_refresh(&self, now: SystemTime) -> bool {
let (Some(_), Some(expires_at)) = (&self.refresh_token, self.expires_at) else {
return false;
};
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
expires_at.saturating_sub(now) < REFRESH_MARGIN.as_secs()
}
fn from_oauth(token: yamuse::models::OAuthToken, now: SystemTime) -> Result<Self> {
let access_token = token
.access_token
.filter(|t| !t.is_empty())
.ok_or_else(|| Error::Api("token response carried no access token".into()))?;
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
Ok(Self {
access_token,
refresh_token: token.refresh_token.filter(|t| !t.is_empty()),
expires_at: token.expires_in.map(|s| now + s),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Poll {
/// The user hasn't confirmed yet. Keep polling at `DeviceCode::interval`.
Pending,
Granted(Credentials),
}
/// Talks to oauth.yandex.ru. Cheap to clone.
#[derive(Debug, Clone)]
pub struct Auth {
client: yamuse::Client,
options: yamuse::DeviceAuthOptions,
}
impl Auth {
pub fn new() -> Result<Self> {
Ok(Self {
client: yamuse::Client::anonymous()?,
options: yamuse::DeviceAuthOptions {
device_name: DEVICE_NAME.to_owned(),
..Default::default()
},
})
}
pub async fn request_code(&self) -> Result<DeviceCode> {
let code = self.client.request_device_code(&self.options).await?;
let missing = |what: &str| Error::Api(format!("device code response carried no {what}"));
Ok(DeviceCode {
device_code: code.device_code.ok_or_else(|| missing("device code"))?,
user_code: code.user_code.ok_or_else(|| missing("user code"))?,
verification_url: code
.verification_url
.unwrap_or_else(|| "https://ya.ru/device".to_owned()),
expires_in: Duration::from_secs(code.expires_in.unwrap_or(300)),
interval: Duration::from_secs(code.interval.unwrap_or(5)).max(MIN_POLL),
})
}
/// Poll once. `Pending` is the normal answer until the user confirms.
pub async fn poll(&self, code: &DeviceCode) -> Result<Poll> {
match self.client.poll_device_token(&code.device_code, &self.options).await? {
None => Ok(Poll::Pending),
Some(token) => Ok(Poll::Granted(Credentials::from_oauth(token, SystemTime::now())?)),
}
}
/// Swap a refresh token for a new pair. Store the result: Yandex rotates the refresh token.
pub async fn refresh(&self, credentials: &Credentials) -> Result<Credentials> {
let refresh = credentials
.refresh_token
.as_deref()
.ok_or_else(|| Error::Unauthorized("no refresh token".into()))?;
let token = self.client.refresh_token(refresh, &self.options).await?;
let mut fresh = Credentials::from_oauth(token, SystemTime::now())?;
// Keep the old refresh token if Yandex didn't rotate it.
if fresh.refresh_token.is_none() {
fresh.refresh_token = credentials.refresh_token.clone();
}
Ok(fresh)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(secs: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(secs)
}
#[test]
fn debug_never_prints_tokens() {
let c = Credentials {
access_token: "secret-access".into(),
refresh_token: Some("secret-refresh".into()),
expires_at: Some(10),
};
let shown = format!("{c:?}");
assert!(!shown.contains("secret"), "{shown}");
}
#[test]
fn credentials_round_trip_and_tolerate_old_shape() {
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(5) };
let json = serde_json::to_string(&c).unwrap();
assert_eq!(serde_json::from_str::<Credentials>(&json).unwrap(), c);
let bare: Credentials = serde_json::from_str(r#"{"access_token":"a"}"#).unwrap();
assert_eq!(bare, Credentials::from_token("a"));
}
#[test]
fn refresh_only_near_expiry_and_only_with_refresh_token() {
let week = 7 * 24 * 3600;
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(10 * week) };
assert!(!c.needs_refresh(at(8 * week)));
assert!(c.needs_refresh(at(9 * week + 1)));
assert!(c.needs_refresh(at(11 * week)));
let pasted = Credentials::from_token(" a \n");
assert_eq!(pasted.access_token, "a");
assert!(!pasted.needs_refresh(at(u64::MAX / 2)));
}
#[test]
fn oauth_token_converts_with_absolute_expiry() {
let token = yamuse::models::OAuthToken {
access_token: Some("a".into()),
refresh_token: Some(String::new()),
expires_in: Some(100),
token_type: Some("bearer".into()),
};
let c = Credentials::from_oauth(token, at(1_000)).unwrap();
assert_eq!(c.expires_at, Some(1_100));
assert_eq!(c.refresh_token, None);
assert!(Credentials::from_oauth(Default::default(), at(0)).is_err());
}
}
+113
View File
@@ -0,0 +1,113 @@
use crate::Result;
use crate::auth::Credentials;
/// The signed-in user as the UI needs them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Account {
pub uid: i64,
pub login: String,
/// Best human-readable name: display name, then full name, then login.
pub name: String,
/// Yandex Plus unlocks full-length tracks; without it the API serves 30-second previews.
pub has_plus: bool,
/// When the current subscription ends, as Yandex formats it (ISO 8601).
pub subscription_end: Option<String>,
}
impl Account {
/// One letter for the avatar.
pub fn initial(&self) -> char {
self.name.chars().find(|c| c.is_alphanumeric()).map_or('?', |c| {
c.to_uppercase().next().unwrap_or(c)
})
}
fn from_status(status: yamuse::models::Status) -> Option<Self> {
let account = status.account?;
let uid = account.uid?;
let login = account.login.unwrap_or_default();
let non_empty = |s: Option<String>| s.filter(|s| !s.trim().is_empty());
let name = non_empty(account.display_name)
.or_else(|| non_empty(account.full_name))
.unwrap_or_else(|| login.clone());
Some(Self {
uid,
login,
name,
has_plus: status.plus.and_then(|p| p.has_plus).unwrap_or(false),
subscription_end: status.subscription.and_then(|s| {
s.end.or_else(|| s.auto_renewable.into_iter().find_map(|a| a.expires))
}),
})
}
}
/// An authenticated API client. Cheap to clone.
#[derive(Debug, Clone)]
pub struct YmClient {
inner: yamuse::Client,
}
impl YmClient {
/// Builds a client for `credentials` and loads the account. Fails with
/// [`crate::Error::Unauthorized`] when the token is no longer valid.
pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> {
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
let status = inner.refresh_account().await?;
let account = Account::from_status(status)
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))?;
Ok((Self { inner }, account))
}
/// A client with no token, for previews and tests. Every account call fails.
pub fn unauthenticated() -> Result<Self> {
Ok(Self { inner: yamuse::Client::anonymous()? })
}
/// Re-reads the account, e.g. after a subscription may have changed.
pub async fn account(&self) -> Result<Account> {
let status = self.inner.refresh_account().await?;
Account::from_status(status)
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn status(json: &str) -> yamuse::models::Status {
serde_json::from_str(json).unwrap()
}
#[test]
fn account_prefers_display_name_and_reads_plus() {
let a = Account::from_status(status(
r#"{"account":{"uid":42,"login":"yuriy.panov","displayName":"Юрий","fullName":"Юрий Панов"},
"plus":{"hasPlus":true},"subscription":{"end":"2027-01-01T00:00:00+03:00"}}"#,
))
.unwrap();
assert_eq!(a.uid, 42);
assert_eq!(a.name, "Юрий");
assert_eq!(a.initial(), 'Ю');
assert!(a.has_plus);
assert_eq!(a.subscription_end.as_deref(), Some("2027-01-01T00:00:00+03:00"));
}
#[test]
fn account_falls_back_to_login_and_no_plus() {
let a = Account::from_status(status(
r#"{"account":{"uid":7,"login":"listener","displayName":" "}}"#,
))
.unwrap();
assert_eq!(a.name, "listener");
assert!(!a.has_plus);
assert_eq!(a.subscription_end, None);
}
#[test]
fn anonymous_status_is_not_an_account() {
assert!(Account::from_status(status(r#"{"account":{"now":"2026-10-15"}}"#)).is_none());
assert!(Account::from_status(status("{}")).is_none());
}
}
+76
View File
@@ -0,0 +1,76 @@
/// Errors the app can act on. Messages are for logs, not for display.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// The token is missing, revoked or expired. Sign in again.
#[error("unauthorized: {0}")]
Unauthorized(String),
/// The sign-in code ran out before the user confirmed it.
#[error("sign-in code expired")]
CodeExpired,
/// The user declined access on Yandex's page.
#[error("sign-in was declined")]
Denied,
/// No connection, DNS failure, timeout: worth retrying.
#[error("network: {0}")]
Network(String),
/// Anything else the server or the decoder rejected.
#[error("api: {0}")]
Api(String),
}
pub type Result<T> = std::result::Result<T, Error>;
impl Error {
pub fn is_retryable(&self) -> bool {
matches!(self, Error::Network(_))
}
}
impl From<yamuse::Error> for Error {
fn from(e: yamuse::Error) -> Self {
use yamuse::Error as Y;
match e {
Y::Unauthorized(m) => Error::Unauthorized(m),
Y::Network(m) => Error::Network(m),
Y::TimedOut => Error::Network("timed out".into()),
Y::RateLimited { message, .. } => Error::Network(message),
Y::DeviceAuth(m) => classify_oauth(&m),
other => Error::Api(other.to_string()),
}
}
}
/// OAuth rejections arrive as free text carrying the RFC 8628 error code.
fn classify_oauth(message: &str) -> Error {
let m = message.to_ascii_lowercase();
if m.contains("expired") || m.contains("timed out") {
Error::CodeExpired
} else if m.contains("denied") {
Error::Denied
} else if m.contains("invalid_grant") || m.contains("bad refresh") {
Error::Unauthorized(message.to_owned())
} else {
Error::Api(message.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn oauth_codes_map_to_actionable_errors() {
assert_eq!(classify_oauth("expired_token: code expired"), Error::CodeExpired);
assert_eq!(classify_oauth("device authorization timed out"), Error::CodeExpired);
assert_eq!(classify_oauth("access_denied"), Error::Denied);
assert!(matches!(classify_oauth("invalid_grant"), Error::Unauthorized(_)));
assert!(matches!(classify_oauth("something new"), Error::Api(_)));
}
#[test]
fn only_network_errors_retry() {
assert!(Error::Network("dns".into()).is_retryable());
assert!(!Error::Unauthorized(String::new()).is_retryable());
assert!(!Error::CodeExpired.is_retryable());
}
}
+9 -2
View File
@@ -1,4 +1,11 @@
//! Client for the unofficial Yandex Music API.
//!
//! Filled in by milestone 3 (sign-in) onwards; the app depends on this crate's
//! own types only, never on whichever upstream wrapper it uses internally.
//! Wraps [`yamuse`] so the app only ever sees this crate's own types: if the
//! upstream wrapper changes or is swapped out, the UI doesn't move.
pub mod auth;
mod client;
mod error;
pub use client::{Account, YmClient};
pub use error::{Error, Result};
+15
View File
@@ -0,0 +1,15 @@
//! Talks to the real Yandex servers. Run with `cargo test -p ym-api -- --ignored`.
use ym_api::auth::{Auth, Poll};
#[tokio::test]
#[ignore = "network"]
async fn device_code_is_issued_and_pending() {
let auth = Auth::new().unwrap();
let code = auth.request_code().await.expect("device code");
assert!(!code.user_code.is_empty());
assert!(code.verification_url.starts_with("https://"));
assert!(code.interval.as_secs() >= 3);
// Nobody confirmed it, so the first poll must say "pending", not fail.
assert_eq!(auth.poll(&code).await.expect("poll"), Poll::Pending);
}