tuigram-cli 1.10.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Notifications for new messages, sent to the terminal as escape codes: the
//! terminal shows them as the system's own notifications, which also works
//! over SSH. Which code depends on the terminal ([`detect`]).
//!
//! TDLib decides what deserves a notification (mutes, mentions, messages
//! already read elsewhere); [`Notifier`] batches what arrives together and
//! keeps a busy chat from sending one every few seconds.

use std::collections::HashMap;
use std::io::Write;
use std::time::Duration;

use base64::Engine;
use serde::{Deserialize, Serialize};
use tokio::time::Instant;

use crate::text;

/// How notifications reach the terminal, set in `settings.toml`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Notifications {
    /// Picked from the terminal tuigram runs in.
    #[default]
    Auto,
    Off,
    /// The bell: most terminals bounce the dock icon or mark the tab.
    Bell,
    /// Text only: iTerm2, Ghostty, kitty, WezTerm, foot.
    Osc9,
    /// A title and text: Ghostty, WezTerm, Konsole, foot, kitty, Windows
    /// Terminal (once `compatibility.allowOSC777` is on).
    Osc777,
    /// A title and text, shown only while the window is in the background:
    /// kitty, foot, Konsole.
    Osc99,
    /// A desktop notification over D-Bus (`org.freedesktop.Notifications`),
    /// shown by the desktop whatever the terminal is.
    Dbus,
}

impl Notifications {
    /// `Auto` turned into what the terminal understands.
    pub fn resolve(self, env: impl Fn(&str) -> Option<String>) -> Notifications {
        match self {
            Notifications::Auto => detect(env),
            other => other,
        }
    }
}

/// The best notification code for the terminal, from what it says about
/// itself in the environment. Inside tmux, `TERM_PROGRAM` is tmux, but the
/// other variables come from the terminal tmux was started in.
pub fn detect(env: impl Fn(&str) -> Option<String>) -> Notifications {
    let is = |name: &str, value: &str| env(name).is_some_and(|v| v == value);
    let set = |name: &str| env(name).is_some_and(|v| !v.is_empty());
    let term = env("TERM").unwrap_or_default();
    if set("KITTY_WINDOW_ID")
        || term == "xterm-kitty"
        || term.starts_with("foot")
        || set("KONSOLE_VERSION")
    {
        Notifications::Osc99
    } else if is("TERM_PROGRAM", "ghostty")
        || set("GHOSTTY_RESOURCES_DIR")
        || is("TERM_PROGRAM", "WezTerm")
        || set("WEZTERM_PANE")
        || set("WT_SESSION")
    {
        Notifications::Osc777
    } else if is("TERM_PROGRAM", "iTerm.app") || is("LC_TERMINAL", "iTerm2") {
        Notifications::Osc9
    } else {
        Notifications::Bell
    }
}

/// One notification, ready to send.
#[derive(Debug, PartialEq)]
pub struct Alert {
    pub title: String,
    pub body: String,
    /// Telegram says to make no sound: the chat's sound is off, or the
    /// messages were sent without one.
    pub silent: bool,
}

/// The escape code that shows `alert`, or `None` if nothing should go out.
/// `id` tells notifications apart, for terminals that track them. Inside
/// tmux, codes other than the bell must be passed through to the terminal
/// (which needs `set -g allow-passthrough on`).
pub fn escape(method: Notifications, alert: &Alert, id: u64, tmux: bool) -> Option<String> {
    // The codes end at a control character, and a `;` separates fields.
    let title = text::flat(&alert.title).replace(';', ",");
    let body = text::flat(&alert.body).replace(';', ",");
    let code = match method {
        // `Dbus` goes over D-Bus instead (`desktop`), no code is sent.
        Notifications::Auto | Notifications::Off | Notifications::Dbus => return None,
        Notifications::Bell if alert.silent => return None,
        // tmux rings the terminal's bell itself.
        Notifications::Bell => return Some("\x07".into()),
        Notifications::Osc9 => format!("\x1b]9;{title}: {body}\x07"),
        Notifications::Osc777 => format!("\x1b]777;notify;{title};{body}\x07"),
        Notifications::Osc99 => {
            let base64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text);
            let sound = if alert.silent { ":s=silent" } else { "" };
            format!(
                "\x1b]99;i={id}:d=0:o=unfocused{sound}:e=1;{}\x1b\\\
                 \x1b]99;i={id}:d=1:p=body:e=1;{}\x1b\\",
                base64(&title),
                base64(&body)
            )
        }
    };
    Some(if tmux {
        format!("\x1bPtmux;{}\x1b\\", code.replace('\x1b', "\x1b\x1b"))
    } else {
        code
    })
}

