feat(qbzd): add search verb + GET /api/search (CONSOLE P1 row 19)
First slice of Proposal A (CONSOLE): qbzd can originate discovery — search Qobuz by name from the CLI, not only receive via QConnect or take track ids by hand. - api/search.rs: GET /api/search?q=&type=&limit=&offset=. Typed searches return SearchResultsPage<T> verbatim under a per-category key; type=all fans out to the four typed searches. Auth-gated (needs_auth); blacklist fail-open by design (documented GUI-parity delta). - api/mod.rs: new P1_ROUTES table + p1_route_table test — the shipped-caller HARD RULE (§3.1.4) applied to the content-verb door; route registered. - cli/search.rs: `qbzd search <q> [--type all|albums|tracks|artists| playlists] [--limit N] [--offset N] [--ids] [--json]`. --ids emits ids one-per-line (pipes into `queue add -`); frozen exit-code table. Verified: `cargo check -p qbzd` clean (no warnings); `cargo test -p qbzd --bin qbzd` → 248 passed, 0 failed (10 new + 238 existing). New files are standard-rustfmt; existing files carry only the minimal logical edits. cc
This commit is contained in:
5 files changed
+594
-1
No files matched your search
@@ -16,6 +16,7 @@
|
||||
// what keeps the 01-architecture.md §8.1 boot order honest.
|
||||
pub mod playback;
|
||||
pub mod queue;
|
||||
pub mod search;
|
||||
pub mod settings;
|
||||
pub mod status;
|
||||
|
||||
@@ -59,6 +60,15 @@ pub const P0_ROUTES: &[(&str, &str)] = &[
|
||||
("POST", "/api/settings/reload"),
|
||||
];
|
||||
|
||||
/// The P1 route table (02 §3.4) — the content-verb surface. SAME HARD RULE as
|
||||
/// P0 (§3.1.4): a route exists only iff a shipped CLI/TUI client calls it, and
|
||||
/// this table grows one row per verb+route pair in the SAME change as the verb.
|
||||
/// Row 19 (this change): `GET /api/search` — caller: `qbzd search`. The
|
||||
/// `p1_route_table_grows_only_with_a_shipped_caller` test pins the count and
|
||||
/// forbids overlap with P0, so the 68-routes failure shape cannot creep in
|
||||
/// through the P1 door either.
|
||||
pub const P1_ROUTES: &[(&str, &str)] = &[("GET", "/api/search")];
|
||||
|
||||
/// A socket bound at boot step 5, not yet serving. Wraps the tiny_http server
|
||||
/// in an `Arc` so the serving thread and the shutdown handle can both hold it
|
||||
/// (`unblock` from the handle terminates the thread's `incoming_requests`).
|
||||
@@ -193,7 +203,12 @@ pub fn probe_is_qbzd(addr: SocketAddr) -> bool {
|
||||
pub fn serve(server: BoundServer, state: ApiState) -> ApiHandle {
|
||||
// The counted P0 surface — logged at boot so an operator sees exactly how
|
||||
// many routes this build exposes (and it anchors the const to production).
|
||||
log::info!("control plane serving {} P0 route(s)", P0_ROUTES.len());
|
||||
log::info!(
|
||||
"control plane serving {} route(s) ({} P0 + {} P1)",
|
||||
P0_ROUTES.len() + P1_ROUTES.len(),
|
||||
P0_ROUTES.len(),
|
||||
P1_ROUTES.len()
|
||||
);
|
||||
let srv = server.server;
|
||||
let srv_handle = srv.clone();
|
||||
let thread = std::thread::Builder::new()
|
||||
@@ -253,6 +268,7 @@ fn route(state: &ApiState, req: &mut Request) -> Response<Cursor<Vec<u8>>> {
|
||||
let body = read_json_body(req);
|
||||
playback::volume(state, &body)
|
||||
}
|
||||
("GET", "/api/search") => search::search(state, &query),
|
||||
("GET", "/api/queue") => queue::list(state, &query),
|
||||
("POST", "/api/queue/add") => {
|
||||
let body = read_json_body(req);
|
||||
@@ -414,6 +430,19 @@ mod tests {
|
||||
assert!(P0_ROUTES.contains(&("POST", "/api/settings/reload")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p1_route_table_grows_only_with_a_shipped_caller() {
|
||||
// 02-cli-and-api.md §3.4 — each P1 route lands with its CLI verb (the
|
||||
// §3.1.4 HARD RULE, applied to the content-verb door). Row 19:
|
||||
// GET /api/search — caller: `qbzd search`. Count is pinned so a route
|
||||
// with no caller cannot creep in; P1 must never overlap P0.
|
||||
assert_eq!(P1_ROUTES.len(), 1);
|
||||
assert!(P1_ROUTES.contains(&("GET", "/api/search")));
|
||||
for r in P1_ROUTES {
|
||||
assert!(!P0_ROUTES.contains(r), "{r:?} is duplicated across P0 and P1");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_time_eq_matches_only_identical_slices() {
|
||||
assert!(constant_time_eq(b"Bearer s3cret", b"Bearer s3cret"));
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
// crates/qbzd/src/api/search.rs — GET /api/search (02-cli-and-api.md §2.3/§3.4
|
||||
// row 19, P1). The first "originate playback" read verb: qbzd can now FIND
|
||||
// music by name, not only receive it via QConnect or take track ids by hand.
|
||||
//
|
||||
// Server-side shaping (stable, typed contract): typed searches return the
|
||||
// core's `SearchResultsPage<T>` (qbz-models/src/types.rs:811) verbatim under a
|
||||
// per-category key; `type=all` runs the four typed searches and assembles them
|
||||
// under one envelope. Reusing the shipped serde shapes keeps `--json` a frozen
|
||||
// machine surface (§3.1.4) instead of leaking `catalog_search`'s raw Qobuz JSON.
|
||||
//
|
||||
// Blacklist filtering is intentionally NOT applied — the daemon opens no
|
||||
// blacklist store (fail-open by design, qbz-core/src/core.rs:127-143); a
|
||||
// documented GUI-parity delta (results may include items the desktop hides).
|
||||
//
|
||||
// Auth: gates on `NeedsAuth` exactly like `queue::add` — the typed searches
|
||||
// call the Qobuz client, which is `CoreError::NotInitialized` without a session,
|
||||
// so a needs-auth daemon answers 409 (→ CLI exit 4) rather than a bare failure.
|
||||
use std::io::Cursor;
|
||||
|
||||
use serde_json::Value;
|
||||
use tiny_http::Response;
|
||||
|
||||
use crate::state::AuthState;
|
||||
|
||||
use super::{err_json, json, ApiState};
|
||||
|
||||
/// Default result count per category when the caller gives no `limit`.
|
||||
const DEFAULT_LIMIT: u32 = 20;
|
||||
/// Upper bound on `limit` — a control-plane search is top-hits, not a pager
|
||||
/// (deep paging belongs in the GUI). Silently clamped, never a 400.
|
||||
const MAX_LIMIT: u32 = 100;
|
||||
|
||||
/// `GET /api/search?q=&type=all|albums|tracks|artists|playlists&limit=&offset=`.
|
||||
/// `query` is the raw query string (no leading `?`); `route()` strips it off the
|
||||
/// path before dispatch. Errors: 409 `needs_auth`, 400 `bad_request` (missing
|
||||
/// query / unknown type), 502 `search_failed` (upstream Qobuz error).
|
||||
pub fn search(state: &ApiState, query: &str) -> Response<Cursor<Vec<u8>>> {
|
||||
if let Some(resp) = auth_gate(state) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
let params = match parse_query(query) {
|
||||
Ok(p) => p,
|
||||
Err((message, hint)) => return err_json(400, "bad_request", &message, &hint),
|
||||
};
|
||||
|
||||
// Which categories to fetch — `all` fans out to the four typed searches;
|
||||
// a typed request populates exactly one key (the rest stay `null`).
|
||||
let (do_albums, do_tracks, do_artists, do_playlists) = match params.stype {
|
||||
SearchType::All => (true, true, true, true),
|
||||
SearchType::One(Category::Albums) => (true, false, false, false),
|
||||
SearchType::One(Category::Tracks) => (false, true, false, false),
|
||||
SearchType::One(Category::Artists) => (false, false, true, false),
|
||||
SearchType::One(Category::Playlists) => (false, false, false, true),
|
||||
};
|
||||
|
||||
let mut albums = Value::Null;
|
||||
let mut tracks = Value::Null;
|
||||
let mut artists = Value::Null;
|
||||
let mut playlists = Value::Null;
|
||||
|
||||
if do_albums {
|
||||
match state.rt.block_on(state.runtime.core().search_albums(
|
||||
¶ms.q,
|
||||
params.limit,
|
||||
params.offset,
|
||||
None,
|
||||
)) {
|
||||
Ok(page) => albums = serde_json::to_value(page).unwrap_or(Value::Null),
|
||||
Err(_) => return upstream_error(),
|
||||
}
|
||||
}
|
||||
if do_tracks {
|
||||
match state.rt.block_on(state.runtime.core().search_tracks(
|
||||
¶ms.q,
|
||||
params.limit,
|
||||
params.offset,
|
||||
None,
|
||||
)) {
|
||||
Ok(page) => tracks = serde_json::to_value(page).unwrap_or(Value::Null),
|
||||
Err(_) => return upstream_error(),
|
||||
}
|
||||
}
|
||||
if do_artists {
|
||||
match state.rt.block_on(state.runtime.core().search_artists(
|
||||
¶ms.q,
|
||||
params.limit,
|
||||
params.offset,
|
||||
None,
|
||||
)) {
|
||||
Ok(page) => artists = serde_json::to_value(page).unwrap_or(Value::Null),
|
||||
Err(_) => return upstream_error(),
|
||||
}
|
||||
}
|
||||
if do_playlists {
|
||||
match state.rt.block_on(state.runtime.core().search_playlists(
|
||||
¶ms.q,
|
||||
params.limit,
|
||||
params.offset,
|
||||
)) {
|
||||
Ok(page) => playlists = serde_json::to_value(page).unwrap_or(Value::Null),
|
||||
Err(_) => return upstream_error(),
|
||||
}
|
||||
}
|
||||
|
||||
json(
|
||||
200,
|
||||
serde_json::json!({
|
||||
"query": params.q,
|
||||
"type": params.stype.as_str(),
|
||||
"limit": params.limit,
|
||||
"offset": params.offset,
|
||||
"albums": albums,
|
||||
"tracks": tracks,
|
||||
"artists": artists,
|
||||
"playlists": playlists,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// ============================ internals ============================
|
||||
|
||||
/// 409 `needs_auth` — search needs a live Qobuz session. Mirrors
|
||||
/// `queue::add`'s gate (this file's self-contained-helpers convention).
|
||||
fn auth_gate(state: &ApiState) -> Option<Response<Cursor<Vec<u8>>>> {
|
||||
let needs_auth = state
|
||||
.shared
|
||||
.lock()
|
||||
.map(|s| s.auth == AuthState::NeedsAuth)
|
||||
.unwrap_or(false);
|
||||
if needs_auth {
|
||||
Some(err_json(
|
||||
409,
|
||||
"needs_auth",
|
||||
"not logged in to Qobuz",
|
||||
"run: qbzd login",
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 502 for any upstream Qobuz/core failure. The code maps to CLI exit 1
|
||||
/// (`error_from_envelope`'s catch-all), never a panic. The `CoreError` is not
|
||||
/// interpolated (matches `queue::add`'s `Err(_)` discipline — the daemon does
|
||||
/// not leak upstream error text through the control plane).
|
||||
fn upstream_error() -> Response<Cursor<Vec<u8>>> {
|
||||
err_json(
|
||||
502,
|
||||
"search_failed",
|
||||
"search request to Qobuz failed",
|
||||
"try again in a moment; check: qbzd status",
|
||||
)
|
||||
}
|
||||
|
||||
/// The four searchable categories (`type=<one>`), plus the `all` fan-out.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Category {
|
||||
Albums,
|
||||
Tracks,
|
||||
Artists,
|
||||
Playlists,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum SearchType {
|
||||
All,
|
||||
One(Category),
|
||||
}
|
||||
|
||||
impl SearchType {
|
||||
/// The canonical `type` string echoed back in the response (matches the CLI
|
||||
/// flag values 1:1 so a script round-trips `--type` through `--json`).
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
SearchType::All => "all",
|
||||
SearchType::One(Category::Albums) => "albums",
|
||||
SearchType::One(Category::Tracks) => "tracks",
|
||||
SearchType::One(Category::Artists) => "artists",
|
||||
SearchType::One(Category::Playlists) => "playlists",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SearchParams {
|
||||
q: String,
|
||||
stype: SearchType,
|
||||
limit: u32,
|
||||
offset: u32,
|
||||
}
|
||||
|
||||
/// Parse `q`/`query` (percent-decoded), `type` (strict literal, default `all`),
|
||||
/// `limit` (clamped 1..=MAX, default 20), `offset` (default 0). A missing/blank
|
||||
/// query is a 400 (§1.4 error voice); an unknown `type` is a 400; malformed
|
||||
/// numeric params degrade to defaults (a read route never 400s on a bad number,
|
||||
/// mirroring `queue::parse_offset_limit`).
|
||||
fn parse_query(query: &str) -> Result<SearchParams, (String, String)> {
|
||||
let mut q: Option<String> = None;
|
||||
let mut stype = SearchType::All;
|
||||
let mut limit = DEFAULT_LIMIT;
|
||||
let mut offset = 0u32;
|
||||
|
||||
for pair in query.split('&') {
|
||||
if pair.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut kv = pair.splitn(2, '=');
|
||||
let key = kv.next().unwrap_or("");
|
||||
let val = kv.next().unwrap_or("");
|
||||
match key {
|
||||
"q" | "query" => {
|
||||
let decoded = urlencoding::decode(val)
|
||||
.map(|c| c.into_owned())
|
||||
.unwrap_or_else(|_| val.to_string());
|
||||
q = Some(decoded);
|
||||
}
|
||||
"type" => {
|
||||
stype = match val {
|
||||
"all" | "" => SearchType::All,
|
||||
"albums" => SearchType::One(Category::Albums),
|
||||
"tracks" => SearchType::One(Category::Tracks),
|
||||
"artists" => SearchType::One(Category::Artists),
|
||||
"playlists" => SearchType::One(Category::Playlists),
|
||||
other => {
|
||||
return Err((
|
||||
format!("unknown type '{other}'"),
|
||||
"type: all | albums | tracks | artists | playlists".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
}
|
||||
"limit" => {
|
||||
if let Ok(n) = val.parse::<u32>() {
|
||||
limit = n.clamp(1, MAX_LIMIT);
|
||||
}
|
||||
}
|
||||
"offset" => {
|
||||
if let Ok(n) = val.parse::<u32>() {
|
||||
offset = n;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let q = match q {
|
||||
Some(q) if !q.trim().is_empty() => q,
|
||||
_ => {
|
||||
return Err((
|
||||
"search requires a query".into(),
|
||||
"usage: qbzd search <QUERY>".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(SearchParams {
|
||||
q,
|
||||
stype,
|
||||
limit,
|
||||
offset,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_query_defaults_type_all_limit_20_offset_0() {
|
||||
let p = parse_query("q=spain").unwrap();
|
||||
assert_eq!(p.q, "spain");
|
||||
assert_eq!(p.stype, SearchType::All);
|
||||
assert_eq!(p.limit, 20);
|
||||
assert_eq!(p.offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_query_percent_decodes_the_query() {
|
||||
// `light as a feather` → space-encoded both ways.
|
||||
let p = parse_query("q=light%20as%20a%20feather").unwrap();
|
||||
assert_eq!(p.q, "light as a feather");
|
||||
let plus = parse_query("q=kind+of+blue").unwrap();
|
||||
// urlencoding treats `+` literally (RFC 3986); a real client encodes
|
||||
// spaces as %20, so `+` stays a plus — documented, not a bug.
|
||||
assert_eq!(plus.q, "kind+of+blue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_query_reads_each_typed_category() {
|
||||
assert_eq!(
|
||||
parse_query("q=x&type=albums").unwrap().stype,
|
||||
SearchType::One(Category::Albums)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_query("q=x&type=tracks").unwrap().stype,
|
||||
SearchType::One(Category::Tracks)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_query("q=x&type=artists").unwrap().stype,
|
||||
SearchType::One(Category::Artists)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_query("q=x&type=playlists").unwrap().stype,
|
||||
SearchType::One(Category::Playlists)
|
||||
);
|
||||
assert_eq!(parse_query("q=x&type=all").unwrap().stype, SearchType::All);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_query_rejects_missing_or_blank_query() {
|
||||
assert!(parse_query("").is_err());
|
||||
assert!(parse_query("type=albums").is_err());
|
||||
assert!(parse_query("q=").is_err());
|
||||
assert!(parse_query("q=%20%20").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_query_rejects_unknown_type() {
|
||||
let (message, _hint) = parse_query("q=x&type=songs").unwrap_err();
|
||||
assert_eq!(message, "unknown type 'songs'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_query_clamps_limit_and_ignores_bad_numbers() {
|
||||
assert_eq!(parse_query("q=x&limit=500").unwrap().limit, MAX_LIMIT);
|
||||
assert_eq!(parse_query("q=x&limit=0").unwrap().limit, 1);
|
||||
assert_eq!(parse_query("q=x&limit=nope").unwrap().limit, DEFAULT_LIMIT);
|
||||
assert_eq!(parse_query("q=x&offset=5").unwrap().offset, 5);
|
||||
assert_eq!(parse_query("q=x&offset=bad").unwrap().offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_type_as_str_round_trips_the_flag_values() {
|
||||
assert_eq!(SearchType::All.as_str(), "all");
|
||||
assert_eq!(SearchType::One(Category::Albums).as_str(), "albums");
|
||||
assert_eq!(SearchType::One(Category::Tracks).as_str(), "tracks");
|
||||
assert_eq!(SearchType::One(Category::Artists).as_str(), "artists");
|
||||
assert_eq!(SearchType::One(Category::Playlists).as_str(), "playlists");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
pub mod client;
|
||||
pub mod copy;
|
||||
pub mod queue;
|
||||
pub mod search;
|
||||
pub mod settings;
|
||||
pub mod status;
|
||||
pub mod transport;
|
||||
@@ -0,0 +1,210 @@
|
||||
// crates/qbzd/src/cli/search.rs — the `qbzd search` verb (02-cli-and-api.md
|
||||
// §2.3). A stateless renderer over one `GET /api/search` (§1.1): one verb, one
|
||||
// request. Three output modes — human top-hits table (default), `--ids` (ids
|
||||
// one-per-line, the composition currency for `... | qbzd queue add -`), and
|
||||
// `--json` (the raw api_version-stamped payload). Exit codes come from the
|
||||
// frozen table via `CliError` (§1.3): 0 · 3 unreachable · 4 needs_auth · 1 else.
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::cli::client::ApiClient;
|
||||
use crate::paths::ProfileRoots;
|
||||
|
||||
/// `qbzd search <QUERY> [--type all|albums|tracks|artists|playlists]
|
||||
/// [--limit N] [--offset N] [--ids] [--json]`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn search(
|
||||
host: Option<String>,
|
||||
query: String,
|
||||
stype: String,
|
||||
limit: u32,
|
||||
offset: u32,
|
||||
ids: bool,
|
||||
json: bool,
|
||||
roots: &ProfileRoots,
|
||||
) -> i32 {
|
||||
let client = ApiClient::new(host, roots);
|
||||
let path = format!(
|
||||
"/api/search?q={}&type={}&limit={}&offset={}",
|
||||
urlencoding::encode(&query),
|
||||
urlencoding::encode(&stype),
|
||||
limit,
|
||||
offset,
|
||||
);
|
||||
let payload = match client.get(&path).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
|
||||
if json {
|
||||
println!("{}", serde_json::to_string(&payload).unwrap_or_default());
|
||||
} else if ids {
|
||||
for id in collect_ids(&payload) {
|
||||
println!("{id}");
|
||||
}
|
||||
} else {
|
||||
print!("{}", render(&payload));
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
// ============================ rendering ============================
|
||||
|
||||
/// The category order used by both the human table and `--ids`. `tracks` leads
|
||||
/// so `qbzd search "..." --type tracks --ids | qbzd queue add -` is the obvious
|
||||
/// pipeline; the order is stable so scripts can rely on it.
|
||||
const CATEGORIES: [(&str, &str); 4] = [
|
||||
("tracks", "TRACKS"),
|
||||
("albums", "ALBUMS"),
|
||||
("artists", "ARTISTS"),
|
||||
("playlists", "PLAYLISTS"),
|
||||
];
|
||||
|
||||
/// Human top-hits table. Defensive against missing optional fields — a category
|
||||
/// with no results is skipped; an item with no title/artist degrades gracefully
|
||||
/// rather than erroring (the `--json` payload is the exact contract; this is a
|
||||
/// convenience view).
|
||||
fn render(p: &Value) -> String {
|
||||
let mut out = String::new();
|
||||
for (key, label) in CATEGORIES {
|
||||
let page = match p.get(key) {
|
||||
Some(v) if v.is_object() => v,
|
||||
_ => continue,
|
||||
};
|
||||
let items = match page.get("items").and_then(|v| v.as_array()) {
|
||||
Some(a) if !a.is_empty() => a,
|
||||
_ => continue,
|
||||
};
|
||||
let total = page
|
||||
.get("total")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(items.len() as u64);
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&format!("{label} ({total})\n"));
|
||||
for it in items {
|
||||
let id = id_str(it.get("id"));
|
||||
let title = it
|
||||
.get("title")
|
||||
.or_else(|| it.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("(untitled)");
|
||||
match secondary_name(it) {
|
||||
Some(s) => out.push_str(&format!(" {id} {s} — {title}\n")),
|
||||
None => out.push_str(&format!(" {id} {title}\n")),
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push_str("no results\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The ids of every returned item, in `CATEGORIES` order — the composition
|
||||
/// currency. For a typed search only one category is populated; for `--type
|
||||
/// all` this emits all ids (album ids are strings, track/artist ids numbers —
|
||||
/// realistic pipelines use a typed search, but mixing is not an error).
|
||||
fn collect_ids(p: &Value) -> Vec<String> {
|
||||
let mut ids = Vec::new();
|
||||
for (key, _label) in CATEGORIES {
|
||||
if let Some(items) = p
|
||||
.get(key)
|
||||
.and_then(|v| v.get("items"))
|
||||
.and_then(|v| v.as_array())
|
||||
{
|
||||
for it in items {
|
||||
let id = id_str(it.get("id"));
|
||||
if !id.is_empty() {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// A best-effort "artist" line: an album/track carries `artist.name` or
|
||||
/// `performer.name`; an artist/playlist has neither (its `name` is the title).
|
||||
fn secondary_name(it: &Value) -> Option<&str> {
|
||||
it.get("artist")
|
||||
.and_then(|a| a.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.or_else(|| {
|
||||
it.get("performer")
|
||||
.and_then(|a| a.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
/// Stringify an id `Value` without quotes: a string id (album) prints bare, a
|
||||
/// numeric id (track/artist/playlist) prints as its integer. Missing/other →
|
||||
/// empty (skipped by the callers).
|
||||
fn id_str(v: Option<&Value>) -> String {
|
||||
match v {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn payload() -> Value {
|
||||
serde_json::json!({
|
||||
"query": "feather", "type": "all", "limit": 20, "offset": 0,
|
||||
"albums": {"items": [
|
||||
{"id": "c9vd8vvvrbpkc", "title": "Light as a Feather",
|
||||
"artist": {"name": "Chick Corea"}}
|
||||
], "total": 27, "offset": 0, "limit": 20},
|
||||
"tracks": {"items": [
|
||||
{"id": 176544871, "title": "Spain", "performer": {"name": "Chick Corea"}}
|
||||
], "total": 5, "offset": 0, "limit": 20},
|
||||
"artists": Value::Null,
|
||||
"playlists": Value::Null
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_ids_leads_with_tracks_then_albums() {
|
||||
// CATEGORIES order: tracks first (queue-pipe target), then albums.
|
||||
assert_eq!(collect_ids(&payload()), vec!["176544871", "c9vd8vvvrbpkc"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_str_handles_string_and_numeric_ids_without_quotes() {
|
||||
assert_eq!(
|
||||
id_str(Some(&serde_json::json!("c9vd8vvvrbpkc"))),
|
||||
"c9vd8vvvrbpkc"
|
||||
);
|
||||
assert_eq!(id_str(Some(&serde_json::json!(176544871u64))), "176544871");
|
||||
assert_eq!(id_str(Some(&Value::Null)), "");
|
||||
assert_eq!(id_str(None), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_shows_present_categories_with_ids_and_names() {
|
||||
let out = render(&payload());
|
||||
assert!(out.contains("TRACKS (5)"), "{out}");
|
||||
assert!(out.contains(" 176544871 Chick Corea — Spain"), "{out}");
|
||||
assert!(out.contains("ALBUMS (27)"), "{out}");
|
||||
assert!(
|
||||
out.contains(" c9vd8vvvrbpkc Chick Corea — Light as a Feather"),
|
||||
"{out}"
|
||||
);
|
||||
// null categories are skipped entirely.
|
||||
assert!(!out.contains("ARTISTS"), "{out}");
|
||||
assert!(!out.contains("PLAYLISTS"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_empty_payload_says_no_results() {
|
||||
let empty = serde_json::json!({"albums": Value::Null, "tracks": Value::Null});
|
||||
assert_eq!(render(&empty), "no results\n");
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,15 @@ enum Cmd {
|
||||
Ping { #[arg(long)] json: bool },
|
||||
/// One-line now-playing
|
||||
Now { #[arg(long)] json: bool },
|
||||
/// Search Qobuz — top hits with ids (--ids pipes into `queue add -`)
|
||||
Search {
|
||||
query: String,
|
||||
#[arg(long = "type", default_value = "all")] kind: String,
|
||||
#[arg(long, default_value_t = 20)] limit: u32,
|
||||
#[arg(long, default_value_t = 0)] offset: u32,
|
||||
#[arg(long)] ids: bool,
|
||||
#[arg(long)] json: bool,
|
||||
},
|
||||
Play, Pause, Toggle, Stop, Next, Prev,
|
||||
/// Absolute secs, +N/-N, or mm:ss
|
||||
Seek { position: String },
|
||||
@@ -194,6 +203,10 @@ async fn main() {
|
||||
let roots = paths::ProfileRoots::resolve(None, None);
|
||||
cli::transport::now(cli.host, json, &roots).await
|
||||
}
|
||||
Cmd::Search { query, kind, limit, offset, ids, json } => {
|
||||
let roots = paths::ProfileRoots::resolve(None, None);
|
||||
cli::search::search(cli.host, query, kind, limit, offset, ids, json, &roots).await
|
||||
}
|
||||
Cmd::Play => {
|
||||
let roots = paths::ProfileRoots::resolve(None, None);
|
||||
cli::transport::play(cli.host, &roots).await
|
||||
|
||||
Reference in new issue
Block a user