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
//! Polls: drawn as text in their bubble, with how people voted once you
//! have (as in Telegram), and Enter to vote.

use tdlib_rs::enums::PollType;
use tdlib_rs::types;

use crate::lang;
use crate::messages::without_spoilers;
use crate::text;

/// Cells of the bar that shows an answer's share of the votes.
const BAR: usize = 10;

/// A poll, as its message shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Poll {
    pub question: String,
    pub answers: Vec<Answer>,
    pub voters: i32,
    /// Voters can pick more than one answer.
    pub several: bool,
    /// A quiz has one right answer.
    pub quiz: bool,
    /// The right answer of a quiz, once Telegram says: after you answered,
    /// or once it's closed.
    pub correct: Option<usize>,
    pub anonymous: bool,
    pub closed: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Answer {
    pub text: String,
    pub voters: i32,
    pub percent: i32,
    /// You picked it.
    pub chosen: bool,
}

impl Poll {
    pub fn new(poll: &types::Poll) -> Self {
        let line = |text: &types::FormattedText| text::flat(&without_spoilers(text));
        let (several, quiz, correct) = match &poll.r#type {
            PollType::Regular(r) => (r.allow_multiple_answers, false, None),
            PollType::Quiz(q) => (false, true, usize::try_from(q.correct_option_id).ok()),
        };
        Poll {
            question: line(&poll.question),
            answers: poll
                .options
                .iter()
                .map(|o| Answer {
                    text: line(&o.text),
                    voters: o.voter_count,
                    percent: o.vote_percentage.clamp(0, 100),
                    chosen: o.is_chosen,
                })
                .collect(),
            voters: poll.total_voter_count,
            several,
            quiz,
            correct,
            anonymous: poll.is_anonymous,
            closed: poll.is_closed,
        }
    }

    pub fn voted(&self) -> bool {
        self.answers.iter().any(|a| a.chosen)
    }

    /// Why Enter can't vote in it, if it can't.
    pub fn cant_vote(&self) -> Option<&'static str> {
        if self.closed && self.quiz {
            Some(lang::tc("quiz", "This poll is closed"))
        } else if self.closed {
            Some(lang::t("This poll is closed"))
        } else if self.quiz && self.voted() {
            Some(lang::t("You answered this quiz"))
        } else {
            None
        }
    }

    /// The poll as its bubble's text: the question, what kind of poll it
    /// is, then the answers, with how they're doing once you voted or it
    /// closed, as Telegram shows them.
    pub fn text(&self) -> String {
        let kind = match (self.anonymous, self.quiz) {
            (true, true) => lang::t("Anonymous quiz"),
            (true, false) => lang::t("Anonymous poll"),
            (false, true) => lang::t("Quiz"),
            (false, false) => lang::t("Poll"),
        };
        let votes = lang::n(self.voters.into(), "{n} vote", "{n} votes", &[]);
        let mut about = vec![kind.to_string()];
        if self.several {
            about.push(lang::t("pick several").into());
        }
        about.push(votes);
        if self.closed {
            let closed = match self.quiz {
                true => lang::tc("quiz", "closed"),
                false => lang::t("closed"),
            };
            about.push(closed.into());
        }
        let mut lines = vec![format!("📊 {}", self.question), about.join(" · ")];
        let results = self.voted() || self.closed;
        for (i, answer) in self.answers.iter().enumerate() {
            let mark = match () {
                _ if results && self.correct == Some(i) => "✓",
                _ if answer.chosen && self.quiz => "✗",
                _ if answer.chosen => "●",
                _ => "○",
            };
            lines.push(format!("{mark} {}", answer.text));
            if results {
                let filled = (answer.percent as usize * BAR + 50) / 100;
                let bar = format!("{}{}", "█".repeat(filled), "░".repeat(BAR - filled));
                lines.push(format!("  {bar} {}%", answer.percent));
            }
        }
        lines.join("\n")
    }
}

/// Enter on a poll: its answers to vote for. With several allowed, Space
/// ticks them and Enter sends the ticked ones.
pub struct VoteMenu {
    pub message_id: i64,
    pub question: String,
    pub answers: Vec<String>,
    pub ticked: Vec<bool>,
    pub several: bool,
    /// You voted, so a last row takes it back.
    pub can_retract: bool,
    pub selected: usize,
}

