chore(release): v2.0.0

This commit is contained in:
marwy 2026-11-29 02:28:03 +03:00
parent a6f33284a7
commit 7fbf34ff2e
81 changed files with 16727 additions and 3280 deletions

431
packaging/windows/installer/Cargo.lock generated Normal file
View file

@ -0,0 +1,431 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"moxcms",
"num-traits",
"png",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "toml"
version = "1.2.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "windows"
version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-link",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "winresource"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml",
"version_check",
]
[[package]]
name = "yandex-music-rs-setup"
version = "0.1.9"
dependencies = [
"flate2",
"image",
"windows",
"windows-numerics",
"winresource",
]
[[package]]
name = "zlib-rs"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"

View file

@ -0,0 +1,50 @@
[package]
name = "yandex-music-rs-setup"
version = "2.0.0"
edition = "2021"
description = "Pure native Win32 + Direct2D Yandex Music desktop client installer"
[[bin]]
name = "yandex-music-rs-setup"
path = "src/main.rs"
[dependencies]
flate2 = "1"
image = { version = "0.25", default-features = false, features = ["png"] }
[target.'cfg(windows)'.dependencies]
windows-numerics = "0.2"
windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Graphics_Direct2D",
"Win32_Graphics_Direct2D_Common",
"Win32_Graphics_DirectWrite",
"Win32_Graphics_Dwm",
"Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_Variant",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
"Win32_UI_Shell_PropertiesSystem",
"Win32_UI_WindowsAndMessaging",
] }
[build-dependencies]
flate2 = "1"
[target.'cfg(windows)'.build-dependencies]
winresource = "0.1"
[profile.release]
opt-level = "z"
lto = "thin"
codegen-units = 1
strip = true
panic = "abort"

View file

