first commit

This commit is contained in:
marwy 2026-11-27 13:16:36 +03:00
commit a408df2a76
218 changed files with 52376 additions and 0 deletions

614
src/native/mod.rs Normal file
View file

@ -0,0 +1,614 @@
//! Native Windows desktop integrations matching Yandex Music Electron `index.js`:
//! 1. System Tray icon + context menu (`tray-icon`)
//! 2. Windows SMTC (System Media Transport Controls — lockscreen/volume overlay via `souvlaki`)
//! 3. Isolated zero-resident-RAM WebView2 OAuth subprocess (`--auth-webview` via `wry`)
#[derive(Debug, Clone)]
pub enum NativeEvent {
ShowWindow,
ToggleWindow,
CheckUpdates,
QuitApp,
Play,
Pause,
TogglePlay,
Next,
Prev,
Stop,
SeekMs(u64),
}
// =============================================================================
// WINDOWS IMPLEMENTATION
// =============================================================================
#[cfg(windows)]
mod imp {
use super::NativeEvent;
use crate::api::models::Track;
use crate::api::signing::extract_oauth_token;
use crate::api::YANDEX_OAUTH_URL;
use crate::covers::CoverCache;
use crossbeam_channel::{unbounded, Receiver, Sender};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use souvlaki::{
MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition,
PlatformConfig,
};
use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use std::time::Duration;
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem, Submenu};
use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::window::{Window, WindowAttributes, WindowId};
const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:";
pub struct NativeDesktop {
_tray: Option<TrayIcon>,
item_toggle_win: Option<MenuItem>,
item_play: Option<MenuItem>,
menu_toggle_win_id: Option<MenuId>,
menu_updates_id: Option<MenuId>,
menu_play_id: Option<MenuId>,
menu_prev_id: Option<MenuId>,
menu_next_id: Option<MenuId>,
menu_quit_id: Option<MenuId>,
is_ru: bool,
smtc: Option<MediaControls>,
rx_smtc: Receiver<NativeEvent>,
last_track_id: Option<String>,
last_playing: Option<bool>,
}
impl NativeDesktop {
pub fn new(window: &Window, is_ru: bool) -> Self {
// 1. Build System Tray icon + exact 5.129.0 menu matching Yandex Music Desktop!
let mut item_toggle_win_slot = None;
let mut item_play_slot = None;
let mut menu_toggle_win_id = None;
let mut menu_updates_id = None;
let mut menu_play_id = None;
let mut menu_prev_id = None;
let mut menu_next_id = None;
let mut menu_quit_id = None;
let tray = (|| -> Option<TrayIcon> {
let menu = Menu::new();
let item_toggle_win = MenuItem::new(if is_ru { "Скрыть" } else { "Hide" }, true, None);
let item_updates = MenuItem::new(
if is_ru { "Проверить обновления" } else { "Check updates" },
true,
None,
);
let item_play = MenuItem::new(if is_ru { "Играть" } else { "Play" }, true, None);
let item_prev = MenuItem::new(
if is_ru { "Предыдущий трек" } else { "Previous song" },
true,
None,
);
let item_next = MenuItem::new(
if is_ru { "Следующий трек" } else { "Next song" },
true,
None,
);
let about_sub = Submenu::new(if is_ru { "О приложении" } else { "About the app" }, true);
let about_ver = MenuItem::new(
if is_ru { "Яндекс Музыка 5.129.0" } else { "Yandex Music 5.129.0" },
false,
None,
);
let _ = about_sub.append(&about_ver);
let item_quit = MenuItem::new(
if is_ru { "Закрыть приложение" } else { "Close app" },
true,
None,
);
menu_toggle_win_id = Some(item_toggle_win.id().clone());
menu_updates_id = Some(item_updates.id().clone());
menu_play_id = Some(item_play.id().clone());
menu_prev_id = Some(item_prev.id().clone());
menu_next_id = Some(item_next.id().clone());
menu_quit_id = Some(item_quit.id().clone());
let _ = menu.append(&item_toggle_win);
let _ = menu.append(&item_updates);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&item_play);
let _ = menu.append(&item_prev);
let _ = menu.append(&item_next);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&about_sub);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&item_quit);
item_toggle_win_slot = Some(item_toggle_win);
item_play_slot = Some(item_play);
let icon = build_tray_icon()?;
TrayIconBuilder::new()
.with_menu(Box::new(menu))
.with_tooltip(if is_ru { "Яндекс Музыка" } else { "Yandex Music" })
.with_icon(icon)
.build()
.ok()
})();
// 2. Build Windows SMTC (`souvlaki::MediaControls`) bound to our Win32 HWND
let (tx_smtc, rx_smtc): (Sender<NativeEvent>, Receiver<NativeEvent>) = unbounded();
let smtc = (|| -> Option<MediaControls> {
let hwnd = match window.window_handle().ok()?.as_raw() {
RawWindowHandle::Win32(h) => h.hwnd.get() as *mut std::ffi::c_void,
_ => return None,
};
let config = PlatformConfig {
dbus_name: "yandex_music_rs",
display_name: "Яндекс Музыка",
hwnd: Some(hwnd),
};
let mut controls = MediaControls::new(config).ok()?;
controls
.attach(move |ev: MediaControlEvent| {
let mapped = match ev {
MediaControlEvent::Play => Some(NativeEvent::Play),
MediaControlEvent::Pause => Some(NativeEvent::Pause),
MediaControlEvent::Toggle => Some(NativeEvent::TogglePlay),
MediaControlEvent::Next => Some(NativeEvent::Next),
MediaControlEvent::Previous => Some(NativeEvent::Prev),
MediaControlEvent::Stop => Some(NativeEvent::Stop),
MediaControlEvent::SetPosition(MediaPosition(dur)) => {
Some(NativeEvent::SeekMs(dur.as_millis() as u64))
}
_ => None,
};
if let Some(m) = mapped {
let _ = tx_smtc.send(m);
}
})
.ok()?;
Some(controls)
})();
Self {
_tray: tray,
item_toggle_win: item_toggle_win_slot,
item_play: item_play_slot,
menu_toggle_win_id,
menu_updates_id,
menu_play_id,
menu_prev_id,
menu_next_id,
menu_quit_id,
is_ru,
smtc,
rx_smtc,
last_track_id: None,
last_playing: None,
}
}
pub fn set_window_visible_label(&self, visible: bool) {
if let Some(ref item) = self.item_toggle_win {
item.set_text(if visible {
if self.is_ru { "Скрыть" } else { "Hide" }
} else {
if self.is_ru { "Показать" } else { "Show" }
});
}
}
pub fn poll_events(&self) -> Vec<NativeEvent> {
let mut out = Vec::new();
while let Ok(ev) = self.rx_smtc.try_recv() {
out.push(ev);
}
while let Ok(ev) = TrayIconEvent::receiver().try_recv() {
match ev {
TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
}
| TrayIconEvent::DoubleClick {
button: MouseButton::Left,
..
} => {
out.push(NativeEvent::ShowWindow);
}
_ => {}
}
}
while let Ok(ev) = MenuEvent::receiver().try_recv() {
if self.menu_toggle_win_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::ToggleWindow);
} else if self.menu_updates_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::CheckUpdates);
} else if self.menu_play_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::TogglePlay);
} else if self.menu_next_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::Next);
} else if self.menu_prev_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::Prev);
} else if self.menu_quit_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::QuitApp);
}
}
out
}
pub fn sync_playback(
&mut self,
track: Option<&Track>,
is_playing: bool,
position_ms: u64,
) {
if self.last_playing != Some(is_playing) {
if let Some(ref item) = self.item_play {
item.set_text(if is_playing {
if self.is_ru { "Пауза" } else { "Pause" }
} else {
if self.is_ru { "Играть" } else { "Play" }
});
}
}
let Some(ref mut smtc) = self.smtc else {
self.last_playing = Some(is_playing);
return;
};
let track_id = track.map(|t| t.id.as_str());
if track_id != self.last_track_id.as_deref() {
self.last_track_id = track_id.map(String::from);
if let Some(tr) = track {
let artists = tr.artists_string();
let cover_url = tr
.cover_uri
.as_deref()
.map(|u| CoverCache::format_url(u, 400));
let _ = smtc.set_metadata(MediaMetadata {
title: Some(&tr.title),
artist: Some(&artists),
album: tr.album_title.as_deref(),
cover_url: cover_url.as_deref(),
duration: Some(Duration::from_millis(tr.duration_ms)),
});
} else {
let _ = smtc.set_playback(MediaPlayback::Stopped);
self.last_playing = None;
return;
}
}
if track.is_some() && self.last_playing != Some(is_playing) {
self.last_playing = Some(is_playing);
let progress = Some(MediaPosition(Duration::from_millis(position_ms)));
let state = if is_playing {
MediaPlayback::Playing { progress }
} else {
MediaPlayback::Paused { progress }
};
let _ = smtc.set_playback(state);
}
}
}
/// Exact official Yandex Music Desktop 5.129.0 32×32 tray icon (`resources/assets/icons/icon_32x32.png`)
fn build_tray_icon() -> Option<tray_icon::Icon> {
let png_bytes = include_bytes!("../../assets/icons/tray_32.png");
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
let (w, h) = img.dimensions();
tray_icon::Icon::from_rgba(img.into_raw(), w, h).ok()
}
/// Exact official Yandex Music Desktop 5.129.0 48×48 window/taskbar icon (`resources/assets/icons/icon_48x48.png`)
pub fn load_window_icon() -> Option<winit::window::Icon> {
let png_bytes = include_bytes!("../../assets/icons/app_48.png");
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
let (w, h) = img.dimensions();
winit::window::Icon::from_rgba(img.into_raw(), w, h).ok()
}
// =========================================================================
// ISOLATED ZERO-RESIDENT-RAM WEBVIEW2 OAUTH SUBPROCESS (`--auth-webview`)
// =========================================================================
struct AuthWebViewApp {
window: Option<Window>,
_webview: Option<wry::WebView>,
}
impl ApplicationHandler for AuthWebViewApp {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let attrs = WindowAttributes::default()
.with_title("Вход — Яндекс ID")
.with_inner_size(LogicalSize::new(480.0, 680.0))
.with_resizable(true);
let window = match event_loop.create_window(attrs) {
Ok(w) => w,
Err(_) => {
event_loop.exit();
return;
}
};
let emit_and_exit = |url: &str| -> bool {
if url.contains("access_token=") {
if let Some(tok) = extract_oauth_token(url) {
println!("{}{}", OAUTH_TOKEN_PREFIX, tok);
let _ = std::io::stdout().flush();
std::process::exit(0);
}
}
true
};
// Watch both full navigations AND hash/fragment updates (`#access_token=...`)
let init_js = r#"
(function() {
function check() {
try {
var h = window.location.href || '';
if (h.indexOf('access_token=') !== -1) {
window.ipc.postMessage(h);
}
} catch (e) {}
}
check();
window.addEventListener('hashchange', check);
setInterval(check, 250);
})();
"#;
let webview = wry::WebViewBuilder::new()
.with_url(YANDEX_OAUTH_URL)
.with_initialization_script(init_js)
.with_navigation_handler(move |url| emit_and_exit(&url))
.with_ipc_handler(move |req| {
let _ = emit_and_exit(req.body());
})
.build(&window);
match webview {
Ok(wv) => {
self.window = Some(window);
self._webview = Some(wv);
}
Err(e) => {
eprintln!("WebView2 init failed: {}", e);
std::process::exit(2);
}
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_id: WindowId,
event: WindowEvent,
) {
if matches!(event, WindowEvent::CloseRequested) {
event_loop.exit();
}
}
}
/// Entry point for the short-lived `--auth-webview` subprocess.
/// Exits immediately upon capturing the OAuth token — 0 bytes of WebView2 stay in main app RAM!
pub fn run_auth_webview_subprocess() {
let event_loop = match EventLoop::new() {
Ok(el) => el,
Err(_) => std::process::exit(1),
};
let mut app = AuthWebViewApp {
window: None,
_webview: None,
};
let _ = event_loop.run_app(&mut app);
}
/// Spawn the isolated `--auth-webview` subprocess and return the captured OAuth token.
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
let exe = std::env::current_exe()?;
let mut child = Command::new(exe)
.arg("--auth-webview")
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("Missing auth subprocess stdout"))?;
let reader = BufReader::new(stdout);
for line in reader.lines() {
if let Ok(l) = line {
if let Some(tok) = l.strip_prefix(OAUTH_TOKEN_PREFIX) {
let _ = child.wait();
return Ok(tok.trim().to_string());
}
}
}
let status = child.wait()?;
if status.code() == Some(2) {
anyhow::bail!("WebView2 runtime unavailable")
}
anyhow::bail!("Окно входа закрыто")
}
}
#[cfg(target_os = "linux")]
mod imp {
use super::NativeEvent;
use crate::api::models::Track;
use crate::api::signing::extract_oauth_token;
use crate::api::YANDEX_OAUTH_URL;
use gtk::prelude::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
use winit::window::Window;
use wry::{WebViewBuilder, WebViewBuilderExtUnix};
const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:";
pub struct NativeDesktop;
impl NativeDesktop {
pub fn new(_window: &Window, _is_ru: bool) -> Self {
Self
}
pub fn set_window_visible_label(&self, _visible: bool) {}
pub fn poll_events(&self) -> Vec<NativeEvent> {
Vec::new()
}
pub fn sync_playback(&mut self, _track: Option<&Track>, _is_playing: bool, _pos_ms: u64) {}
}
pub fn load_window_icon() -> Option<winit::window::Icon> {
let png_bytes = include_bytes!("../../assets/icons/app_icon.png");
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
let (w, h) = img.dimensions();
winit::window::Icon::from_rgba(img.into_raw(), w, h).ok()
}
/// Entry point for the short-lived `--auth-webview` subprocess on Linux (GTK3 + WebKitGTK).
pub fn run_auth_webview_subprocess() {
// Avoid blank WebKitGTK window on NVIDIA/Wayland/VM drivers during OAuth login.
if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
if gtk::init().is_err() {
eprintln!("GTK init failed");
std::process::exit(2);
}
gtk::glib::set_prgname(Some("yandex-music-rs"));
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.set_title("Вход — Яндекс ID");
window.set_icon_name(Some("yandex-music-rs"));
window.set_default_size(480, 680);
window.set_resizable(true);
window.connect_delete_event(|_, _| {
gtk::main_quit();
gtk::glib::Propagation::Proceed
});
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
window.add(&vbox);
let emit_and_exit = |url: &str| -> bool {
if url.contains("access_token=") {
if let Some(tok) = extract_oauth_token(url) {
println!("{}{}", OAUTH_TOKEN_PREFIX, tok);
let _ = std::io::stdout().flush();
std::process::exit(0);
}
}
true
};
let init_js = r#"
(function() {
function check() {
try {
var h = window.location.href || '';
if (h.indexOf('access_token=') !== -1) {
window.ipc.postMessage(h);
}
} catch (e) {}
}
check();
window.addEventListener('hashchange', check);
setInterval(check, 250);
})();
"#;
let webview = WebViewBuilder::new()
.with_url(YANDEX_OAUTH_URL)
.with_initialization_script(init_js)
.with_navigation_handler(move |url| emit_and_exit(&url))
.with_ipc_handler(move |req| {
let _ = emit_and_exit(req.body());
})
.build_gtk(&vbox);
let _webview = match webview {
Ok(wv) => wv,
Err(e) => {
eprintln!("WebKitGTK init failed: {}", e);
std::process::exit(2);
}
};
window.show_all();
gtk::main();
}
/// Spawn the isolated `--auth-webview` subprocess and return the captured OAuth token.
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
let exe = std::env::current_exe()?;
let mut child = Command::new(exe)
.arg("--auth-webview")
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("Missing auth subprocess stdout"))?;
let reader = BufReader::new(stdout);
for line in reader.lines() {
if let Ok(l) = line {
if let Some(tok) = l.strip_prefix(OAUTH_TOKEN_PREFIX) {
let _ = child.wait();
return Ok(tok.trim().to_string());
}
}
}
let status = child.wait()?;
if status.code() == Some(2) {
anyhow::bail!("WebKitGTK runtime unavailable")
}
anyhow::bail!("Окно входа закрыто")
}
}
#[cfg(not(any(windows, target_os = "linux")))]
mod imp {
use super::NativeEvent;
use crate::api::models::Track;
use winit::window::Window;
pub struct NativeDesktop;
impl NativeDesktop {
pub fn new(_window: &Window, _is_ru: bool) -> Self {
Self
}
pub fn set_window_visible_label(&self, _visible: bool) {}
pub fn poll_events(&self) -> Vec<NativeEvent> {
Vec::new()
}
pub fn sync_playback(&mut self, _track: Option<&Track>, _is_playing: bool, _pos_ms: u64) {}
}
pub fn load_window_icon() -> Option<winit::window::Icon> {
None
}
pub fn run_auth_webview_subprocess() {}
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
anyhow::bail!("WebView2 auth is only available on Windows")
}
}
pub use imp::{load_window_icon, run_auth_webview_subprocess, spawn_auth_webview_subprocess, NativeDesktop};