Skip to main content

fritz_core/
telephony.rs

1//! The telephony of a device: its numbers and internet telephony accounts,
2//! call deflections, answering machines and DECT handsets. Not the calls
3//! and the phonebook, which are personal.
4
5use serde::Serialize;
6
7use crate::generic::Error;
8use crate::lists::{self, Item};
9use crate::read::Reader;
10
11/// The most DECT handsets read, as a guard against a device that never
12/// ends the list.
13pub const MAX_HANDSETS: u32 = 100;
14
15/// The telephony.
16#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
17pub struct Telephony {
18    pub numbers: Vec<Number>,
19    pub accounts: Vec<Account>,
20    pub deflections: Vec<Deflection>,
21    pub answering_machines: Vec<AnsweringMachine>,
22    pub handsets: Vec<Handset>,
23}
24
25/// A number of the device.
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
27pub struct Number {
28    pub number: Option<String>,
29    /// Like `eVoIP` or `eAnalog`.
30    pub kind: Option<String>,
31    pub name: Option<String>,
32}
33
34/// An internet telephony account with a number. Without its user name.
35#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
36pub struct Account {
37    pub index: u32,
38    pub number: String,
39    pub registrar: Option<String>,
40    /// Like `registered` or `not registered`.
41    pub status: Option<String>,
42}
43
44/// A call deflection.
45#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
46pub struct Deflection {
47    pub enabled: bool,
48    /// What the deflection is for, like `fromNumber` or `toAny`.
49    pub kind: Option<String>,
50    /// The number it is for, if any.
51    pub number: Option<String>,
52    /// The number calls go to.
53    pub to: Option<String>,
54    /// Like `eImmediately` or `eDelayed`.
55    pub mode: Option<String>,
56}
57
58/// An answering machine.
59#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
60pub struct AnsweringMachine {
61    pub index: u32,
62    pub name: Option<String>,
63    pub enabled: bool,
64}
65
66/// A DECT handset.
67#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
68pub struct Handset {
69    pub id: Option<String>,
70    pub name: Option<String>,
71    pub model: Option<String>,
72    /// Whether it is in reach.
73    pub active: bool,
74    pub update_available: Option<bool>,
75}
76
77/// Reads the telephony.
78///
79/// # Errors
80///
81/// The errors of reading other than missing parts, see
82/// [`Reader::try_read`], and [`Error::InvalidDocument`] if a list is not
83/// valid.
84pub async fn telephony(reader: &mut Reader) -> Result<Telephony, Error> {
85    let numbers = list(reader, ("X_VoIP1", "X_AVM-DE_GetNumbers"), "NewNumberList")
86        .await?
87        .iter()
88        .map(|item| Number {
89            number: item.text("Number"),
90            kind: item.text("Type"),
91            name: item.text("Name"),
92        })
93        .collect();
94    Ok(Telephony {
95        numbers,
96        accounts: accounts(reader).await?,
97        deflections: list(
98            reader,
99            ("X_AVM-DE_OnTel1", "GetDeflections"),
100            "NewDeflectionList",
101        )
102        .await?
103        .iter()
104        .map(|item| Deflection {
105            enabled: item.flag("Enable").unwrap_or_default(),
106            kind: item.text("Type"),
107            number: item.text("Number"),
108            to: item.text("DeflectionToNumber"),
109            mode: item.text("Mode"),
110        })
111        .collect(),
112        answering_machines: list(reader, ("X_AVM-DE_TAM1", "GetList"), "NewTAMList")
113            .await?
114            .iter()
115            .filter(|item| item.flag("Display").unwrap_or_default())
116            .map(|item| AnsweringMachine {
117                index: item.number("Index").unwrap_or_default(),
118                name: item.text("Name"),
119                enabled: item.flag("Enable").unwrap_or_default(),
120            })
121            .collect(),
122        handsets: handsets(reader).await?,
123    })
124}
125
126/// The items of a `<List>` that `action` returns in the output `output`.
127async fn list(
128    reader: &mut Reader,
129    (service, action): (&str, &'static str),
130    output: &str,
131) -> Result<Vec<Item>, Error> {
132    let Some(xml) = reader
133        .try_read(service, action, &[])
134        .await?
135        .and_then(|values| values.text(output))
136    else {
137        return Ok(Vec::new());
138    };
139    lists::items(&xml, action, "List", "Item")
140}
141
142/// The accounts with a number, each with its status.
143async fn accounts(reader: &mut Reader) -> Result<Vec<Account>, Error> {
144    let Some(xml) = reader
145        .try_read("X_VoIP1", "X_AVM-DE_GetVoIPAccounts", &[])
146        .await?
147        .and_then(|values| values.text("NewX_AVM-DE_VoIPAccountList"))
148    else {
149        return Ok(Vec::new());
150    };
151    let mut accounts = Vec::new();
152    for item in lists::items(&xml, "VoIP account list", "AccountList", "Account")? {
153        let Some(number) = item.text("VoIPNumber") else {
154            continue;
155        };
156        let index: u32 = item.number("VoIPAccountIndex").unwrap_or_default();
157        let status = reader
158            .try_read(
159                "X_VoIP1",
160                "X_AVM-DE_GetVoIPStatus",
161                &[("NewVoIPAccountIndex", &index.to_string())],
162            )
163            .await?
164            .and_then(|values| values.text("NewX_AVM-DE_VoIPStatus"));
165        accounts.push(Account {
166            index,
167            number,
168            registrar: item.text("VoIPRegistrar"),
169            status,
170        });
171    }
172    Ok(accounts)
173}
174
175async fn handsets(reader: &mut Reader) -> Result<Vec<Handset>, Error> {
176    let entries = reader
177        .entries(
178            "X_AVM-DE_Dect1",
179            ("GetNumberOfDectEntries", "NewNumberOfEntries"),
180            ("GetGenericDectEntry", "NewIndex"),
181            MAX_HANDSETS,
182        )
183        .await?
184        .map_or_else(Vec::new, |(_, entries)| entries);
185    Ok(entries
186        .iter()
187        .map(|entry| Handset {
188            id: entry.text("NewID"),
189            name: entry.text("NewName"),
190            model: entry.text("NewModel"),
191            active: entry.flag("NewActive").unwrap_or_default(),
192            update_available: entry.flag("NewUpdateAvailable"),
193        })
194        .collect())
195}