feat: add a controller-driven Subsonic player for SteamOS
Browses a Subsonic library and plays it through mpv, driven by a gamepad or keyboard. The UI scales from the window's physical height rather than the compositor's scale factor, so it keeps its proportions on a Steam Deck and on a 4K TV, where other players open small or scale badly.
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
Generated
+6782
File diff suppressed because it is too large
Load Diff
+25
@@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "remus"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.104"
|
||||||
|
directories = "6.0.0"
|
||||||
|
env_logger = "0.11.11"
|
||||||
|
fontique = { version = "0.11", default-features = false, features = ["fontconfig-dlopen"] }
|
||||||
|
gilrs = "0.11.2"
|
||||||
|
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||||
|
libc = "0.2.191"
|
||||||
|
log = "0.4.35"
|
||||||
|
lru = "0.19.0"
|
||||||
|
md5 = "0.8.1"
|
||||||
|
reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] }
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
serde_json = "1.0.154"
|
||||||
|
slint = "1.18.1"
|
||||||
|
tokio = { version = "1.54.1", features = ["rt-multi-thread", "sync", "macros", "time"] }
|
||||||
|
toml = "1.1.8"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
slint-build = "1.18.1"
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# remus
|
||||||
|
|
||||||
|
A controller-first music player for a Subsonic library, built for SteamOS on a Steam Deck or a TV.
|
||||||
|
|
||||||
|
It opens fullscreen. Its UI is sized from the window's physical height, not from the scale factor the compositor reports, so it keeps the same proportions at 1280×800 and at 4K. Cover art is requested at the size it is drawn.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- `mpv` on the PATH. remus runs it as a child process and controls it over its JSON IPC socket.
|
||||||
|
- A Subsonic or OpenSubsonic server (Navidrome, Gonic, Airsonic...).
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo run --release # fullscreen
|
||||||
|
cargo run --release -- --windowed
|
||||||
|
```
|
||||||
|
|
||||||
|
On first start remus asks for the server address, username and password. It stores the address, the username and an auth token (md5 of password + salt) in `~/.config/remus/config.toml`, mode 0600. The token is enough to log in to that server, so treat the file as a credential. Delete it to log in again.
|
||||||
|
|
||||||
|
Covers are cached in `~/.cache/remus/covers`.
|
||||||
|
|
||||||
|
## Controls
|
||||||
|
|
||||||
|
| Gamepad | Keyboard | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| D-pad / left stick | Arrows | Move |
|
||||||
|
| A | Enter | Open, play |
|
||||||
|
| B | Esc, Backspace | Back |
|
||||||
|
| X | Space | Play / pause |
|
||||||
|
| Y | Q | Add album, playlist or track to the queue |
|
||||||
|
| LB / RB | P / N | Previous / next track |
|
||||||
|
| LT / RT | Shift+Tab / Tab | Previous / next section |
|
||||||
|
| Right stick | , / . | Seek 10 s |
|
||||||
|
| Menu | F | Now playing |
|
||||||
|
| View | / | Search |
|
||||||
|
| | F11 | Toggle fullscreen |
|
||||||
|
| | Ctrl+Q | Quit |
|
||||||
|
|
||||||
|
With Steam running, remus listens only to Steam's virtual controller, so a pad Steam also exposes does not send every press twice. On a Deck, Steam + X opens the on-screen keyboard for the login and search fields.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo test
|
||||||
|
REMUS_TEST_URL=https://demo.navidrome.org REMUS_TEST_USER=demo REMUS_TEST_PASS=demo \
|
||||||
|
cargo test -- --ignored # every API call against a real server
|
||||||
|
```
|
||||||
|
|
||||||
|
`REMUS_DEV_SCRIPT` replays actions and saves screenshots, which is how layouts are checked at different sizes without a controller:
|
||||||
|
|
||||||
|
```
|
||||||
|
REMUS_DEV_SCRIPT="size:full,wait:3000,shot:home.png,right,activate,wait:2000,shot:album.png,quit" cargo run
|
||||||
|
```
|
||||||
|
|
||||||
|
Steps: `size:WxH`, `size:full`, `wait:MS`, `shot:PATH`, and action names (`up`, `down`, `left`, `right`, `activate`, `back`, `queue`, `next`, `play-pause`, `section-next`, `now-playing`, `search`, `quit`). Point `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` at a scratch directory to keep test runs away from your own config.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
slint_build::compile("ui/app.slint").expect("compiling ui/app.slint");
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
max_width = 120
|
||||||
+1785
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use directories::ProjectDirs;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Server credentials. `token` is md5(password + salt): not the password,
|
||||||
|
/// but enough to log in to this server, so the file is written 0600.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Config {
|
||||||
|
pub url: String,
|
||||||
|
pub username: String,
|
||||||
|
pub salt: String,
|
||||||
|
pub token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dirs() -> Option<ProjectDirs> {
|
||||||
|
ProjectDirs::from("", "", "remus")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config_path() -> Option<PathBuf> {
|
||||||
|
dirs().map(|d| d.config_dir().join("config.toml"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cache_dir() -> Option<PathBuf> {
|
||||||
|
dirs().map(|d| d.cache_dir().to_path_buf())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load() -> Result<Option<Config>> {
|
||||||
|
let Some(path) = config_path() else { return Ok(None) };
|
||||||
|
match fs::read_to_string(&path) {
|
||||||
|
Ok(text) => Ok(Some(
|
||||||
|
toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
|
||||||
|
)),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(cfg: &Config) -> Result<()> {
|
||||||
|
let path = config_path().context("no config directory")?;
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
fs::create_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let text = toml::to_string(cfg)?;
|
||||||
|
// Write aside, sync, then rename over the old file, so a power cut
|
||||||
|
// mid-save leaves either the old login or the new one, never a torn file.
|
||||||
|
let tmp = path.with_extension("toml.tmp");
|
||||||
|
let mut f = fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(true)
|
||||||
|
.mode(0o600)
|
||||||
|
.open(&tmp)
|
||||||
|
.with_context(|| format!("writing {}", tmp.display()))?;
|
||||||
|
f.write_all(text.as_bytes())?;
|
||||||
|
f.sync_all()?;
|
||||||
|
fs::rename(&tmp, &path).with_context(|| format!("replacing {}", path.display()))?;
|
||||||
|
if let Some(dir) = path.parent()
|
||||||
|
&& let Ok(d) = fs::File::open(dir)
|
||||||
|
{
|
||||||
|
let _ = d.sync_all();
|
||||||
|
}
|
||||||
|
log::info!("saved login to {}", path.display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
//! Scripted UI driving for development: replays actions and saves screenshots,
|
||||||
|
//! so layout can be checked at several resolutions without a controller.
|
||||||
|
//!
|
||||||
|
//! REMUS_DEV_SCRIPT="size:1280x800,wait:2000,shot:home.png,right,activate,wait:1500,shot:album.png,quit"
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use slint::{ComponentHandle, PhysicalSize, Timer};
|
||||||
|
|
||||||
|
use crate::{Action, AppWindow, app};
|
||||||
|
|
||||||
|
pub fn run(ui: &AppWindow, script: &str) {
|
||||||
|
let steps: Vec<String> = script
|
||||||
|
.split(',')
|
||||||
|
.map(|s| s.trim().to_string())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.collect();
|
||||||
|
step(ui.as_weak(), steps, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(ui: slint::Weak<AppWindow>, steps: Vec<String>, i: usize) {
|
||||||
|
let Some(cmd) = steps.get(i).cloned() else { return };
|
||||||
|
let Some(win) = ui.upgrade() else { return };
|
||||||
|
let mut delay = Duration::from_millis(250);
|
||||||
|
match cmd.split_once(':') {
|
||||||
|
Some(("wait", ms)) => delay = Duration::from_millis(ms.parse().unwrap_or(1000)),
|
||||||
|
Some(("size", "full")) => {
|
||||||
|
win.window().set_fullscreen(true);
|
||||||
|
delay = Duration::from_millis(800);
|
||||||
|
}
|
||||||
|
Some(("size", wh)) => {
|
||||||
|
if let Some((w, h)) = wh.split_once('x') {
|
||||||
|
win.window()
|
||||||
|
.set_size(PhysicalSize::new(w.parse().unwrap_or(1280), h.parse().unwrap_or(800)));
|
||||||
|
}
|
||||||
|
delay = Duration::from_millis(500);
|
||||||
|
}
|
||||||
|
Some(("shot", path)) => {
|
||||||
|
let w = win.window();
|
||||||
|
log::info!(
|
||||||
|
"window: {:?} physical, scale factor {}, fullscreen {}, theme scale {}",
|
||||||
|
w.size(),
|
||||||
|
w.scale_factor(),
|
||||||
|
w.is_fullscreen(),
|
||||||
|
win.global::<crate::Theme>().get_s()
|
||||||
|
);
|
||||||
|
match w.take_snapshot() {
|
||||||
|
Ok(buf) => {
|
||||||
|
let img = image::RgbaImage::from_raw(buf.width(), buf.height(), buf.as_bytes().to_vec());
|
||||||
|
match img.map(|img| img.save(path)) {
|
||||||
|
Some(Ok(())) => log::info!("saved {path} ({}x{})", buf.width(), buf.height()),
|
||||||
|
Some(Err(e)) => log::error!("saving {path}: {e}"),
|
||||||
|
None => log::error!("snapshot buffer has the wrong size"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => log::error!("snapshot failed: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(("login", creds)) => {
|
||||||
|
let mut parts = creds.splitn(3, '|').map(str::to_string);
|
||||||
|
let (url, user, pass) = (
|
||||||
|
parts.next().unwrap_or_default(),
|
||||||
|
parts.next().unwrap_or_default(),
|
||||||
|
parts.next().unwrap_or_default(),
|
||||||
|
);
|
||||||
|
app::with_app(move |app| app.dev_login(&url, &user, &pass));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let action = match cmd.as_str() {
|
||||||
|
"up" => Action::Up,
|
||||||
|
"down" => Action::Down,
|
||||||
|
"left" => Action::Left,
|
||||||
|
"right" => Action::Right,
|
||||||
|
"activate" => Action::Activate,
|
||||||
|
"back" => Action::Back,
|
||||||
|
"queue" => Action::Queue,
|
||||||
|
"next" => Action::Next,
|
||||||
|
"play-pause" => Action::PlayPause,
|
||||||
|
"section-next" => Action::SectionNext,
|
||||||
|
"now-playing" => Action::NowPlaying,
|
||||||
|
"search" => Action::Search,
|
||||||
|
"quit" => Action::Quit,
|
||||||
|
other => {
|
||||||
|
log::warn!("unknown dev script step {other}");
|
||||||
|
Action::None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
app::with_app(move |app| app.action(action));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Timer::single_shot(delay, move || step(ui, steps, i + 1));
|
||||||
|
}
|
||||||
+175
@@ -0,0 +1,175 @@
|
|||||||
|
//! Gamepad input. Buttons map to the same `Action`s as the keyboard bindings in app.slint.
|
||||||
|
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use gilrs::{Axis, Button, EventType, GamepadId, Gilrs};
|
||||||
|
|
||||||
|
use crate::Action;
|
||||||
|
|
||||||
|
/// Steam's virtual controllers. When one is present the physical pad behind it
|
||||||
|
/// also shows up as an evdev device, so only Steam's is listened to.
|
||||||
|
const STEAM_VENDOR: u16 = 0x28de;
|
||||||
|
|
||||||
|
const REPEAT_DELAY: Duration = Duration::from_millis(380);
|
||||||
|
const REPEAT_SLOW: Duration = Duration::from_millis(110);
|
||||||
|
const REPEAT_FAST: Duration = Duration::from_millis(45);
|
||||||
|
const FAST_AFTER: Duration = Duration::from_millis(1500);
|
||||||
|
const STICK_ON: f32 = 0.55;
|
||||||
|
const STICK_OFF: f32 = 0.35;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
enum Source {
|
||||||
|
DPad,
|
||||||
|
LeftStick,
|
||||||
|
RightStick,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Held {
|
||||||
|
source: Source,
|
||||||
|
action: Action,
|
||||||
|
since: Instant,
|
||||||
|
next: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_gamepad(emit: impl Fn(Action) + Send + 'static) {
|
||||||
|
let spawned = std::thread::Builder::new().name("gamepad".into()).spawn(move || {
|
||||||
|
let mut gilrs = match Gilrs::new() {
|
||||||
|
Ok(g) => g,
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!("gamepad support unavailable: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (_, pad) in gilrs.gamepads() {
|
||||||
|
log::info!("gamepad: {} (vendor {:04x?})", pad.name(), pad.vendor_id());
|
||||||
|
}
|
||||||
|
let mut held: Option<Held> = None;
|
||||||
|
loop {
|
||||||
|
while let Some(ev) = gilrs.next_event_blocking(Some(Duration::from_millis(15))) {
|
||||||
|
if !accept_from(&gilrs, ev.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match ev.event {
|
||||||
|
EventType::ButtonPressed(b, _) => {
|
||||||
|
if let Some(a) = dpad_action(b) {
|
||||||
|
held = Some(start_hold(Source::DPad, a));
|
||||||
|
emit(a);
|
||||||
|
} else if let Some(a) = button_action(b) {
|
||||||
|
emit(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventType::ButtonReleased(b, _) => {
|
||||||
|
if dpad_action(b).is_some() && held.as_ref().is_some_and(|h| h.source == Source::DPad) {
|
||||||
|
held = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventType::AxisChanged(axis, value, _) => {
|
||||||
|
let source = match axis {
|
||||||
|
Axis::LeftStickX | Axis::LeftStickY => Source::LeftStick,
|
||||||
|
Axis::RightStickX => Source::RightStick,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
let pad = gilrs.gamepad(ev.id);
|
||||||
|
let dir = stick_direction(source, &pad, value, held.as_ref());
|
||||||
|
match (dir, held.as_ref()) {
|
||||||
|
(Some(a), Some(h)) if h.source == source && h.action == a => {}
|
||||||
|
(Some(a), _) => {
|
||||||
|
held = Some(start_hold(source, a));
|
||||||
|
emit(a);
|
||||||
|
}
|
||||||
|
(None, Some(h)) if h.source == source => held = None,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventType::Disconnected => held = None,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(h) = held.as_mut() {
|
||||||
|
let now = Instant::now();
|
||||||
|
if now >= h.next {
|
||||||
|
emit(h.action);
|
||||||
|
let step = if now - h.since > FAST_AFTER {
|
||||||
|
REPEAT_FAST
|
||||||
|
} else {
|
||||||
|
REPEAT_SLOW
|
||||||
|
};
|
||||||
|
h.next = now + step;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Err(e) = spawned {
|
||||||
|
log::warn!("could not start gamepad thread: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accept_from(gilrs: &Gilrs, id: GamepadId) -> bool {
|
||||||
|
let steam_present = gilrs.gamepads().any(|(_, p)| p.vendor_id() == Some(STEAM_VENDOR));
|
||||||
|
!steam_present || gilrs.gamepad(id).vendor_id() == Some(STEAM_VENDOR)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_hold(source: Source, action: Action) -> Held {
|
||||||
|
let now = Instant::now();
|
||||||
|
Held {
|
||||||
|
source,
|
||||||
|
action,
|
||||||
|
since: now,
|
||||||
|
next: now + REPEAT_DELAY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dpad_action(b: Button) -> Option<Action> {
|
||||||
|
Some(match b {
|
||||||
|
Button::DPadUp => Action::Up,
|
||||||
|
Button::DPadDown => Action::Down,
|
||||||
|
Button::DPadLeft => Action::Left,
|
||||||
|
Button::DPadRight => Action::Right,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn button_action(b: Button) -> Option<Action> {
|
||||||
|
Some(match b {
|
||||||
|
Button::South => Action::Activate,
|
||||||
|
Button::East => Action::Back,
|
||||||
|
Button::West => Action::PlayPause,
|
||||||
|
Button::North => Action::Queue,
|
||||||
|
Button::LeftTrigger => Action::Prev,
|
||||||
|
Button::RightTrigger => Action::Next,
|
||||||
|
Button::LeftTrigger2 => Action::SectionPrev,
|
||||||
|
Button::RightTrigger2 => Action::SectionNext,
|
||||||
|
Button::Start => Action::NowPlaying,
|
||||||
|
Button::Select => Action::Search,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the stick's dominant direction, with hysteresis so a stick resting
|
||||||
|
/// near the threshold does not flicker between held and released.
|
||||||
|
fn stick_direction(source: Source, pad: &gilrs::Gamepad<'_>, _changed: f32, held: Option<&Held>) -> Option<Action> {
|
||||||
|
let holding = held.is_some_and(|h| h.source == source);
|
||||||
|
let threshold = if holding { STICK_OFF } else { STICK_ON };
|
||||||
|
match source {
|
||||||
|
Source::LeftStick => {
|
||||||
|
let x = pad.value(Axis::LeftStickX);
|
||||||
|
let y = pad.value(Axis::LeftStickY);
|
||||||
|
if x.abs() < threshold && y.abs() < threshold {
|
||||||
|
None
|
||||||
|
} else if x.abs() > y.abs() {
|
||||||
|
Some(if x > 0.0 { Action::Right } else { Action::Left })
|
||||||
|
} else {
|
||||||
|
Some(if y > 0.0 { Action::Up } else { Action::Down })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Source::RightStick => {
|
||||||
|
let x = pad.value(Axis::RightStickX);
|
||||||
|
if x.abs() < threshold {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(if x > 0.0 { Action::SeekForward } else { Action::SeekBack })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Source::DPad => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
slint::include_modules!();
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
mod config;
|
||||||
|
mod devscript;
|
||||||
|
mod input;
|
||||||
|
mod player;
|
||||||
|
mod subsonic;
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("remus=info")).init();
|
||||||
|
|
||||||
|
let dev_script = std::env::var("REMUS_DEV_SCRIPT").ok();
|
||||||
|
let windowed = std::env::args().any(|a| a == "--windowed") || std::env::var_os("REMUS_WINDOWED").is_some();
|
||||||
|
|
||||||
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let ui = AppWindow::new()?;
|
||||||
|
app::install(&ui, rt.handle().clone());
|
||||||
|
input::spawn_gamepad(|action| {
|
||||||
|
let _ = slint::invoke_from_event_loop(move || app::with_app(move |app| app.action(action)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Kept alive until the event loop ends.
|
||||||
|
let fullscreen_retry = slint::Timer::default();
|
||||||
|
if !windowed {
|
||||||
|
ui.window().set_fullscreen(true);
|
||||||
|
// Compositors ignore the request until the window is mapped, and a
|
||||||
|
// tiling one (COSMIC) can take the window back right after granting
|
||||||
|
// it. Keep asking until fullscreen has held for a second, giving up
|
||||||
|
// after five. Then stop, so a later F11 to leave fullscreen sticks.
|
||||||
|
let weak = ui.as_weak();
|
||||||
|
let (mut ticks, mut held) = (0, 0);
|
||||||
|
fullscreen_retry.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
|
||||||
|
let Some(ui) = weak.upgrade() else { return };
|
||||||
|
if ticks >= 50 || held >= 10 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ticks += 1;
|
||||||
|
if ui.window().is_fullscreen() {
|
||||||
|
held += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
held = 0;
|
||||||
|
log::debug!("not fullscreen yet ({:?}), asking again", ui.window().size());
|
||||||
|
ui.window().set_fullscreen(false);
|
||||||
|
ui.window().set_fullscreen(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(script) = dev_script {
|
||||||
|
devscript::run(&ui, &script);
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.run()?;
|
||||||
|
app::shutdown();
|
||||||
|
drop(rt);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+186
@@ -0,0 +1,186 @@
|
|||||||
|
//! Playback through an mpv child process, controlled over its JSON IPC socket.
|
||||||
|
|
||||||
|
use std::io::{BufRead, BufReader, Write};
|
||||||
|
use std::os::unix::net::UnixStream;
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum PlayerEvent {
|
||||||
|
Position(f64),
|
||||||
|
Duration(f64),
|
||||||
|
Paused(bool),
|
||||||
|
/// Index into the mpv playlist, None when nothing is loaded.
|
||||||
|
Track(Option<usize>),
|
||||||
|
Exited,
|
||||||
|
}
|
||||||
|
|
||||||
|
const OBSERVED: [&str; 4] = ["time-pos", "duration", "pause", "playlist-pos"];
|
||||||
|
|
||||||
|
pub struct Player {
|
||||||
|
writer: Mutex<UnixStream>,
|
||||||
|
child: Mutex<Child>,
|
||||||
|
socket: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Player {
|
||||||
|
pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Result<Player> {
|
||||||
|
let dir = std::env::var_os("XDG_RUNTIME_DIR")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(std::env::temp_dir);
|
||||||
|
let socket = dir.join(format!("remus-mpv-{}.sock", std::process::id()));
|
||||||
|
let _ = std::fs::remove_file(&socket);
|
||||||
|
|
||||||
|
let mut cmd = Command::new("mpv");
|
||||||
|
cmd.args([
|
||||||
|
"--idle=yes",
|
||||||
|
"--config=no",
|
||||||
|
"--no-video",
|
||||||
|
"--no-terminal",
|
||||||
|
"--audio-display=no",
|
||||||
|
"--prefetch-playlist=yes",
|
||||||
|
"--cache=yes",
|
||||||
|
"--volume=100",
|
||||||
|
])
|
||||||
|
.arg(format!("--input-ipc-server={}", socket.display()))
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null());
|
||||||
|
// Take mpv down with us if we crash, so it never keeps playing orphaned.
|
||||||
|
unsafe {
|
||||||
|
cmd.pre_exec(|| {
|
||||||
|
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut child = cmd.spawn().context("could not start mpv (is it installed?)")?;
|
||||||
|
|
||||||
|
let stream = (0..50).find_map(|_| {
|
||||||
|
UnixStream::connect(&socket).ok().or_else(|| {
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
None
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let Some(stream) = stream else {
|
||||||
|
let _ = child.kill();
|
||||||
|
bail!("mpv did not open its IPC socket at {}", socket.display());
|
||||||
|
};
|
||||||
|
|
||||||
|
let reader = BufReader::new(stream.try_clone()?);
|
||||||
|
std::thread::Builder::new().name("mpv-ipc".into()).spawn(move || {
|
||||||
|
for line in reader.lines() {
|
||||||
|
let Ok(line) = line else { break };
|
||||||
|
if let Some(ev) = parse_event(&line) {
|
||||||
|
on_event(ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
on_event(PlayerEvent::Exited);
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let player = Player {
|
||||||
|
writer: Mutex::new(stream),
|
||||||
|
child: Mutex::new(child),
|
||||||
|
socket,
|
||||||
|
};
|
||||||
|
for (i, name) in OBSERVED.iter().enumerate() {
|
||||||
|
player.command(json!(["observe_property", i + 1, name]));
|
||||||
|
}
|
||||||
|
Ok(player)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(&self, args: Value) {
|
||||||
|
let mut line = json!({ "command": args }).to_string();
|
||||||
|
line.push('\n');
|
||||||
|
if let Ok(mut w) = self.writer.lock()
|
||||||
|
&& let Err(e) = w.write_all(line.as_bytes())
|
||||||
|
{
|
||||||
|
log::warn!("mpv ipc write failed: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces the playlist with `urls` and starts at `start`.
|
||||||
|
pub fn play_list(&self, urls: &[String], start: usize) {
|
||||||
|
self.command(json!(["stop"]));
|
||||||
|
for url in urls {
|
||||||
|
self.command(json!(["loadfile", url, "append"]));
|
||||||
|
}
|
||||||
|
self.command(json!(["playlist-play-index", start]));
|
||||||
|
self.command(json!(["set_property", "pause", false]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn append(&self, url: &str) {
|
||||||
|
self.command(json!(["loadfile", url, "append-play"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn play_index(&self, index: usize) {
|
||||||
|
self.command(json!(["playlist-play-index", index]));
|
||||||
|
self.command(json!(["set_property", "pause", false]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn toggle_pause(&self) {
|
||||||
|
self.command(json!(["cycle", "pause"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next(&self) {
|
||||||
|
self.command(json!(["playlist-next"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prev(&self) {
|
||||||
|
self.command(json!(["playlist-prev"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn seek(&self, seconds: f64) {
|
||||||
|
self.command(json!(["seek", seconds, "relative"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Player {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.command(json!(["quit"]));
|
||||||
|
if let Ok(mut child) = self.child.lock() {
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_file(&self.socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_event(line: &str) -> Option<PlayerEvent> {
|
||||||
|
let v: Value = serde_json::from_str(line).ok()?;
|
||||||
|
if v.get("event")?.as_str()? != "property-change" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let data = v.get("data");
|
||||||
|
match v.get("name")?.as_str()? {
|
||||||
|
"time-pos" => Some(PlayerEvent::Position(data.and_then(Value::as_f64).unwrap_or(0.0))),
|
||||||
|
"duration" => Some(PlayerEvent::Duration(data.and_then(Value::as_f64).unwrap_or(0.0))),
|
||||||
|
"pause" => Some(PlayerEvent::Paused(data.and_then(Value::as_bool).unwrap_or(false))),
|
||||||
|
"playlist-pos" => Some(PlayerEvent::Track(
|
||||||
|
data.and_then(Value::as_i64).filter(|&i| i >= 0).map(|i| i as usize),
|
||||||
|
)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_property_changes() {
|
||||||
|
let ev = parse_event(r#"{"event":"property-change","id":4,"name":"playlist-pos","data":2}"#);
|
||||||
|
assert!(matches!(ev, Some(PlayerEvent::Track(Some(2)))));
|
||||||
|
let ev = parse_event(r#"{"event":"property-change","id":4,"name":"playlist-pos","data":-1}"#);
|
||||||
|
assert!(matches!(ev, Some(PlayerEvent::Track(None))));
|
||||||
|
let ev = parse_event(r#"{"event":"property-change","id":1,"name":"time-pos"}"#);
|
||||||
|
assert!(matches!(ev, Some(PlayerEvent::Position(p)) if p == 0.0));
|
||||||
|
assert!(parse_event(r#"{"request_id":0,"error":"success"}"#).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
+484
@@ -0,0 +1,484 @@
|
|||||||
|
//! Minimal OpenSubsonic client covering what the browser and player need.
|
||||||
|
|
||||||
|
use std::hash::{BuildHasher, RandomState};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde::de::{DeserializeOwned, Deserializer};
|
||||||
|
|
||||||
|
const API_VERSION: &str = "1.16.1";
|
||||||
|
const CLIENT_NAME: &str = "remus";
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Client {
|
||||||
|
http: reqwest::Client,
|
||||||
|
base: String,
|
||||||
|
user: String,
|
||||||
|
salt: String,
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
pub fn new(base: &str, user: &str, salt: &str, token: &str) -> Self {
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.user_agent(concat!("remus/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.timeout(std::time::Duration::from_secs(30))
|
||||||
|
.build()
|
||||||
|
.expect("http client");
|
||||||
|
Client {
|
||||||
|
http,
|
||||||
|
base: normalize_base(base),
|
||||||
|
user: user.to_string(),
|
||||||
|
salt: salt.to_string(),
|
||||||
|
token: token.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derives a token from the password so the password itself is never stored.
|
||||||
|
/// The token is still password-equivalent for this server.
|
||||||
|
pub fn from_password(base: &str, user: &str, password: &str) -> Self {
|
||||||
|
let salt = random_salt();
|
||||||
|
let token = format!("{:x}", md5::compute(format!("{password}{salt}")));
|
||||||
|
Client::new(base, user, &salt, &token)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn base(&self) -> &str {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
pub fn user(&self) -> &str {
|
||||||
|
&self.user
|
||||||
|
}
|
||||||
|
pub fn salt(&self) -> &str {
|
||||||
|
&self.salt
|
||||||
|
}
|
||||||
|
pub fn token(&self) -> &str {
|
||||||
|
&self.token
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint_url(&self, endpoint: &str, params: &[(&str, String)]) -> Result<reqwest::Url> {
|
||||||
|
let mut all: Vec<(&str, String)> = vec![
|
||||||
|
("u", self.user.clone()),
|
||||||
|
("t", self.token.clone()),
|
||||||
|
("s", self.salt.clone()),
|
||||||
|
("v", API_VERSION.to_string()),
|
||||||
|
("c", CLIENT_NAME.to_string()),
|
||||||
|
("f", "json".to_string()),
|
||||||
|
];
|
||||||
|
all.extend(params.iter().cloned());
|
||||||
|
reqwest::Url::parse_with_params(&format!("{}/rest/{endpoint}", self.base), &all)
|
||||||
|
.with_context(|| format!("invalid server url {}", self.base))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call<T: DeserializeOwned>(&self, endpoint: &str, params: &[(&str, String)]) -> Result<T> {
|
||||||
|
let url = self.endpoint_url(endpoint, params)?;
|
||||||
|
let resp = self
|
||||||
|
.http
|
||||||
|
.get(url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(redact)
|
||||||
|
.with_context(|| format!("{endpoint} request failed"))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
bail!("{endpoint}: server returned {status}");
|
||||||
|
}
|
||||||
|
let mut body: serde_json::Value = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(redact)
|
||||||
|
.with_context(|| format!("{endpoint}: invalid json"))?;
|
||||||
|
let inner = body
|
||||||
|
.get_mut("subsonic-response")
|
||||||
|
.map(serde_json::Value::take)
|
||||||
|
.ok_or_else(|| anyhow!("{endpoint}: not a subsonic response"))?;
|
||||||
|
if inner.get("status").and_then(|s| s.as_str()) != Some("ok") {
|
||||||
|
let msg = inner
|
||||||
|
.pointer("/error/message")
|
||||||
|
.and_then(|m| m.as_str())
|
||||||
|
.unwrap_or("unknown error");
|
||||||
|
bail!("{msg}");
|
||||||
|
}
|
||||||
|
serde_json::from_value(inner).with_context(|| format!("{endpoint}: unexpected response shape"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn ping(&self) -> Result<()> {
|
||||||
|
let _: serde_json::Value = self.call("ping", &[]).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `kind` is a getAlbumList2 type: newest, random, alphabeticalByName, frequent, recent...
|
||||||
|
pub async fn album_list(&self, kind: &str, size: u32, offset: u32) -> Result<Vec<Album>> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
#[serde(rename = "albumList2", default)]
|
||||||
|
list: AlbumList,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct AlbumList {
|
||||||
|
#[serde(default)]
|
||||||
|
album: Vec<Album>,
|
||||||
|
}
|
||||||
|
let r: R = self
|
||||||
|
.call(
|
||||||
|
"getAlbumList2",
|
||||||
|
&[
|
||||||
|
("type", kind.into()),
|
||||||
|
("size", size.to_string()),
|
||||||
|
("offset", offset.to_string()),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(r.list.album)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn artists(&self) -> Result<Vec<Artist>> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
#[serde(default)]
|
||||||
|
artists: Indexes,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct Indexes {
|
||||||
|
#[serde(default)]
|
||||||
|
index: Vec<Index>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Index {
|
||||||
|
#[serde(default)]
|
||||||
|
artist: Vec<Artist>,
|
||||||
|
}
|
||||||
|
let r: R = self.call("getArtists", &[]).await?;
|
||||||
|
Ok(r.artists.index.into_iter().flat_map(|i| i.artist).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn artist(&self, id: &str) -> Result<ArtistDetail> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
artist: ArtistDetail,
|
||||||
|
}
|
||||||
|
let r: R = self.call("getArtist", &[("id", id.into())]).await?;
|
||||||
|
Ok(r.artist)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn album(&self, id: &str) -> Result<AlbumDetail> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
album: AlbumDetail,
|
||||||
|
}
|
||||||
|
let r: R = self.call("getAlbum", &[("id", id.into())]).await?;
|
||||||
|
Ok(r.album)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn playlists(&self) -> Result<Vec<Playlist>> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
#[serde(default)]
|
||||||
|
playlists: Lists,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct Lists {
|
||||||
|
#[serde(default)]
|
||||||
|
playlist: Vec<Playlist>,
|
||||||
|
}
|
||||||
|
let r: R = self.call("getPlaylists", &[]).await?;
|
||||||
|
Ok(r.playlists.playlist)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn playlist(&self, id: &str) -> Result<PlaylistDetail> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
playlist: PlaylistDetail,
|
||||||
|
}
|
||||||
|
let r: R = self.call("getPlaylist", &[("id", id.into())]).await?;
|
||||||
|
Ok(r.playlist)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn search(&self, query: &str) -> Result<SearchResult> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct R {
|
||||||
|
#[serde(rename = "searchResult3", default)]
|
||||||
|
result: SearchResult,
|
||||||
|
}
|
||||||
|
let r: R = self
|
||||||
|
.call(
|
||||||
|
"search3",
|
||||||
|
&[
|
||||||
|
("query", query.into()),
|
||||||
|
("artistCount", "20".into()),
|
||||||
|
("albumCount", "40".into()),
|
||||||
|
("songCount", "80".into()),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(r.result)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn scrobble(&self, id: &str, submission: bool) -> Result<()> {
|
||||||
|
let _: serde_json::Value = self
|
||||||
|
.call("scrobble", &[("id", id.into()), ("submission", submission.to_string())])
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn cover_art(&self, id: &str, size: u32) -> Result<Vec<u8>> {
|
||||||
|
let url = self.endpoint_url("getCoverArt", &[("id", id.into()), ("size", size.to_string())])?;
|
||||||
|
let resp = self.http.get(url).send().await.map_err(redact)?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
bail!("getCoverArt: server returned {status}");
|
||||||
|
}
|
||||||
|
let is_json = resp
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|v| v.contains("json") || v.contains("xml"));
|
||||||
|
if is_json {
|
||||||
|
bail!("getCoverArt: no image for {id}");
|
||||||
|
}
|
||||||
|
Ok(resp.bytes().await.map_err(redact)?.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stream_url(&self, id: &str) -> String {
|
||||||
|
self.endpoint_url("stream", &[("id", id.into())])
|
||||||
|
.map(|u| u.to_string())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request URLs carry the auth token, so they must never reach an error
|
||||||
|
/// message: those end up on screen and in the logs.
|
||||||
|
fn redact(e: reqwest::Error) -> reqwest::Error {
|
||||||
|
e.without_url()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_base(base: &str) -> String {
|
||||||
|
let base = base.trim().trim_end_matches('/');
|
||||||
|
let base = base.strip_suffix("/rest").unwrap_or(base);
|
||||||
|
if base.starts_with("http://") || base.starts_with("https://") {
|
||||||
|
base.to_string()
|
||||||
|
} else {
|
||||||
|
format!("https://{base}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_salt() -> String {
|
||||||
|
let nanos = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let a = RandomState::new().hash_one(nanos);
|
||||||
|
let b = RandomState::new().hash_one(a ^ u64::from(std::process::id()));
|
||||||
|
format!("{a:016x}{b:016x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Older servers send ids as numbers, OpenSubsonic as strings.
|
||||||
|
fn de_id<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||||
|
Ok(match serde_json::Value::deserialize(d)? {
|
||||||
|
serde_json::Value::String(s) => s,
|
||||||
|
serde_json::Value::Number(n) => n.to_string(),
|
||||||
|
other => other.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn de_opt_id<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||||
|
Ok(match Option::<serde_json::Value>::deserialize(d)? {
|
||||||
|
Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s),
|
||||||
|
Some(serde_json::Value::Number(n)) => Some(n.to_string()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Album {
|
||||||
|
#[serde(deserialize_with = "de_id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub artist: Option<String>,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub year: Option<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Artist {
|
||||||
|
#[serde(deserialize_with = "de_id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub album_count: Option<u32>,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ArtistDetail {
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub album: Vec<Album>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AlbumDetail {
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub artist: Option<String>,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub year: Option<i32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration: Option<u32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub song: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Song {
|
||||||
|
#[serde(deserialize_with = "de_id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub artist: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub album: Option<String>,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration: Option<u32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub track: Option<u32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub disc_number: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Playlist {
|
||||||
|
#[serde(deserialize_with = "de_id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub song_count: Option<u32>,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub owner: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct PlaylistDetail {
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default, deserialize_with = "de_opt_id")]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration: Option<u32>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub entry: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
pub struct SearchResult {
|
||||||
|
#[serde(default)]
|
||||||
|
pub artist: Vec<Artist>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub album: Vec<Album>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub song: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base_url_is_normalized() {
|
||||||
|
assert_eq!(normalize_base("music.example.com/"), "https://music.example.com");
|
||||||
|
assert_eq!(normalize_base("http://nas:4533/rest"), "http://nas:4533");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numeric_ids_are_accepted() {
|
||||||
|
let a: Album = serde_json::from_str(r#"{"id": 42, "name": "X", "coverArt": 7}"#).unwrap();
|
||||||
|
assert_eq!(a.id, "42");
|
||||||
|
assert_eq!(a.cover_art.as_deref(), Some("7"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exercises every endpoint against a real server:
|
||||||
|
/// REMUS_TEST_URL=... REMUS_TEST_USER=... REMUS_TEST_PASS=... cargo test -- --ignored
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore]
|
||||||
|
async fn live_server() {
|
||||||
|
let var = |k| std::env::var(k).unwrap_or_else(|_| panic!("{k} not set"));
|
||||||
|
let c = Client::from_password(&var("REMUS_TEST_URL"), &var("REMUS_TEST_USER"), &var("REMUS_TEST_PASS"));
|
||||||
|
c.ping().await.unwrap();
|
||||||
|
|
||||||
|
let albums = c.album_list("newest", 10, 0).await.unwrap();
|
||||||
|
assert!(!albums.is_empty(), "no albums");
|
||||||
|
let album = c.album(&albums[0].id).await.unwrap();
|
||||||
|
assert!(!album.song.is_empty(), "album has no songs");
|
||||||
|
println!(
|
||||||
|
"album: {} by {:?}, {} songs",
|
||||||
|
album.name,
|
||||||
|
album.artist,
|
||||||
|
album.song.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
let cover = album.cover_art.as_deref().expect("album has no cover id");
|
||||||
|
let bytes = c.cover_art(cover, 256).await.unwrap();
|
||||||
|
let img = image::load_from_memory(&bytes).unwrap();
|
||||||
|
println!("cover: {}x{}", img.width(), img.height());
|
||||||
|
|
||||||
|
let artists = c.artists().await.unwrap();
|
||||||
|
assert!(!artists.is_empty(), "no artists");
|
||||||
|
let artist = c.artist(&artists[0].id).await.unwrap();
|
||||||
|
println!("artist: {} with {} albums", artist.name, artist.album.len());
|
||||||
|
|
||||||
|
let playlists = c.playlists().await.unwrap();
|
||||||
|
if let Some(p) = playlists.first() {
|
||||||
|
let p = c.playlist(&p.id).await.unwrap();
|
||||||
|
println!("playlist: {} with {} entries", p.name, p.entry.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
let found = c.search(&album.name).await.unwrap();
|
||||||
|
assert!(!found.album.is_empty(), "search found nothing for {}", album.name);
|
||||||
|
|
||||||
|
let url = c.stream_url(&album.song[0].id);
|
||||||
|
let resp = reqwest::get(&url).await.unwrap();
|
||||||
|
assert!(resp.status().is_success(), "stream returned {}", resp.status());
|
||||||
|
println!("stream content-type: {:?}", resp.headers().get("content-type"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn errors_never_contain_the_token() {
|
||||||
|
// Port 1 on loopback refuses the connection, so the request fails.
|
||||||
|
let c = Client::new("http://127.0.0.1:1", "u", "somesalt", "secrettoken");
|
||||||
|
let err = format!("{:#}", c.ping().await.unwrap_err());
|
||||||
|
assert!(!err.contains("secrettoken"), "token leaked: {err}");
|
||||||
|
assert!(!err.contains("somesalt"), "salt leaked: {err}");
|
||||||
|
let err = format!("{:#}", c.cover_art("al-1", 256).await.unwrap_err());
|
||||||
|
assert!(!err.contains("secrettoken"), "token leaked: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn token_is_md5_of_password_and_salt() {
|
||||||
|
let c = Client::from_password("http://x", "u", "sesame");
|
||||||
|
let expected = format!("{:x}", md5::compute(format!("sesame{}", c.salt())));
|
||||||
|
assert_eq!(c.token(), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1102
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user