use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::form::{self, ChoiceDefault, FormError, QuestionKind};
use super::thread::HostVerb;
use super::{Block, FeedItem, FormRecord, Inbox, ItemKind, Kind, Marker, Op, Thread, feed, ops};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiError {
pub code: &'static str,
pub message: String,
}
impl ApiError {
fn new(code: &'static str, message: impl Into<String>) -> Self {
Self { code, message: message.into() }
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::new("not-found", message)
}
pub fn invalid(message: impl Into<String>) -> Self {
Self::new("invalid", message)
}
pub fn denied(message: impl Into<String>) -> Self {
Self::new("denied", message)
}
pub fn closed_form(message: impl Into<String>) -> Self {
Self::new("closed-form", message)
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn bind_failed(message: impl Into<String>) -> Self {
Self::new("bind-failed", message)
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn failed(message: impl Into<String>) -> Self {
Self::new("failed", message)
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn internal(e: anyhow::Error) -> Self {
Self::new("internal", format!("{e:#}"))
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn unknown_method(method: &str) -> Self {
Self::new("unknown-method", format!("unknown method `{method}`"))
}
}
#[derive(Debug, Serialize)]
pub struct ThreadSummary {
pub id: u64,
pub owner: String,
pub owner_name: String,
pub key: Option<String>,
pub kind: &'static str,
pub state: Option<&'static str>,
pub status: Option<String>,
pub title: String,
pub level: Option<&'static str>,
pub unread: bool,
pub archived: bool,
pub needs_you: bool,
pub changed_at: u64,
}
#[derive(Debug, Serialize)]
pub struct ThreadDetail {
#[serde(flatten)]
pub summary: ThreadSummary,
pub link: Option<String>,
pub child: Option<String>,
pub compose: Option<ComposeView>,
pub actions: Vec<ActionView>,
pub feed: Vec<FeedItemView>,
pub notes: Vec<NoteView>,
pub events_pending: usize,
}
#[derive(Debug, Serialize)]
pub struct ComposeView {
pub placeholder: Option<String>,
pub hint: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ActionView {
pub id: String,
pub label: String,
pub done: bool,
pub host: Option<&'static str>,
pub sends_event: bool,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum FeedItemView {
Message { seq: u64, at: u64, id: String, blocks: Vec<BlockView>, edited: bool, withdrawn: bool },
Reply { seq: u64, at: u64, text: String },
Action { seq: u64, at: u64, action: String, label: String },
Submission { seq: u64, at: u64, message: String, form: String, answers: Value },
Marker { seq: u64, at: u64, marker: &'static str, from: Option<String>, to: Option<String> },
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum BlockView {
Markdown { text: String },
Fields { items: Vec<FieldView> },
Form {
id: String,
title: Option<String>,
submit: String,
questions: Vec<QuestionView>,
state: &'static str,
draft: Value,
answers: Option<Value>,
},
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum QuestionView {
Choice {
id: String,
label: String,
context: Option<String>,
required: bool,
under: Option<String>,
when: Option<String>,
options: Vec<OptionView>,
multiple: bool,
default: Option<Value>,
},
Text {
id: String,
label: String,
context: Option<String>,
required: bool,
under: Option<String>,
when: Option<String>,
placeholder: Option<String>,
default: Option<String>,
multiline: bool,
max: usize,
},
Confirm {
id: String,
label: String,
context: Option<String>,
required: bool,
under: Option<String>,
when: Option<String>,
yes: Option<String>,
no: Option<String>,
default: Option<bool>,
},
}
#[derive(Debug, Serialize)]
pub struct OptionView {
pub id: String,
pub label: String,
pub description: Option<String>,
}
impl BlockView {
pub(crate) fn of(b: &Block, record: Option<&FormRecord>) -> Self {
match b {
Block::Markdown { text } => BlockView::Markdown { text: text.clone() },
Block::Fields { items } => BlockView::Fields {
items: items.iter().map(|f| FieldView { label: f.label.clone(), value: f.value.clone() }).collect(),
},
Block::Form(f) => {
let (state, draft, answers) = match record.map(|r| (&r.state, &r.draft)) {
Some((form::FormState::Submitted { answers, .. }, _)) => {
("submitted", json!({}), Some(form::answers_json(f, answers)))
}
Some((state, draft)) => (state.as_str(), form::partial_json(draft), None),
None => ("open", json!({}), None),
};
BlockView::Form {
id: f.id.clone(),
title: f.title.clone(),
submit: f.submit.clone(),
questions: f.questions.iter().map(QuestionView::of).collect(),
state,
draft,
answers,
}
}
}
}
}
impl QuestionView {
pub(crate) fn of(q: &form::Question) -> Self {
let (id, label, context, required) = (q.id.clone(), q.label.clone(), q.context.clone(), q.required);
let (under, when) = (q.under.clone(), q.when.clone());
match &q.kind {
QuestionKind::Choice { options, multiple, default } => QuestionView::Choice {
id,
label,
context,
required,
under,
when,
options: options
.iter()
.map(|o| OptionView { id: o.id.clone(), label: o.label.clone(), description: o.description.clone() })
.collect(),
multiple: *multiple,
default: default.as_ref().map(|d| match d {
ChoiceDefault::One(o) => json!(o),
ChoiceDefault::Many(os) => json!(os),
}),
},
QuestionKind::Text { placeholder, default, multiline, max } => QuestionView::Text {
id,
label,
context,
required,
under,
when,
placeholder: placeholder.clone(),
default: default.clone(),
multiline: *multiline,
max: *max,
},
QuestionKind::Confirm { yes, no, default } => {
QuestionView::Confirm { id, label, context, required, under, when, yes: yes.clone(), no: no.clone(), default: *default }
}
}
}
}
#[derive(Debug, Serialize)]
pub struct FieldView {
pub label: String,
pub value: String,
}
impl FeedItemView {
pub fn of(item: &FeedItem, thread_feed: &[FeedItem]) -> Self {
let (seq, at) = (item.seq, item.at);
match &item.kind {
ItemKind::Message { id, blocks, edited, withdrawn, form } => FeedItemView::Message {
seq,
at,
id: id.clone(),
blocks: blocks.iter().map(|b| BlockView::of(b, form.as_ref())).collect(),
edited: *edited,
withdrawn: *withdrawn,
},
ItemKind::Submission { message, form: form_id, answers, .. } => FeedItemView::Submission {
seq,
at,
message: message.clone(),
form: form_id.clone(),
answers: match feed::form_of(thread_feed, message) {
Some((f, _)) if &f.id == form_id => form::answers_json(f, answers),
_ => form::partial_json(answers),
},
},
ItemKind::Reply { text, .. } => FeedItemView::Reply { seq, at, text: text.clone() },
ItemKind::Action { action, label, .. } => {
FeedItemView::Action { seq, at, action: action.clone(), label: label.clone() }
}
ItemKind::Marker(m) => {
let (marker, from, to) = match m {
Marker::Done { .. } => ("done", None, None),
Marker::Reopen { .. } => ("reopen", None, None),
Marker::State { from, to } => ("state", Some(from.as_str().to_string()), Some(to.as_str().to_string())),
Marker::Status { from, to } => ("status", from.clone(), to.clone()),
};
FeedItemView::Marker { seq, at, marker, from, to }
}
}
}
}
#[derive(Debug, Serialize)]
pub struct NoteView {
pub id: u64,
pub level: &'static str,
pub msg: String,
pub link: Option<String>,
pub at: u64,
}
fn kind_str(kind: Kind) -> &'static str {
match kind {
Kind::Notify => "notify",
Kind::Thread => "thread",
}
}
fn host_verb_str(verb: &HostVerb) -> &'static str {
match verb {
HostVerb::Vscode(_) => "vscode",
HostVerb::Terminal(_) => "terminal",
HostVerb::Logs(_) => "logs",
HostVerb::Forward(_) => "forward",
HostVerb::Open(_) => "open",
HostVerb::Rm(_) => "rm",
}
}
impl ThreadSummary {
pub fn of(t: &Thread) -> Self {
let title = match t.kind {
Kind::Thread => t.title.clone(),
Kind::Notify => t.head().map_or("", |r| r.msg.lines().next().unwrap_or("")).to_string(),
};
Self {
id: t.id,
owner: t.owner.clone(),
owner_name: t.owner_name.clone(),
key: t.key.clone(),
kind: kind_str(t.kind),
state: t.state.map(|s| s.as_str()),
status: t.status.clone(),
title,
level: t.head().map(|r| r.level.as_str()),
unread: t.unread,
archived: t.archived,
needs_you: t.needs_you(),
changed_at: t.changed_at(),
}
}
}
impl ThreadDetail {
pub fn of(t: &Thread) -> Self {
Self {
summary: ThreadSummary::of(t),
link: t.link.clone().or_else(|| t.head().and_then(|r| r.link.clone())),
child: t.child.clone(),
compose: t
.compose
.as_ref()
.map(|c| ComposeView { placeholder: c.placeholder.clone(), hint: c.hint.clone() }),
actions: t
.actions
.iter()
.map(|a| ActionView {
id: a.id.clone(),
label: a.label.clone(),
done: a.done,
host: a.host.as_ref().map(host_verb_str),
sends_event: a.enqueues_event(),
})
.collect(),
feed: t.feed.iter().map(|i| FeedItemView::of(i, &t.feed)).collect(),
notes: t
.notes
.iter()
.map(|n| NoteView {
id: n.id,
level: n.record.level.as_str(),
msg: n.record.msg.clone(),
link: n.record.link.clone(),
at: n.record.at,
})
.collect(),
events_pending: t.events.len(),
}
}
}
pub fn summaries(inbox: &Inbox, view: super::View) -> Vec<ThreadSummary> {
let mut rows: Vec<&Thread> = inbox.threads.iter().filter(|t| view.shows(t)).collect();
rows.sort_by_key(|t| std::cmp::Reverse(t.changed_at()));
rows.into_iter().map(ThreadSummary::of).collect()
}
#[derive(Debug, Default, Deserialize)]
pub struct Addr {
#[serde(default)]
pub thread: Option<u64>,
#[serde(default)]
pub owner: Option<String>,
#[serde(default)]
pub key: Option<String>,
}
impl Addr {
pub fn id(id: u64) -> Self {
Self { thread: Some(id), ..Self::default() }
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn is_empty(&self) -> bool {
self.thread.is_none() && self.owner.is_none() && self.key.is_none()
}
}
pub fn resolve<'a>(inbox: &'a Inbox, addr: &Addr) -> Result<&'a Thread, ApiError> {
let id = match (addr.thread, &addr.owner, &addr.key) {
(Some(id), None, None) => Some(id),
(None, Some(owner), Some(key)) => ops::thread_id(inbox, owner, key).or_else(|| {
inbox
.threads
.iter()
.filter(|t| t.kind == Kind::Thread && t.owner_name == *owner && t.key.as_deref() == Some(key))
.min_by_key(|t| (t.archived, std::cmp::Reverse(t.changed_at())))
.map(|t| t.id)
}),
_ => return Err(ApiError::invalid("name the thread by `thread` (its id), or by `owner` and `key`")),
};
let found = id.and_then(|id| inbox.threads.iter().find(|t| t.id == id));
found.ok_or_else(|| match (addr.thread, &addr.owner, &addr.key) {
(Some(id), ..) => ApiError::not_found(format!("no thread {id}")),
(_, Some(owner), Some(key)) => ApiError::not_found(format!("no thread `{key}` from `{owner}`")),
_ => ApiError::not_found("no such thread"),
})
}
pub fn user_target<'a>(inbox: &'a Inbox, addr: &Addr) -> Result<&'a Thread, ApiError> {
let t = resolve(inbox, addr)?;
if t.kind != Kind::Thread {
return Err(ApiError::invalid(format!("thread {} is a notification, not an owner thread", t.id)));
}
if t.archived {
return Err(ApiError::denied(format!("thread {} is archived: its owner was removed", t.id)));
}
Ok(t)
}
pub fn decide_done(inbox: &Inbox, addr: &Addr) -> Result<Vec<Op>, ApiError> {
Ok(vec![Op::MarkDone(user_target(inbox, addr)?.id)])
}
pub fn decide_reopen(inbox: &Inbox, addr: &Addr) -> Result<Vec<Op>, ApiError> {
Ok(vec![Op::Reopen(user_target(inbox, addr)?.id)])
}
pub fn decide_act(inbox: &Inbox, addr: &Addr, action: &str) -> Result<Vec<Op>, ApiError> {
let t = user_target(inbox, addr)?;
let Some(a) = t.actions.iter().find(|a| a.id == action) else {
return Err(ApiError::not_found(format!("thread {} has no action `{action}`", t.id)));
};
if !a.enqueues_event() {
return Err(ApiError::invalid(format!(
"action `{}` only runs on the host ({}); the API doesn't run host verbs",
a.id,
a.host.as_ref().map_or("?", host_verb_str)
)));
}
Ok(vec![Op::Act { thread: t.id, action: a.id.clone() }])
}
pub fn decide_reply(inbox: &Inbox, addr: &Addr, text: &str) -> Result<Vec<Op>, ApiError> {
if text.trim().is_empty() {
return Err(ApiError::invalid("empty reply"));
}
let t = user_target(inbox, addr)?;
if t.compose.is_none() {
return Err(ApiError::denied(format!("thread {} takes no replies", t.id)));
}
Ok(vec![Op::Reply { thread: t.id, text: text.to_string() }])
}
fn form_target<'a>(
inbox: &'a Inbox,
addr: &Addr,
message: &str,
answers: &serde_json::Map<String, Value>,
) -> Result<(&'a Thread, &'a form::Form, &'a FormRecord, std::collections::BTreeMap<String, form::Answer>), ApiError> {
let t = user_target(inbox, addr)?;
let (f, record) = feed::form_of(&t.feed, message)
.ok_or_else(|| ApiError::not_found(format!("thread {} has no message `{message}` with a form", t.id)))?;
let answers = form::answers_from_json(f, answers).map_err(ApiError::invalid)?;
Ok((t, f, record, answers))
}
fn form_error(e: FormError) -> ApiError {
match e {
FormError::Closed(why) => ApiError::closed_form(why),
FormError::Invalid(why) => ApiError::invalid(why),
}
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn decide_save_draft(
inbox: &Inbox,
addr: &Addr,
message: &str,
answers: &serde_json::Map<String, Value>,
) -> Result<Vec<Op>, ApiError> {
let (t, f, record, answers) = form_target(inbox, addr, message, answers)?;
form::validate_draft(f, record, &answers).map_err(form_error)?;
Ok(vec![Op::SaveDraft { thread: t.id, message: message.to_string(), answers }])
}
pub fn decide_submit(
inbox: &Inbox,
addr: &Addr,
message: &str,
answers: &serde_json::Map<String, Value>,
) -> Result<Vec<Op>, ApiError> {
let (t, f, record, answers) = form_target(inbox, addr, message, answers)?;
form::resolve_submission(f, record, &answers).map_err(form_error)?;
Ok(vec![Op::Submit { thread: t.id, message: message.to_string(), answers }])
}