//! 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; use crate::i18n::{tr, trf}; #[derive(Debug, Clone)] pub enum Msg { GetCode, CodeReady(Result), Tick(Instant), Polled(Result), CopyCode, OpenPage, ToggleToken, TokenChanged(String), UseToken, Cancel, } enum Stage { Idle, Requesting, Waiting(Box), } struct Waiting { code: DeviceCode, qr: Option, started: Instant, now: Instant, next_poll: Instant, polling: bool, copied_at: Option, } 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, 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), /// 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(tr("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(trf("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 { 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(tr("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( tr("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( tr("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, tr("Get sign-in code"), Some(Msg::GetCode)), ] .into(), Stage::Requesting => column![primary(t, tr("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![ // Taller line so descenders (j, g, y) aren't clipped; padding shrinks to keep the card size. container(line(spaced(&w.code.user_code), theme::DISPLAY, size::DISPLAY_S, t.fg).line_height(1.5)) .padding([11, 18]) .style(theme::card), ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("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( trf("Waiting for confirmation · code expires in {}", &[&format!("{}:{:02}", remaining / 60, remaining % 60)]), theme::BODY, 13.5, t.muted, ), space().width(12), button(line(tr("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(trf("Open {}", &[&host]), theme::MEDIUM, size::BODY, t.fg), para(tr("On this computer or your phone. You can also scan the QR code."), 13.5, t.muted), ghost(t, Icon::Globe, tr("Open in browser"), Msg::OpenPage), ].spacing(6)), step(t, 2, column![ line(tr("Enter this code"), theme::MEDIUM, size::BODY, t.fg), code_box, ].spacing(10)), step(t, 3, column![ line(tr("Come back here"), theme::MEDIUM, size::BODY, t.fg), para(tr("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 { tr("Hide token sign-in") } else { tr("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(tr("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(tr("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(), tr("Scan to open the sign-in page"), ), None => ( container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78))) .center(200) .into(), tr("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 => tr("The code expired before it was confirmed. Get a new code to try again."), Error::Denied => tr("Access was declined on Yandex's page. Get a new code if that was a mistake."), Error::Network(_) => tr("Can't reach Yandex. Check your connection and try again."), Error::Unauthorized(_) => tr("Yandex didn't accept the sign-in. Get a new code to try again."), Error::Api(_) => tr("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> { 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) -> 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")); } }