Skip to main content

fritz_core/
personal.rs

1//! The personal lists of a device: the calls, the phonebooks and the event
2//! log. They name people, numbers and devices, so they are only read on
3//! request.
4
5use serde::Serialize;
6
7use crate::generic::Error;
8use crate::lists;
9use crate::read::Reader;
10
11mod categories;
12mod filter;
13
14pub use categories::{LOG_PAGE, parse_web_log, web_log};
15pub use filter::{
16    CALL_KINDS, CATEGORIES, CallFilter, FilterError, LogFilter, MAX_CALLS, Since, call_kind,
17    category, filter_log, find_calls, now, timestamp,
18};
19
20/// The most phonebooks read, as a guard against a device that lists
21/// endless ids.
22pub const MAX_PHONEBOOKS: usize = 20;
23
24/// A call.
25#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
26pub struct Call {
27    /// `incoming`, `missed`, `outgoing`, `rejected`, `active incoming`,
28    /// `active outgoing` or `unknown`.
29    pub kind: &'static str,
30    /// Like `2026-11-20 18:05`, in the time zone of the device.
31    pub date: Option<String>,
32    /// How long it took, in minutes.
33    pub minutes: Option<u32>,
34    /// The number of the other party.
35    pub number: Option<String>,
36    /// The name of the other party, from the phonebook.
37    pub name: Option<String>,
38    /// The own number the call came in on or went out from.
39    pub own_number: Option<String>,
40    /// The phone or answering machine that took it.
41    pub device: Option<String>,
42}
43
44/// A phonebook.
45#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
46pub struct Phonebook {
47    pub id: u32,
48    pub name: Option<String>,
49    pub contacts: Vec<Contact>,
50}
51
52/// A contact of a phonebook.
53#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
54pub struct Contact {
55    pub name: Option<String>,
56    pub numbers: Vec<ContactNumber>,
57}
58
59/// A number of a contact.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
61pub struct ContactNumber {
62    pub number: String,
63    /// Like `home`, `mobile` or `work`.
64    pub kind: Option<String>,
65}
66
67impl Contact {
68    /// Whether the name contains `search`, ignoring case, or a number
69    /// contains its digits, ignoring spaces and dashes.
70    pub fn matches(&self, search: &str) -> bool {
71        text_matches(
72            self.name.as_deref(),
73            self.numbers.iter().map(|n| &n.number),
74            search,
75        )
76    }
77}
78
79/// Whether `name` contains `search`, ignoring case, or one of `numbers`
80/// contains its digits, ignoring spaces and dashes.
81fn text_matches<'a>(
82    name: Option<&str>,
83    mut numbers: impl Iterator<Item = &'a String>,
84    search: &str,
85) -> bool {
86    let text = search.to_lowercase();
87    if name.is_some_and(|n| n.to_lowercase().contains(&text)) {
88        return true;
89    }
90    let wanted = digits(search);
91    !wanted.is_empty() && numbers.any(|n| digits(n).contains(&wanted))
92}
93
94/// The phonebooks with only the contacts that match `search`, see
95/// [`Contact::matches`], and without the phonebooks left empty.
96pub fn search(phonebooks: Vec<Phonebook>, search: &str) -> Vec<Phonebook> {
97    phonebooks
98        .into_iter()
99        .filter_map(|mut phonebook| {
100            phonebook.contacts.retain(|c| c.matches(search));
101            (!phonebook.contacts.is_empty()).then_some(phonebook)
102        })
103        .collect()
104}
105
106/// An entry of the event log.
107#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
108pub struct LogEntry {
109    /// Like `2026-11-20 18:05:42`, in the time zone of the device.
110    pub time: Option<String>,
111    pub message: String,
112    /// One of [`CATEGORIES`], or as the device names it. Only the event
113    /// log of the web interface carries categories, see [`web_log`].
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub category: Option<String>,
116}
117
118/// Reads the latest calls, at most `max`, the latest first. Empty if the
119/// device has no call list.
120///
121/// # Errors
122///
123/// The errors of reading other than missing parts, see
124/// [`Reader::try_read`], and [`Error::InvalidDocument`] if the list is not
125/// valid.
126pub async fn calls(reader: &mut Reader, max: u32) -> Result<Vec<Call>, Error> {
127    let Some(xml) = reader
128        .document_with(
129            "X_AVM-DE_OnTel1",
130            ("GetCallList", &[]),
131            "NewCallListURL",
132            &format!("max={max}"),
133        )
134        .await?
135    else {
136        return Ok(Vec::new());
137    };
138    let mut calls = parse_calls(&xml)?;
139    calls.truncate(usize::try_from(max).unwrap_or(usize::MAX));
140    Ok(calls)
141}
142
143/// Parses a call list: `<root><Call><Type>1</Type>…</Call></root>`.
144///
145/// # Errors
146///
147/// [`Error::InvalidDocument`] if it is not such a list.
148pub fn parse_calls(xml: &str) -> Result<Vec<Call>, Error> {
149    Ok(lists::items(xml, "call list", "root", "Call")?
150        .into_iter()
151        .map(|item| {
152            let (kind, incoming) = match item.text("Type").as_deref() {
153                Some("1") => ("incoming", true),
154                Some("2") => ("missed", true),
155                Some("3") => ("outgoing", false),
156                Some("9") => ("active incoming", true),
157                Some("10") => ("rejected", true),
158                Some("11") => ("active outgoing", false),
159                _ => ("unknown", true),
160            };
161            let (number, own_number) = if incoming {
162                (item.text("Caller"), item.text("CalledNumber"))
163            } else {
164                (item.text("Called"), item.text("CallerNumber"))
165            };
166            Call {
167                kind,
168                date: item.text("Date").map(|d| date(&d)),
169                minutes: item.text("Duration").and_then(|d| minutes(&d)),
170                number,
171                name: item.text("Name"),
172                own_number,
173                device: item.text("Device"),
174            }
175        })
176        .collect())
177}
178
179/// Reads the phonebooks with their contacts. Empty if the device has none.
180///
181/// # Errors
182///
183/// The errors of reading other than missing parts, see
184/// [`Reader::try_read`], and [`Error::InvalidDocument`] if a phonebook is
185/// not valid.
186pub async fn phonebooks(reader: &mut Reader) -> Result<Vec<Phonebook>, Error> {
187    let Some(list) = reader
188        .try_read("X_AVM-DE_OnTel1", "GetPhonebookList", &[])
189        .await?
190        .and_then(|values| values.text("NewPhonebookList"))
191    else {
192        return Ok(Vec::new());
193    };
194    let ids = list
195        .split(',')
196        .filter_map(|id| id.trim().parse::<u32>().ok())
197        .take(MAX_PHONEBOOKS);
198    let mut phonebooks = Vec::new();
199    for id in ids {
200        let text = id.to_string();
201        let arguments = [("NewPhonebookID", text.as_str())];
202        let Some(xml) = reader
203            .document_with(
204                "X_AVM-DE_OnTel1",
205                ("GetPhonebook", &arguments),
206                "NewPhonebookURL",
207                "",
208            )
209            .await?
210        else {
211            continue;
212        };
213        phonebooks.push(parse_phonebook(id, &xml)?);
214    }
215    Ok(phonebooks)
216}
217
218/// Parses a phonebook: `<phonebooks><phonebook name="…"><contact>
219/// <person><realName>…</realName></person><telephony><number type="home">…
220/// </number></telephony></contact></phonebook></phonebooks>`.
221///
222/// # Errors
223///
224/// [`Error::InvalidDocument`] if it is not such a phonebook.
225pub fn parse_phonebook(id: u32, xml: &str) -> Result<Phonebook, Error> {
226    let invalid = |reason: String| Error::InvalidDocument {
227        document: "phonebook",
228        reason,
229    };
230    let parsed = roxmltree::Document::parse(xml).map_err(|e| invalid(e.to_string()))?;
231    let root = parsed.root_element();
232    if root.tag_name().name() != "phonebooks" {
233        return Err(invalid(format!(
234            "the root is {}, not phonebooks",
235            root.tag_name().name()
236        )));
237    }
238    let text = |node: roxmltree::Node| {
239        node.text()
240            .map(str::trim)
241            .filter(|t| !t.is_empty())
242            .map(str::to_owned)
243    };
244    let contacts = root
245        .descendants()
246        .filter(|n| n.has_tag_name("contact"))
247        .map(|contact| Contact {
248            name: contact
249                .descendants()
250                .find(|n| n.has_tag_name("realName"))
251                .and_then(text),
252            numbers: contact
253                .descendants()
254                .filter(|n| n.has_tag_name("number"))
255                .filter_map(|n| {
256                    Some(ContactNumber {
257                        number: text(n)?,
258                        kind: n
259                            .attribute("type")
260                            .filter(|t| !t.is_empty())
261                            .map(str::to_owned),
262                    })
263                })
264                .collect(),
265        })
266        .collect();
267    let name = root
268        .children()
269        .find(|n| n.has_tag_name("phonebook"))
270        .and_then(|n| n.attribute("name"))
271        .filter(|n| !n.is_empty())
272        .map(str::to_owned);
273    Ok(Phonebook { id, name, contacts })
274}
275
276/// Reads the latest entries of the event log, at most `max`, the latest
277/// first. Empty if the device has no log.
278///
279/// # Errors
280///
281/// The errors of reading other than missing parts, see
282/// [`Reader::try_read`].
283pub async fn log(reader: &mut Reader, max: usize) -> Result<Vec<LogEntry>, Error> {
284    let log = reader
285        .try_read("DeviceInfo1", "GetDeviceLog", &[])
286        .await?
287        .and_then(|values| values.text("NewDeviceLog"))
288        .unwrap_or_default();
289    Ok(parse_log(&log).into_iter().take(max).collect())
290}
291
292/// Parses the event log: a line per entry, like `20.11.26 18:05:42 Text`.
293/// A line without a time is kept as a message.
294pub fn parse_log(log: &str) -> Vec<LogEntry> {
295    log.lines()
296        .map(str::trim)
297        .filter(|line| !line.is_empty())
298        .map(|line| {
299            let mut parts = line.splitn(3, ' ');
300            let (day, time) = (parts.next().unwrap_or_default(), parts.next());
301            match (time, parts.next(), is_date(day)) {
302                (Some(time), Some(message), true) if time.contains(':') => LogEntry {
303                    time: Some(date(&format!("{day} {time}"))),
304                    message: message.trim().to_owned(),
305                    category: None,
306                },
307                _ => LogEntry {
308                    time: None,
309                    message: line.to_owned(),
310                    category: None,
311                },
312            }
313        })
314        .collect()
315}
316
317/// Whether `text` is a date like `20.11.26`.
318pub(crate) fn is_date(text: &str) -> bool {
319    let parts: Vec<&str> = text.split('.').collect();
320    parts.len() == 3
321        && parts
322            .iter()
323            .all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))
324}
325
326/// A date of the device, like `20.11.26 18:05`, as `2026-11-20 18:05`.
327/// Other texts stay as they are.
328pub(crate) fn date(text: &str) -> String {
329    let (day, time) = text.split_once(' ').unwrap_or((text, ""));
330    if !is_date(day) {
331        return text.to_owned();
332    }
333    let parts: Vec<&str> = day.split('.').collect();
334    let date = format!("20{}-{}-{}", parts[2], parts[1], parts[0]);
335    if time.is_empty() {
336        date
337    } else {
338        format!("{date} {time}")
339    }
340}
341
342/// A duration like `1:05` in minutes.
343fn minutes(text: &str) -> Option<u32> {
344    let (hours, minutes) = text.split_once(':')?;
345    let hours: u32 = hours.trim().parse().ok()?;
346    let minutes: u32 = minutes.trim().parse().ok()?;
347    Some(hours * 60 + minutes)
348}
349
350pub(crate) fn digits(text: &str) -> String {
351    text.chars().filter(char::is_ascii_digit).collect()
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn parses_calls() {
360        let xml = "<root><timestamp>1</timestamp>\
361            <Call><Id>2</Id><Type>3</Type><Called>phone-2</Called><Caller></Caller>\
362            <CallerNumber>phone-1</CallerNumber><Name>name-2</Name><Device>name-3</Device>\
363            <Date>20.11.26 18:05</Date><Duration>1:05</Duration></Call>\
364            <Call><Id>1</Id><Type>2</Type><Caller>phone-3</Caller>\
365            <CalledNumber>phone-1</CalledNumber><Date>soon</Date><Duration>x</Duration></Call>\
366            <Call><Type>7</Type></Call></root>";
367        let calls = parse_calls(xml).unwrap();
368        assert_eq!(
369            calls[0],
370            Call {
371                kind: "outgoing",
372                date: Some("2026-11-20 18:05".to_owned()),
373                minutes: Some(65),
374                number: Some("phone-2".to_owned()),
375                name: Some("name-2".to_owned()),
376                own_number: Some("phone-1".to_owned()),
377                device: Some("name-3".to_owned()),
378            }
379        );
380        assert_eq!(calls[1].kind, "missed");
381        assert_eq!(calls[1].number.as_deref(), Some("phone-3"));
382        assert_eq!(calls[1].own_number.as_deref(), Some("phone-1"));
383        assert_eq!(calls[1].date.as_deref(), Some("soon"));
384        assert_eq!(calls[1].minutes, None);
385        assert_eq!(calls[2].kind, "unknown");
386        let kinds: Vec<_> = ["1", "9", "10", "11"]
387            .iter()
388            .map(|t| {
389                parse_calls(&format!("<root><Call><Type>{t}</Type></Call></root>")).unwrap()[0].kind
390            })
391            .collect();
392        assert_eq!(
393            kinds,
394            ["incoming", "active incoming", "rejected", "active outgoing"]
395        );
396        assert!(parse_calls("<list/>").is_err());
397    }
398
399    #[test]
400    fn parses_a_phonebook() {
401        let xml = r#"<?xml version="1.0"?><phonebooks><phonebook name="name-1">
402            <contact><person><realName>Name-2</realName></person><telephony>
403            <number type="home" prio="1">+49 30 1234-5</number><number type="mobile"> </number>
404            </telephony></contact><contact><telephony/></contact></phonebook></phonebooks>"#;
405        let phonebook = parse_phonebook(1, xml).unwrap();
406        assert_eq!(
407            (phonebook.id, phonebook.name.as_deref()),
408            (1, Some("name-1"))
409        );
410        let contacts = &phonebook.contacts;
411        assert_eq!(
412            contacts,
413            &vec![
414                Contact {
415                    name: Some("Name-2".to_owned()),
416                    numbers: vec![ContactNumber {
417                        number: "+49 30 1234-5".to_owned(),
418                        kind: Some("home".to_owned()),
419                    }],
420                },
421                Contact::default(),
422            ]
423        );
424        assert!(contacts[0].matches("name-2"));
425        assert!(contacts[0].matches("3012"));
426        assert!(!contacts[0].matches("999"));
427        assert!(!contacts[0].matches("other"));
428        assert!(!contacts[1].matches("x"));
429        let found = search(vec![phonebook.clone()], "3012");
430        assert_eq!(found[0].contacts.len(), 1);
431        assert_eq!(search(vec![phonebook.clone()], "nobody"), []);
432        let unnamed = parse_phonebook(0, "<phonebooks><phonebook/></phonebooks>").unwrap();
433        assert_eq!(unnamed, Phonebook::default());
434        assert!(parse_phonebook(0, "<root/>").is_err());
435        assert!(parse_phonebook(0, "not xml").is_err());
436    }
437
438    #[test]
439    fn parses_the_log() {
440        let log = "20.11.26 18:05:42 Internet connected.\n\n  \
441            19.11.26 07:00:01 DSL ready.\nno time here\n1.2.3 4:5 odd";
442        assert_eq!(
443            parse_log(log),
444            vec![
445                LogEntry {
446                    time: Some("2026-11-20 18:05:42".to_owned()),
447                    message: "Internet connected.".to_owned(),
448                    category: None,
449                },
450                LogEntry {
451                    time: Some("2026-11-19 07:00:01".to_owned()),
452                    message: "DSL ready.".to_owned(),
453                    category: None,
454                },
455                LogEntry {
456                    time: None,
457                    message: "no time here".to_owned(),
458                    category: None,
459                },
460                LogEntry {
461                    time: None,
462                    message: "1.2.3 4:5 odd".to_owned(),
463                    category: None,
464                },
465            ]
466        );
467        assert_eq!(date("20.11.26"), "2026-11-20");
468        assert_eq!(minutes("0:01"), Some(1));
469    }
470}