/// What Enter in the vote popup does.
#[derive(Debug, PartialEq, Eq)]
pub enum Vote {
    /// Vote for these answers, by index.
    For(Vec<i32>),
    Retract,
}

impl VoteMenu {
    pub fn new(message_id: i64, poll: &Poll) -> Self {
        Self {
            message_id,
            question: poll.question.clone(),
            answers: poll.answers.iter().map(|a| a.text.clone()).collect(),
            ticked: poll.answers.iter().map(|a| a.chosen).collect(),
            several: poll.several,
            can_retract: poll.voted(),
            // On your answer, so it's clear what you voted for.
            selected: poll.answers.iter().position(|a| a.chosen).unwrap_or(0),
        }
    }

    /// Rows: the answers, then "take back" if you voted.
    pub fn rows(&self) -> usize {
        self.answers.len() + usize::from(self.can_retract)
    }

    pub fn move_by(&mut self, delta: isize) {
        let last = self.rows().saturating_sub(1);
        self.selected = self.selected.saturating_add_signed(delta).min(last);
    }

    /// Space: ticks or unticks the answer under the cursor, in a poll that
    /// takes several.
    pub fn tick(&mut self) {
        if self.several
            && let Some(ticked) = self.ticked.get_mut(self.selected)
        {
            *ticked = !*ticked;
        }
    }

    /// Enter: the answer under the cursor, or the ticked ones in a poll
    /// that takes several (the one under the cursor if none are).
    pub fn vote(&self) -> Vote {
        if self.selected >= self.answers.len() {
            return Vote::Retract;
        }
        let ticked: Vec<i32> = (0..self.answers.len())
            .filter(|&i| self.ticked[i])
            .map(|i| i as i32)
            .collect();
        if self.several && !ticked.is_empty() {
            Vote::For(ticked)
        } else {
            Vote::For(vec![self.selected as i32])
        }
    }
}

/// The fewest answers a poll takes, as Telegram allows.
pub const MIN_ANSWERS: usize = 2;
/// The most answers a poll takes, as Telegram allows.
pub const MAX_ANSWERS: usize = 10;
/// The longest question Telegram takes, in characters.
pub const MAX_QUESTION: usize = 255;
/// The longest answer Telegram takes, in characters.
pub const MAX_ANSWER: usize = 100;

/// A text's length as Telegram counts it: in UTF-16 units, two for an emoji
/// past U+FFFF.
fn telegram_length(text: &str) -> usize {
    text.encode_utf16().count()
}

/// Which line of a poll the `:poll` prompts are asking for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollStep {
    Question,
    /// One answer at a time; an empty line finishes them.
    Answer,
    Flags,
}

/// A poll being made through the `:poll` prompts: what's gathered so far.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PollDraft {
    pub question: String,
    pub answers: Vec<String>,
}

impl PollDraft {
    /// The question line: kept if it isn't empty or longer than Telegram
    /// takes, then answers are asked.
    pub fn set_question(&mut self, text: &str) -> Result<PollStep, String> {
        let text = text.trim();
        if text.is_empty() {
            return Err(lang::t("A poll needs a question").into());
        }
        if telegram_length(text) > MAX_QUESTION {
            return Err(lang::f(
                "A poll's question takes at most {max} characters",
                &[("max", &MAX_QUESTION)],
            ));
        }
        self.question = text.into();
        Ok(PollStep::Answer)
    }

    /// An answer line, or an empty one to stop adding: with at least
    /// [`MIN_ANSWERS`] it's on to the flags; with fewer it says so and
    /// stays. The [`MAX_ANSWERS`]th answer goes to the flags by itself.
    /// One Telegram wouldn't take, too long or there already, stays to fix.
    pub fn add_answer(&mut self, text: &str) -> Result<PollStep, String> {
        let text = text.trim();
        if text.is_empty() {
            if self.answers.len() < MIN_ANSWERS {
                return Err(lang::f(
                    "A poll takes at least {min} answers",
                    &[("min", &MIN_ANSWERS)],
                ));
            }
            return Ok(PollStep::Flags);
        }
        if telegram_length(text) > MAX_ANSWER {
            return Err(lang::f(
                "An answer takes at most {max} characters",
                &[("max", &MAX_ANSWER)],
            ));
        }
        if self.answers.iter().any(|a| a == text) {
            return Err(lang::t("That answer is there already").into());
        }
        self.answers.push(text.into());
        Ok(match self.answers.len() {
            MAX_ANSWERS => PollStep::Flags,
            _ => PollStep::Answer,
        })
    }
}

