Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 11.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub inbox`: the notifications of the account signed in, from
5//! section 21 of `docs/hub.md`.
6//!
7//! Listing never marks anything: `inbox read` marks notifications read,
8//! `inbox done` takes one out of the inbox, and `inbox mute` and `unmute`
9//! stop or bring back the notifications of one thread, named
10//! `OWNER/NAME#NUMBER`. The inbox is where notifications are: the hub sends
11//! no e-mail. With `--json` each prints what the hub answered. Exit
12//! statuses as the other hub commands: 0 done, 1 refused, 3 when the hub
13//! could not be reached or failed.
14//!
15//! Titles and logins are anyone's words: printed without `--json`, they go
16//! through [`shown`], so that no control character of theirs reaches a
17//! terminal raw.
18
19use std::fmt::Write;
20use std::process::ExitCode;
21
22use anyhow::{Context, Result};
23use braid_hubproto::RepoPath;
24use braid_hubproto::notifications::{Marked, Notification, Notifications, ThreadSubscription};
25use clap::{Args, Subcommand};
26use serde_json::json;
27
28use super::creds::{self, HubEnv};
29use super::http::HttpHub;
30use super::remote::{HubError, shown};
31use super::social_common::{exit_for, print};
32use crate::Cli;
33
34/// `hub inbox`.
35#[derive(Debug, Args)]
36#[command(args_conflicts_with_subcommands = true)]
37pub(crate) struct InboxArgs {
38 #[command(subcommand)]
39 pub(crate) action: Option<InboxAction>,
40 /// Show the notifications read too (default: the unread ones).
41 #[arg(long)]
42 pub(crate) all: bool,
43 /// Only the notifications of this repository.
44 #[arg(short = 'R', long = "hub-repo", value_name = "OWNER/NAME")]
45 pub(crate) hub_repo: Option<String>,
46 /// The most notifications to list, 1 to 100 (default: 30).
47 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))]
48 pub(crate) limit: Option<u32>,
49 /// Where to start: the `next` of the page before.
50 #[arg(long, value_name = "CURSOR")]
51 pub(crate) after: Option<String>,
52}
53
54/// What `hub inbox` does besides listing.
55#[derive(Debug, Subcommand)]
56pub(crate) enum InboxAction {
57 /// Mark notifications read, by id, or all of them.
58 Read(ReadArgs),
59 /// Take a notification out of the inbox.
60 Done(DoneArgs),
61 /// Stop the notifications of a thread.
62 Mute(ThreadArgs),
63 /// Get the notifications of a thread again.
64 Unmute(ThreadArgs),
65}
66
67/// `hub inbox read`.
68#[derive(Debug, Args)]
69pub(crate) struct ReadArgs {
70 /// The notifications to mark read, by id.
71 #[arg(
72 value_name = "ID",
73 required_unless_present = "all",
74 conflicts_with = "all"
75 )]
76 pub(crate) ids: Vec<u64>,
77 /// Mark every notification read.
78 #[arg(long)]
79 pub(crate) all: bool,
80}
81
82/// `hub inbox done`.
83#[derive(Debug, Args)]
84pub(crate) struct DoneArgs {
85 /// The notification, by id.
86 #[arg(value_name = "ID")]
87 pub(crate) id: u64,
88}
89
90/// `hub inbox mute` and `unmute`.
91#[derive(Debug, Args)]
92pub(crate) struct ThreadArgs {
93 /// The thread: OWNER/NAME#NUMBER.
94 #[arg(value_name = "OWNER/NAME#NUMBER")]
95 pub(crate) thread: String,
96}
97
98pub(crate) fn inbox(cli: &Cli, args: &InboxArgs) -> Result<ExitCode> {
99 match &args.action {
100 None => list(cli, args),
101 Some(InboxAction::Read(read)) => mark(cli, read),
102 Some(InboxAction::Done(done)) => finish(cli, done),
103 Some(InboxAction::Mute(thread)) => subscribe(cli, thread, false),
104 Some(InboxAction::Unmute(thread)) => subscribe(cli, thread, true),
105 }
106}
107
108/// The hub signed in to: BRAID_HUB_URL, else the hub signed in to last,
109/// else the public hub.
110fn signed_in_hub() -> Result<HttpHub> {
111 let env = HubEnv::from_process();
112 let creds = env.credentials()?;
113 let url = creds::hub_url(&env, &creds, None)?;
114 Ok(super::client(&env, &url)?.0)
115}
116
117/// What a command answers when the hub refused it or could not be
118/// reached: the error, and the exit status it calls for.
119fn failed(err: &HubError) -> ExitCode {
120 eprintln!("braid: error: {err}");
121 ExitCode::from(exit_for(err))
122}
123
124/// `text` as a value of a query string: everything but letters, digits
125/// and `-._~` percent-encoded.
126fn query_value(text: &str) -> String {
127 let mut out = String::with_capacity(text.len());
128 for byte in text.bytes() {
129 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
130 out.push(char::from(byte));
131 } else {
132 let _ = write!(out, "%{byte:02X}");
133 }
134 }
135 out
136}
137
138/// A repository given on the command line: OWNER/NAME.
139fn repo_arg(text: &str) -> Result<RepoPath> {
140 text.parse()
141 .with_context(|| format!("{text:?} is not OWNER/NAME"))
142}
143
144/// A thread given on the command line: OWNER/NAME#NUMBER.
145fn thread_arg(text: &str) -> Result<(RepoPath, u64)> {
146 let parsed = text.split_once('#').and_then(|(repo, number)| {
147 let number = number.parse::<u64>().ok().filter(|number| *number > 0)?;
148 Some((repo.parse::<RepoPath>().ok()?, number))
149 });
150 parsed.with_context(|| format!("{text:?} is not a thread: give OWNER/NAME#NUMBER"))
151}
152
153/// A notification in a line: `*` when unread, its id, where, its words,
154/// and who did what, why and when.
155fn line(notification: &Notification) -> String {
156 let mut out = format!(
157 "{} {}",
158 if notification.unread { "*" } else { " " },
159 notification.id
160 );
161 if let Some(repo) = &notification.repo {
162 let _ = write!(out, " {}/{}", shown(&repo.owner), shown(&repo.name));
163 }
164 match &notification.thread {
165 Some(thread) => {
166 let _ = write!(out, "#{} {}", thread.number, shown(&thread.title));
167 }
168 None => {
169 let _ = write!(
170 out,
171 " {}",
172 shown(notification.code.as_deref().unwrap_or("notice"))
173 );
174 }
175 }
176 let mut about = Vec::new();
177 if notification.thread.is_some() {
178 let what = shown(notification.code.as_deref().unwrap_or(""));
179 about.push(match &notification.actor {
180 Some(actor) => format!("{} {what}", shown(actor)),
181 None => what,
182 });
183 }
184 about.push(shown(&notification.reason));
185 about.push(shown(&notification.updated));
186 let _ = write!(out, " ({})", about.join(", "));
187 out
188}
189
190/// `hub inbox [--all] [-R OWNER/NAME] [--limit N] [--after CURSOR]`.
191fn list(cli: &Cli, args: &InboxArgs) -> Result<ExitCode> {
192 let repo = args.hub_repo.as_deref().map(repo_arg).transpose()?;
193 let mut query = Vec::new();
194 if args.all {
195 query.push("all=true".to_owned());
196 }
197 if let Some(repo) = &repo {
198 query.push(format!("repo={}", query_value(&repo.to_string())));
199 }
200 if let Some(limit) = args.limit {
201 query.push(format!("limit={limit}"));
202 }
203 if let Some(after) = &args.after {
204 query.push(format!("after={}", query_value(after)));
205 }
206 let mut route = "/v1/notifications".to_owned();
207 if !query.is_empty() {
208 route = format!("{route}?{}", query.join("&"));
209 }
210 let hub = signed_in_hub()?;
211 let page: Notifications = match hub.call_json("GET", &route, &[], None) {
212 Ok(page) => page,
213 Err(err) => return Ok(failed(&err)),
214 };
215 print(cli, &serde_json::to_value(&page)?, || {
216 let mut out = String::new();
217 if page.notifications.is_empty() {
218 out.push_str(if args.all {
219 "No notifications."
220 } else {
221 "No unread notifications."
222 });
223 }
224 for notification in &page.notifications {
225 if !out.is_empty() {
226 out.push('\n');
227 }
228 out.push_str(&line(notification));
229 }
230 let _ = write!(out, "\n{} unread.", page.unread);
231 if let Some(next) = &page.next {
232 let _ = write!(out, "\nMore: braid hub inbox");
233 if args.all {
234 out.push_str(" --all");
235 }
236 if let Some(repo) = &repo {
237 let _ = write!(out, " -R {repo}");
238 }
239 let _ = write!(out, " --after {}", shown(next));
240 }
241 out
242 })?;
243 Ok(ExitCode::SUCCESS)
244}
245
246/// `hub inbox read ID... | --all`.
247fn mark(cli: &Cli, args: &ReadArgs) -> Result<ExitCode> {
248 let body = if args.all {
249 json!({"all": true})
250 } else {
251 json!({"ids": args.ids})
252 };
253 let hub = signed_in_hub()?;
254 let marked: Marked = match hub.call_json("POST", "/v1/notifications/read", &[], Some(&body)) {
255 Ok(marked) => marked,
256 Err(err) => return Ok(failed(&err)),
257 };
258 print(cli, &serde_json::to_value(marked)?, || {
259 match marked.marked {
260 0 => "Nothing to mark: no unread notification among those.".to_owned(),
261 1 => "Marked 1 notification read.".to_owned(),
262 n => format!("Marked {n} notifications read."),
263 }
264 })?;
265 Ok(ExitCode::SUCCESS)
266}
267
268/// `hub inbox done ID`.
269fn finish(cli: &Cli, args: &DoneArgs) -> Result<ExitCode> {
270 let hub = signed_in_hub()?;
271 let route = format!("/v1/notifications/{}", args.id);
272 if let Err(err) = hub.call("DELETE", &route, &[], None) {
273 return Ok(failed(&err));
274 }
275 print(cli, &json!({"id": args.id, "done": true}), || {
276 format!("Notification {} is done.", args.id)
277 })?;
278 Ok(ExitCode::SUCCESS)
279}
280
281/// `hub inbox mute|unmute OWNER/NAME#NUMBER`.
282fn subscribe(cli: &Cli, args: &ThreadArgs, subscribed: bool) -> Result<ExitCode> {
283 let (repo, number) = thread_arg(&args.thread)?;
284 let hub = signed_in_hub()?;
285 let route = format!("{}/threads/{number}/subscription", repo.api_path());
286 let body = json!({ "subscribed": subscribed });
287 let answer: ThreadSubscription = match hub.call_json("PUT", &route, &[], Some(&body)) {
288 Ok(answer) => answer,
289 Err(err) => return Ok(failed(&err)),
290 };
291 let mut value = serde_json::to_value(&answer)?;
292 value["repo"] = json!(repo.to_string());
293 value["number"] = json!(number);
294 print(cli, &value, || {
295 if answer.subscribed {
296 format!("Following {repo}#{number}: it notifies you again.")
297 } else if subscribed {
298 // Asked to follow it, but the repository is ignored.
299 format!(
300 "{repo}#{number} still notifies you of nothing: you ignore its repository (braid hub watch changes that)."
301 )
302 } else {
303 format!("Muted {repo}#{number}: it notifies you no more.")
304 }
305 })?;
306 Ok(ExitCode::SUCCESS)
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use braid_hubproto::cards::RepoRef;
313 use braid_hubproto::notifications::NotificationThread;
314
315 #[test]
316 fn threads_and_lines_as_given() {
317 let (repo, number) = thread_arg("ada/demo#4").unwrap();
318 assert_eq!((repo.to_string().as_str(), number), ("ada/demo", 4));
319 for bad in [
320 "ada/demo",
321 "ada/demo#",
322 "ada/demo#0",
323 "ada#4",
324 "ada/demo#x",
325 "#4",
326 ] {
327 assert!(thread_arg(bad).is_err(), "{bad}");
328 }
329 assert!(repo_arg("ada/demo").is_ok() && repo_arg("ada").is_err());
330 assert_eq!(query_value("ada/demo"), "ada%2Fdemo");
331 let notification = Notification {
332 id: 7,
333 repo: Some(RepoRef {
334 owner: "ada".into(),
335 name: "demo".into(),
336 }),
337 thread: Some(NotificationThread {
338 kind: "issue".into(),
339 number: 4,
340 title: "a\u{1b}[31m title".into(),
341 }),
342 reason: "mention".into(),
343 actor: Some("bob".into()),
344 code: Some("commented".into()),
345 updated: "2026-10-18T12:00:00Z".into(),
346 unread: true,
347 url: String::new(),
348 };
349 let shown = line(&notification);
350 assert!(
351 shown.starts_with("* 7 ada/demo#4 a\\u{1b}[31m title (bob commented, mention, "),
352 "{shown}"
353 );
354 assert!(!shown.contains('\u{1b}'));
355 }
356}