android auto: the car's queue works like the page's, and every row gets its cover
"Needs the app" is gone. It named what the cold service could not do — the resolver and the Soulseek session live in the page, and a car that starts the app cold has no page — and Kyle's answer to the label was the right one: a tap should find a copy and play it, in the background, and a playlist should keep going through rows that are not here exactly as the page keeps going. headless_slsk.rs is a Soulseek session for a process with no page: the stored account, one search (artist + simplified title, the server's excluded phrases stripped), copies ranked by rules close to the page's songCandidates — the title in the filename, streamable formats, a duration within eight per cent, lossless over 320 over the rest, the artist in the path, a free upload slot before anything else — and a download into the same stream cache the page uses. Its own tokio runtime: a car-started process has no Tauri one. headless.rs is the page's queue in Rust. resolve_playable queues EVERY row of a playlist in order, a row not here with its remembered peer file and no path. The engine starts a row from its file when it is whole, from the fetch already filling its cache file when one is, and otherwise finds it on the network right then (the remembered peer first, then the search), playing the bytes as they land; a peer that sends nothing for fifteen seconds is dropped for the next copy, twice, and when a row has no copy anywhere the queue moves on — only the last row's failure reaches the card. The next three rows are fetched ahead of time, four seconds after a start so nothing competes with the track that is starting, and when the immediate next is whole before the current one ends it is appended to the sink and the boundary is gapless — the page's preloadLocal and preloadCachedStream in one. Fetches are keyed by cache file, not index, so a shuffle cannot start the same file from the same peer twice. The card shows the title at once with a spinner (STATE_BUFFERING through headlessState), then the track; every source is remembered in the mirror, so the row is "here" next time. One session per process: when the app opens over it, login_inner ADOPTS the client and reads its events through subscribe() instead of logging in again — two logins from one address in quick succession is what the server throttles — and the fetches in flight become the page's own preloads, so the row the car was fetching ahead lands gaplessly under the page too. Covers, always, like the desktop. Thirty of GhettoTechie's forty rows have no catalog cover, and the car drew the app icon over them. In the cold process the cover embedded in the file is extracted — the desktop's own tagger::extract_art, keyed by the audio path under <library>/.soulstream/stream-art/by-file/, a miss remembered as an empty file — for browse rows, the card and the Continue row, and a row fetched cold gets the same once 200 kB of it have landed. On the phone, coverart.svelte.js is the desktop's playlist backfill as a background walk over every playlist: the file before the catalog (the row's own cached copy, persisted as art_path), then the ONE strict ladder the import review uses (findCatalogTrack, persisted as art_url + track_id) — never a loose name lookup. After boot, on every playlist change, every six hours, the open page's rows first, a miss remembered for a day and only when the catalog answered. The player does the same for the track that is playing (ensureStreamArt: embedded, then catalog), makes the URL the entry's art key and hands it to the walk to persist. The page's own hole is closed too: a streamed row with no cover got no art key at all, and where it had one the extractor's FILE PATH was stored where a data URL belongs; such rows get a "stream:" key and the file is read as a thumbnail, and a stream row's art_path now draws on the phone. A car that starts the app cold has no page to walk for it, so the cold process asks the catalog itself. cover_hunt.rs is catalogMatch.js in Rust — the same Deezer field queries through the metadata crate, a match only when the artist agrees, the base title agrees, the version qualifiers are compatible and a known duration does not contradict; the two are meant to stay in step — fed by every browse and every queue built from a playlist. A blank stream row is answered from what was asked before (stream-art/catalog.json, a miss for a day and only when the catalog answered), else queued for one thread that looks rows up one at a time behind the client's own Deezer pacing, writes the answer on the row (art_url and the track id, only ever filling a NULL; the library is WAL and the page's writer is another connection), and re-lists the playlist on the car. The track that is playing gets the same, through an entry that moves only the card's art and never its position. The cold Soulseek search is the page's two-rung ladder as well: artist plus the simplified title, then the title alone with the artist required in the peer's path; the hunt's last rung is the page's last rung too, the artist's whole shelf flattened to tracks, for the records the search index buries — spent only on the track that is playing, bounded to forty seconds, and the cover memory carries the matcher's version so a "no" from an older matcher is no answer once a rung is added. Two things the head unit found in the seam. media3's default onSubscribe answers "not supported", so nobody was ever subscribed and the re-list notice reached nobody; LibraryTree accepts subscriptions now, and covers land on the car's list within seconds of being found. And the Soulseek client spawns a download's transfer task with tokio::spawn, which needs a runtime on the calling thread — the engine's resolver thread is not a Tauri command, the spawn panicked, the thread died without a word, and the card sat on BUFFERING; every client call from an engine thread runs under the cold runtime's enter() now. The phone's artist page never ran the MusicBrainz pass. It built its discography from Deezer's list alone, so the releases Deezer's artist listing omits — EPs, and whole albums — never appeared, nor the authoritative release types or the guest-appearance and co-tenant arbitration. The desktop's identity merge is a plain module now (lib/artistIdentity.js, moved out of state.svelte.js verbatim, the desktop importing it back), and the phone runs it after the page is on screen — one implementation for both surfaces. What the restarted head unit found, all in the seam between a car session and the page — and one bug older than this branch. The pump's calls into Kotlin never worked. "auto advanced to" has not appeared in a single log while cold queues advanced through whole albums under a card stuck on track one, and the new end-of-queue notice did not fire either. FindClass on the self-attached pump thread resolves through the system class loader, which cannot see com.soulstream.mediasession .AutoNative; the lookup failed and the exception was cleared, silently, every time. The class is taken from the object Kotlin hands every JNI entry — on a Java thread, through the app's own loader — and kept as a global reference; every pump call goes through call_auto_native. Autoplay on connection worked unprompted and resumed Starboy at 3:50 of 3:50: the page writes the position one last time when a track runs out, so a resume point can sit at the end. resume_queue treats a position within two seconds of the duration as "the next item from the top", keeps every entry (one not here is found on reach, like any other), and the headless engine reports end-of-queue to Kotlin, which turns the card to paused. A seek on the page reached the resume point only at the pump's next five-second flush; seekSecs writes the session at once. Opening the app over a cold car session handed the page the right queue and the page called it a paused session that needed re-sourcing: the transport snapshot it reads is built only from events after the page subscribes, and an engine already playing sends no Playing. The bar said paused, the card said PAUSED, the audio kept going. playback::init seeds the snapshot from the engine's own progress when it adopts a running engine, so the page follows what is sounding. preview::init opened two more output streams at every launch for the desktop's hover previews, which the phone never calls — three live AAudio tracks on our uid with one sounding. It is gated off on Android.
This commit is contained in:
1 parent
5ddb6d4d59
commit
9f7661afab
22 files changed
+3069
-485
No files matched your search
+165
-37
@@ -86,7 +86,7 @@ impl Node {
|
||||
/// called here because it takes a `tauri::AppHandle`). The database itself
|
||||
/// always lives under `<library>/.soulstream/`, which is the rule that keeps
|
||||
/// stored paths portable.
|
||||
fn db_path(data_dir: &Path) -> PathBuf {
|
||||
pub(crate) fn db_path(data_dir: &Path) -> PathBuf {
|
||||
let configured = std::fs::read_to_string(data_dir.join("config.json"))
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
|
||||
@@ -348,13 +348,75 @@ fn resume_row(data_dir: &Path) -> Option<Node> {
|
||||
subtitle: format!("Continue · {source}{at}"),
|
||||
browsable: false,
|
||||
playable: true,
|
||||
art: t.art.clone(),
|
||||
path: Some(t.path.to_string_lossy().into_owned()),
|
||||
art: t
|
||||
.art
|
||||
.clone()
|
||||
.or_else(|| crate::cover_hunt::cached(data_dir, &t.artist, &t.title)),
|
||||
path: t.here().map(|p| p.to_string_lossy().into_owned()),
|
||||
})
|
||||
}
|
||||
|
||||
/// A playlist row's playable file from this process: its local path when it
|
||||
/// has one, else the byte-complete cache copy of its remembered peer file.
|
||||
/// The cover embedded in an audio file, as a file the car can be handed.
|
||||
///
|
||||
/// Thirty of GhettoTechie's forty rows have no catalog cover at all — the
|
||||
/// import never matched them — and the car drew the app's icon over every
|
||||
/// one (2026-09-18). Most of those files carry their real cover in the tag:
|
||||
/// the desktop's `stream_embedded_art` extracts exactly this, keyed by the
|
||||
/// bytes' hash. Here it is keyed by the AUDIO path, so "already extracted"
|
||||
/// is one `stat` and a browse of forty rows reads forty tags once, ever.
|
||||
/// Written beside the desktop's own extractions, under
|
||||
/// `<library>/.soulstream/stream-art/`, which the FileProvider roots reach.
|
||||
pub(crate) fn embedded_cover(data_dir: &Path, audio: &Path) -> Option<PathBuf> {
|
||||
embedded_cover_from(data_dir, audio, audio, true)
|
||||
}
|
||||
|
||||
/// [`embedded_cover`] for a file that is still arriving: keyed by the
|
||||
/// cache path it will be (`key`), read from the partial it is now
|
||||
/// (`read`). A miss is remembered only when `remember_miss` — the tag of
|
||||
/// a partial file may simply not all be here yet.
|
||||
pub(crate) fn embedded_cover_from(
|
||||
data_dir: &Path,
|
||||
key: &Path,
|
||||
read: &Path,
|
||||
remember_miss: bool,
|
||||
) -> Option<PathBuf> {
|
||||
let dir = db_path(data_dir).parent()?.join("stream-art").join("by-file");
|
||||
let mut hash: u64 = 0xcbf29ce484222325;
|
||||
for b in key.to_string_lossy().bytes() {
|
||||
hash ^= b as u64;
|
||||
hash = hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
let out = dir.join(format!("{hash:016x}.img"));
|
||||
if matches!(std::fs::metadata(&out), Ok(md) if md.len() > 0) {
|
||||
return Some(out);
|
||||
}
|
||||
// A miss is remembered as an EMPTY file, so a tag with no picture is not
|
||||
// re-read on every browse. (A file that later gains a cover is a case
|
||||
// this library does not have.)
|
||||
if std::fs::metadata(&out).is_ok() {
|
||||
return None;
|
||||
}
|
||||
let bytes = match tagger::extract_art(read) {
|
||||
Ok(Some(b)) if !b.is_empty() => b,
|
||||
_ => {
|
||||
if remember_miss {
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::fs::write(&out, b"");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let tmp = out.with_extension("img.tmp");
|
||||
std::fs::write(&tmp, &bytes).ok()?;
|
||||
std::fs::rename(&tmp, &out).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A playlist row from this process: its local file when it has one; for a
|
||||
/// streamed row, the byte-complete cache copy of its remembered peer file
|
||||
/// when that is here, else `None` with the peer file itself so the queue
|
||||
/// can fetch it again when it gets there (`headless.rs`).
|
||||
fn row_file(
|
||||
data_dir: &Path,
|
||||
kind: &str,
|
||||
@@ -362,23 +424,25 @@ fn row_file(
|
||||
track_id: Option<&str>,
|
||||
artist: &str,
|
||||
title: &str,
|
||||
) -> Option<(PathBuf, Option<crate::resume::StreamRef>)> {
|
||||
) -> (Option<PathBuf>, Option<crate::resume::StreamRef>) {
|
||||
if kind == "local" {
|
||||
return path.map(|p| (PathBuf::from(p), None));
|
||||
return (path.map(PathBuf::from), None);
|
||||
}
|
||||
if kind != "stream" {
|
||||
return None;
|
||||
return (None, None);
|
||||
}
|
||||
let src = crate::stream_sources::lookup(data_dir, track_id, Some(artist), Some(title))?;
|
||||
let file = crate::stream_sources::cached_file(data_dir, &src)?;
|
||||
Some((
|
||||
let Some(src) = crate::stream_sources::lookup(data_dir, track_id, Some(artist), Some(title)) else {
|
||||
return (None, None);
|
||||
};
|
||||
let file = crate::stream_sources::cached_file(data_dir, &src);
|
||||
(
|
||||
file,
|
||||
Some(crate::resume::StreamRef {
|
||||
username: src.username,
|
||||
path: src.path,
|
||||
size: src.size,
|
||||
}),
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// Playlists, newest first, as browsable rows.
|
||||
@@ -446,7 +510,7 @@ fn playlist_counts(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusq
|
||||
for row in rows.flatten() {
|
||||
n += 1;
|
||||
let (kind, path, track_id, artist, title) = row;
|
||||
if row_file(data_dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title).is_some() {
|
||||
if row_file(data_dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title).0.is_some() {
|
||||
here += 1;
|
||||
}
|
||||
}
|
||||
@@ -459,7 +523,7 @@ fn playlist_counts(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusq
|
||||
/// so the list matches the phone's.
|
||||
fn playlist_items(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusqlite::Result<Vec<Node>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, title, artist, album, path, COALESCE(art_path, art_url), kind, track_id
|
||||
"SELECT id, title, artist, album, path, COALESCE(art_path, art_url), kind, track_id, duration_secs
|
||||
FROM playlist_items
|
||||
WHERE playlist_id = ?1
|
||||
ORDER BY position",
|
||||
@@ -473,7 +537,8 @@ fn playlist_items(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusql
|
||||
let art: Option<String> = r.get(5)?;
|
||||
let kind: String = r.get(6)?;
|
||||
let track_id: Option<String> = r.get(7)?;
|
||||
let file = row_file(data_dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title);
|
||||
let duration = r.get::<_, Option<i64>>(8)?.map(|s| s as f64);
|
||||
let (file, _) = row_file(data_dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title);
|
||||
// Every real row is PLAYABLE, whether or not its file is here: a
|
||||
// non-playable, non-browsable item is drawn by the host as a bare
|
||||
// tile in a list of rows (the first head-unit run showed four rows
|
||||
@@ -481,17 +546,46 @@ fn playlist_items(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusql
|
||||
// its subtitle, and a tap on it is the hand-off (warm) or the error
|
||||
// card (cold) — never a silent nothing. Kotlin marks the ones whose
|
||||
// file is here with the host's own "downloaded" indicator.
|
||||
// A row whose bytes are not here yet is still a row that plays: the
|
||||
// tap finds a copy on the network from this process now
|
||||
// (headless_slsk.rs). It is not marked "downloaded"; that is the
|
||||
// whole difference, and it thins out as rows are heard or kept.
|
||||
let unresolved = kind == "unresolved";
|
||||
let sub = if unresolved {
|
||||
format!("{artist} · unresolved")
|
||||
} else if file.is_none() {
|
||||
format!("{artist} · needs the app")
|
||||
} else {
|
||||
match &album {
|
||||
Some(al) if !al.is_empty() => format!("{artist} · {al}"),
|
||||
_ => artist.clone(),
|
||||
}
|
||||
};
|
||||
// No catalog cover: the one in the file's own tag, if it has one;
|
||||
// then what the cover hunt has found; and a row still blank is
|
||||
// handed to the hunt, which re-lists this playlist on the car
|
||||
// when it has an answer (cover_hunt.rs).
|
||||
let art = art
|
||||
.or_else(|| {
|
||||
file.as_ref()
|
||||
.and_then(|p| embedded_cover(data_dir, p))
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
})
|
||||
.or_else(|| {
|
||||
if kind != "stream" {
|
||||
return None;
|
||||
}
|
||||
let found = crate::cover_hunt::cached(data_dir, &artist, &title);
|
||||
if found.is_none() {
|
||||
crate::cover_hunt::request(crate::cover_hunt::Job {
|
||||
data_dir: data_dir.to_path_buf(),
|
||||
item_id: id,
|
||||
artist: artist.clone(),
|
||||
title: title.clone(),
|
||||
duration,
|
||||
parent: format!("ss:playlist:{playlist_id}"),
|
||||
});
|
||||
}
|
||||
found
|
||||
});
|
||||
Ok(Node {
|
||||
id: format!("ss:pitem:{id}"),
|
||||
title,
|
||||
@@ -499,7 +593,7 @@ fn playlist_items(conn: &Connection, data_dir: &Path, playlist_id: i64) -> rusql
|
||||
browsable: false,
|
||||
playable: !unresolved,
|
||||
art,
|
||||
path: file.map(|(p, _)| p.to_string_lossy().into_owned()),
|
||||
path: file.map(|p| p.to_string_lossy().into_owned()),
|
||||
})
|
||||
})?;
|
||||
rows.collect()
|
||||
@@ -592,7 +686,7 @@ pub(crate) fn resolve_playable(
|
||||
id,
|
||||
PlayTrack {
|
||||
id: Some(id.to_string()),
|
||||
path: PathBuf::from(r.get::<_, String>(1)?),
|
||||
path: Some(PathBuf::from(r.get::<_, String>(1)?)),
|
||||
title: r.get(2)?,
|
||||
artist: r.get(3)?,
|
||||
duration: r.get::<_, Option<i64>>(4)?.map(|s| s as f64),
|
||||
@@ -611,12 +705,13 @@ pub(crate) fn resolve_playable(
|
||||
let (rows, from) = album_tracks(id.parse::<i64>().ok()?).ok()?;
|
||||
return Some((rows.into_iter().map(|(_, t)| t).collect(), 0, from));
|
||||
}
|
||||
// A playlist plays the entries this process can: its local files and the
|
||||
// streamed rows whose cache copy is whole, in order, skipping the ones
|
||||
// that need the resolver. Silently dropping those is the right call
|
||||
// here: the row that led here already said "4 of 9 here", so the gap was
|
||||
// declared before the tap rather than discovered after it.
|
||||
let playlist_here = |playlist_id: i64| -> rusqlite::Result<(Vec<(i64, PlayTrack)>, String)> {
|
||||
// A playlist plays EVERY row, in order, exactly as the page would: the
|
||||
// local files and whole cache copies from their files, and the rows
|
||||
// whose bytes are not here found on the network when the queue reaches
|
||||
// them — the remembered peer file first, else a search — with the next
|
||||
// few fetched ahead (`headless.rs`). Only a row the page itself could
|
||||
// not play (`unresolved`, no title) is left out.
|
||||
let playlist_rows = |playlist_id: i64| -> rusqlite::Result<(Vec<(i64, PlayTrack)>, String)> {
|
||||
let name: String = conn
|
||||
.query_row("SELECT name FROM playlists WHERE id = ?1", [playlist_id], |r| r.get(0))
|
||||
.unwrap_or_default();
|
||||
@@ -641,11 +736,41 @@ pub(crate) fn resolve_playable(
|
||||
let mut out = Vec::new();
|
||||
for row in rows.flatten() {
|
||||
let (id, title, artist, album, duration, path, art, kind, track_id) = row;
|
||||
let Some((file, stream)) =
|
||||
row_file(dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title)
|
||||
else {
|
||||
if title.trim().is_empty() || !(kind == "local" || kind == "stream") {
|
||||
continue;
|
||||
};
|
||||
}
|
||||
let (file, stream) =
|
||||
row_file(dir, &kind, path.as_deref(), track_id.as_deref(), &artist, &title);
|
||||
if kind == "local" && file.is_none() {
|
||||
continue;
|
||||
}
|
||||
// No catalog cover: the file's own, so the playback screen and
|
||||
// the colour the car washes it with are the record's, not the
|
||||
// app icon's; else what the cover hunt has found, and a row
|
||||
// still blank is handed to it.
|
||||
let art = art
|
||||
.or_else(|| {
|
||||
file.as_ref()
|
||||
.and_then(|f| embedded_cover(dir, f))
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
})
|
||||
.or_else(|| {
|
||||
if kind != "stream" {
|
||||
return None;
|
||||
}
|
||||
let found = crate::cover_hunt::cached(dir, &artist, &title);
|
||||
if found.is_none() {
|
||||
crate::cover_hunt::request(crate::cover_hunt::Job {
|
||||
data_dir: dir.to_path_buf(),
|
||||
item_id: id,
|
||||
artist: artist.clone(),
|
||||
title: title.clone(),
|
||||
duration,
|
||||
parent: format!("ss:playlist:{playlist_id}"),
|
||||
});
|
||||
}
|
||||
found
|
||||
});
|
||||
out.push((
|
||||
id,
|
||||
PlayTrack {
|
||||
@@ -663,7 +788,7 @@ pub(crate) fn resolve_playable(
|
||||
Ok((out, name))
|
||||
};
|
||||
if let Some(id) = media_id.strip_prefix("ss:playlist:") {
|
||||
let (rows, from) = playlist_here(id.parse::<i64>().ok()?).ok()?;
|
||||
let (rows, from) = playlist_rows(id.parse::<i64>().ok()?).ok()?;
|
||||
return Some((rows.into_iter().map(|(_, t)| t).collect(), 0, from));
|
||||
}
|
||||
if let Some(id) = media_id.strip_prefix("ss:pitem:") {
|
||||
@@ -675,10 +800,9 @@ pub(crate) fn resolve_playable(
|
||||
|r| r.get(0),
|
||||
)
|
||||
.ok()?;
|
||||
let (rows, from) = playlist_here(playlist_id).ok()?;
|
||||
// The tapped row itself must be playable here, or the tap means a
|
||||
// hand-off — starting the playlist from a different row than the one
|
||||
// under the driver's finger would be a lie.
|
||||
let (rows, from) = playlist_rows(playlist_id).ok()?;
|
||||
// The tapped row is where the queue starts — the one under the
|
||||
// driver's finger, never a neighbour of it.
|
||||
let idx = rows.iter().position(|(i, _)| *i == item_id)?;
|
||||
return Some((rows.into_iter().map(|(_, t)| t).collect(), idx, from));
|
||||
}
|
||||
@@ -836,10 +960,12 @@ extern "C" {
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_soulstream_mediasession_AutoNative_browse(
|
||||
mut env: JNIEnv,
|
||||
_this: JObject,
|
||||
this: JObject,
|
||||
data_dir: JString,
|
||||
parent: JString,
|
||||
) -> jstring {
|
||||
// The class, for the pump's calls back into Kotlin — see headless.rs.
|
||||
crate::headless::remember_auto_native(&mut env, &this);
|
||||
// Read both strings before anything else borrows `env`; a closure over it
|
||||
// would have to be `mut` and then collide with the hand-back below.
|
||||
let dir: Option<String> = env.get_string(&data_dir).ok().map(Into::into);
|
||||
@@ -872,11 +998,12 @@ pub extern "system" fn Java_com_soulstream_mediasession_AutoNative_browse(
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_soulstream_mediasession_AutoNative_play(
|
||||
mut env: JNIEnv,
|
||||
_this: JObject,
|
||||
this: JObject,
|
||||
data_dir: JString,
|
||||
media_id: JString,
|
||||
start_ms: jni::sys::jlong,
|
||||
) -> jstring {
|
||||
crate::headless::remember_auto_native(&mut env, &this);
|
||||
let dir: Option<String> = env.get_string(&data_dir).ok().map(Into::into);
|
||||
let id: Option<String> = env.get_string(&media_id).ok().map(Into::into);
|
||||
let out = match (dir, id) {
|
||||
@@ -1052,9 +1179,10 @@ pub extern "system" fn Java_com_soulstream_mediasession_AutoNative_shuffle(
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_soulstream_mediasession_AutoNative_transport(
|
||||
mut env: JNIEnv,
|
||||
_this: JObject,
|
||||
this: JObject,
|
||||
action: JString,
|
||||
) {
|
||||
crate::headless::remember_auto_native(&mut env, &this);
|
||||
let Some(a) = env.get_string(&action).ok().map(String::from) else {
|
||||
return;
|
||||
};
|
||||
|
||||
+51
-16
@@ -515,27 +515,62 @@ pub(crate) async fn login_inner(
|
||||
cfg.shared_folders = shares;
|
||||
cfg.description = "Shared with SoulStream".into();
|
||||
|
||||
// The previous session's listener releases its port a moment after
|
||||
// shutdown; retry briefly instead of failing with WSAEADDRINUSE.
|
||||
let (client, mut events) = {
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match Client::connect(cfg.clone()).await {
|
||||
Ok(pair) => break pair,
|
||||
Err(e) if attempt < 8 && e.to_string().contains("10048") => {
|
||||
attempt += 1;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
// A car may already have signed this process in (headless_slsk.rs) to
|
||||
// stream a row before the page existed. Take that session over rather
|
||||
// than logging in again — two logins from one address in quick
|
||||
// succession is what the server throttles — and read its events from
|
||||
// here on; the fetch in flight keeps going on the same client.
|
||||
#[cfg(target_os = "android")]
|
||||
let adopted = crate::headless_slsk::adopt().map(|(client, user)| {
|
||||
log::info!("soulseek: adopting the car's session as {user}");
|
||||
(client, crate::headless_slsk::subscribe())
|
||||
});
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let adopted: Option<(Client, tokio::sync::mpsc::UnboundedReceiver<Event>)> = None;
|
||||
|
||||
let (client, mut events, greeting) = match adopted {
|
||||
Some((client, events)) => {
|
||||
// The car's queue may be fetching the rows ahead of it. Those
|
||||
// downloads are the page's preloads from here on: their
|
||||
// completion reaches the page as `soulseek:preload`, the same
|
||||
// way its own next-track fetches do, and the page's queue —
|
||||
// which took the car's over (`restoreSession`'s handover) —
|
||||
// appends them for the gapless boundary as they land.
|
||||
#[cfg(target_os = "android")]
|
||||
if let (Some(audio), Some(ps)) =
|
||||
(crate::headless::audio_if_up(), app.try_state::<PlayerState>())
|
||||
{
|
||||
let mut preloads = ps.preloads.lock().unwrap();
|
||||
for (id, cache) in audio.fetches_in_flight() {
|
||||
preloads.entry(id).or_insert(cache);
|
||||
}
|
||||
Err(e) => return Err(format!("could not reach server: {e}")),
|
||||
}
|
||||
(client, events, "adopted".to_string())
|
||||
}
|
||||
None => {
|
||||
// The previous session's listener releases its port a moment after
|
||||
// shutdown; retry briefly instead of failing with WSAEADDRINUSE.
|
||||
let (client, events) = {
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match Client::connect(cfg.clone()).await {
|
||||
Ok(pair) => break pair,
|
||||
Err(e) if attempt < 8 && e.to_string().contains("10048") => {
|
||||
attempt += 1;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
}
|
||||
Err(e) => return Err(format!("could not reach server: {e}")),
|
||||
}
|
||||
}
|
||||
};
|
||||
let greeting = client
|
||||
.login(&username, &password)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
(client, events, greeting)
|
||||
}
|
||||
};
|
||||
|
||||
let greeting = client
|
||||
.login(&username, &password)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if remember {
|
||||
let mut save = stored.clone();
|
||||
save.username = username.clone();
|
||||
|
||||
@@ -535,6 +535,14 @@ pub fn remember_secrets_dir(app: &tauri::AppHandle) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The same, from a process that has no `AppHandle` — the media service a
|
||||
/// car starts cold, which needs the stored password to sign in to Soulseek
|
||||
/// for a row the phone does not hold yet (headless_slsk.rs).
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn remember_secrets_dir_path(dir: &std::path::Path) {
|
||||
let _ = SECRETS_DIR.set(dir.to_path_buf());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
fn secrets_path() -> Option<PathBuf> {
|
||||
let dir = SECRETS_DIR.get()?;
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
//! Covers for rows the catalog was never asked about — in the process that
|
||||
//! has no page to ask for them.
|
||||
//!
|
||||
//! The car draws the app icon over a row with no cover, and a browse of a
|
||||
//! pasted-tracklist playlist is mostly such rows. The page fills them in
|
||||
//! the background when the app is up (`src/mobile/coverart.svelte.js`); a
|
||||
//! car that starts the app COLD has no page, so this does the same from
|
||||
//! Rust: the catalog's track search (the metadata crate, the same Deezer
|
||||
//! field queries the page's ladder asks), and a match only when the artist
|
||||
//! agrees, the title agrees once its version wording is set aside, the
|
||||
//! versions are compatible, and a known duration confirms rather than
|
||||
//! contradicts. `src/lib/catalogMatch.js` is the reference for every rule
|
||||
//! here and this is its twin for a process with no JavaScript — keep them
|
||||
//! in step. A loose lookup once put one record's cover on seven unrelated
|
||||
//! songs, so no match means no art; a blank tile is the honest answer.
|
||||
//!
|
||||
//! What is found is written on the ROW (`playlist_items.art_url`, and the
|
||||
//! track id beside it) — the one place the page, the car and the resume
|
||||
//! point all read. The library is WAL and this is a second connection
|
||||
//! from a second process, which SQLite was built for; the page's own
|
||||
//! backfill writes the same column through `playlist_relink_item`, and
|
||||
//! both only ever fill a NULL. What was asked is remembered beside the
|
||||
//! extracted covers (`<library>/.soulstream/stream-art/catalog.json`), a
|
||||
//! miss for a day, so a cold browse does not re-ask the catalog thirty
|
||||
//! times about rows it already said no to.
|
||||
//!
|
||||
//! The browse answers at once with what is known; the rest is looked up
|
||||
//! on one thread, one row at a time behind the metadata client's own
|
||||
//! Deezer pacing, and each row found re-lists its parent on the car
|
||||
//! (`AutoNative.headlessCovers` → `notifyChildrenChanged`).
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A row that wants a cover.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Job {
|
||||
pub data_dir: PathBuf,
|
||||
pub item_id: i64,
|
||||
pub artist: String,
|
||||
pub title: String,
|
||||
pub duration: Option<f64>,
|
||||
/// The browse parent to re-list on the car once this row has its cover.
|
||||
pub parent: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize)]
|
||||
struct Known {
|
||||
/// `None` is a real answer: the catalog was asked and nothing cleared
|
||||
/// the bar.
|
||||
url: Option<String>,
|
||||
#[serde(default)]
|
||||
track_id: Option<u64>,
|
||||
/// Unix seconds; a miss expires after [`MISS_TTL`].
|
||||
at: u64,
|
||||
/// The matcher that answered. A miss from an older one is no answer:
|
||||
/// the shelf rung arrived after a "no" for Nirvana's studio cut had
|
||||
/// been remembered for the day, and the new rung never got to run
|
||||
/// (2026-09-18). Bump [`HUNT_VERSION`] whenever a rung is added.
|
||||
#[serde(default)]
|
||||
v: u32,
|
||||
}
|
||||
|
||||
const MISS_TTL: u64 = 24 * 3600;
|
||||
const HUNT_VERSION: u32 = 2;
|
||||
|
||||
static CACHE: Mutex<Option<(PathBuf, HashMap<String, Known>)>> = Mutex::new(None);
|
||||
static QUEUE: Mutex<VecDeque<Job>> = Mutex::new(VecDeque::new());
|
||||
static WORKING: Mutex<bool> = Mutex::new(false);
|
||||
/// Behind an `Arc` because the shelf walk takes `self: &Arc<Self>`.
|
||||
static CLIENT: OnceLock<std::sync::Arc<metadata::MetadataClient>> = OnceLock::new();
|
||||
/// When the catalog last returned anything at all. A row every query
|
||||
/// comes back empty for is a MISS while the catalog is demonstrably
|
||||
/// answering (a single-word underground title, 2026-09-18: four empty
|
||||
/// lists), and "unreachable" only when nothing has answered for a while.
|
||||
static LAST_ANSWER: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
const REACHABLE_FOR: Duration = Duration::from_secs(120);
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn cache_file(data_dir: &Path) -> Option<PathBuf> {
|
||||
Some(
|
||||
crate::auto_browse::db_path(data_dir)
|
||||
.parent()?
|
||||
.join("stream-art")
|
||||
.join("catalog.json"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The remembered answers, read once per process.
|
||||
fn with_cache<R>(data_dir: &Path, f: impl FnOnce(&mut HashMap<String, Known>) -> R) -> R {
|
||||
let mut guard = lock(&CACHE);
|
||||
let Some(file) = cache_file(data_dir) else {
|
||||
let mut empty = HashMap::new();
|
||||
return f(&mut empty);
|
||||
};
|
||||
if guard.as_ref().is_none_or(|(p, _)| *p != file) {
|
||||
let map: HashMap<String, Known> = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
*guard = Some((file, map));
|
||||
}
|
||||
let (_, map) = guard.as_mut().expect("cache just loaded");
|
||||
f(map)
|
||||
}
|
||||
|
||||
fn save(data_dir: &Path) {
|
||||
let guard = lock(&CACHE);
|
||||
let Some((file, map)) = guard.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if cache_file(data_dir).as_ref() != Some(file) {
|
||||
return;
|
||||
}
|
||||
if let Some(parent) = file.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(s) = serde_json::to_string(map) {
|
||||
let tmp = file.with_extension("json.tmp");
|
||||
if std::fs::write(&tmp, s).is_ok() {
|
||||
let _ = std::fs::rename(&tmp, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn key_of(artist: &str, title: &str) -> String {
|
||||
format!("{}|{}", name_norm(artist), name_norm(title))
|
||||
}
|
||||
|
||||
/// A cover already found for this track, if any. Never asks anything.
|
||||
pub(crate) fn cached(data_dir: &Path, artist: &str, title: &str) -> Option<String> {
|
||||
if artist.trim().is_empty() || title.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let key = key_of(artist, title);
|
||||
with_cache(data_dir, |map| map.get(&key).and_then(|k| k.url.clone()))
|
||||
}
|
||||
|
||||
/// Answered already — a cover, or a miss that has not expired.
|
||||
fn known(data_dir: &Path, artist: &str, title: &str) -> bool {
|
||||
let key = key_of(artist, title);
|
||||
let now = now_secs();
|
||||
with_cache(data_dir, |map| {
|
||||
map.get(&key).is_some_and(|k| {
|
||||
k.url.is_some() || (k.v >= HUNT_VERSION && now.saturating_sub(k.at) < MISS_TTL)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Ask for this row's cover in the background. Nothing happens for a row
|
||||
/// already answered or already waiting.
|
||||
pub(crate) fn request(job: Job) {
|
||||
if job.artist.trim().is_empty() || job.title.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
if known(&job.data_dir, &job.artist, &job.title) {
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut q = lock(&QUEUE);
|
||||
if q.iter().any(|j| j.item_id == job.item_id) {
|
||||
return;
|
||||
}
|
||||
q.push_back(job);
|
||||
}
|
||||
let mut working = lock(&WORKING);
|
||||
if *working {
|
||||
return;
|
||||
}
|
||||
*working = true;
|
||||
drop(working);
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("cover-hunt".into())
|
||||
.spawn(work);
|
||||
}
|
||||
|
||||
fn work() {
|
||||
// parents with a row newly covered, re-listed on the car at most every
|
||||
// couple of seconds, and once more when the queue runs dry
|
||||
let mut pending: HashSet<String> = HashSet::new();
|
||||
let mut last_notice = Instant::now() - Duration::from_secs(10);
|
||||
loop {
|
||||
let job = lock(&QUEUE).pop_front();
|
||||
let Some(job) = job else {
|
||||
break;
|
||||
};
|
||||
// the same track may sit in several playlists; one answer serves all
|
||||
let found = lookup(&job.data_dir, &job.artist, &job.title, job.duration, false);
|
||||
if let Some((url, track_id)) = found {
|
||||
persist(&job.data_dir, job.item_id, &job.artist, &job.title, &url, track_id);
|
||||
pending.insert(job.parent.clone());
|
||||
}
|
||||
if !pending.is_empty() && last_notice.elapsed() >= Duration::from_secs(2) {
|
||||
for p in pending.drain() {
|
||||
notify(&p);
|
||||
}
|
||||
last_notice = Instant::now();
|
||||
}
|
||||
}
|
||||
for p in pending.drain() {
|
||||
notify(&p);
|
||||
}
|
||||
*lock(&WORKING) = false;
|
||||
// a request that landed between the last pop and the flag
|
||||
if !lock(&QUEUE).is_empty() {
|
||||
let mut working = lock(&WORKING);
|
||||
if !*working {
|
||||
*working = true;
|
||||
drop(working);
|
||||
let _ = std::thread::Builder::new().name("cover-hunt".into()).spawn(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(parent: &str) {
|
||||
let json = serde_json::json!({ "parent": parent }).to_string();
|
||||
crate::headless::call_auto_native("headlessCovers", &json);
|
||||
}
|
||||
|
||||
/// How long the shelf walk may take for the track that is PLAYING. It
|
||||
/// opens up to thirty tracklists behind the Deezer pacing, and a card
|
||||
/// that gets its cover four minutes in has not really got it.
|
||||
const SHELF_PATIENCE: Duration = Duration::from_secs(40);
|
||||
/// A miss that ended in a timeout is asked again sooner than a real one.
|
||||
const SHORT_MISS: u64 = 3600;
|
||||
|
||||
/// The catalog's cover for this track, strictly — remembered either way.
|
||||
/// Blocks for the lookups; call from a thread of your own. `deep` adds the
|
||||
/// page's last rung, the artist's whole shelf flattened to tracks — spent
|
||||
/// on the track someone is listening to, not on every row of a browse:
|
||||
/// the search rungs answer most rows in half a second, the shelf walk is
|
||||
/// the expensive exception, and the phone's own walk (which does run it)
|
||||
/// writes what it finds on the row for the car to read.
|
||||
pub(crate) fn lookup(
|
||||
data_dir: &Path,
|
||||
artist: &str,
|
||||
title: &str,
|
||||
duration: Option<f64>,
|
||||
deep: bool,
|
||||
) -> Option<(String, Option<u64>)> {
|
||||
if artist.trim().is_empty() || title.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let key = key_of(artist, title);
|
||||
let now = now_secs();
|
||||
let remembered = with_cache(data_dir, |map| map.get(&key).cloned());
|
||||
if let Some(k) = remembered {
|
||||
if let Some(url) = k.url {
|
||||
return Some((url, k.track_id));
|
||||
}
|
||||
if k.v >= HUNT_VERSION && now.saturating_sub(k.at) < MISS_TTL {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let client = CLIENT.get_or_init(|| std::sync::Arc::new(metadata::MetadataClient::new()));
|
||||
let want_dur = duration.map(|d| d.round() as u32).filter(|d| *d > 0);
|
||||
let mut hit: Option<metadata::CatalogTrack> = None;
|
||||
let mut answered = false;
|
||||
for q in queries(artist, title) {
|
||||
let tracks = crate::headless_slsk::rt().block_on(client.catalog_search_tracks(&q, 10));
|
||||
// the client folds "down" and "nothing" into one empty list; a
|
||||
// list with anything in it proves the catalog is answering
|
||||
if !tracks.is_empty() {
|
||||
answered = true;
|
||||
*lock(&LAST_ANSWER) = Some(Instant::now());
|
||||
}
|
||||
if let Some(t) = pick(&tracks, artist, title, want_dur) {
|
||||
hit = Some(t.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The page's last rung: the artist's whole shelf, flattened to tracks,
|
||||
// for records the search index buries — Deezer's search answers
|
||||
// "Nirvana Smells Like Teen Spirit" with six live takes and never the
|
||||
// studio cut (2026-09-18), while Nevermind's own tracklist has it.
|
||||
let mut ran_out = false;
|
||||
if hit.is_none() && deep {
|
||||
let lead = primary_artist(artist);
|
||||
let walk = client.catalog_artist_track_candidates(&lead, title);
|
||||
let shelf = crate::headless_slsk::rt()
|
||||
.block_on(async { tokio::time::timeout(SHELF_PATIENCE, walk).await.ok() });
|
||||
match shelf {
|
||||
Some(tracks) => {
|
||||
if !tracks.is_empty() {
|
||||
answered = true;
|
||||
*lock(&LAST_ANSWER) = Some(Instant::now());
|
||||
}
|
||||
hit = pick(&tracks, artist, title, want_dur).cloned();
|
||||
}
|
||||
None => {
|
||||
ran_out = true;
|
||||
crate::auto_browse::warn(&format!(
|
||||
"cover hunt: the shelf walk for '{artist}' ran out of time"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let found = hit.and_then(|t| t.cover.as_deref().map(|c| (hq_cover(c), Some(t.id))));
|
||||
let reachable = answered
|
||||
|| lock(&LAST_ANSWER).is_some_and(|at| at.elapsed() < REACHABLE_FOR);
|
||||
if found.is_none() && !reachable {
|
||||
// offline, or the catalog unreachable: not a miss
|
||||
crate::auto_browse::warn(&format!("cover hunt: catalog unreachable for '{title}'"));
|
||||
return None;
|
||||
}
|
||||
with_cache(data_dir, |map| {
|
||||
map.insert(
|
||||
key,
|
||||
Known {
|
||||
url: found.as_ref().map(|(u, _)| u.clone()),
|
||||
track_id: found.as_ref().and_then(|(_, id)| *id),
|
||||
// a miss cut short by the clock is asked again within the
|
||||
// hour, not the day
|
||||
at: if ran_out && found.is_none() { now.saturating_sub(MISS_TTL - SHORT_MISS) } else { now },
|
||||
v: HUNT_VERSION,
|
||||
},
|
||||
);
|
||||
});
|
||||
save(data_dir);
|
||||
match &found {
|
||||
Some((u, _)) => crate::auto_browse::warn(&format!("cover hunt: '{artist} — {title}' → {u}")),
|
||||
None => crate::auto_browse::warn(&format!("cover hunt: nothing certain for '{artist} — {title}'")),
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Write the cover on the row — and on every other stream row of the same
|
||||
/// track that has none. Only a NULL is ever filled.
|
||||
fn persist(data_dir: &Path, item_id: i64, artist: &str, title: &str, url: &str, track_id: Option<u64>) {
|
||||
let db = crate::auto_browse::db_path(data_dir);
|
||||
let Ok(conn) = rusqlite::Connection::open(&db) else {
|
||||
return;
|
||||
};
|
||||
let _ = conn.busy_timeout(Duration::from_secs(3));
|
||||
let updated = conn.execute(
|
||||
"UPDATE playlist_items SET art_url = ?1
|
||||
WHERE art_url IS NULL AND art_path IS NULL AND kind = 'stream'
|
||||
AND (id = ?2 OR (lower(artist) = lower(?3) AND lower(title) = lower(?4)))",
|
||||
rusqlite::params![url, item_id, artist, title],
|
||||
);
|
||||
if let Some(id) = track_id {
|
||||
let _ = conn.execute(
|
||||
"UPDATE playlist_items SET track_id = ?1
|
||||
WHERE (track_id IS NULL OR track_id = '') AND kind = 'stream'
|
||||
AND (id = ?2 OR (lower(artist) = lower(?3) AND lower(title) = lower(?4)))",
|
||||
rusqlite::params![id.to_string(), item_id, artist, title],
|
||||
);
|
||||
}
|
||||
if let Err(e) = updated {
|
||||
crate::auto_browse::warn(&format!("cover hunt: could not write row {item_id}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/* ── the matcher: catalogMatch.js, in Rust ─────────────────────────── */
|
||||
|
||||
/// Fold to comparable letters and digits: case, accents and punctuation
|
||||
/// all differ freely between a tag, a tracklist line and a catalog row.
|
||||
/// (`nameNorm`: NFKD there; a table of the Latin accents here.)
|
||||
pub(crate) fn name_norm(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut space = true;
|
||||
let push = |c: char, out: &mut String, space: &mut bool| {
|
||||
if c.is_alphanumeric() {
|
||||
out.push(c);
|
||||
*space = false;
|
||||
} else if !*space {
|
||||
out.push(' ');
|
||||
*space = true;
|
||||
}
|
||||
};
|
||||
for c in s.chars() {
|
||||
if c == '&' {
|
||||
for a in " and ".chars() {
|
||||
push(a, &mut out, &mut space);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for lc in c.to_lowercase() {
|
||||
match fold(lc) {
|
||||
Some(folded) => {
|
||||
for fc in folded.chars() {
|
||||
push(fc, &mut out, &mut space);
|
||||
}
|
||||
}
|
||||
None => push(lc, &mut out, &mut space),
|
||||
}
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
fn fold(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => "a",
|
||||
'æ' => "ae",
|
||||
'ç' | 'ć' | 'č' => "c",
|
||||
'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ė' | 'ę' | 'ě' => "e",
|
||||
'ì' | 'í' | 'î' | 'ï' | 'ī' | 'į' => "i",
|
||||
'ñ' | 'ń' | 'ň' => "n",
|
||||
'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ő' => "o",
|
||||
'œ' => "oe",
|
||||
'ù' | 'ú' | 'û' | 'ü' | 'ū' | 'ů' | 'ű' => "u",
|
||||
'ý' | 'ÿ' => "y",
|
||||
'ß' => "ss",
|
||||
'š' | 'ś' => "s",
|
||||
'ž' | 'ź' | 'ż' => "z",
|
||||
'ł' => "l",
|
||||
'đ' => "d",
|
||||
'ř' => "r",
|
||||
'ť' => "t",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A different MASTER of one performance: same recording, repackaged.
|
||||
const EDITION_WORDS: &[&str] = &[
|
||||
"remaster", "remastered", "remasterd", "stereo", "mono", "deluxe", "anniversary", "reissue",
|
||||
"expanded", "digital", "album version", "single version", "original version", "radio edit",
|
||||
"explicit", "clean", "bonus", "mix master", "from the vault",
|
||||
];
|
||||
/// A different PERFORMANCE: another take, another artist's hands on it.
|
||||
const IDENTITY_WORDS: &[&str] = &[
|
||||
"remix", "live", "acoustic", "instrumental", "demo", "cover", "karaoke", "unplugged", "reprise",
|
||||
"vip", "bootleg", "session", "rework", "flip", "mashup", "dub", "edit", "mix", "version", "take",
|
||||
"alternate", "orchestral", "piano", "8 bit", "tribute", "originally", "made famous",
|
||||
];
|
||||
|
||||
/// `phrase` as whole words inside an already-normalized string.
|
||||
fn has_phrase(norm: &str, phrase: &str) -> bool {
|
||||
format!(" {norm} ").contains(&format!(" {phrase} "))
|
||||
}
|
||||
|
||||
fn is_year(norm: &str) -> bool {
|
||||
norm.len() == 4 && norm.chars().all(|c| c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// What a qualifier means for identity: "none", a different master
|
||||
/// ("edition"), or a different performance ("identity"). An unrecognized
|
||||
/// qualifier counts as a different performance — the strict reading.
|
||||
fn qualifier_class(qualifier: &str) -> &'static str {
|
||||
let n = name_norm(qualifier);
|
||||
if n.is_empty() {
|
||||
return "none";
|
||||
}
|
||||
let first = n.split(' ').next().unwrap_or("");
|
||||
if ["feat", "featuring", "ft", "with", "w"].contains(&first) {
|
||||
return "edition";
|
||||
}
|
||||
if is_year(&n) {
|
||||
return "edition";
|
||||
}
|
||||
if EDITION_WORDS.iter().any(|w| has_phrase(&n, w)) {
|
||||
return "edition";
|
||||
}
|
||||
"identity"
|
||||
}
|
||||
|
||||
/// "Title (2011 Remaster)" / "Title - Remastered 2011" / "Title -album
|
||||
/// version-" → the base name and the trailing qualifier(s). One trailing
|
||||
/// group per pass, repeatedly.
|
||||
pub(crate) fn split_version(title: &str) -> (String, String) {
|
||||
let mut base = title.trim().to_owned();
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let before = base.clone();
|
||||
if let Some((b, q)) = trailing_bracket(&base) {
|
||||
base = b;
|
||||
parts.push(q);
|
||||
continue;
|
||||
}
|
||||
if let Some((b, q)) = dashes_both_sides(&base) {
|
||||
base = b;
|
||||
parts.push(q);
|
||||
continue;
|
||||
}
|
||||
let dashed = base
|
||||
.rsplit_once(" - ")
|
||||
.map(|(b, tail)| (b.trim().to_owned(), tail.trim().to_owned()));
|
||||
if let Some((b, tail)) = dashed {
|
||||
let t = name_norm(&tail);
|
||||
let qualifier = EDITION_WORDS.iter().any(|w| has_phrase(&t, w))
|
||||
|| IDENTITY_WORDS.iter().any(|w| has_phrase(&t, w))
|
||||
|| is_year(&t);
|
||||
if qualifier && !b.is_empty() {
|
||||
base = b;
|
||||
parts.push(tail);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if base == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
parts.reverse();
|
||||
(base, parts.join(" "))
|
||||
}
|
||||
|
||||
/// "Name (group)" at the very end, the group holding no opening bracket.
|
||||
fn trailing_bracket(s: &str) -> Option<(String, String)> {
|
||||
let t = s.trim_end();
|
||||
let close = t.chars().last()?;
|
||||
let open = match close {
|
||||
')' => '(',
|
||||
']' => '[',
|
||||
'}' => '{',
|
||||
_ => return None,
|
||||
};
|
||||
let start = t.rfind(open)?;
|
||||
let inner = &t[start + open.len_utf8()..t.len() - close.len_utf8()];
|
||||
if inner.contains(['(', '[', '{']) {
|
||||
return None;
|
||||
}
|
||||
let head = t[..start].trim_end();
|
||||
if head.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((head.to_owned(), inner.trim().to_owned()))
|
||||
}
|
||||
|
||||
/// "Title -album version-": dashes on both sides of the tail.
|
||||
fn dashes_both_sides(s: &str) -> Option<(String, String)> {
|
||||
let t = s.trim_end();
|
||||
let t = t.strip_suffix('-')?.trim_end();
|
||||
let cut = t.rfind(" -")?;
|
||||
let head = t[..cut].trim_end();
|
||||
let tail = t[cut + 2..].trim();
|
||||
if head.is_empty() || tail.is_empty() || tail.contains('-') {
|
||||
return None;
|
||||
}
|
||||
Some((head.to_owned(), tail.to_owned()))
|
||||
}
|
||||
|
||||
/// The comma-separated lead artist; never split on "&" or "and".
|
||||
fn primary_artist(artist: &str) -> String {
|
||||
let first = artist.split(',').next().unwrap_or("").trim();
|
||||
if first.is_empty() {
|
||||
artist.trim().to_owned()
|
||||
} else {
|
||||
first.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// The act without its backing band: "Joan Jett and the Blackhearts" →
|
||||
/// "joan jett" (normalized). Only a trailing "and the …" / "with …" comes
|
||||
/// off, never a bare word.
|
||||
fn band_core(artist: &str) -> String {
|
||||
let n = name_norm(artist);
|
||||
let mut best: Option<usize> = None;
|
||||
for sep in [" and ", " with "] {
|
||||
for (i, _) in n.match_indices(sep) {
|
||||
let rest = &n[i + sep.len()..];
|
||||
let rest = rest.strip_prefix("the ").unwrap_or(rest);
|
||||
if i > 0 && !rest.trim().is_empty() {
|
||||
best = Some(best.map_or(i, |b| b.min(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
match best {
|
||||
Some(i) => n[..i].trim().to_owned(),
|
||||
None => n,
|
||||
}
|
||||
}
|
||||
|
||||
/// Do these two artist strings name the same act?
|
||||
fn artist_agrees(want: &str, cand: &str) -> bool {
|
||||
let w = name_norm(want);
|
||||
let c = name_norm(cand);
|
||||
if w.is_empty() || c.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if w == c {
|
||||
return true;
|
||||
}
|
||||
let wp = name_norm(&primary_artist(want));
|
||||
let cp = name_norm(&primary_artist(cand));
|
||||
if wp == c || cp == w || (!wp.is_empty() && wp == cp) {
|
||||
return true;
|
||||
}
|
||||
let wc = band_core(&wp);
|
||||
let cc = band_core(&cp);
|
||||
(!wc.is_empty() && (wc == c || wc == cc)) || (!cc.is_empty() && cc == w)
|
||||
}
|
||||
|
||||
/// Durations both sides know that disagree by more than this are
|
||||
/// different cuts; within [`DURATION_CONFIRM_SECS`] the duration confirms.
|
||||
const DURATION_TOLERANCE_SECS: u32 = 20;
|
||||
const DURATION_CONFIRM_SECS: u32 = 7;
|
||||
|
||||
/// The best catalog track for the wanted one, or `None` when nothing
|
||||
/// clears the bar — `pickCatalogMatch`, rule for rule.
|
||||
pub(crate) fn pick<'a>(
|
||||
tracks: &'a [metadata::CatalogTrack],
|
||||
want_artist: &str,
|
||||
want_title: &str,
|
||||
want_dur: Option<u32>,
|
||||
) -> Option<&'a metadata::CatalogTrack> {
|
||||
let (want_base_raw, want_qual_raw) = split_version(want_title);
|
||||
let want_base = name_norm(&want_base_raw);
|
||||
let want_class = qualifier_class(&want_qual_raw);
|
||||
let want_qual = name_norm(&want_qual_raw);
|
||||
if want_base.is_empty() || name_norm(want_artist).is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut best: Option<&metadata::CatalogTrack> = None;
|
||||
let mut best_score = f64::MIN;
|
||||
for t in tracks {
|
||||
if !artist_agrees(want_artist, &t.artist) {
|
||||
continue;
|
||||
}
|
||||
let (cand_base_raw, cand_qual_raw) = split_version(&t.title);
|
||||
let cand_base = name_norm(&cand_base_raw);
|
||||
let cand_class = qualifier_class(&cand_qual_raw);
|
||||
let cand_qual = name_norm(&cand_qual_raw);
|
||||
if cand_base.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let shorter = cand_base.len().min(want_base.len());
|
||||
let longer = cand_base.len().max(want_base.len());
|
||||
let title_score = if cand_base == want_base {
|
||||
4.0
|
||||
} else if (cand_base.contains(&want_base) || want_base.contains(&cand_base))
|
||||
&& shorter >= 6
|
||||
&& (shorter as f64) / (longer as f64) >= 0.6
|
||||
{
|
||||
2.0
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if want_class == "identity" || cand_class == "identity" {
|
||||
let shared = !want_qual.is_empty()
|
||||
&& !cand_qual.is_empty()
|
||||
&& want_qual
|
||||
.split(' ')
|
||||
.any(|w| w.len() > 2 && cand_qual.contains(w));
|
||||
if !shared {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let both_know = want_dur.is_some() && t.duration_secs.is_some_and(|d| d > 0);
|
||||
let delta = if both_know {
|
||||
Some(t.duration_secs.unwrap_or(0).abs_diff(want_dur.unwrap_or(0)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(d) = delta {
|
||||
if d > DURATION_TOLERANCE_SECS {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let mut score = title_score;
|
||||
if delta.is_some_and(|d| d <= DURATION_CONFIRM_SECS) {
|
||||
score += 2.0;
|
||||
}
|
||||
if want_class == cand_class {
|
||||
score += 1.0;
|
||||
}
|
||||
score += (t.rank.unwrap_or(0) as f64 / 1_000_000.0).min(1.0);
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best = Some(t);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Quote-safe value for Deezer's field search syntax.
|
||||
fn q(s: &str) -> String {
|
||||
s.replace(['"', '\\'], " ").trim().to_owned()
|
||||
}
|
||||
|
||||
/// The queries to try for one wanted track, strongest first — the page's
|
||||
/// `catalogQueries`: the precise field syntax with the base name, the
|
||||
/// band-core spelling, the full name, then the blunt way.
|
||||
pub(crate) fn queries(artist: &str, title: &str) -> Vec<String> {
|
||||
let artist_q = q(&primary_artist(artist));
|
||||
let full = q(title);
|
||||
let base = q(&split_version(title).0);
|
||||
let core = q(&band_core(&artist_q));
|
||||
let mut out = Vec::new();
|
||||
if !artist_q.is_empty() && !base.is_empty() {
|
||||
out.push(format!("artist:\"{artist_q}\" track:\"{base}\""));
|
||||
}
|
||||
if !core.is_empty() && !base.is_empty() && core != name_norm(&artist_q) {
|
||||
out.push(format!("artist:\"{core}\" track:\"{base}\""));
|
||||
}
|
||||
if !artist_q.is_empty() && !full.is_empty() && full != base {
|
||||
out.push(format!("artist:\"{artist_q}\" track:\"{full}\""));
|
||||
}
|
||||
if !artist_q.is_empty() && !base.is_empty() {
|
||||
out.push(format!("{artist_q} {base}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The largest Deezer rendition of a cover URL (`hqCover`).
|
||||
pub(crate) fn hq_cover(url: &str) -> String {
|
||||
let host_ok = url
|
||||
.split("://")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('/').next())
|
||||
.is_some_and(|h| h.ends_with("dzcdn.net"));
|
||||
if !host_ok {
|
||||
return url.to_owned();
|
||||
}
|
||||
let Some((head, seg)) = url.rsplit_once('/') else {
|
||||
return url.to_owned();
|
||||
};
|
||||
// "250x250-000000-80-0-0.jpg" → "1000x1000-000000-80-0-0.jpg"
|
||||
let digits = |s: &str| s.chars().take_while(|c| c.is_ascii_digit()).count();
|
||||
let w = digits(seg);
|
||||
if !(2..=4).contains(&w) || seg[w..].chars().next() != Some('x') {
|
||||
return url.to_owned();
|
||||
}
|
||||
let h = digits(&seg[w + 1..]);
|
||||
if !(2..=4).contains(&h) {
|
||||
return url.to_owned();
|
||||
}
|
||||
let rest = &seg[w + 1 + h..];
|
||||
let ext_ok = rest.rsplit_once('.').is_some_and(|(_, e)| {
|
||||
matches!(e.to_ascii_lowercase().as_str(), "jpg" | "png" | "webp")
|
||||
});
|
||||
if !ext_ok || !(rest.starts_with('-') || rest.starts_with('.')) {
|
||||
return url.to_owned();
|
||||
}
|
||||
format!("{head}/1000x1000{rest}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn versions_split_like_the_page() {
|
||||
assert_eq!(split_version("Bohemian Rhapsody - Remastered 2011").0, "Bohemian Rhapsody");
|
||||
assert_eq!(split_version("Lola (Stereo Remastered 2020) [Bonus]").0, "Lola");
|
||||
assert_eq!(split_version("Kiss - Detroit Rock City").0, "Kiss - Detroit Rock City");
|
||||
assert_eq!(split_version("A-Punk").0, "A-Punk");
|
||||
let (b, qual) = split_version("Parking Lot - VIGILE Remix");
|
||||
assert_eq!(b, "Parking Lot");
|
||||
assert_eq!(qualifier_class(&qual), "identity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artists_agree_like_the_page() {
|
||||
assert!(artist_agrees("Joan Jett and the Blackhearts", "Joan Jett"));
|
||||
assert!(artist_agrees("Ennio Morricone, Joan Baez", "Ennio Morricone"));
|
||||
assert!(!artist_agrees("Queen", "Queen Latifah"));
|
||||
assert_eq!(band_core("Joan Jett and the Blackhearts"), "joan jett");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn covers_upscale() {
|
||||
assert_eq!(
|
||||
hq_cover("https://cdn-images.dzcdn.net/images/cover/abc/250x250-000000-80-0-0.jpg"),
|
||||
"https://cdn-images.dzcdn.net/images/cover/abc/1000x1000-000000-80-0-0.jpg"
|
||||
);
|
||||
assert_eq!(hq_cover("https://i.ytimg.com/vi/x/maxresdefault.jpg"), "https://i.ytimg.com/vi/x/maxresdefault.jpg");
|
||||
}
|
||||
}
|
||||
+730
-157
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,436 @@
|
||||
//! A Soulseek session for a process with no page — so a row the phone does
|
||||
//! not hold yet can be found and streamed from the car.
|
||||
//!
|
||||
//! "Needs the app" was the honest label for what the cold service could not
|
||||
//! do: the resolver and the Soulseek session live in the page, and a car
|
||||
//! that starts the app cold has no page. Kyle's answer to that label was the
|
||||
//! right one — a tap should find a copy and play it, in the background —
|
||||
//! and this is the smallest thing that does it: the stored account signs
|
||||
//! in from here, one search, the best copy by rules close to the page's
|
||||
//! (`src/lib/sources.js` songCandidates), a download into the same stream
|
||||
//! cache the page uses, and the engine plays the bytes as they land, the
|
||||
//! way `play_stream` does for the page.
|
||||
//!
|
||||
//! **One session per process, and the page adopts it.** When the app opens
|
||||
//! over a car session, `commands::login_inner` takes this client instead of
|
||||
//! logging in again (two logins from one address in quick succession is
|
||||
//! what the server throttles), and every event from here on is forwarded to
|
||||
//! the page's own pump through [`subscribe`]. The download in flight keeps
|
||||
//! going: dropping a `Client` handle does not tear the connection down.
|
||||
//!
|
||||
//! Its own tokio runtime, because there is no Tauri one in a process the
|
||||
//! car started; the two coexist when the app comes up.
|
||||
|
||||
use player::StreamProgress;
|
||||
use soulseek_client::{Client, Config, DownloadState, Event};
|
||||
use soulseek_proto::types::SearchResponse;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::auto_browse::warn;
|
||||
|
||||
static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
|
||||
/// The handle, until the page adopts it.
|
||||
static CLIENT: Mutex<Option<Client>> = Mutex::new(None);
|
||||
/// Signed in, from this process's point of view.
|
||||
static CONNECTED: Mutex<Option<String>> = Mutex::new(None);
|
||||
/// token → the responses that came back for it.
|
||||
static SEARCHES: Mutex<Vec<(u32, Vec<SearchResponse>)>> = Mutex::new(Vec::new());
|
||||
/// download id → the progress the engine is reading.
|
||||
static DOWNLOADS: Mutex<Vec<(u64, Arc<StreamProgress>)>> = Mutex::new(Vec::new());
|
||||
/// The server's excluded search phrases, lowercased — a query containing
|
||||
/// one returns nothing network-wide.
|
||||
static EXCLUDED: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Where the page's pump listens once it exists.
|
||||
static SUBSCRIBER: Mutex<Option<mpsc::UnboundedSender<Event>>> = Mutex::new(None);
|
||||
|
||||
pub(crate) fn rt() -> &'static tokio::runtime::Runtime {
|
||||
RT.get_or_init(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.thread_name("slsk-cold")
|
||||
.build()
|
||||
.expect("a tokio runtime for the cold Soulseek session")
|
||||
})
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// True once this process has signed in (and the page has not yet adopted
|
||||
/// the session — after adoption the page's own state is the truth).
|
||||
pub fn connected() -> bool {
|
||||
lock(&CONNECTED).is_some() && lock(&CLIENT).is_some()
|
||||
}
|
||||
|
||||
/// The library root, the way auto_browse derives it: `download_dir` from
|
||||
/// config.json, else `<data_dir>/Library`.
|
||||
fn library_dir(data_dir: &Path) -> PathBuf {
|
||||
std::fs::read_to_string(data_dir.join("config.json"))
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
|
||||
.and_then(|v| v.get("download_dir").and_then(|d| d.as_str()).map(str::to_owned))
|
||||
.filter(|s| !s.is_empty())
|
||||
.map_or_else(|| data_dir.join("Library"), PathBuf::from)
|
||||
}
|
||||
|
||||
/// Sign in with the stored account, once. Blocks the caller — a car tap
|
||||
/// arrives on a worker thread that may wait — for up to ~20 s.
|
||||
pub fn ensure_session(data_dir: &Path) -> Result<(), String> {
|
||||
if connected() {
|
||||
return Ok(());
|
||||
}
|
||||
crate::config::remember_secrets_dir_path(data_dir);
|
||||
let cfg_json = std::fs::read_to_string(data_dir.join("config.json"))
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let username = cfg_json
|
||||
.get("username")
|
||||
.and_then(|u| u.as_str())
|
||||
.map(str::to_owned)
|
||||
.filter(|u| !u.is_empty())
|
||||
.ok_or("no Soulseek account on this phone")?;
|
||||
let password = crate::config::load_password(&username)
|
||||
.ok_or("the Soulseek account is not signed in on this phone")?;
|
||||
|
||||
let mut cfg = Config::default();
|
||||
if let Some(p) = cfg_json.get("listen_port").and_then(|p| p.as_u64()) {
|
||||
cfg.listen_port = p as u16;
|
||||
}
|
||||
let downloads = library_dir(data_dir);
|
||||
cfg.downloads_dir = downloads.clone();
|
||||
cfg.shared_folders = vec![downloads];
|
||||
cfg.description = "Shared with SoulStream".into();
|
||||
|
||||
let (client, events) = rt()
|
||||
.block_on(async {
|
||||
let (client, events) =
|
||||
tokio::time::timeout(Duration::from_secs(15), Client::connect(cfg))
|
||||
.await
|
||||
.map_err(|_| "could not reach the Soulseek server in time".to_string())?
|
||||
.map_err(|e| format!("could not reach the Soulseek server: {e}"))?;
|
||||
tokio::time::timeout(Duration::from_secs(15), client.login(&username, &password))
|
||||
.await
|
||||
.map_err(|_| "Soulseek did not answer the sign-in in time".to_string())?
|
||||
.map_err(|e| format!("Soulseek refused the sign-in: {e}"))?;
|
||||
Ok::<_, String>((client, events))
|
||||
})?;
|
||||
warn(&format!("cold soulseek: signed in as {username}"));
|
||||
*lock(&CLIENT) = Some(client);
|
||||
*lock(&CONNECTED) = Some(username);
|
||||
rt().spawn(consume(events));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The one consumer of the session's events: search replies and download
|
||||
/// progress land in the tables above, and everything is forwarded to the
|
||||
/// page's pump once one has subscribed.
|
||||
async fn consume(mut events: mpsc::UnboundedReceiver<Event>) {
|
||||
while let Some(ev) = events.recv().await {
|
||||
match &ev {
|
||||
Event::SearchResult { token, response } => {
|
||||
let mut s = lock(&SEARCHES);
|
||||
if let Some((_, list)) = s.iter_mut().find(|(t, _)| t == token) {
|
||||
list.push(response.clone());
|
||||
}
|
||||
}
|
||||
Event::Download(u) => {
|
||||
let progress = lock(&DOWNLOADS)
|
||||
.iter()
|
||||
.find(|(id, _)| *id == u.id)
|
||||
.map(|(_, p)| p.clone());
|
||||
if let Some(p) = progress {
|
||||
let (done, failed) = match &u.state {
|
||||
DownloadState::Complete { .. } => (true, None),
|
||||
DownloadState::Failed { reason } => (false, Some(reason.clone())),
|
||||
DownloadState::Cancelled => (false, Some("stream cancelled".to_string())),
|
||||
_ => (false, None),
|
||||
};
|
||||
p.update(u.received, done, failed);
|
||||
if done {
|
||||
lock(&DOWNLOADS).retain(|(id, _)| *id != u.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::ExcludedSearchPhrases(p) => {
|
||||
*lock(&EXCLUDED) = p.iter().map(|s| s.to_lowercase()).collect();
|
||||
}
|
||||
Event::Disconnected { reason } => {
|
||||
warn(&format!("cold soulseek: disconnected ({reason})"));
|
||||
*lock(&CONNECTED) = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(tx) = lock(&SUBSCRIBER).as_ref() {
|
||||
let _ = tx.send(ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page taking the session over: the client handle, and the account.
|
||||
/// `None` when there is nothing to adopt (the page then signs in itself).
|
||||
pub fn adopt() -> Option<(Client, String)> {
|
||||
let client = lock(&CLIENT).take()?;
|
||||
let user = lock(&CONNECTED).clone()?;
|
||||
Some((client, user))
|
||||
}
|
||||
|
||||
/// Where the page's pump reads this session's events from after adoption.
|
||||
pub fn subscribe() -> mpsc::UnboundedReceiver<Event> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
*lock(&SUBSCRIBER) = Some(tx);
|
||||
rx
|
||||
}
|
||||
|
||||
/* ── finding a copy ───────────────────────────────────────────────────── */
|
||||
|
||||
/// Streamable, the page's list (RESOLVER_STREAMABLE).
|
||||
const STREAMABLE: [&str; 8] = ["flac", "mp3", "m4a", "ogg", "opus", "wav", "aiff", "aif"];
|
||||
const LOSSLESS: [&str; 4] = ["flac", "wav", "aiff", "aif"];
|
||||
|
||||
/// Lowercased, punctuation folded to spaces, whitespace collapsed — the
|
||||
/// page's normText, near enough for a contains() test.
|
||||
fn norm(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut space = true;
|
||||
for c in s.chars().flat_map(|c| c.to_lowercase()) {
|
||||
if c.is_alphanumeric() {
|
||||
out.push(c);
|
||||
space = false;
|
||||
} else if !space {
|
||||
out.push(' ');
|
||||
space = true;
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
/// The page's `simplifyTitle`, for the query: the title up to the first
|
||||
/// `; : ( [`, and its first six words. The full title still has to be in
|
||||
/// the filename.
|
||||
fn simplify(title: &str) -> String {
|
||||
let first = title
|
||||
.split(|c| c == ';' || c == ':' || c == '(' || c == '[')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim();
|
||||
let base = if first.is_empty() { title } else { first };
|
||||
let words: Vec<&str> = base.split_whitespace().take(6).collect();
|
||||
let out = words.join(" ");
|
||||
if out.is_empty() {
|
||||
title.to_owned()
|
||||
} else {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pick {
|
||||
pub username: String,
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub duration: Option<f64>,
|
||||
pub score: i64,
|
||||
pub slot: bool,
|
||||
}
|
||||
|
||||
/// The best copies of a track on the network, best first. With
|
||||
/// `require_identity` — the page's `requireIdentityEvidence`, for a rung
|
||||
/// that searched by title alone — the artist has to appear somewhere in
|
||||
/// the peer's path, or the copy is another artist's song of that name.
|
||||
fn candidates(
|
||||
responses: &[SearchResponse],
|
||||
title: &str,
|
||||
artist: &str,
|
||||
expect_secs: Option<f64>,
|
||||
require_identity: bool,
|
||||
) -> Vec<Pick> {
|
||||
let want = norm(title);
|
||||
let want_short = norm(&simplify(title));
|
||||
let artist_key = norm(artist);
|
||||
let mut out: Vec<Pick> = Vec::new();
|
||||
for r in responses {
|
||||
for f in &r.files {
|
||||
let name = f.filename.rsplit('\\').next().unwrap_or(&f.filename);
|
||||
let stem = name.rsplit_once('.').map(|(s, _)| s).unwrap_or(name);
|
||||
let nname = norm(stem);
|
||||
if !(nname.contains(&want) || (!want_short.is_empty() && nname.contains(&want_short))) {
|
||||
continue;
|
||||
}
|
||||
let ext = f.extension.to_lowercase();
|
||||
if !STREAMABLE.contains(&ext.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if f.size == 0 || f.size > 400 * 1024 * 1024 {
|
||||
continue;
|
||||
}
|
||||
let bitrate = f.attributes.iter().find(|(k, _)| *k == 0).map(|(_, v)| *v);
|
||||
let duration = f.attributes.iter().find(|(k, _)| *k == 1).map(|(_, v)| *v as f64);
|
||||
if let (Some(want), Some(got)) = (expect_secs, duration) {
|
||||
// the page's durationMismatch: a copy that is not the same
|
||||
// recording — a radio edit, a live take — is not this song
|
||||
if (want - got).abs() > (want * 0.08).max(8.0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let lossless = LOSSLESS.contains(&ext.as_str());
|
||||
let mut score: i64 = if lossless { 3000 } else { 1000 };
|
||||
if let Some(b) = bitrate {
|
||||
score += (b.min(400) as i64) * 2;
|
||||
}
|
||||
if f.size < 800 * 1024 {
|
||||
score -= 2000; // a snippet, not the song
|
||||
}
|
||||
let path_n = norm(&f.filename);
|
||||
let artist_evidence = !artist_key.is_empty() && path_n.contains(&artist_key);
|
||||
if require_identity && !artist_key.is_empty() && !artist_evidence {
|
||||
continue;
|
||||
}
|
||||
if artist_evidence {
|
||||
score += 400;
|
||||
}
|
||||
if nname.ends_with(&want) {
|
||||
score += 250;
|
||||
}
|
||||
if r.queue_length > 0 {
|
||||
score -= (r.queue_length.min(50) as i64) * 20;
|
||||
}
|
||||
out.push(Pick {
|
||||
username: r.username.clone(),
|
||||
path: f.filename.clone(),
|
||||
size: f.size,
|
||||
duration,
|
||||
score,
|
||||
slot: r.has_free_upload_slot,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.score.cmp(&a.score));
|
||||
// Streaming needs bytes NOW: peers with a free slot first, best within
|
||||
// each half (the page's rule, learned on "Da Funk" 2026-08-03).
|
||||
let (free, busy): (Vec<Pick>, Vec<Pick>) = out.into_iter().partition(|p| p.slot);
|
||||
free.into_iter().chain(busy).collect()
|
||||
}
|
||||
|
||||
fn strip_excluded(query: &str) -> String {
|
||||
let excluded = lock(&EXCLUDED).clone();
|
||||
let mut words: Vec<&str> = query.split_whitespace().collect();
|
||||
for phrase in &excluded {
|
||||
let lower = query.to_lowercase();
|
||||
if lower.contains(phrase.as_str()) {
|
||||
let bad: Vec<&str> = phrase.split_whitespace().collect();
|
||||
words.retain(|w| !bad.iter().any(|b| w.eq_ignore_ascii_case(b)));
|
||||
}
|
||||
}
|
||||
words.join(" ")
|
||||
}
|
||||
|
||||
/// Every word of the artist still in the query, after the server's
|
||||
/// excluded phrases came out of it.
|
||||
fn keeps_artist(query: &str, artist: &str) -> bool {
|
||||
let q = norm(query);
|
||||
let words: Vec<&str> = q.split(' ').collect();
|
||||
norm(artist)
|
||||
.split(' ')
|
||||
.filter(|w| !w.is_empty())
|
||||
.all(|w| words.contains(&w))
|
||||
}
|
||||
|
||||
/// The page's ladder for a song (`streamSong`): artist + simplified title,
|
||||
/// then the simplified title alone. Each rung is one search, a few seconds
|
||||
/// of replies, the best copies; the first rung that produces any wins. A
|
||||
/// rung without the artist in it — the second, or the first once the
|
||||
/// server's excluded phrases took the artist out — matches by title
|
||||
/// alone, so the artist has to appear in the peer's path instead.
|
||||
pub fn find(title: &str, artist: &str, expect_secs: Option<f64>) -> Result<Vec<Pick>, String> {
|
||||
let simple = simplify(title);
|
||||
let rungs = [format!("{artist} {simple}"), simple.clone()];
|
||||
for raw in rungs {
|
||||
let stripped = strip_excluded(&raw);
|
||||
let query = if stripped.trim().is_empty() { raw.clone() } else { stripped };
|
||||
if query.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let require_identity = !keeps_artist(&query, artist);
|
||||
// the client may spawn onto its runtime from any call; this thread
|
||||
// is not on it (see `fetch`)
|
||||
let _rt = rt().enter();
|
||||
let token = {
|
||||
let guard = lock(&CLIENT);
|
||||
let client = guard.as_ref().ok_or("not signed in to Soulseek")?;
|
||||
client.search(&query).map_err(|e| e.to_string())?
|
||||
};
|
||||
lock(&SEARCHES).push((token, Vec::new()));
|
||||
let started = Instant::now();
|
||||
let mut best: Vec<Pick> = Vec::new();
|
||||
let mut files = 0usize;
|
||||
// Up to eight seconds; done early once a dozen usable copies are in.
|
||||
while started.elapsed() < Duration::from_secs(8) {
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
let responses = lock(&SEARCHES)
|
||||
.iter()
|
||||
.find(|(t, _)| *t == token)
|
||||
.map(|(_, r)| r.clone())
|
||||
.unwrap_or_default();
|
||||
files = responses.iter().map(|r| r.files.len()).sum();
|
||||
best = candidates(&responses, title, artist, expect_secs, require_identity);
|
||||
if best.len() >= 12 && started.elapsed() > Duration::from_millis(2500) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(client) = lock(&CLIENT).as_ref() {
|
||||
client.stop_search(token);
|
||||
}
|
||||
lock(&SEARCHES).retain(|(t, _)| *t != token);
|
||||
warn(&format!("cold soulseek: '{query}' → {files} files, {} copies", best.len()));
|
||||
if !best.is_empty() {
|
||||
return Ok(best);
|
||||
}
|
||||
}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Start fetching a peer's copy into the stream cache. Returns the cache
|
||||
/// path, the partial path the bytes land in, the progress the engine reads,
|
||||
/// and the download id.
|
||||
pub fn fetch(
|
||||
data_dir: &Path,
|
||||
username: &str,
|
||||
path: &str,
|
||||
size: u64,
|
||||
) -> Result<(PathBuf, PathBuf, Arc<StreamProgress>, u64), String> {
|
||||
let dir = crate::playback::cache_dir_in(data_dir);
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let cache = crate::playback::cache_file_in(&dir, username, path);
|
||||
let partial = crate::playback::partial_path(&cache);
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
let progress = StreamProgress::new();
|
||||
let id = {
|
||||
// `download_to` spawns the transfer task with `tokio::spawn`, which
|
||||
// needs a runtime on the CALLING thread — and the caller here is
|
||||
// the engine's resolver thread, not a Tauri command. Without this
|
||||
// the spawn panics, the thread dies without a word (a cold process
|
||||
// has no stderr in logcat), and the card sits on BUFFERING for as
|
||||
// long as anyone looks (2026-09-18, the first cold fetch).
|
||||
let _rt = rt().enter();
|
||||
let guard = lock(&CLIENT);
|
||||
let client = guard.as_ref().ok_or("not signed in to Soulseek")?;
|
||||
client.download_to(username, path, size, cache.clone())
|
||||
};
|
||||
lock(&DOWNLOADS).push((id, progress.clone()));
|
||||
Ok((cache, partial, progress, id))
|
||||
}
|
||||
|
||||
/// Give up on a fetch that never delivered.
|
||||
pub fn cancel(id: u64) {
|
||||
let _rt = rt().enter();
|
||||
if let Some(client) = lock(&CLIENT).as_ref() {
|
||||
client.cancel_download(id);
|
||||
}
|
||||
lock(&DOWNLOADS).retain(|(i, _)| *i != id);
|
||||
}
|
||||
@@ -11,6 +11,15 @@ mod commands;
|
||||
/// process that has no Activity — and so there is never a second one.
|
||||
#[cfg(target_os = "android")]
|
||||
mod headless;
|
||||
/// A Soulseek session for a process with no page, so a row the phone does
|
||||
/// not hold yet is found and streamed from the car — and adopted by the
|
||||
/// page when the app opens over it.
|
||||
#[cfg(target_os = "android")]
|
||||
mod headless_slsk;
|
||||
/// Covers for rows the catalog was never asked about, from the process
|
||||
/// with no page to ask — the page's cover walk, in Rust, for the car.
|
||||
#[cfg(target_os = "android")]
|
||||
mod cover_hunt;
|
||||
mod community;
|
||||
mod config;
|
||||
mod cover_logo;
|
||||
@@ -121,6 +130,13 @@ pub fn run() {
|
||||
thumbbar::init(app.handle());
|
||||
playback::init(app.handle());
|
||||
playback::prune_cache(app.handle());
|
||||
// Hover previews are the desktop's (ANDROID.md, "Off by design"),
|
||||
// and their init opens TWO more output streams — on the phone
|
||||
// that was three live AAudio streams per launch for one that
|
||||
// ever sounds (seen 2026-09-18 in `dumpsys audio`). The phone
|
||||
// never calls a preview command, so nothing here misses the
|
||||
// state.
|
||||
#[cfg(not(target_os = "android"))]
|
||||
preview::init(app.handle());
|
||||
loudness::init(app.handle());
|
||||
diagnostics::init(app.handle());
|
||||
|
||||
@@ -208,7 +208,7 @@ pub fn init(app: &tauri::AppHandle) {
|
||||
plays next and two things advancing one engine would skip a track each
|
||||
time. Nothing about the desktop changes. */
|
||||
#[cfg(target_os = "android")]
|
||||
let (player, events, handover) = {
|
||||
let (player, events, handover, first) = {
|
||||
if let Ok(dir) = crate::paths::app_data(app) {
|
||||
crate::headless::set_data_dir(&dir);
|
||||
}
|
||||
@@ -221,12 +221,33 @@ pub fn init(app: &tauri::AppHandle) {
|
||||
// older session of its own over live audio.
|
||||
let handover = if audio.driving() { audio.resume_point() } else { None };
|
||||
audio.clear_queue();
|
||||
(audio.player.clone(), rx, handover)
|
||||
// What the engine is doing RIGHT NOW, for a page that is about to
|
||||
// ask. The snapshot below is otherwise built from the events that
|
||||
// arrive after this subscription — and an engine a car started was
|
||||
// playing before there was anyone to tell, so no Playing ever
|
||||
// arrives: the page read "idle", called the handover a paused
|
||||
// session that needed re-sourcing, and pushed PAUSED to the card
|
||||
// over audio that kept going (2026-09-18, Strictly Acid at 21 s).
|
||||
let (position, sounding) = audio.progress();
|
||||
let first = PlaybackSnapshot {
|
||||
status: if sounding { "playing".into() } else { "idle".into() },
|
||||
position: if sounding { position } else { 0.0 },
|
||||
duration: None,
|
||||
};
|
||||
(audio.player.clone(), rx, handover, first)
|
||||
};
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let (player, events, handover) = {
|
||||
let (player, events, handover, first) = {
|
||||
let (p, e) = Player::spawn_with_device(output_device);
|
||||
(p, e, None)
|
||||
(
|
||||
p,
|
||||
e,
|
||||
None,
|
||||
PlaybackSnapshot {
|
||||
status: "idle".into(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
};
|
||||
app.manage(PlayerState {
|
||||
handover: Mutex::new(handover),
|
||||
@@ -238,10 +259,7 @@ pub fn init(app: &tauri::AppHandle) {
|
||||
waveform_jobs: Mutex::new(HashMap::new()),
|
||||
preloads: Mutex::new(HashMap::new()),
|
||||
deferred_saves: Mutex::new(HashMap::new()),
|
||||
last_transport: Mutex::new(PlaybackSnapshot {
|
||||
status: "idle".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
last_transport: Mutex::new(first),
|
||||
});
|
||||
|
||||
let handle = app.clone();
|
||||
|
||||
Reference in new issue
Block a user