/// The flags line of the `:poll` wizard: `a` for an anonymous poll (on to
/// start with), `m` to allow several answers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PollFlags {
    pub anonymous: bool,
    pub several: bool,
}

impl PollFlags {
    /// The flags as typed, so `am` and `ma` are the same. Anything that
    /// isn't `a` or `m` is a typo, and is said; so is a public poll in a
    /// `channel`, which Telegram doesn't take.
    pub fn parse(text: &str, channel: bool) -> Result<Self, String> {
        let text = text.trim();
        if !text.chars().all(|c| matches!(c, 'a' | 'm')) {
            return Err(
                lang::t("Poll flags are only a (anonymous) and m (several answers)").into(),
            );
        }
        let anonymous = text.contains('a');
        if channel && !anonymous {
            return Err(lang::t("Polls in a channel are anonymous: keep the a").into());
        }
        Ok(Self {
            anonymous,
            several: text.contains('m'),
        })
    }
}

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

    fn poll(chosen: Option<usize>, closed: bool) -> Poll {
        let answer = |text: &str, voters, percent, i| Answer {
            text: text.into(),
            voters,
            percent,
            chosen: chosen == Some(i),
        };
        Poll {
            question: "Lunch?".into(),
            answers: vec![answer("Pizza", 5, 62, 0), answer("Sushi", 3, 38, 1)],
            voters: 8,
            several: false,
            quiz: false,
            correct: None,
            anonymous: true,
            closed,
        }
    }

    #[test]
    fn the_poll_wizard_gathers_a_question_then_two_to_ten_answers() {
        let mut draft = PollDraft::default();
        assert_eq!(
            draft.set_question("  "),
            Err("A poll needs a question".into())
        );
        assert_eq!(draft.set_question(" Lunch? "), Ok(PollStep::Answer));
        assert_eq!(draft.question, "Lunch?");

        // An empty line before two answers stays, saying why.
        assert_eq!(
            draft.add_answer(""),
            Err("A poll takes at least 2 answers".into())
        );
        assert_eq!(draft.add_answer("Pizza"), Ok(PollStep::Answer));
        assert_eq!(draft.add_answer(" Sushi "), Ok(PollStep::Answer));
        assert_eq!(draft.answers, ["Pizza", "Sushi"]);

        // With two, an empty line is on to the flags.
        assert_eq!(draft.add_answer(""), Ok(PollStep::Flags));

        // More answers, to the most: the tenth goes on by itself.
        let mut draft = PollDraft::default();
        for i in 1..MAX_ANSWERS {
            assert_eq!(draft.add_answer(&format!("{i}")), Ok(PollStep::Answer));
        }
        assert_eq!(draft.add_answer("10"), Ok(PollStep::Flags));
        assert_eq!(draft.answers.len(), MAX_ANSWERS);
    }

    #[test]
    fn the_poll_wizard_refuses_what_telegram_would_and_keeps_the_rest() {
        let mut draft = PollDraft::default();
        let long = "?".repeat(MAX_QUESTION + 1);
        assert!(draft.set_question(&long).is_err());
        assert!(draft.question.is_empty(), "not kept");
        let longest = "?".repeat(MAX_QUESTION);
        assert_eq!(draft.set_question(&longest), Ok(PollStep::Answer));

        assert!(draft.add_answer(&"!".repeat(MAX_ANSWER + 1)).is_err());
        // Telegram counts UTF-16 units, which an emoji past U+FFFF takes two of.
        let emoji = "🗳".repeat(MAX_ANSWER / 2 + 1);
        assert!(
            draft.add_answer(&emoji).is_err(),
            "{} units",
            MAX_ANSWER + 2
        );
        assert_eq!(
            draft.add_answer(&"!".repeat(MAX_ANSWER)),
            Ok(PollStep::Answer)
        );
        assert_eq!(draft.add_answer("Yes"), Ok(PollStep::Answer));
        assert_eq!(
            draft.add_answer(" Yes "),
            Err("That answer is there already".into())
        );
        assert_eq!(draft.answers.len(), 2, "the one refused isn't kept");

        // A channel's polls are anonymous.
        assert!(PollFlags::parse("m", true).is_err());
        assert!(PollFlags::parse("am", true).is_ok());
        assert!(PollFlags::parse("m", false).is_ok());
    }

    #[test]
    fn the_flags_line_toggles_anonymous_and_several_answers() {
        let flags = |text| PollFlags::parse(text, false);
        assert_eq!(
            flags("a"),
            Ok(PollFlags {
                anonymous: true,
                several: false
            })
        );
        assert_eq!(
            flags("m"),
            Ok(PollFlags {
                anonymous: false,
                several: true
            })
        );
        assert_eq!(flags("am"), flags("ma"), "the order doesn't matter");
        assert_eq!(
            flags(""),
            Ok(PollFlags::default()),
            "neither: public, one answer"
        );
        assert!(flags("am ").is_ok(), "spaces around are fine");
        assert!(flags("x").is_err());
        assert!(flags("a x").is_err());
    }

    #[test]
    fn results_show_once_you_voted_or_the_poll_closed() {
        assert_eq!(
            poll(None, false).text(),
            "📊 Lunch?\nAnonymous poll · 8 votes\n○ Pizza\n○ Sushi"
        );
        assert_eq!(
            poll(Some(1), false).text(),
            "📊 Lunch?\nAnonymous poll · 8 votes\n○ Pizza\n  ██████░░░░ 62%\n● Sushi\n  ████░░░░░░ 38%"
        );
        assert!(
            poll(None, true)
                .text()
                .contains("closed\n○ Pizza\n  ██████")
        );
    }

    #[test]
    fn a_quiz_marks_the_right_answer_and_yours_if_wrong() {
        let mut quiz = poll(Some(1), false);
        quiz.quiz = true;
        quiz.correct = Some(0);
        let text = quiz.text();
        assert!(
            text.contains("✓ Pizza") && text.contains("✗ Sushi"),
            "{text}"
        );
        assert_eq!(quiz.cant_vote(), Some("You answered this quiz"));
        assert_eq!(poll(None, true).cant_vote(), Some("This poll is closed"));
        assert_eq!(poll(Some(0), false).cant_vote(), None, "a vote can change");
    }

    #[test]
    fn in_russian_a_poll_counts_its_votes_in_russian() {
        crate::lang::set(crate::lang::Lang::Ru);
        assert_eq!(
            poll(None, false).text(),
            "📊 Lunch?\nАнонимный опрос · 8 голосов\n○ Pizza\n○ Sushi"
        );
        let mut one = poll(None, true);
        one.voters = 21;
        one.several = true;
        assert!(
            one.text()
                .contains("Анонимный опрос · несколько ответов · 21 голос · завершён"),
            "{}",
            one.text()
        );
        one.voters = 3;
        assert!(one.text().contains("3 голоса"));
        assert_eq!(one.cant_vote(), Some("Этот опрос завершён"));
    }

    #[test]
    fn in_vietnamese_a_count_of_votes_has_one_form() {
        crate::lang::set(crate::lang::Lang::Vi);
        let mut one = poll(None, true);
        one.voters = 21;
        one.several = true;
        assert!(
            one.text()
                .contains("Bình chọn ẩn danh · chọn nhiều · 21 phiếu · đã kết thúc"),
            "{}",
            one.text()
        );
        one.quiz = true;
        assert_eq!(one.cant_vote(), Some("Câu đố này đã kết thúc"));
    }

    #[test]
    fn the_vote_popup_picks_one_ticks_several_or_takes_yours_back() {
        let mut menu = VoteMenu::new(1, &poll(None, false));
        assert_eq!(menu.rows(), 2);
        menu.move_by(1);
        assert_eq!(menu.vote(), Vote::For(vec![1]));
        menu.tick();
        assert_eq!(
            menu.vote(),
            Vote::For(vec![1]),
            "nothing to tick in a one-answer poll"
        );

        let mut several = poll(Some(0), false);
        several.several = true;
        let mut menu = VoteMenu::new(1, &several);
        assert_eq!(menu.selected, 0, "on your answer");
        assert_eq!(menu.rows(), 3, "with take back");
        menu.move_by(1);
        menu.tick();
        assert_eq!(menu.vote(), Vote::For(vec![0, 1]));
        menu.move_by(5);
        assert_eq!(menu.vote(), Vote::Retract);
    }
}