/// Sets the window title: "(3) tuigram" with three unmuted chats unread.
pub fn title(unread_chats: i32) -> String {
    if unread_chats > 0 {
        format!("\x1b]2;({unread_chats}) tuigram\x07")
    } else {
        "\x1b]2;tuigram\x07".into()
    }
}

/// Whether a notification goes to the desktop rather than the terminal:
/// when set so, or inside tmux with no client attached (`attached`, asked
/// only then), where escape codes would reach no window; but then not over
/// SSH, where the desktop is another computer's, in front of someone else.
pub fn goes_to_desktop(
    with: Notifications,
    in_tmux: bool,
    over_ssh: bool,
    attached: impl FnOnce() -> bool,
) -> bool {
    with == Notifications::Dbus
        || (with != Notifications::Off && in_tmux && !over_ssh && !attached())
}

/// Shows `alert` as a desktop notification: over D-Bus
/// (`org.freedesktop.Notifications`) on Linux and the BSDs, the system's
/// own elsewhere. The desktop shows it whatever terminal tuigram runs in,
/// so it works when no one is watching the window, e.g. in a detached tmux
/// session. Sent from a thread of its own: with no notification server
/// listening, D-Bus answers only once it times out.
pub fn desktop(alert: &Alert) {
    let title = alert.title.clone();
    let body = alert.body.clone();
    let silent = alert.silent;
    let _ = std::thread::Builder::new()
        .name("notify".into())
        .spawn(move || {
            let markup = reads_markup();
            let (title, body) = (desktop_title(&title, markup), desktop_body(&body, markup));
            let mut notification = notify_rust::Notification::new();
            notification.appname("tuigram").summary(&title).body(&body);
            #[cfg(all(unix, not(target_os = "macos")))]
            if silent {
                notification.hint(notify_rust::Hint::SuppressSound(true));
            }
            #[cfg(not(all(unix, not(target_os = "macos"))))]
            let _ = silent;
            let _ = notification.show();
        });
}

/// `body` on one line, and where the desktop reads markup in it, as text:
/// a sender's `<a href>` or `<img>` would otherwise be a link or a picture
/// fetched.
fn desktop_body(body: &str, markup: bool) -> String {
    let body = text::flat(body);
    if markup { markup_as_text(&body) } else { body }
}

/// The title on one line. The spec makes it plain text, shown as written,
/// but dunst and mako lay it into their markup too, so where the desktop
/// reads markup a sender's `<`, `>` and `&` become lookalikes that are
/// right on both.
fn desktop_title(title: &str, markup: bool) -> String {
    let title = text::flat(title);
    if markup {
        title.replace('<', "‹").replace('>', "›").replace('&', "&")
    } else {
        title
    }
}

/// The freedesktop notification server reads markup in a body: it says so.
/// One that can't be asked is taken to, as escaped text is only less tidy.
#[cfg(all(unix, not(target_os = "macos")))]
fn reads_markup() -> bool {
    notify_rust::get_capabilities().map_or(true, |caps| caps.iter().any(|c| c == "body-markup"))
}

#[cfg(not(all(unix, not(target_os = "macos"))))]
fn reads_markup() -> bool {
    false
}

fn markup_as_text(body: &str) -> String {
    body.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Writes a code to the terminal, between frames.
pub fn send(code: &str) {
    let mut out = std::io::stdout();
    let _ = out.write_all(code.as_bytes());
    let _ = out.flush();
}

/// Saves the window title, for [`RESTORE_TITLE`] at exit.
pub const SAVE_TITLE: &str = "\x1b[22;0t";
/// Puts back the title [`SAVE_TITLE`] saved. Terminals that can't clear it
/// instead, so it doesn't stay "tuigram".
pub const RESTORE_TITLE: &str = "\x1b]2;\x07\x1b[23;0t";

/// At most `max` characters of `text`, ending with `…` if cut.
fn cut(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_string();
    }
    let mut out: String = text.chars().take(max - 1).collect();
    out.push('…');
    out
}

