8447
Co
conveyor / files
conveyor / crates / conveyor-app / src / client.rs
2.7 KB
1//! Talks to conveyord over its socket, and turns its snapshot into what widgets read. 2use crate::api::{Activity, Data, Project, Ticket}; 3use serde_json::{Value, json}; 4use std::{io::{BufRead, BufReader, Write}, os::unix::net::UnixStream, path::PathBuf}; 5 6/// One request, one reply line. 7pub fn call(req: &str) -> Option<Value> { 8 let path = std::env::var("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(|_| "/tmp".into()).join("conveyor.sock"); 9 let mut c = UnixStream::connect(path).ok()?; 10 writeln!(c, "{}", req.replace('\n', " ")).ok()?; 11 let mut line = String::new(); 12 BufReader::new(c).read_line(&mut line).ok()?; 13 serde_json::from_str(&line).ok() 14} 15 16/// Sends a request without waiting on it, from a thread: the UI never blocks on conveyord. 17pub fn send(req: String) { 18 std::thread::spawn(move || if call(&req).is_none() { eprintln!("conveyord didn't answer: {req}") }); 19} 20 21pub fn state() -> Option<Value> { 22 call(&json!({"op": "state"}).to_string()) 23} 24 25/// The snapshot's projects, tickets and activity, as the library's types. 26pub fn data(v: &Value) -> Data { 27 let s = |v: &Value, k: &str| v[k].as_str().unwrap_or("").to_owned(); 28 let n = |v: &Value, k: &str| v[k].as_u64().unwrap_or(0); 29 let all = |k: &str| v[k].as_array().cloned().unwrap_or_default(); 30 Data { 31 projects: all("projects").iter().map(|p| Project { slug: s(p, "slug"), path: s(p, "path"), slots: n(p, "slots") as u32 }).collect(), 32 tickets: all("tickets").iter().map(|t| Ticket { 33 project: s(t, "project"), id: n(t, "id") as u32, title: s(t, "title"), state: s(t, "state"), body: s(t, "body"), 34 created: n(t, "created"), since: n(t, "since"), 35 files: t["files"].as_array().into_iter().flatten().filter_map(|f| Some(f.as_str()?.to_owned())).collect(), 36 thread: t["thread"].as_array().into_iter().flatten() 37 .map(|e| Activity { at: n(e, "at"), project: s(t, "project"), ticket: n(t, "id") as u32, kind: s(e, "kind"), text: s(e, "text") }).collect(), 38 }).collect(), 39 activity: all("activity").iter().map(|a| Activity { at: n(a, "at"), project: s(a, "project"), ticket: n(a, "ticket") as u32, kind: s(a, "kind"), text: s(a, "text") }).collect(), 40 connected: true, 41 } 42} 43 44/// Each widget build, with its ticket's title, state, time in that state and conversation. 45pub fn builds(v: &Value) -> Vec<Value> { 46 let tickets = v["tickets"].as_array().cloned().unwrap_or_default(); 47 v["builds"].as_array().into_iter().flatten().filter_map(|b| { 48 let t = tickets.iter().find(|t| t["project"] == "widgets" && t["id"] == b["id"])?; 49 let mut b = b.clone(); 50 for k in ["title", "state", "since", "thread"] { b[k] = t[k].clone(); } 51 Some(b) 52 }).collect() 53}