| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | | use super::identity::{owner_home, recorded_owner}; |
| 7 | | use super::{ui, Ctx}; |
| 8 | | use anyhow::{bail, Context, Result}; |
| 9 | | use serde_json::{json, Value}; |
| 10 | | use spectra_core::conversation::{self as conv, Author, Post, Posted, Signer}; |
| 11 | | use spectra_core::keys::KeyPair; |
| 12 | | use spectra_core::ledger::Ledger; |
| 13 | | use spectra_core::principals::Principals; |
| 14 | | use spectra_mcp::client::Client; |
| 15 | | use std::path::PathBuf; |
| 16 | |
|
| 17 | |
|
| 18 | 3× | async fn owner_client(ctx: &Ctx, home: &std::path::Path) -> Result<Option<Client>> { |
| 19 | 3× | if !Client::alive(&ctx.socket()).await { |
| 20 | 1× | return Ok(None); |
| 21 | 2× | } |
| 22 | 2× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 23 | 2× | Ok(Some(Client::new(&ctx.socket(), Some(recorded_owner(&ledger, home).await?)))) |
| 24 | 3× | } |
| 25 | |
|
| 26 | 1× | async fn api(c: &Client, method: &str, path: &str, body: Option<Value>) -> Result<Value> { |
| 27 | 1× | let r = c.send(method, path, &[], body.map(|b| serde_json::to_vec(&b)).transpose()?.unwrap_or_default()).await?; |
| 28 | 1× | let v: Value = r.json().unwrap_or(Value::Null); |
| 29 | 1× | if r.status >= 400 { |
| 30 | 0× | let why = v |
| 31 | 0× | .get("detail") |
| 32 | 0× | .or(v.get("title")) |
| 33 | 0× | .and_then(Value::as_str) |
| 34 | 0× | .map(String::from) |
| 35 | 0× | .unwrap_or_else(|| String::from_utf8_lossy(&r.body).into()); |
| 36 | 0× | bail!("{why}"); |
| 37 | 1× | } |
| 38 | 1× | Ok(v) |
| 39 | 1× | } |
| 40 | |
|
| 41 | 1× | fn encode(s: &str) -> String { |
| 42 | 1× | s.bytes() |
| 43 | 7× | .map(|b| match b { |
| 44 | 7× | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), |
| 45 | 0× | _ => format!("%{b:02X}"), |
| 46 | 7× | }) |
| 47 | 1× | .collect() |
| 48 | 1× | } |
| 49 | |
|
| 50 | 2× | pub async fn say( |
| 51 | 2× | ctx: &Ctx, |
| 52 | 2× | channel: Option<String>, |
| 53 | 2× | reply_to: Option<String>, |
| 54 | 2× | body: String, |
| 55 | 2× | owner_home_flag: Option<PathBuf>, |
| 56 | 2× | as_json: bool, |
| 57 | 2× | ) -> Result<i32> { |
| 58 | 2× | let home = owner_home(ctx, owner_home_flag); |
| 59 | 2× | let (id, where_) = match owner_client(ctx, &home).await? { |
| 60 | 1× | Some(c) => { |
| 61 | 1× | let ch = channel.clone().unwrap_or_else(|| "general".into()); |
| 62 | 1× | let v = api( |
| 63 | 1× | &c, |
| 64 | 1× | "POST", |
| 65 | 1× | &format!("/api/v1/channels/{}/messages", encode(ch.trim_start_matches('#'))), |
| 66 | 1× | Some(json!({ "body": body, "reply_to": reply_to })), |
| 67 | 1× | ) |
| 68 | 1× | .await?; |
| 69 | 1× | if v["duplicate"] == true { |
| 70 | 0× | bail!("you said exactly this in the last minute ({})", v["id"].as_str().unwrap_or("")); |
| 71 | 1× | } |
| 72 | 1× | (v["id"].as_str().unwrap_or("").to_string(), v["channel"].as_str().unwrap_or("").to_string()) |
| 73 | | } |
| 74 | | None => { |
| 75 | 1× | let ledger = ctx.writer().await?; |
| 76 | 1× | let owner = KeyPair::load_home(&home)?; |
| 77 | 1× | let principal = Principals::load(&ledger) |
| 78 | 1× | .await? |
| 79 | 1× | .principal(&owner.key, spectra_core::ids::now_ms()) |
| 80 | 1× | .map_err(anyhow::Error::msg) |
| 81 | 1× | .context("run `spectra identity refresh` first")?; |
| 82 | 1× | let author = Author { principal, signer: Signer::Cli(&owner) }; |
| 83 | 1× | let post = Post { |
| 84 | 1× | channel: if reply_to.is_some() { None } else { Some(channel.unwrap_or_else(|| "general".into())) }, |
| 85 | 1× | body, |
| 86 | 1× | reply_to, |
| 87 | 1× | ..Default::default() |
| 88 | | }; |
| 89 | 1× | let posted = conv::post(&ledger, &author, post, spectra_core::ids::now_ms()).await?; |
| 90 | 1× | ledger.checkpoint().await?; |
| 91 | 1× | match posted { |
| 92 | 1× | Posted::Message { id, channel } => (id, channel), |
| 93 | 0× | Posted::Duplicate { id } => bail!("you said exactly this in the last minute ({id})"), |
| 94 | | } |
| 95 | | } |
| 96 | | }; |
| 97 | 2× | if as_json { |
| 98 | 2× | println!("{}", json!({ "id": id, "channel": where_ })); |
| 99 | 2× | } else { |
| 100 | 0× | println!("{} {}{}{}", ui::done("Posted"), ui::subject(&where_), ui::sep(), ui::id(&id)); |
| 101 | 0× | } |
| 102 | 2× | Ok(0) |
| 103 | 2× | } |
| 104 | |
|
| 105 | 0× | fn print_item(i: &Value) { |
| 106 | 0× | let kind = i["kind"].as_str().unwrap_or(""); |
| 107 | 0× | let mark = if kind == "dm" { ui::warn(ui::glyph("✉", "@")) } else { ui::ok(ui::glyph("●", "*")) }; |
| 108 | 0× | let from = i["from_display"].as_str().or(i["from"].as_str()).unwrap_or(""); |
| 109 | 0× | let at = i["at_ms"].as_u64().map(ui::ago).unwrap_or_default(); |
| 110 | 0× | println!( |
| 111 | | "{mark} {} {}{}{}{}{}", |
| 112 | 0× | ui::dim(kind), |
| 113 | 0× | ui::author(from), |
| 114 | 0× | ui::sep(), |
| 115 | 0× | i["channel"].as_str().unwrap_or(""), |
| 116 | 0× | ui::sep(), |
| 117 | 0× | ui::dim(at) |
| 118 | | ); |
| 119 | 0× | println!(" {}", i["summary"].as_str().unwrap_or("")); |
| 120 | 0× | println!(" {}", ui::dim(format!("reply: spectra say --reply-to {} \"…\"", i["id"].as_str().unwrap_or("")))); |
| 121 | 0× | } |
| 122 | |
|
| 123 | 1× | pub async fn inbox(ctx: &Ctx, follow: bool, owner_home_flag: Option<PathBuf>, as_json: bool) -> Result<i32> { |
| 124 | 1× | let home = owner_home(ctx, owner_home_flag); |
| 125 | 1× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 126 | 1× | let mut items: Vec<Value> = Vec::new(); |
| 127 | 1× | for i in conv::inbox(&ledger, "human", None).await? { |
| 128 | 0× | let from_display = conv::display_name(&ledger, &i.from).await; |
| 129 | 0× | let mut v = serde_json::to_value(&i)?; |
| 130 | 0× | v["from_display"] = from_display.into(); |
| 131 | 0× | items.push(v); |
| 132 | | } |
| 133 | 1× | if as_json && !follow { |
| 134 | 1× | println!("{}", Value::Array(items)); |
| 135 | 1× | return Ok(0); |
| 136 | 0× | } |
| 137 | 0× | if items.is_empty() && !follow { |
| 138 | 0× | println!("{} {}", ui::note(), ui::dim("nothing unread")); |
| 139 | 0× | } |
| 140 | 0× | let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new(); |
| 141 | 0× | for i in &items { |
| 142 | 0× | seen.insert(i["id"].as_str().unwrap_or("").to_string()); |
| 143 | 0× | if as_json { |
| 144 | 0× | println!("{i}"); |
| 145 | 0× | } else { |
| 146 | 0× | print_item(i); |
| 147 | 0× | } |
| 148 | | } |
| 149 | 0× | if !follow { |
| 150 | 0× | return Ok(0); |
| 151 | 0× | } |
| 152 | 0× | let client = owner_client(ctx, &home).await?.context("--follow needs `spectra serve` running")?; |
| 153 | 0× | if !as_json { |
| 154 | 0× | println!("{} {}", ui::note(), ui::dim("following; Ctrl-C stops")); |
| 155 | 0× | } |
| 156 | | |
| 157 | 0× | let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<()>(); |
| 158 | 0× | let watcher = tokio::spawn(async move { |
| 159 | 0× | client |
| 160 | 0× | .stream("/api/v1/events?follow=1&kind=message.posted", |l| { |
| 161 | 0× | if l.starts_with("data:") { |
| 162 | 0× | let _ = tx.send(()); |
| 163 | 0× | } |
| 164 | 0× | true |
| 165 | 0× | }) |
| 166 | 0× | .await |
| 167 | 0× | }); |
| 168 | 0× | while rx.recv().await.is_some() { |
| 169 | 0× | for i in conv::inbox(&ledger, "human", None).await? { |
| 170 | 0× | if seen.insert(i.id.clone()) { |
| 171 | 0× | let mut v = serde_json::to_value(&i)?; |
| 172 | 0× | v["from_display"] = conv::display_name(&ledger, &i.from).await.into(); |
| 173 | 0× | if as_json { |
| 174 | 0× | println!("{v}"); |
| 175 | 0× | } else { |
| 176 | 0× | print_item(&v); |
| 177 | 0× | } |
| 178 | 0× | } |
| 179 | | } |
| 180 | | } |
| 181 | 0× | watcher.await??; |
| 182 | 0× | Ok(0) |
| 183 | 1× | } |
| 184 | |
|
| 185 | 1× | pub async fn search( |
| 186 | 1× | ctx: &Ctx, |
| 187 | 1× | query: &str, |
| 188 | 1× | channel: Option<String>, |
| 189 | 1× | author: Option<String>, |
| 190 | 1× | since: Option<String>, |
| 191 | 1× | limit: u32, |
| 192 | 1× | as_json: bool, |
| 193 | 1× | ) -> Result<i32> { |
| 194 | 1× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 195 | 1× | let owner = Principals::load(&ledger).await?; |
| 196 | 1× | let me = owner.owner().context("no owner is recorded")?; |
| 197 | 1× | let principal = spectra_core::principals::Principal::Owner { key: me.hash(), name: me.name.clone() }; |
| 198 | 1× | let since = since.as_deref().and_then(|s| spectra_mcp::tools::parse_since(s, spectra_core::ids::now_ms())); |
| 199 | 1× | let hits = conv::search(&ledger, &principal, query, channel.as_deref(), author.as_deref(), since, limit).await?; |
| 200 | 1× | if as_json { |
| 201 | 1× | println!("{}", serde_json::to_string(&hits)?); |
| 202 | 1× | return Ok(0); |
| 203 | 0× | } |
| 204 | 0× | if hits.is_empty() { |
| 205 | 0× | println!("{} {}", ui::note(), ui::dim("no matches")); |
| 206 | 0× | } |
| 207 | 0× | for h in hits { |
| 208 | 0× | let who = conv::display_name(&ledger, &h.author).await; |
| 209 | 0× | println!( |
| 210 | | "{} {}{}{}{}{}", |
| 211 | 0× | ui::id(&h.id[..12.min(h.id.len())]), |
| 212 | 0× | ui::author(who), |
| 213 | 0× | ui::sep(), |
| 214 | | h.channel, |
| 215 | 0× | ui::sep(), |
| 216 | 0× | ui::dim(ui::ago(h.at_ms as u64)) |
| 217 | | ); |
| 218 | 0× | println!(" {}", h.snippet); |
| 219 | | } |
| 220 | 0× | Ok(0) |
| 221 | 1× | } |
| 222 | |
|
| 223 | |
|
| 224 | |
|
| 225 | 1× | pub async fn raw(ctx: &Ctx, method: &str, path: &str, data: Option<String>, owner_home_flag: Option<PathBuf>) -> Result<i32> { |
| 226 | 1× | let home = owner_home(ctx, owner_home_flag); |
| 227 | 1× | let c = owner_client(ctx, &home).await?.context("`spectra api` needs `spectra serve` running")?; |
| 228 | 1× | let r = c.send(&method.to_uppercase(), path, &[], data.map(String::into_bytes).unwrap_or_default()).await?; |
| 229 | 1× | println!("{}", String::from_utf8_lossy(&r.body)); |
| 230 | 1× | Ok(if r.status < 400 { 0 } else { 2 }) |
| 231 | 1× | } |