@ -0,0 +1,100 @@
use flate2::write::GzEncoder;
use flate2::Compression;
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
fn read_root_version(root_cargo_toml: &Path) -> String {
if let Ok(text) = fs::read_to_string(root_cargo_toml) {
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("version") {
if let Some(val) = rest.trim().strip_prefix('=') {
let v = val.trim().trim_matches('"').trim_matches('\'');
if !v.is_empty() {
return v.to_string();
}
}
}
}
}
env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.1.9".to_string())
}
fn main() {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let repo_root = manifest_dir
.parent()
.and_then(|p| p.parent())
.and_then(|p| p.parent())
.expect("installer must live under packaging/windows/installer");
let root_cargo = repo_root.join("Cargo.toml");
println!("cargo:rerun-if-changed={}", root_cargo.display());
println!("cargo:rerun-if-env-changed=YM_PAYLOAD_EXE");
println!("cargo:rerun-if-env-changed=YM_ALLOW_EMPTY_PAYLOAD");
let app_version = read_root_version(&root_cargo);
println!("cargo:rustc-env=YM_APP_VERSION={}", app_version);
let payload_src = env::var("YM_PAYLOAD_EXE")
.map(PathBuf::from)
.unwrap_or_else(|_| repo_root.join("target").join("release").join("yandex-music-rs.exe"));
println!("cargo:rerun-if-changed={}", payload_src.display());
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let payload_gz = out_dir.join("payload.gz");
let raw_bytes = if payload_src.exists() {
fs::read(&payload_src).unwrap_or_else(|e| {
panic!(
"Failed to read app binary {}: {}",
payload_src.display(),
e
)
})
} else if env::var("YM_ALLOW_EMPTY_PAYLOAD").as_deref() == Ok("1") {
println!(
"cargo:warning=Using empty placeholder payload because {} does not exist",
payload_src.display()
);
Vec::new()
} else {
panic!(
"App binary not found at {}. Run `cargo build --release` in repo root first (or set YM_PAYLOAD_EXE).",
payload_src.display()
);
};
let uncompressed_kb = ((raw_bytes.len() as u64) + 1023) / 1024;
println!("cargo:rustc-env=YM_PAYLOAD_KB={}", uncompressed_kb.max(1));
let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder
.write_all(&raw_bytes)
.expect("Failed to compress payload");
let compressed = encoder.finish().expect("Failed to finish gzip stream");
fs::write(&payload_gz, compressed).expect("Failed to write payload.gz");
#[cfg(target_os = "windows")]
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let ico = repo_root
.join("packaging")
.join("icons")
.join("yandex-music-rs.ico");
println!("cargo:rerun-if-changed={}", ico.display());
if ico.exists() {
let mut res = winresource::WindowsResource::new();
res.set_icon(ico.to_string_lossy().as_ref());
res.set("ProductName", "Яндекс Музыка — Установщик");
res.set("FileDescription", "Yandex Music Desktop Client Installer");
res.set("CompanyName", "marwy");
res.set("ProductVersion", &app_version);
res.set("FileVersion", &app_version);
if let Err(e) = res.compile() {
println!("cargo:warning=winresource failed: {}", e);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,622 @@
#![cfg(windows)]
use flate2::read::GzDecoder;
use std::fs;
use std::io::Read;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::Duration;
use windows::core::{Interface, GUID, HSTRING, PCWSTR, PWSTR};
use windows::Win32::Foundation::{HWND, PROPERTYKEY};
use windows::Win32::Graphics::Dwm::{
DwmSetWindowAttribute, DWMWA_USE_IMMERSIVE_DARK_MODE, DWMWA_WINDOW_CORNER_PREFERENCE,
DWMWCP_ROUND,
};
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, IPersistFile,
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED,
};
use windows::Win32::System::Registry::{
RegCloseKey, RegCreateKeyExW, RegDeleteTreeW, RegDeleteValueW, RegOpenKeyExW,
RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_DWORD,
REG_OPTION_NON_VOLATILE, REG_SZ,
};
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
use windows::Win32::UI::Shell::{
FOLDERID_Desktop, FOLDERID_Programs, FileOpenDialog, IFileOpenDialog, IShellLinkW,
SHGetKnownFolderPath, ShellLink, FOS_FORCEFILESYSTEM, FOS_PICKFOLDERS, KF_FLAG_DEFAULT,
SIGDN_FILESYSPATH,
};
pub const APP_VERSION: &str = env!("YM_APP_VERSION");
const PAYLOAD_GZ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/payload.gz"));
const UNINSTALL_REG_SUBKEY: &str =
r"Software\Microsoft\Windows\CurrentVersion\Uninstall\YandexMusicRs";
const RUN_REG_SUBKEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE_NAME: &str = "YandexMusicRs";
const APP_EXE_NAME: &str = "yandex-music-rs.exe";
const UNINSTALL_EXE_NAME: &str = "uninstall.exe";
const SHORTCUT_NAME: &str = "Яндекс Музыка.lnk";
const APP_USER_MODEL_ID: &str = "ru.marwy.yandex-music-rs";
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// PKEY_AppUserModel_ID = {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 5
const PKEY_APP_USER_MODEL_ID: PROPERTYKEY = PROPERTYKEY {
fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3),
pid: 5,
};
#[derive(Debug, Clone)]
pub struct ExistingInstall {
pub installed: bool,
pub installed_version: Option<String>,
pub install_dir: String,
pub target_version: String,
pub has_desktop_shortcut: bool,
pub has_start_menu_shortcut: bool,
pub has_autostart: bool,
pub mode: String, // "install" | "update" | "reinstall" | "uninstall"
}
#[derive(Debug, Clone)]
pub struct InstallOptions {
pub install_dir: String,
pub desktop_shortcut: bool,
pub start_menu_shortcut: bool,
pub autostart: bool,
pub launch_after: bool,
}
#[derive(Debug, Clone)]
pub struct UninstallOptions {
pub remove_user_data: bool,
}
struct ComGuard;
impl ComGuard {
fn init() -> Self {
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
}
Self
}
}
impl Drop for ComGuard {
fn drop(&mut self) {
unsafe {
CoUninitialize();
}
}
}
fn wide_null(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
pub fn apply_window_chrome(hwnd: isize) {
let hwnd = HWND(hwnd as *mut _);
unsafe {
let dark: i32 = 1;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_USE_IMMERSIVE_DARK_MODE,
&dark as *const _ as *const _,
std::mem::size_of::<i32>() as u32,
);
let corner = DWMWCP_ROUND;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_WINDOW_CORNER_PREFERENCE,
&corner as *const _ as *const _,
std::mem::size_of_val(&corner) as u32,
);
}
}
pub fn default_install_dir() -> PathBuf {
if let Ok(local) = std::env::var("LOCALAPPDATA") {
PathBuf::from(local).join("Programs").join("YandexMusicRs")
} else if let Ok(profile) = std::env::var("USERPROFILE") {
PathBuf::from(profile)
.join("AppData")
.join("Local")
.join("Programs")
.join("YandexMusicRs")
} else {
PathBuf::from(r"C:\YandexMusicRs")
}
}
fn known_folder_path(folder_id: &GUID) -> Option<PathBuf> {
unsafe {
let ptr: PWSTR = SHGetKnownFolderPath(folder_id, KF_FLAG_DEFAULT, None).ok()?;
let s = ptr.to_string().ok();
CoTaskMemFree(Some(ptr.0 as *const _));
s.map(PathBuf::from)
}
}
fn desktop_shortcut_path() -> Option<PathBuf> {
known_folder_path(&FOLDERID_Desktop).map(|d| d.join(SHORTCUT_NAME))
}
fn start_menu_shortcut_path() -> Option<PathBuf> {
known_folder_path(&FOLDERID_Programs).map(|p| p.join(SHORTCUT_NAME))
}
fn reg_read_string(subkey: &str, value_name: &str) -> Option<String> {
let subkey_w = wide_null(subkey);
let value_w = wide_null(value_name);
unsafe {
let mut hkey = HKEY::default();
if RegOpenKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
KEY_READ,
&mut hkey,
)
.is_err()
{
return None;
}
let mut size: u32 = 0;
let query_len = RegQueryValueExW(
hkey,
PCWSTR(value_w.as_ptr()),
None,
None,
None,
Some(&mut size),
);
if query_len.is_err() || size < 2 {
let _ = RegCloseKey(hkey);
return None;
}
let mut buf: Vec<u16> = vec![0u16; (size as usize + 1) / 2];
let query_val = RegQueryValueExW(
hkey,
PCWSTR(value_w.as_ptr()),
None,
None,
Some(buf.as_mut_ptr() as *mut u8),
Some(&mut size),
);
let _ = RegCloseKey(hkey);
if query_val.is_err() {
return None;
}
let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
Some(String::from_utf16_lossy(&buf[..end]))
}
}
fn reg_write_sz(hkey: HKEY, name: &str, value: &str) -> Result<(), String> {
let name_w = wide_null(name);
let val_w = wide_null(value);
let bytes =
unsafe { std::slice::from_raw_parts(val_w.as_ptr() as *const u8, val_w.len() * 2) };
unsafe {
RegSetValueExW(hkey, PCWSTR(name_w.as_ptr()), Some(0), REG_SZ, Some(bytes))
.ok()
.map_err(|e| format!("RegSetValueExW({name}): {e}"))
}
}
fn reg_write_dword(hkey: HKEY, name: &str, value: u32) -> Result<(), String> {
let name_w = wide_null(name);
let bytes = value.to_le_bytes();
unsafe {
RegSetValueExW(
hkey,
PCWSTR(name_w.as_ptr()),
Some(0),
REG_DWORD,
Some(&bytes),
)
.ok()
.map_err(|e| format!("RegSetValueExW({name}): {e}"))
}
}
pub fn detect_existing_install(uninstall_flag: bool) -> ExistingInstall {
let default_dir = default_install_dir();
let reg_dir = reg_read_string(UNINSTALL_REG_SUBKEY, "InstallLocation");
let reg_ver = reg_read_string(UNINSTALL_REG_SUBKEY, "DisplayVersion");
let candidate_dir = reg_dir
.as_deref()
.map(PathBuf::from)
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| default_dir.clone());
let exe_exists = candidate_dir.join(APP_EXE_NAME).exists();
let installed = exe_exists || reg_ver.is_some();
let has_desktop = desktop_shortcut_path().map_or(false, |p| p.exists());
let has_start = start_menu_shortcut_path().map_or(false, |p| p.exists());
let has_autostart = reg_read_string(RUN_REG_SUBKEY, RUN_VALUE_NAME).is_some();
let mode = if uninstall_flag {
"uninstall".to_string()
} else if !installed {
"install".to_string()
} else if reg_ver.as_deref() == Some(APP_VERSION) {
"reinstall".to_string()
} else {
"update".to_string()
};
ExistingInstall {
installed,
installed_version: reg_ver,
install_dir: candidate_dir.to_string_lossy().to_string(),
target_version: APP_VERSION.to_string(),
has_desktop_shortcut: if installed { has_desktop } else { true },
has_start_menu_shortcut: if installed { has_start } else { true },
has_autostart,
mode,
}
}
pub fn pick_folder_dialog(initial: Option<&str>) -> Option<String> {
let _com = ComGuard::init();
unsafe {
let dialog: IFileOpenDialog =
CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?;
let mut opts = dialog.GetOptions().ok()?;
opts |= FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM;
dialog.SetOptions(opts).ok()?;
let _ = dialog.SetTitle(&HSTRING::from("Выберите папку установки"));
let _ = initial; // keep dialog clean even if folder does not exist yet
if dialog.Show(None).is_err() {
return None;
}
let item = dialog.GetResult().ok()?;
let path_pwstr = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
let result = path_pwstr.to_string().ok();
CoTaskMemFree(Some(path_pwstr.0 as *const _));
result
}
}
fn close_running_app() {
let _ = Command::new("taskkill")
.args(["/IM", APP_EXE_NAME])
.creation_flags(CREATE_NO_WINDOW)
.output();
// Give graceful close up to 1.5s, then force-close if still alive
for _ in 0..6 {
thread::sleep(Duration::from_millis(250));
let out = Command::new("tasklist")
.args(["/FI", &format!("IMAGENAME eq {}", APP_EXE_NAME), "/NH"])
.creation_flags(CREATE_NO_WINDOW)
.output();
if let Ok(o) = out {
let stdout = String::from_utf8_lossy(&o.stdout);
if !stdout
.to_ascii_lowercase()
.contains(&APP_EXE_NAME.to_ascii_lowercase())
{
return;
}
}
}
let _ = Command::new("taskkill")
.args(["/F", "/IM", APP_EXE_NAME])
.creation_flags(CREATE_NO_WINDOW)
.output();
thread::sleep(Duration::from_millis(350));
}
fn create_shortcut(
lnk_path: &Path,
target_exe: &Path,
working_dir: &Path,
description: &str,
) -> Result<(), String> {
let _com = ComGuard::init();
if let Some(parent) = lnk_path.parent() {
let _ = fs::create_dir_all(parent);
}
unsafe {
let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)
.map_err(|e| format!("CoCreateInstance(ShellLink): {e}"))?;
let target_w = wide_null(&target_exe.to_string_lossy());
let work_w = wide_null(&working_dir.to_string_lossy());
let desc_w = wide_null(description);
link.SetPath(PCWSTR(target_w.as_ptr()))
.map_err(|e| format!("SetPath: {e}"))?;
link.SetWorkingDirectory(PCWSTR(work_w.as_ptr()))
.map_err(|e| format!("SetWorkingDirectory: {e}"))?;
link.SetIconLocation(PCWSTR(target_w.as_ptr()), 0)
.map_err(|e| format!("SetIconLocation: {e}"))?;
link.SetDescription(PCWSTR(desc_w.as_ptr()))
.map_err(|e| format!("SetDescription: {e}"))?;
if let Ok(store) = link.cast::<IPropertyStore>() {
let val = PROPVARIANT::from(APP_USER_MODEL_ID);
let _ = store.SetValue(&PKEY_APP_USER_MODEL_ID, &val);
let _ = store.Commit();
}
let persist: IPersistFile = link
.cast()
.map_err(|e| format!("cast IPersistFile: {e}"))?;
let lnk_w = wide_null(&lnk_path.to_string_lossy());
persist
.Save(PCWSTR(lnk_w.as_ptr()), true)
.map_err(|e| format!("IPersistFile::Save: {e}"))?;
}
Ok(())
}
fn set_autostart(exe_path: Option<&Path>) -> Result<(), String> {
let subkey_w = wide_null(RUN_REG_SUBKEY);
let val_name_w = wide_null(RUN_VALUE_NAME);
unsafe {
let mut hkey = HKEY::default();
RegCreateKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
PCWSTR::null(),
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
None,
&mut hkey,
None,
)
.ok()
.map_err(|e| format!("RegCreateKeyExW(Run): {e}"))?;
let res = match exe_path {
Some(path) => reg_write_sz(hkey, RUN_VALUE_NAME, &format!("\"{}\"", path.display())),
None => {
let _ = RegDeleteValueW(hkey, PCWSTR(val_name_w.as_ptr()));
Ok(())
}
};
let _ = RegCloseKey(hkey);
res
}
}
fn write_uninstall_registry(
install_dir: &Path,
exe_path: &Path,
uninstall_exe: &Path,
size_kb: u32,
) -> Result<(), String> {
let subkey_w = wide_null(UNINSTALL_REG_SUBKEY);
unsafe {
let mut hkey = HKEY::default();
RegCreateKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
PCWSTR::null(),
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
None,
&mut hkey,
None,
)
.ok()
.map_err(|e| format!("RegCreateKeyExW(Uninstall): {e}"))?;
let res = (|| {
reg_write_sz(hkey, "DisplayName", "Яндекс Музыка (yandex-music-rs)")?;
reg_write_sz(hkey, "DisplayVersion", APP_VERSION)?;
reg_write_sz(hkey, "Publisher", "marwy")?;
reg_write_sz(hkey, "DisplayIcon", &format!("{},0", exe_path.display()))?;
reg_write_sz(hkey, "InstallLocation", &install_dir.to_string_lossy())?;
reg_write_sz(
hkey,
"UninstallString",
&format!("\"{}\" --uninstall", uninstall_exe.display()),
)?;
reg_write_sz(
hkey,
"URLInfoAbout",
"https://git.tatar/marwy/yandex-music-rs",
)?;
reg_write_dword(hkey, "EstimatedSize", size_kb)?;
reg_write_dword(hkey, "NoModify", 1)?;
reg_write_dword(hkey, "NoRepair", 1)?;
Ok(())
})();
let _ = RegCloseKey(hkey);
res
}
}
fn delete_uninstall_registry() {
let subkey_w = wide_null(UNINSTALL_REG_SUBKEY);
unsafe {
let _ = RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr()));
}
}
pub fn install_or_update<F>(opts: &InstallOptions, mut on_progress: F) -> Result<PathBuf, String>
where
F: FnMut(u8, &str),
{
let install_dir = PathBuf::from(opts.install_dir.trim());
if install_dir.as_os_str().is_empty() {
return Err("Не указана папка установки".into());
}
on_progress(10, "step_closing");
close_running_app();
on_progress(25, "step_preparing");
fs::create_dir_all(&install_dir)
.map_err(|e| format!("Не удалось создать папку {}: {}", install_dir.display(), e))?;
on_progress(45, "step_extracting");
let mut decoder = GzDecoder::new(PAYLOAD_GZ);
let mut exe_bytes = Vec::new();
decoder
.read_to_end(&mut exe_bytes)
.map_err(|e| format!("Ошибка распаковки приложения: {}", e))?;
if exe_bytes.is_empty() {
return Err("В установщик не встроен бинарник yandex-music-rs.exe".into());
}
let target_exe = install_dir.join(APP_EXE_NAME);
let temp_exe = install_dir.join("yandex-music-rs.exe.tmp");
fs::write(&temp_exe, &exe_bytes)
.map_err(|e| format!("Не удалось записать файл {}: {}", temp_exe.display(), e))?;
if let Err(e) = fs::rename(&temp_exe, &target_exe) {
// Retry once after brief wait if antivirus/handle was holding target
thread::sleep(Duration::from_millis(400));
if let Err(_) = fs::remove_file(&target_exe) {}
fs::rename(&temp_exe, &target_exe).map_err(|e2| {
let _ = fs::remove_file(&temp_exe);
format!("Не удалось заменить {}: {} ({})", target_exe.display(), e2, e)
})?;
}
on_progress(68, "step_uninstaller");
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
if let Ok(self_exe) = std::env::current_exe() {
let same_file = self_exe
.canonicalize()
.ok()
.zip(uninstall_exe.canonicalize().ok())
.map_or(false, |(a, b)| a == b);
if !same_file {
let _ = fs::copy(&self_exe, &uninstall_exe);
}
}
on_progress(82, "step_shortcuts");
if let Some(desk_lnk) = desktop_shortcut_path() {
if opts.desktop_shortcut {
create_shortcut(
&desk_lnk,
&target_exe,
&install_dir,
"Яндекс Музыка (yandex-music-rs)",
)?;
} else if desk_lnk.exists() {
let _ = fs::remove_file(desk_lnk);
}
}
if let Some(start_lnk) = start_menu_shortcut_path() {
if opts.start_menu_shortcut {
create_shortcut(
&start_lnk,
&target_exe,
&install_dir,
"Яндекс Музыка (yandex-music-rs)",
)?;
} else if start_lnk.exists() {
let _ = fs::remove_file(start_lnk);
}
}
on_progress(92, "step_registry");
let size_kb = (((exe_bytes.len() as u64) + 1023) / 1024).max(1) as u32;
write_uninstall_registry(&install_dir, &target_exe, &uninstall_exe, size_kb)?;
set_autostart(if opts.autostart {
Some(&target_exe)
} else {
None
})?;
on_progress(100, "step_done");
Ok(target_exe)
}
pub fn uninstall_app<F>(
install_dir_str: &str,
opts: &UninstallOptions,
mut on_progress: F,
) -> Result<bool, String>
where
F: FnMut(u8, &str),
{
let install_dir = PathBuf::from(install_dir_str.trim());
on_progress(15, "step_closing");
close_running_app();
on_progress(40, "step_removing_files");
let app_exe = install_dir.join(APP_EXE_NAME);
if app_exe.exists() {
let _ = fs::remove_file(&app_exe);
}
on_progress(60, "step_removing_shortcuts");
if let Some(desk_lnk) = desktop_shortcut_path() {
let _ = fs::remove_file(desk_lnk);
}
if let Some(start_lnk) = start_menu_shortcut_path() {
let _ = fs::remove_file(start_lnk);
}
on_progress(75, "step_removing_registry");
let _ = set_autostart(None);
delete_uninstall_registry();
if opts.remove_user_data {
on_progress(88, "step_removing_data");
if let Ok(appdata) = std::env::var("APPDATA") {
let _ = fs::remove_dir_all(PathBuf::from(appdata).join("YandexMusicRust"));
}
if let Ok(local) = std::env::var("LOCALAPPDATA") {
let _ = fs::remove_dir_all(PathBuf::from(local).join("YandexMusicRust"));
}
}
// Check whether we are currently running as `<install_dir>\uninstall.exe`
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
let running_from_install_dir = std::env::current_exe()
.ok()
.and_then(|p| p.canonicalize().ok())
.zip(uninstall_exe.canonicalize().ok())
.map_or(false, |(a, b)| a == b);
if !running_from_install_dir {
let _ = fs::remove_file(&uninstall_exe);
let _ = fs::remove_dir(&install_dir);
}
on_progress(100, "step_uninstalled");
Ok(running_from_install_dir)
}
pub fn schedule_self_cleanup(install_dir_str: &str) {
let install_dir = PathBuf::from(install_dir_str.trim());
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
let cmd = format!(
"ping 127.0.0.1 -n 3 >NUL & del /F /Q \"{}\" >NUL 2>&1 & rmdir \"{}\" >NUL 2>&1",
uninstall_exe.display(),
install_dir.display()
);
let _ = Command::new("cmd.exe")
.args(["/C", &cmd])
.creation_flags(CREATE_NO_WINDOW)
.spawn();
}
pub fn launch_app(exe_path: &Path) -> Result<(), String> {
let mut cmd = Command::new(exe_path);
if let Some(dir) = exe_path.parent() {
cmd.current_dir(dir);
}
cmd.spawn()
.map(|_| ())
.map_err(|e| format!("Не удалось запустить приложение: {}", e))
}