/// Notifications go out at most this often; what arrives meanwhile waits
/// and goes out together.
const GAP: Duration = Duration::from_secs(3);
/// After a notification for a chat, its messages for this long send none:
/// you already know it's talking.
const QUIET_CHAT: Duration = Duration::from_secs(30);
const MAX_TITLE: usize = 60;
const MAX_BODY: usize = 150;

/// A new message to tell the user about.
#[derive(Clone, Debug)]
pub struct Note {
    /// TDLib's notification id, for when it takes the notification back.
    pub id: i32,
    pub chat_id: i64,
    pub chat: String,
    /// "Alice: see you at 5" in groups, "see you at 5" in private chats.
    pub text: String,
    pub silent: bool,
}

#[derive(Default)]
pub struct Notifier {
    pending: Vec<Note>,
    last_sent: Option<Instant>,
    /// When each chat last had a notification, while it's quiet.
    quiet: HashMap<i64, Instant>,
}

impl Notifier {
    pub fn add(&mut self, note: Note, now: Instant) {
        let quiet = self
            .quiet
            .get(&note.chat_id)
            .is_some_and(|&sent| now < sent + QUIET_CHAT);
        if !quiet {
            self.pending.push(note);
        }
    }

    /// Drops notifications TDLib took back, e.g. because the message was
    /// read on another device.
    pub fn remove(&mut self, ids: &[i32]) {
        self.pending.retain(|n| !ids.contains(&n.id));
    }

    /// Drops what's waiting, e.g. when the user comes back to tuigram.
    pub fn clear(&mut self) {
        self.pending.clear();
    }

    /// What to send now, if anything: everything waiting, as one.
    pub fn due(&mut self, now: Instant) -> Option<Alert> {
        if self.pending.is_empty() || self.last_sent.is_some_and(|sent| now < sent + GAP) {
            return None;
        }
        let notes = std::mem::take(&mut self.pending);
        self.last_sent = Some(now);
        self.quiet.retain(|_, &mut sent| now < sent + QUIET_CHAT);
        for note in &notes {
            self.quiet.insert(note.chat_id, now);
        }
        Some(alert(&notes))
    }

    /// When notifications held back by [`GAP`] can go out.
    pub fn next_at(&self) -> Option<Instant> {
        let at = self.last_sent? + GAP;
        (!self.pending.is_empty()).then_some(at)
    }
}

