BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / typing.rs

typing.rs

typing.rs 10.6 KiB Download Raw
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use chrono::{DateTime, Utc};
5
6use crate::format::first_name;
7
8pub const SEND_INTERVAL: Duration = Duration::from_secs(20);
9pub const REMOTE_TIMEOUT: Duration = Duration::from_secs(22);
10const UNKNOWN_NAME: &str = "Someone";
11const LISTED_FIRST_NAMES: usize = 2;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14struct Typer {
15 user_id: String,
16 name: String,
17 last_seen: Instant,
18 last_seen_at: DateTime<Utc>,
19}
20
21#[derive(Debug, Default)]
22pub struct TypingState {
23 conversations: HashMap<String, Vec<Typer>>,
24}
25
26impl TypingState {
27 pub fn start(
28 &mut self,
29 conversation_id: &str,
30 user_id: &str,
31 name: &str,
32 now: Instant,
33 at: DateTime<Utc>,
34 ) {
35 let typers = self
36 .conversations
37 .entry(conversation_id.to_owned())
38 .or_default();
39 match typers.iter_mut().find(|typer| typer.user_id == user_id) {
40 Some(typer) => {
41 typer.last_seen = now;
42 typer.last_seen_at = at;
43 if !name.is_empty() {
44 typer.name = name.to_owned();
45 }
46 }
47 None => typers.push(Typer {
48 user_id: user_id.to_owned(),
49 name: name.to_owned(),
50 last_seen: now,
51 last_seen_at: at,
52 }),
53 }
54 }
55
56 pub fn clear(&mut self, conversation_id: &str, user_id: &str) -> bool {
57 self.remove_where(conversation_id, |typer| typer.user_id == user_id)
58 }
59
60 pub fn message_from(
61 &mut self,
62 conversation_id: &str,
63 user_id: &str,
64 sent_at: DateTime<Utc>,
65 ) -> bool {
66 self.remove_where(conversation_id, |typer| {
67 typer.user_id == user_id && sent_at >= typer.last_seen_at
68 })
69 }
70
71 pub fn expire(&mut self, now: Instant) -> bool {
72 let before = self.conversations.values().map(Vec::len).sum::<usize>();
73 for typers in self.conversations.values_mut() {
74 typers.retain(|typer| now.duration_since(typer.last_seen) < REMOTE_TIMEOUT);
75 }
76 self.conversations.retain(|_, typers| !typers.is_empty());
77 before != self.conversations.values().map(Vec::len).sum::<usize>()
78 }
79
80 pub fn next_expiry(&self) -> Option<Instant> {
81 self.conversations
82 .values()
83 .flatten()
84 .map(|typer| typer.last_seen + REMOTE_TIMEOUT)
85 .min()
86 }
87
88 pub fn names(&self, conversation_id: &str) -> Vec<String> {
89 self.conversations
90 .get(conversation_id)
91 .into_iter()
92 .flatten()
93 .map(|typer| match typer.name.trim() {
94 "" => UNKNOWN_NAME.to_owned(),
95 name => name.to_owned(),
96 })
97 .collect()
98 }
99
100 pub fn is_active(&self, conversation_id: &str) -> bool {
101 self.conversations.contains_key(conversation_id)
102 }
103
104 fn remove_where(&mut self, conversation_id: &str, matches: impl Fn(&Typer) -> bool) -> bool {
105 let Some(typers) = self.conversations.get_mut(conversation_id) else {
106 return false;
107 };
108 let before = typers.len();
109 typers.retain(|typer| !matches(typer));
110 let changed = typers.len() != before;
111 if typers.is_empty() {
112 self.conversations.remove(conversation_id);
113 }
114 changed
115 }
116}
117
118pub fn typing_label(names: &[String]) -> String {
119 match names {
120 [] => String::new(),
121 [only] => format!("{only} is typing"),
122 [first, second] => {
123 format!("{first} and {second} are typing")
124 }
125 [first, second, third] => format!(
126 "{}, {}, and {} are typing",
127 first_name(first),
128 first_name(second),
129 first_name(third)
130 ),
131 _ => format!(
132 "{}, {}, and {} others are typing",
133 first_name(&names[0]),
134 first_name(&names[1]),
135 names.len() - LISTED_FIRST_NAMES
136 ),
137 }
138}
139
140pub fn preview_label(names: &[String], one_on_one: bool) -> String {
141 match names {
142 [] => String::new(),
143 [_] if one_on_one => "typing...".to_owned(),
144 [only] => format!("{} is typing...", first_name(only)),
145 _ => format!("{} people are typing...", names.len()),
146 }
147}
148
149#[derive(Debug, Default)]
150pub struct OutgoingTyping {
151 sent_at: Option<Instant>,
152}
153
154impl OutgoingTyping {
155 /// `Some(true)` asks for a Typing signal, `Some(false)` for a ClearTyping.
156 pub fn on_text(&mut self, has_text: bool, now: Instant) -> Option<bool> {
157 if !has_text {
158 return self.sent_at.take().map(|_| false);
159 }
160 let due = self
161 .sent_at
162 .is_none_or(|sent_at| now.duration_since(sent_at) >= SEND_INTERVAL);
163 due.then(|| {
164 self.sent_at = Some(now);
165 true
166 })
167 }
168
169 pub fn stop(&mut self) -> bool {
170 self.sent_at.take().is_some()
171 }
172
173 pub fn reset(&mut self) {
174 self.sent_at = None;
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 fn names(list: &[&str]) -> Vec<String> {
183 list.iter().map(|name| (*name).to_owned()).collect()
184 }
185
186 fn at(seconds: i64) -> DateTime<Utc> {
187 DateTime::from_timestamp(1_790_000_000 + seconds, 0).unwrap()
188 }
189
190 #[test]
191 fn label_has_four_forms() {
192 assert_eq!(typing_label(&[]), "");
193 assert_eq!(
194 typing_label(&names(&["Ada Lovelace"])),
195 "Ada Lovelace is typing"
196 );
197 assert_eq!(
198 typing_label(&names(&["Ada Lovelace", "Alan Turing"])),
199 "Ada Lovelace and Alan Turing are typing"
200 );
201 assert_eq!(
202 typing_label(&names(&["Ada Lovelace", "Alan Turing", "Grace Hopper"])),
203 "Ada, Alan, and Grace are typing"
204 );
205 assert_eq!(
206 typing_label(&names(&[
207 "Ada Lovelace",
208 "Alan Turing",
209 "Grace Hopper",
210 "Linus T"
211 ])),
212 "Ada, Alan, and 2 others are typing"
213 );
214 assert_eq!(
215 typing_label(&names(&["A B", "C D", "E F", "G H", "I J"])),
216 "A, C, and 3 others are typing"
217 );
218 }
219
220 #[test]
221 fn preview_label_depends_on_chat_kind_and_count() {
222 assert_eq!(preview_label(&names(&["Ada Lovelace"]), true), "typing...");
223 assert_eq!(
224 preview_label(&names(&["Ada Lovelace"]), false),
225 "Ada is typing..."
226 );
227 assert_eq!(
228 preview_label(&names(&["Ada Lovelace", "Alan Turing"]), false),
229 "2 people are typing..."
230 );
231 assert_eq!(preview_label(&[], false), "");
232 }
233
234 #[test]
235 fn start_refreshes_without_duplicating_and_keeps_order() {
236 let mut state = TypingState::default();
237 let now = Instant::now();
238 state.start("c", "u1", "Ada", now, at(0));
239 state.start("c", "u2", "Alan", now, at(0));
240 state.start("c", "u1", "", now + Duration::from_secs(5), at(5));
241 assert_eq!(state.names("c"), names(&["Ada", "Alan"]));
242 assert!(state.is_active("c"));
243 assert!(!state.is_active("other"));
244 }
245
246 #[test]
247 fn blank_names_read_as_someone() {
248 let mut state = TypingState::default();
249 state.start("c", "u1", " ", Instant::now(), at(0));
250 assert_eq!(state.names("c"), names(&["Someone"]));
251 }
252
253 #[test]
254 fn clear_removes_only_that_user() {
255 let mut state = TypingState::default();
256 let now = Instant::now();
257 state.start("c", "u1", "Ada", now, at(0));
258 state.start("c", "u2", "Alan", now, at(0));
259 assert!(state.clear("c", "u1"));
260 assert!(!state.clear("c", "u1"));
261 assert_eq!(state.names("c"), names(&["Alan"]));
262 assert!(state.clear("c", "u2"));
263 assert!(!state.is_active("c"));
264 }
265
266 #[test]
267 fn a_message_clears_its_sender_only_when_sent_after_the_typing() {
268 let mut state = TypingState::default();
269 let now = Instant::now();
270 state.start("c", "u1", "Ada", now, at(10));
271 assert!(!state.message_from("c", "u1", at(9)));
272 assert!(!state.message_from("c", "u2", at(11)));
273 assert!(!state.message_from("other", "u1", at(11)));
274 assert!(state.message_from("c", "u1", at(11)));
275 assert!(!state.is_active("c"));
276 }
277
278 #[test]
279 fn typers_expire_after_the_timeout_and_a_refresh_extends_it() {
280 let mut state = TypingState::default();
281 let start = Instant::now();
282 state.start("c", "u1", "Ada", start, at(0));
283 state.start("c", "u2", "Alan", start + Duration::from_secs(10), at(10));
284 assert_eq!(state.next_expiry(), Some(start + REMOTE_TIMEOUT));
285 assert!(!state.expire(start + REMOTE_TIMEOUT - Duration::from_millis(1)));
286 assert!(state.expire(start + REMOTE_TIMEOUT));
287 assert_eq!(state.names("c"), names(&["Alan"]));
288 assert_eq!(
289 state.next_expiry(),
290 Some(start + Duration::from_secs(10) + REMOTE_TIMEOUT)
291 );
292 assert!(state.expire(start + Duration::from_secs(32)));
293 assert_eq!(state.next_expiry(), None);
294 assert!(!state.expire(start + Duration::from_secs(100)));
295 }
296
297 #[test]
298 fn outgoing_sends_at_most_every_twenty_seconds_while_typing() {
299 let mut outgoing = OutgoingTyping::default();
300 let start = Instant::now();
301 assert_eq!(outgoing.on_text(true, start), Some(true));
302 assert_eq!(
303 outgoing.on_text(true, start + Duration::from_secs(19)),
304 None
305 );
306 assert_eq!(
307 outgoing.on_text(true, start + Duration::from_secs(20)),
308 Some(true)
309 );
310 }
311
312 #[test]
313 fn outgoing_clears_once_when_the_text_empties() {
314 let mut outgoing = OutgoingTyping::default();
315 let start = Instant::now();
316 assert_eq!(outgoing.on_text(false, start), None);
317 outgoing.on_text(true, start);
318 assert_eq!(outgoing.on_text(false, start), Some(false));
319 assert_eq!(outgoing.on_text(false, start), None);
320 assert_eq!(outgoing.on_text(true, start), Some(true));
321 }
322
323 #[test]
324 fn outgoing_stop_reports_only_after_a_typing_was_sent() {
325 let mut outgoing = OutgoingTyping::default();
326 assert!(!outgoing.stop());
327 outgoing.on_text(true, Instant::now());
328 assert!(outgoing.stop());
329 assert!(!outgoing.stop());
330 }
331
332 #[test]
333 fn outgoing_reset_forgets_without_a_clear() {
334 let mut outgoing = OutgoingTyping::default();
335 let start = Instant::now();
336 outgoing.on_text(true, start);
337 outgoing.reset();
338 assert_eq!(outgoing.on_text(false, start), None);
339 }
340}