1use std::collections::{HashMap, VecDeque};
9use std::io;
10use std::time::Duration;
11
12use serde::Serialize;
13use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, BufReader};
14use tokio::net::TcpStream;
15
16use crate::personal::{self, Phonebook};
17
18pub const PORT: u16 = 1012;
20
21pub const HINT: &str = "the call monitor may be off: dial #96*5* on a phone connected to the \
23 device to turn it on, #96*4* turns it off";
24
25const MAX_LINE: u64 = 512;
27
28const BACKOFF: Duration = Duration::from_secs(1);
31const MAX_BACKOFF: Duration = Duration::from_secs(60);
32
33const SEEN: usize = 64;
35
36#[derive(Debug, thiserror::Error)]
38#[error("cannot connect to the call monitor at {address}: {error}; {HINT}")]
39pub struct Error {
40 pub address: String,
41 pub error: io::Error,
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
47pub struct Event {
48 pub time: String,
50 pub kind: &'static str,
52 pub id: u32,
54 pub number: Option<String>,
56 pub name: Option<String>,
58 pub own_number: Option<String>,
60 pub extension: Option<String>,
62 pub line: Option<String>,
64 pub seconds: Option<u64>,
66}
67
68pub fn parse(line: &str) -> Option<Event> {
71 let line = line.trim_end_matches(['\r', '\n']);
72 let fields: Vec<&str> = line.strip_suffix(';')?.split(';').collect();
73 let (time, kind, id) = (fields.first()?, fields.get(1)?, fields.get(2)?);
74 let event = Event {
75 time: time_of(time)?,
76 id: count(id, 5)?,
77 ..Event::default()
78 };
79 let field = |index: usize| fields.get(index).copied();
80 let event = match (*kind, fields.len()) {
81 ("RING", 6) => Event {
82 kind: "ring",
83 number: number(field(3)?)?,
84 own_number: number(field(4)?)?,
85 line: Some(line_of(field(5)?)?),
86 ..event
87 },
88 ("CALL", 7) => Event {
89 kind: "call",
90 extension: Some(extension(field(3)?)?),
91 own_number: number(field(4)?)?,
92 number: number(field(5)?)?,
93 line: Some(line_of(field(6)?)?),
94 ..event
95 },
96 ("CONNECT", 5) => Event {
97 kind: "connect",
98 extension: Some(extension(field(3)?)?),
99 number: number(field(4)?)?,
100 ..event
101 },
102 ("DISCONNECT", 4) => Event {
103 kind: "disconnect",
104 seconds: Some(count(field(3)?, 9)?),
105 ..event
106 },
107 _ => return None,
108 };
109 Some(event)
110}
111
112fn time_of(text: &str) -> Option<String> {
114 let (day, time) = text.split_once(' ')?;
115 let parts: Vec<&str> = time.split(':').collect();
116 let valid = personal::is_date(day)
117 && parts.len() == 3
118 && parts.iter().all(|p| p.len() == 2 && is_digits(p, 2));
119 valid.then(|| personal::date(text))
120}
121
122#[allow(clippy::option_option)]
125fn number(text: &str) -> Option<Option<String>> {
126 let digits = text.strip_prefix('+').unwrap_or(text);
127 let valid = text.len() <= 40
128 && digits
129 .bytes()
130 .all(|b| b.is_ascii_digit() || b == b'*' || b == b'#');
131 match text {
132 "" => Some(None),
133 _ if valid && !digits.is_empty() => Some(Some(text.to_owned())),
134 _ => None,
135 }
136}
137
138fn extension(text: &str) -> Option<String> {
140 is_digits(text, 4).then(|| text.to_owned())
141}
142
143fn line_of(text: &str) -> Option<String> {
145 let valid =
146 !text.is_empty() && text.len() <= 16 && text.bytes().all(|b| b.is_ascii_alphanumeric());
147 valid.then(|| text.to_owned())
148}
149
150fn count<T: std::str::FromStr>(text: &str, max: usize) -> Option<T> {
152 is_digits(text, max).then(|| text.parse().ok()).flatten()
153}
154
155fn is_digits(text: &str, max: usize) -> bool {
157 (1..=max).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
158}
159
160#[derive(Debug, Clone, Default)]
162pub struct Names(HashMap<String, String>);
163
164impl Names {
165 pub fn new(phonebooks: &[Phonebook]) -> Self {
167 let mut names = HashMap::new();
168 for contact in phonebooks.iter().flat_map(|p| &p.contacts) {
169 let Some(name) = &contact.name else { continue };
170 for number in &contact.numbers {
171 let digits = personal::digits(&number.number);
172 if !digits.is_empty() {
173 names.entry(digits).or_insert_with(|| name.clone());
174 }
175 }
176 }
177 Self(names)
178 }
179
180 pub fn name(&self, event: &mut Event) {
182 let digits = event.number.as_deref().map(personal::digits);
183 event.name = digits.and_then(|d| self.0.get(&d)).cloned();
184 }
185}
186
187#[derive(Debug)]
189pub struct Monitor {
190 address: (String, u16),
191 stream: Option<BufReader<TcpStream>>,
192 backoff: Duration,
193 seen: VecDeque<(String, &'static str, u32)>,
194}
195
196impl Monitor {
197 pub async fn connect(host: &str, port: u16) -> Result<Self, Error> {
205 let host = host.trim_start_matches('[').trim_end_matches(']');
206 let address = (host.to_owned(), port);
207 let stream = open(&address).await.map_err(|error| Error {
208 address: format!("{}:{port}", address.0),
209 error,
210 })?;
211 Ok(Self {
212 address,
213 stream: Some(stream),
214 backoff: BACKOFF,
215 seen: VecDeque::new(),
216 })
217 }
218
219 pub async fn next(&mut self, note: &mut impl FnMut(String)) -> Event {
223 loop {
224 if let Some(stream) = &mut self.stream {
225 match read_line(stream).await {
226 Ok(Some(line)) => match self.accept(&line) {
227 Some(event) => return event,
228 None => continue,
229 },
230 Ok(None) => note("the call monitor closed the connection".to_owned()),
231 Err(error) => note(format!("lost the call monitor: {error}")),
232 }
233 self.stream = None;
234 }
235 note(format!("connecting again in {}s", self.backoff.as_secs()));
236 tokio::time::sleep(self.backoff).await;
237 self.backoff = (self.backoff * 2).min(MAX_BACKOFF);
238 match open(&self.address).await {
239 Ok(stream) => self.stream = Some(stream),
240 Err(error) => note(format!("cannot connect to the call monitor: {error}")),
241 }
242 }
243 }
244
245 fn accept(&mut self, line: &str) -> Option<Event> {
247 let Some(event) = parse(line) else {
248 tracing::debug!(bytes = line.len(), "skipped a line that is not an event");
249 return None;
250 };
251 let key = (event.time.clone(), event.kind, event.id);
252 if self.seen.contains(&key) {
253 tracing::debug!("skipped an event seen before");
254 return None;
255 }
256 if self.seen.len() == SEEN {
257 self.seen.pop_front();
258 }
259 self.seen.push_back(key);
260 self.backoff = BACKOFF;
261 Some(event)
262 }
263}
264
265async fn open(address: &(String, u16)) -> io::Result<BufReader<TcpStream>> {
266 let stream = TcpStream::connect((address.0.as_str(), address.1)).await?;
267 Ok(BufReader::new(stream))
268}
269
270async fn read_line(stream: &mut BufReader<TcpStream>) -> io::Result<Option<String>> {
273 let mut line = Vec::new();
274 let read = (&mut *stream)
275 .take(MAX_LINE)
276 .read_until(b'\n', &mut line)
277 .await?;
278 Ok((read > 0).then(|| String::from_utf8_lossy(&line).into_owned()))
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284 use crate::personal::{Contact, ContactNumber};
285
286 #[test]
287 fn parses_events() {
288 let ring = parse("23.11.26 18:02:11;RING;0;030987;030123;SIP0;\r\n").unwrap();
289 assert_eq!(
290 ring,
291 Event {
292 time: "2026-11-23 18:02:11".to_owned(),
293 kind: "ring",
294 id: 0,
295 number: Some("030987".to_owned()),
296 own_number: Some("030123".to_owned()),
297 line: Some("SIP0".to_owned()),
298 ..Event::default()
299 }
300 );
301 let call = parse("23.11.26 18:10:03;CALL;1;10;030123;+49157*#;SIP1;").unwrap();
302 assert_eq!(
303 (call.kind, call.extension.as_deref(), call.number.as_deref()),
304 ("call", Some("10"), Some("+49157*#"))
305 );
306 let connect = parse("23.11.26 18:02:15;CONNECT;0;12;;").unwrap();
307 assert_eq!((connect.kind, connect.number), ("connect", None));
308 let disconnect = parse("23.11.26 18:04:40;DISCONNECT;0;145;").unwrap();
309 assert_eq!(
310 (disconnect.kind, disconnect.seconds),
311 ("disconnect", Some(145))
312 );
313 }
314
315 #[test]
316 fn skips_invalid_lines() {
317 for line in [
318 "",
319 "hello",
320 "23.11.26 18:02:11;RING;0;030987;030123;SIP0;extra;",
321 "23.11.26 18:02:11;HANGUP;0;",
322 "23.11.2026 18:02:11;DISCONNECT;0;1;",
323 "23.11.26 18:02;DISCONNECT;0;1;",
324 "23.11.26 18:02:1x;DISCONNECT;0;1;",
325 "23.11.26;DISCONNECT;0;1;",
326 "23.11.26 18:02:11;DISCONNECT;x;1;",
327 "23.11.26 18:02:11;DISCONNECT;0;-1;",
328 "23.11.26 18:02:11;RING;0;03\x1b[2J;030123;SIP0;",
329 "23.11.26 18:02:11;RING;0;+;030123;SIP0;",
330 "23.11.26 18:02:11;RING;0;030987;030123;;",
331 "23.11.26 18:02:11;RING;0;030987;030123;SIP 0;",
332 "23.11.26 18:02:11;CALL;0;abc;030123;030987;SIP0;",
333 "23.11.26 18:02:11;CALL;0;10;030123;030987;SIP0",
334 ] {
335 assert_eq!(parse(line), None, "{line:?}");
336 }
337 let long = format!("23.11.26 18:02:11;RING;0;{};1;SIP0;", "1".repeat(41));
338 assert_eq!(parse(&long), None);
339 }
340
341 #[test]
342 fn forgets_the_oldest_event_seen() {
343 let mut monitor = Monitor {
344 address: ("localhost".to_owned(), 1012),
345 stream: None,
346 backoff: BACKOFF,
347 seen: VecDeque::new(),
348 };
349 let line = |id: usize| format!("23.11.26 18:02:11;DISCONNECT;{id};1;");
350 for id in 0..=SEEN {
351 assert!(monitor.accept(&line(id)).is_some());
352 }
353 assert_eq!(monitor.seen.len(), SEEN);
354 assert!(monitor.accept(&line(SEEN)).is_none());
355 assert!(monitor.accept(&line(0)).is_some());
356 }
357
358 #[test]
359 fn finds_names() {
360 let contact = |name: Option<&str>, number: &str| Contact {
361 name: name.map(str::to_owned),
362 numbers: vec![ContactNumber {
363 number: number.to_owned(),
364 kind: None,
365 }],
366 };
367 let names = Names::new(&[Phonebook {
368 contacts: vec![
369 contact(Some("name-1"), "030 98-7"),
370 contact(Some("name-2"), "030987"),
371 contact(None, "0301"),
372 contact(Some("name-3"), "-"),
373 ],
374 ..Phonebook::default()
375 }]);
376 let mut event = Event {
377 number: Some("030987".to_owned()),
378 ..Event::default()
379 };
380 names.name(&mut event);
381 assert_eq!(event.name.as_deref(), Some("name-1"));
382 event.number = Some("0301".to_owned());
383 names.name(&mut event);
384 assert_eq!(event.name, None);
385 }
386}