/// One notification for all of `notes`, which isn't empty.
fn alert(notes: &[Note]) -> Alert {
    let mut chats: Vec<&str> = Vec::new();
    for note in notes {
        if !chats.contains(&note.chat.as_str()) {
            chats.push(&note.chat);
        }
    }
    let new = |n: usize| crate::lang::n(n as i64, "{n} new message", "{n} new messages", &[]);
    let (title, body) = match (notes, chats.as_slice()) {
        ([note], _) => (note.chat.clone(), note.text.clone()),
        (_, [chat]) => (chat.to_string(), new(notes.len())),
        _ => (new(notes.len()), chats.join(", ")),
    };
    Alert {
        title: cut(&text::flat(&title), MAX_TITLE),
        body: cut(&text::flat(&body), MAX_BODY),
        silent: notes.iter().all(|n| n.silent),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_detached_tmux_session_notifies_the_desktop_only_if_its_this_computers() {
        use Notifications::{Auto, Dbus, Off};
        let attached = || true;
        let detached = || false;
        assert!(goes_to_desktop(Dbus, false, false, attached));
        assert!(goes_to_desktop(Dbus, false, true, attached), "asked for");
        assert!(goes_to_desktop(Auto, true, false, detached));
        assert!(!goes_to_desktop(Auto, true, true, detached), "over SSH");
        assert!(!goes_to_desktop(Auto, true, false, attached));
        assert!(!goes_to_desktop(Auto, false, false, detached), "no tmux");
        assert!(!goes_to_desktop(Off, true, false, detached));
    }

    fn note(id: i32, chat_id: i64, chat: &str, text: &str) -> Note {
        Note {
            id,
            chat_id,
            chat: chat.into(),
            text: text.into(),
            silent: false,
        }
    }

    fn alert(title: &str, body: &str) -> Alert {
        Alert {
            title: title.into(),
            body: body.into(),
            silent: false,
        }
    }

    #[test]
    fn the_terminal_is_recognized_from_its_environment() {
        let detect_with = |vars: &[(&str, &str)]| {
            let vars: HashMap<String, String> = vars
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();
            detect(|name| vars.get(name).cloned())
        };
        assert_eq!(
            detect_with(&[("TERM_PROGRAM", "ghostty")]),
            Notifications::Osc777
        );
        assert_eq!(
            detect_with(&[("TERM_PROGRAM", "tmux"), ("GHOSTTY_RESOURCES_DIR", "/x")]),
            Notifications::Osc777,
            "inside tmux"
        );
        assert_eq!(
            detect_with(&[("TERM", "xterm-kitty")]),
            Notifications::Osc99
        );
        assert_eq!(detect_with(&[("TERM", "foot")]), Notifications::Osc99);
        assert_eq!(
            detect_with(&[("LC_TERMINAL", "iTerm2")]),
            Notifications::Osc9
        );
        assert_eq!(
            detect_with(&[("TERM_PROGRAM", "Apple_Terminal")]),
            Notifications::Bell
        );
        assert_eq!(
            Notifications::Off.resolve(|_| Some("ghostty".into())),
            Notifications::Off,
            "a setting wins"
        );
    }

    #[test]
    fn each_code_carries_the_title_and_text() {
        let hi = alert("Alice", "see you at 5");
        assert_eq!(
            escape(Notifications::Osc777, &hi, 1, false).unwrap(),
            "\x1b]777;notify;Alice;see you at 5\x07"
        );
        assert_eq!(
            escape(Notifications::Osc9, &hi, 1, false).unwrap(),
            "\x1b]9;Alice: see you at 5\x07"
        );
        assert_eq!(
            escape(Notifications::Osc99, &hi, 7, false).unwrap(),
            "\x1b]99;i=7:d=0:o=unfocused:e=1;QWxpY2U=\x1b\\\
             \x1b]99;i=7:d=1:p=body:e=1;c2VlIHlvdSBhdCA1\x1b\\"
        );
        assert_eq!(escape(Notifications::Bell, &hi, 1, false).unwrap(), "\x07");
        assert_eq!(escape(Notifications::Off, &hi, 1, false), None);
    }

    #[test]
    fn dbus_is_set_by_name_and_sends_no_escape_code() {
        assert_eq!(
            serde_json::from_str::<Notifications>("\"dbus\"").unwrap(),
            Notifications::Dbus
        );
        let hi = alert("Alice", "see you at 5");
        assert_eq!(escape(Notifications::Dbus, &hi, 1, false), None);
    }

    #[test]
    fn a_senders_markup_reaches_the_desktop_as_text() {
        let body = r#"<a href="https://evil">Bank</a> & <img src=x>"#;
        assert_eq!(
            desktop_body(body, true),
            r#"&lt;a href="https://evil"&gt;Bank&lt;/a&gt; &amp; &lt;img src=x&gt;"#
        );
        assert_eq!(desktop_body(body, false), body, "shown as written");

        // The spec makes the title plain text, which GNOME shows as written,
        // but dunst and mako put it in their markup too: lookalikes suit both.
        let name = "<b>Bank</b> & Co";
        assert_eq!(desktop_title(name, true), "‹b›Bank‹/b› & Co");
        assert_eq!(desktop_title(name, false), name);
    }

    #[test]
    fn silent_chats_ring_no_bell() {
        let quiet = Alert {
            silent: true,
            ..alert("Alice", "hi")
        };
        assert_eq!(escape(Notifications::Bell, &quiet, 1, false), None);
        assert!(
            escape(Notifications::Osc99, &quiet, 1, false)
                .unwrap()
                .contains(":s=silent:")
        );
    }

    #[test]
    fn text_from_others_cannot_end_the_code_early() {
        let sneaky = alert("Eve;x", "a\x07b\x1b]0;pwned\x1b\\c\nd;e");
        assert_eq!(
            escape(Notifications::Osc777, &sneaky, 1, false).unwrap(),
            "\x1b]777;notify;Eve,x;ab]0,pwned\\c d,e\x07"
        );
    }

    #[test]
    fn inside_tmux_codes_are_passed_through() {
        let hi = alert("Alice", "hi");
        assert_eq!(
            escape(Notifications::Osc777, &hi, 1, true).unwrap(),
            "\x1bPtmux;\x1b\x1b]777;notify;Alice;hi\x07\x1b\\"
        );
        assert_eq!(escape(Notifications::Bell, &hi, 1, true).unwrap(), "\x07");
    }

    #[test]
    fn messages_arriving_together_make_one_notification() {
        let mut notifier = Notifier::default();
        let now = Instant::now();
        notifier.add(note(1, 10, "Alice", "hi"), now);
        assert_eq!(notifier.due(now).unwrap(), alert("Alice", "hi"));
        assert_eq!(notifier.due(now), None, "nothing left");

        let later = now + QUIET_CHAT;
        notifier.add(note(2, 10, "Alice", "one"), later);
        notifier.add(note(3, 10, "Alice", "two"), later);
        assert_eq!(
            notifier.due(later).unwrap(),
            alert("Alice", "2 new messages")
        );

        let later = later + QUIET_CHAT;
        notifier.add(note(4, 20, "Bob", "yo"), later);
        notifier.add(note(5, 30, "Dev team", "ship it"), later);
        notifier.add(note(6, 20, "Bob", "?"), later);
        assert_eq!(
            notifier.due(later).unwrap(),
            alert("3 new messages", "Bob, Dev team")
        );
    }

    #[test]
    fn in_russian_messages_together_are_counted_in_russian() {
        crate::lang::set(crate::lang::Lang::Ru);
        let mut notifier = Notifier::default();
        let now = Instant::now();
        for (id, chat_id, chat) in [(1, 10, "Alice"), (2, 20, "Bob"), (3, 10, "Alice")] {
            notifier.add(note(id, chat_id, chat, "привет"), now);
        }
        assert_eq!(
            notifier.due(now).unwrap(),
            alert("3 новых сообщения", "Alice, Bob")
        );
        crate::lang::set(crate::lang::Lang::En);
    }

    #[test]
    fn in_vietnamese_messages_together_are_counted_in_vietnamese() {
        crate::lang::set(crate::lang::Lang::Vi);
        let mut notifier = Notifier::default();
        let now = Instant::now();
        for (id, chat_id, chat) in [(1, 10, "Alice"), (2, 20, "Bob"), (3, 10, "Alice")] {
            notifier.add(note(id, chat_id, chat, "chào"), now);
        }
        assert_eq!(
            notifier.due(now).unwrap(),
            alert("3 tin nhắn mới", "Alice, Bob")
        );
        crate::lang::set(crate::lang::Lang::En);
    }

    #[test]
    fn notifications_are_spaced_out_and_busy_chats_stay_quiet() {
        let mut notifier = Notifier::default();
        let now = Instant::now();
        notifier.add(note(1, 10, "Alice", "hi"), now);
        assert!(notifier.due(now).is_some());

        // Bob, a second later, waits for the gap to pass.
        let soon = now + Duration::from_secs(1);
        notifier.add(note(2, 20, "Bob", "yo"), soon);
        assert_eq!(notifier.due(soon), None);
        assert_eq!(notifier.next_at(), Some(now + GAP));
        assert_eq!(notifier.due(now + GAP).unwrap(), alert("Bob", "yo"));

        // Alice again within half a minute: you already know.
        notifier.add(
            note(3, 10, "Alice", "you there?"),
            now + Duration::from_secs(10),
        );
        assert_eq!(notifier.next_at(), None);
        notifier.add(note(4, 10, "Alice", "hello?"), now + QUIET_CHAT);
        assert!(notifier.due(now + QUIET_CHAT).is_some());
    }

    #[test]
    fn notifications_taken_back_are_not_sent() {
        let mut notifier = Notifier::default();
        let now = Instant::now();
        notifier.add(note(1, 10, "Alice", "hi"), now);
        assert!(notifier.due(now).is_some());
        notifier.add(note(2, 20, "Bob", "yo"), now);
        notifier.remove(&[2]);
        assert_eq!(notifier.due(now + GAP), None);
    }

    #[test]
    fn long_text_is_cut_to_one_line() {
        let long = Note {
            text: format!("first line\nsecond {}", "x".repeat(300)),
            ..note(1, 10, "Alice", "")
        };
        let alert = super::alert(&[long]);
        assert!(alert.body.starts_with("first line second xx"));
        assert_eq!(alert.body.chars().count(), MAX_BODY);
        assert!(alert.body.ends_with('…'));
    }
}