Skip to main content

koan_core/
graphql_client.rs

1//! Lightweight GraphQL client for connecting to a `koan serve` instance.
2//!
3//! Uses blocking reqwest — call from a background thread when used from the TUI.
4
5use serde_json::Value;
6
7/// A GraphQL client that talks to a koan server.
8#[derive(Debug, Clone)]
9pub struct GraphQLClient {
10    url: String,
11    http: reqwest::blocking::Client,
12}
13
14impl GraphQLClient {
15    pub fn new(server_url: &str) -> Self {
16        let url = format!("{}/graphql", server_url.trim_end_matches('/'));
17        Self {
18            url,
19            http: reqwest::blocking::Client::builder()
20                .timeout(std::time::Duration::from_secs(30))
21                .build()
22                .expect("failed to build HTTP client"),
23        }
24    }
25
26    /// Execute a raw GraphQL query/mutation.
27    pub fn execute(&self, query: &str, variables: Option<Value>) -> Result<Value, GraphQLError> {
28        let mut body = serde_json::json!({ "query": query });
29        if let Some(vars) = variables {
30            body["variables"] = vars;
31        }
32
33        let resp: Value = self
34            .http
35            .post(&self.url)
36            .json(&body)
37            .send()
38            .map_err(|e| GraphQLError::Http(e.to_string()))?
39            .json()
40            .map_err(|e| GraphQLError::Http(e.to_string()))?;
41
42        if let Some(errors) = resp.get("errors")
43            && let Some(arr) = errors.as_array()
44            && !arr.is_empty()
45        {
46            let msg = arr[0]
47                .get("message")
48                .and_then(|m| m.as_str())
49                .unwrap_or("unknown error");
50            return Err(GraphQLError::Query(msg.to_string()));
51        }
52
53        Ok(resp.get("data").cloned().unwrap_or(Value::Null))
54    }
55
56    // -----------------------------------------------------------------------
57    // Typed helpers
58    // -----------------------------------------------------------------------
59
60    pub fn now_playing(&self) -> Result<NowPlaying, GraphQLError> {
61        let data = self.execute(
62            "{ nowPlaying { state positionMs durationMs queueItemId \
63             track { trackId title artist album codec sampleRate bitDepth bitrateKbps channels durationMs } } }",
64            None,
65        )?;
66        let np = &data["nowPlaying"];
67        Ok(NowPlaying {
68            state: np["state"].as_str().unwrap_or("STOPPED").to_string(),
69            position_ms: np["positionMs"].as_u64().unwrap_or(0),
70            duration_ms: np["durationMs"].as_u64(),
71            queue_item_id: np["queueItemId"].as_str().map(String::from),
72            track: np.get("track").and_then(|t| {
73                if t.is_null() {
74                    return None;
75                }
76                Some(NowPlayingTrack {
77                    track_id: t["trackId"].as_i64(),
78                    title: t["title"].as_str().unwrap_or("").to_string(),
79                    artist: t["artist"].as_str().unwrap_or("").to_string(),
80                    album: t["album"].as_str().unwrap_or("").to_string(),
81                    codec: t["codec"].as_str().unwrap_or("").to_string(),
82                    sample_rate: t["sampleRate"].as_u64().unwrap_or(0) as u32,
83                    bit_depth: t["bitDepth"].as_u64().map(|v| v as u16),
84                    bitrate_kbps: t["bitrateKbps"].as_u64().map(|v| v as u32),
85                    channels: t["channels"].as_u64().unwrap_or(0) as u16,
86                    duration_ms: t["durationMs"].as_u64().unwrap_or(0),
87                })
88            }),
89        })
90    }
91
92    pub fn queue(&self) -> Result<Vec<QueueEntry>, GraphQLError> {
93        let data = self.execute(
94            "{ queue { queueItemId trackId title artist album codec trackNumber disc durationMs isCurrent } }",
95            None,
96        )?;
97        let entries = data["queue"]
98            .as_array()
99            .map(|arr| {
100                arr.iter()
101                    .map(|e| QueueEntry {
102                        queue_item_id: e["queueItemId"].as_str().unwrap_or("").to_string(),
103                        track_id: e["trackId"].as_i64(),
104                        title: e["title"].as_str().unwrap_or("").to_string(),
105                        artist: e["artist"].as_str().unwrap_or("").to_string(),
106                        album: e["album"].as_str().unwrap_or("").to_string(),
107                        codec: e["codec"].as_str().map(String::from),
108                        track_number: e["trackNumber"].as_i64(),
109                        disc: e["disc"].as_i64(),
110                        duration_ms: e["durationMs"].as_u64(),
111                        is_current: e["isCurrent"].as_bool().unwrap_or(false),
112                    })
113                    .collect()
114            })
115            .unwrap_or_default();
116        Ok(entries)
117    }
118
119    pub fn search(&self, query: &str, limit: u32) -> Result<Vec<TrackResult>, GraphQLError> {
120        let data = self.execute(
121            "query($search: String!, $first: Int) { tracks(search: $search, first: $first) { edges { node { id title artist album albumId artistId disc trackNumber durationMs codec genre source } } } }",
122            Some(serde_json::json!({ "search": query, "first": limit })),
123        )?;
124        parse_track_edges(&data["tracks"])
125    }
126
127    pub fn artists(&self) -> Result<Vec<ArtistResult>, GraphQLError> {
128        let data = self.execute("{ artists { edges { node { id name } } } }", None)?;
129        let edges = data["artists"]["edges"].as_array();
130        Ok(edges
131            .map(|arr| {
132                arr.iter()
133                    .map(|e| {
134                        let n = &e["node"];
135                        ArtistResult {
136                            id: n["id"].as_i64().unwrap_or(0),
137                            name: n["name"].as_str().unwrap_or("").to_string(),
138                        }
139                    })
140                    .collect()
141            })
142            .unwrap_or_default())
143    }
144
145    pub fn albums_for_artist(&self, artist_id: i64) -> Result<Vec<AlbumResult>, GraphQLError> {
146        let data = self.execute(
147            "query($artistId: Int!) { albums(artistId: $artistId) { edges { node { id title artistName date codec } } } }",
148            Some(serde_json::json!({ "artistId": artist_id })),
149        )?;
150        parse_album_edges(&data["albums"])
151    }
152
153    pub fn tracks_for_album(&self, album_id: i64) -> Result<Vec<TrackResult>, GraphQLError> {
154        let data = self.execute(
155            "query($albumId: Int!) { tracks(albumId: $albumId) { edges { node { id title artist album albumId artistId disc trackNumber durationMs codec genre source } } } }",
156            Some(serde_json::json!({ "albumId": album_id })),
157        )?;
158        parse_track_edges(&data["tracks"])
159    }
160
161    pub fn fuzzy_search(
162        &self,
163        query: &str,
164        kind: &str,
165        limit: u32,
166    ) -> Result<Vec<FuzzyMatch>, GraphQLError> {
167        let data = self.execute(
168            "query($query: String!, $kind: FuzzySearchKind!, $limit: Int) { fuzzySearch(query: $query, kind: $kind, limit: $limit) { id name rank kind } }",
169            Some(serde_json::json!({ "query": query, "kind": kind, "limit": limit })),
170        )?;
171        Ok(data["fuzzySearch"]
172            .as_array()
173            .map(|arr| {
174                arr.iter()
175                    .map(|e| FuzzyMatch {
176                        id: e["id"].as_i64().unwrap_or(0),
177                        name: e["name"].as_str().unwrap_or("").to_string(),
178                        rank: e["rank"].as_i64().unwrap_or(0) as i32,
179                    })
180                    .collect()
181            })
182            .unwrap_or_default())
183    }
184
185    // -- Mutations --
186
187    pub fn pause(&self) -> Result<(), GraphQLError> {
188        self.execute("mutation { pause { ok } }", None)?;
189        Ok(())
190    }
191
192    pub fn resume(&self) -> Result<(), GraphQLError> {
193        self.execute("mutation { resume { ok } }", None)?;
194        Ok(())
195    }
196
197    pub fn stop(&self) -> Result<(), GraphQLError> {
198        self.execute("mutation { stop { ok } }", None)?;
199        Ok(())
200    }
201
202    pub fn next(&self) -> Result<(), GraphQLError> {
203        self.execute("mutation { next { ok } }", None)?;
204        Ok(())
205    }
206
207    pub fn previous(&self) -> Result<(), GraphQLError> {
208        self.execute("mutation { previous { ok } }", None)?;
209        Ok(())
210    }
211
212    pub fn seek(&self, position_ms: u64) -> Result<(), GraphQLError> {
213        self.execute(
214            "mutation($positionMs: Int!) { seek(positionMs: $positionMs) { ok } }",
215            Some(serde_json::json!({ "positionMs": position_ms })),
216        )?;
217        Ok(())
218    }
219
220    pub fn play(&self, queue_item_id: &str) -> Result<(), GraphQLError> {
221        self.execute(
222            "mutation($queueItemId: String!) { play(queueItemId: $queueItemId) { ok } }",
223            Some(serde_json::json!({ "queueItemId": queue_item_id })),
224        )?;
225        Ok(())
226    }
227
228    pub fn add_to_queue(&self, track_ids: &[i64]) -> Result<Vec<String>, GraphQLError> {
229        let data = self.execute(
230            "mutation($trackIds: [Int!]!) { addToQueue(trackIds: $trackIds) { ok addedCount queueItemIds } }",
231            Some(serde_json::json!({ "trackIds": track_ids })),
232        )?;
233        Ok(data["addToQueue"]["queueItemIds"]
234            .as_array()
235            .map(|arr| {
236                arr.iter()
237                    .filter_map(|v| v.as_str().map(String::from))
238                    .collect()
239            })
240            .unwrap_or_default())
241    }
242
243    pub fn replace_queue(&self, track_ids: &[i64]) -> Result<Vec<String>, GraphQLError> {
244        let data = self.execute(
245            "mutation($trackIds: [Int!]!) { replaceQueue(trackIds: $trackIds) { ok addedCount queueItemIds } }",
246            Some(serde_json::json!({ "trackIds": track_ids })),
247        )?;
248        Ok(data["replaceQueue"]["queueItemIds"]
249            .as_array()
250            .map(|arr| {
251                arr.iter()
252                    .filter_map(|v| v.as_str().map(String::from))
253                    .collect()
254            })
255            .unwrap_or_default())
256    }
257
258    pub fn clear_queue(&self) -> Result<(), GraphQLError> {
259        self.execute("mutation { clearQueue { ok } }", None)?;
260        Ok(())
261    }
262
263    pub fn favourite(&self, track_id: i64) -> Result<(), GraphQLError> {
264        self.execute(
265            "mutation($trackId: Int!) { favourite(trackId: $trackId) { id } }",
266            Some(serde_json::json!({ "trackId": track_id })),
267        )?;
268        Ok(())
269    }
270
271    pub fn unfavourite(&self, track_id: i64) -> Result<(), GraphQLError> {
272        self.execute(
273            "mutation($trackId: Int!) { unfavourite(trackId: $trackId) { id } }",
274            Some(serde_json::json!({ "trackId": track_id })),
275        )?;
276        Ok(())
277    }
278
279    pub fn save_snapshot(&self, name: &str) -> Result<(), GraphQLError> {
280        self.execute(
281            "mutation($name: String!) { saveSnapshot(name: $name) { ok } }",
282            Some(serde_json::json!({ "name": name })),
283        )?;
284        Ok(())
285    }
286
287    pub fn restore_snapshot(&self, name: &str) -> Result<(), GraphQLError> {
288        self.execute(
289            "mutation($name: String!) { restoreSnapshot(name: $name) { ok } }",
290            Some(serde_json::json!({ "name": name })),
291        )?;
292        Ok(())
293    }
294
295    pub fn enable_radio(&self) -> Result<(), GraphQLError> {
296        self.execute("mutation { enableRadio { ok } }", None)?;
297        Ok(())
298    }
299
300    pub fn disable_radio(&self) -> Result<(), GraphQLError> {
301        self.execute("mutation { disableRadio { ok } }", None)?;
302        Ok(())
303    }
304
305    pub fn library_stats(&self) -> Result<Value, GraphQLError> {
306        self.execute(
307            "{ libraryStats { totalTracks totalArtists totalAlbums localTracks remoteTracks cachedTracks } }",
308            None,
309        )
310    }
311
312    /// Server URL (without /graphql path).
313    pub fn server_url(&self) -> &str {
314        self.url.trim_end_matches("/graphql")
315    }
316}
317
318// ---------------------------------------------------------------------------
319// Result types
320// ---------------------------------------------------------------------------
321
322#[derive(Debug, thiserror::Error)]
323pub enum GraphQLError {
324    #[error("http error: {0}")]
325    Http(String),
326    #[error("query error: {0}")]
327    Query(String),
328}
329
330#[derive(Debug, Clone)]
331pub struct NowPlaying {
332    pub state: String,
333    pub position_ms: u64,
334    pub duration_ms: Option<u64>,
335    pub queue_item_id: Option<String>,
336    pub track: Option<NowPlayingTrack>,
337}
338
339#[derive(Debug, Clone)]
340pub struct NowPlayingTrack {
341    /// Library row id on the server. `None` for a queue entry the server built
342    /// from a file with no database row, which cannot be streamed.
343    pub track_id: Option<i64>,
344    pub title: String,
345    pub artist: String,
346    pub album: String,
347    pub codec: String,
348    pub sample_rate: u32,
349    pub bit_depth: Option<u16>,
350    pub bitrate_kbps: Option<u32>,
351    pub channels: u16,
352    pub duration_ms: u64,
353}
354
355#[derive(Debug, Clone)]
356pub struct QueueEntry {
357    pub queue_item_id: String,
358    pub track_id: Option<i64>,
359    pub title: String,
360    pub artist: String,
361    pub album: String,
362    pub codec: Option<String>,
363    pub track_number: Option<i64>,
364    pub disc: Option<i64>,
365    pub duration_ms: Option<u64>,
366    pub is_current: bool,
367}
368
369#[derive(Debug, Clone)]
370pub struct TrackResult {
371    pub id: i64,
372    pub title: String,
373    pub artist: String,
374    pub album: String,
375    pub album_id: Option<i64>,
376    pub artist_id: Option<i64>,
377    pub disc: Option<i32>,
378    pub track_number: Option<i32>,
379    pub duration_ms: Option<i64>,
380    pub codec: Option<String>,
381    pub genre: Option<String>,
382    pub source: String,
383}
384
385#[derive(Debug, Clone)]
386pub struct ArtistResult {
387    pub id: i64,
388    pub name: String,
389}
390
391#[derive(Debug, Clone)]
392pub struct AlbumResult {
393    pub id: i64,
394    pub title: String,
395    pub artist_name: String,
396    pub date: Option<String>,
397    pub codec: Option<String>,
398}
399
400#[derive(Debug, Clone)]
401pub struct FuzzyMatch {
402    pub id: i64,
403    pub name: String,
404    pub rank: i32,
405}
406
407// ---------------------------------------------------------------------------
408// Parse helpers
409// ---------------------------------------------------------------------------
410
411fn parse_track_edges(connection: &Value) -> Result<Vec<TrackResult>, GraphQLError> {
412    Ok(connection["edges"]
413        .as_array()
414        .map(|arr| {
415            arr.iter()
416                .map(|e| {
417                    let n = &e["node"];
418                    TrackResult {
419                        id: n["id"].as_i64().unwrap_or(0),
420                        title: n["title"].as_str().unwrap_or("").to_string(),
421                        artist: n["artist"].as_str().unwrap_or("").to_string(),
422                        album: n["album"].as_str().unwrap_or("").to_string(),
423                        album_id: n["albumId"].as_i64(),
424                        artist_id: n["artistId"].as_i64(),
425                        disc: n["disc"].as_i64().map(|v| v as i32),
426                        track_number: n["trackNumber"].as_i64().map(|v| v as i32),
427                        duration_ms: n["durationMs"].as_i64(),
428                        codec: n["codec"].as_str().map(String::from),
429                        genre: n["genre"].as_str().map(String::from),
430                        source: n["source"].as_str().unwrap_or("local").to_string(),
431                    }
432                })
433                .collect()
434        })
435        .unwrap_or_default())
436}
437
438fn parse_album_edges(connection: &Value) -> Result<Vec<AlbumResult>, GraphQLError> {
439    Ok(connection["edges"]
440        .as_array()
441        .map(|arr| {
442            arr.iter()
443                .map(|e| {
444                    let n = &e["node"];
445                    AlbumResult {
446                        id: n["id"].as_i64().unwrap_or(0),
447                        title: n["title"].as_str().unwrap_or("").to_string(),
448                        artist_name: n["artistName"].as_str().unwrap_or("").to_string(),
449                        date: n["date"].as_str().map(String::from),
450                        codec: n["codec"].as_str().map(String::from),
451                    }
452                })
453                .collect()
454        })
455        .unwrap_or_default())
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn client_constructs_url() {
464        let c = GraphQLClient::new("http://localhost:4000");
465        assert_eq!(c.url, "http://localhost:4000/graphql");
466    }
467
468    #[test]
469    fn client_trailing_slash() {
470        let c = GraphQLClient::new("http://localhost:4000/");
471        assert_eq!(c.url, "http://localhost:4000/graphql");
472    }
473}