Skip to main content

fritz_sim/
fixture.rs

1//! Fixtures: devices recorded with `fritz capture` and anonymized.
2
3use std::collections::{BTreeMap, HashMap};
4use std::fs;
5use std::io;
6use std::path::{Path, PathBuf};
7
8use serde_json::Value;
9use tr064::{DeviceDescription, Scpd};
10
11/// The files of the fixtures that come with this crate, embedded by
12/// `build.rs`, by path like `fritzbox-7690/8.25/tr64desc.xml`.
13static BUNDLED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
14
15/// Why a fixture cannot be loaded.
16#[derive(Debug, thiserror::Error)]
17pub enum Error {
18    #[error("cannot read {}", path.display())]
19    Io {
20        path: PathBuf,
21        #[source]
22        source: io::Error,
23    },
24    #[error("{} is not valid: {reason}", path.display())]
25    Invalid { path: PathBuf, reason: String },
26    #[error("no fixture {0} comes with fritz-sim")]
27    Unknown(String),
28}
29
30/// A recorded answer to an action call.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Answer {
33    /// The output arguments by name.
34    Ok(BTreeMap<String, String>),
35    /// A UPnP error.
36    Fault { code: u16, description: String },
37}
38
39/// The recorded answers to one action: to a call without index, or to the
40/// calls with each index.
41#[derive(Debug, Clone, Default)]
42pub(crate) struct Recording {
43    pub(crate) once: Option<Answer>,
44    pub(crate) indexed: BTreeMap<u32, Answer>,
45}
46
47/// A device as recorded in a fixture directory:
48///
49/// ```text
50/// tr64desc.xml
51/// scpd/<file>.xml
52/// responses/<service>/<action>[@<index>].json
53/// lists/<name>.<xml|json>
54/// api/<path>.json
55/// data/<page>.json
56/// homeauto/<ain>.xml
57/// ```
58///
59/// A list document `lists/devicehostlist.xml` is served at the path
60/// `/devicehostlist.lua` that an action like `X_AVM-DE_GetHostListPath`
61/// returns. A document `api/v0/smarthome/overview.json` of the REST API is
62/// served at `/api/v0/smarthome/overview`. A page `data/ecoStat.json` of the
63/// web interface answers a form with `page=ecoStat` posted to `/data.lua`.
64/// The statistics `homeauto/116300000001.xml` answer the command
65/// `getbasicdevicestats` of the Smart Home HTTP interface for the device
66/// `11630 0000001`.
67#[derive(Debug, Clone)]
68pub struct Fixture {
69    pub(crate) description_xml: String,
70    pub(crate) description: DeviceDescription,
71    /// The service descriptions by file name, like `hostsSCPD.xml`.
72    pub(crate) scpds: HashMap<String, (String, Scpd)>,
73    /// The recorded answers by service, like `Hosts1`, and action.
74    pub(crate) recordings: HashMap<(String, String), Recording>,
75    /// The list documents by name, like `devicehostlist`.
76    pub(crate) lists: HashMap<String, String>,
77    /// The documents of the REST API by path, like
78    /// `/api/v0/smarthome/overview`.
79    pub(crate) api: HashMap<String, String>,
80    /// The pages of `/data.lua` by path, like `/ecoStat`.
81    pub(crate) pages: HashMap<String, String>,
82    /// The statistics of Smart Home devices by AIN without spaces.
83    pub(crate) stats: HashMap<String, String>,
84}
85
86impl Fixture {
87    /// Loads a fixture that comes with this crate, by name like
88    /// `fritzbox-7690/8.25`. The fixtures are part of the crate, so this
89    /// reads no files. See [`Fixture::bundled_names`].
90    ///
91    /// # Errors
92    ///
93    /// [`Error::Unknown`] if no fixture has the name.
94    pub fn bundled(name: &str) -> Result<Self, Error> {
95        if !Self::bundled_names().iter().any(|n| n == name) {
96            return Err(Error::Unknown(name.to_owned()));
97        }
98        Self::read(Source::Bundled, Path::new(name))
99    }
100
101    /// The names of the fixtures that come with this crate, sorted, like
102    /// `fritzbox-7690/8.25`. Tests can run against each of them.
103    pub fn bundled_names() -> Vec<String> {
104        let mut names: Vec<String> = BUNDLED
105            .iter()
106            .filter_map(|(path, _)| {
107                let mut parts = path.splitn(3, '/');
108                Some(format!("{}/{}", parts.next()?, parts.next()?))
109            })
110            .collect();
111        names.dedup();
112        names
113    }
114
115    /// Loads the fixture in `dir`.
116    ///
117    /// # Errors
118    ///
119    /// The errors of reading the files, and [`Error::Invalid`] if one of
120    /// them cannot be parsed.
121    pub fn load(dir: impl AsRef<Path>) -> Result<Self, Error> {
122        Self::read(Source::Disk, dir.as_ref())
123    }
124
125    /// Reads the fixture in `dir` of `source`.
126    fn read(source: Source, dir: &Path) -> Result<Self, Error> {
127        let read = |path: &Path| source.read(path);
128        let entries = |dir: &Path| source.entries(dir);
129        let path = dir.join("tr64desc.xml");
130        let description_xml = read(&path)?;
131        let description = DeviceDescription::parse(&description_xml).map_err(invalid(&path))?;
132        let mut scpds = HashMap::new();
133        for (name, path) in entries(&dir.join("scpd"))? {
134            let xml = read(&path)?;
135            let scpd = Scpd::parse(&xml).map_err(invalid(&path))?;
136            scpds.insert(name, (xml, scpd));
137        }
138        let mut recordings: HashMap<_, Recording> = HashMap::new();
139        for (service, service_dir) in entries(&dir.join("responses"))? {
140            for (name, path) in entries(&service_dir)? {
141                let Some(stem) = name.strip_suffix(".json") else {
142                    continue;
143                };
144                let (action, index) = match stem.split_once('@') {
145                    Some((action, index)) => {
146                        let index = index.parse().map_err(invalid(&path))?;
147                        (action, Some(index))
148                    }
149                    None => (stem, None),
150                };
151                let Some(answer) = answer(&read(&path)?).map_err(invalid(&path))? else {
152                    continue;
153                };
154                let recording = recordings
155                    .entry((service.clone(), action.to_owned()))
156                    .or_default();
157                match index {
158                    Some(index) => {
159                        recording.indexed.insert(index, answer);
160                    }
161                    None => recording.once = Some(answer),
162                }
163            }
164        }
165        let lists = by_stem(source, &dir.join("lists"))?;
166        let stats = by_stem(source, &dir.join("homeauto"))?;
167        let api = tree(source, &dir.join("api"), "/api")?;
168        let pages = tree(source, &dir.join("data"), "")?;
169        Ok(Self {
170            description_xml,
171            description,
172            scpds,
173            recordings,
174            lists,
175            api,
176            pages,
177            stats,
178        })
179    }
180
181    /// The device description.
182    pub fn description(&self) -> &DeviceDescription {
183        &self.description
184    }
185
186    /// The recorded answer to a call of `action` of the service `service`,
187    /// like `Hosts1`, with the given index or without one.
188    pub fn answer(&self, service: &str, action: &str, index: Option<u32>) -> Option<&Answer> {
189        let recording = self
190            .recordings
191            .get(&(service.to_owned(), action.to_owned()))?;
192        match index {
193            Some(index) => recording.indexed.get(&index),
194            None => recording.once.as_ref(),
195        }
196    }
197
198    /// Records `answer` for calls of `action` of the service `service`,
199    /// like `Hosts1`, with the given index or without one, in place of a
200    /// recorded answer. For tests of answers the fixture lacks.
201    #[must_use]
202    pub fn with_answer(
203        mut self,
204        service: &str,
205        action: &str,
206        index: Option<u32>,
207        answer: Answer,
208    ) -> Self {
209        let recording = self
210            .recordings
211            .entry((service.to_owned(), action.to_owned()))
212            .or_default();
213        match index {
214            Some(index) => {
215                recording.indexed.insert(index, answer);
216            }
217            None => recording.once = Some(answer),
218        }
219        self
220    }
221
222    /// Serves `json` as the page `name` of `/data.lua`, like `log`, in
223    /// place of the page of the fixture. For tests of pages the fixture
224    /// lacks.
225    #[must_use]
226    pub fn with_page(mut self, name: &str, json: impl Into<String>) -> Self {
227        self.pages.insert(format!("/{name}"), json.into());
228        self
229    }
230
231    /// Serves `json` at `path` of the REST API, like
232    /// `/api/v0/generic/vpn`, in place of the document of the fixture. For
233    /// tests of documents the fixture lacks.
234    #[must_use]
235    pub fn with_api(mut self, path: &str, json: impl Into<String>) -> Self {
236        self.api.insert(path.to_owned(), json.into());
237        self
238    }
239}
240
241/// Parses a recorded answer: `{"status": "ok", "out": {…}}` or
242/// `{"status": "fault", "code": 714, "description": "…"}`. Calls that failed
243/// without an answer, `{"status": "failed", …}`, count as not recorded.
244fn answer(json: &str) -> Result<Option<Answer>, String> {
245    let value: Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
246    match value["status"].as_str() {
247        Some("ok") => {
248            let out = value["out"].as_object().ok_or("no output arguments")?;
249            out.iter()
250                .map(|(name, value)| {
251                    let value = value.as_str().ok_or(format!("{name} is not a string"))?;
252                    Ok((name.clone(), value.to_owned()))
253                })
254                .collect::<Result<_, String>>()
255                .map(|out| Some(Answer::Ok(out)))
256        }
257        Some("fault") => {
258            let code = value["code"].as_u64().and_then(|c| u16::try_from(c).ok());
259            Ok(Some(Answer::Fault {
260                code: code.ok_or("no error code")?,
261                description: value["description"].as_str().unwrap_or_default().to_owned(),
262            }))
263        }
264        Some("failed") => Ok(None),
265        _ => Err("unknown status".to_owned()),
266    }
267}
268
269/// The files in `dir`, if it exists, by their names without the extension.
270fn by_stem(source: Source, dir: &Path) -> Result<HashMap<String, String>, Error> {
271    let mut found = HashMap::new();
272    if source.is_dir(dir) {
273        for (name, path) in source.entries(dir)? {
274            let name = name.split_once('.').map_or(name.as_str(), |(stem, _)| stem);
275            found.insert(name.to_owned(), source.read(&path)?);
276        }
277    }
278    Ok(found)
279}
280
281/// Adds the JSON documents in `dir` and its subdirectories to `found`, by
282/// their path under `prefix` without the extension.
283/// The documents below `dir`, if it exists, by their paths after `prefix`,
284/// like `/api/v0/smarthome/overview` for `prefix` `/api`.
285fn tree(source: Source, dir: &Path, prefix: &str) -> Result<HashMap<String, String>, Error> {
286    let mut found = HashMap::new();
287    if source.is_dir(dir) {
288        documents(source, dir, prefix, &mut found)?;
289    }
290    Ok(found)
291}
292
293fn documents(
294    source: Source,
295    dir: &Path,
296    prefix: &str,
297    found: &mut HashMap<String, String>,
298) -> Result<(), Error> {
299    for (name, path) in source.entries(dir)? {
300        if source.is_dir(&path) {
301            documents(source, &path, &format!("{prefix}/{name}"), found)?;
302        } else if let Some(stem) = name.strip_suffix(".json") {
303            found.insert(format!("{prefix}/{stem}"), source.read(&path)?);
304        }
305    }
306    Ok(())
307}
308
309/// Where the files of a fixture come from.
310#[derive(Debug, Clone, Copy)]
311enum Source {
312    /// The file system.
313    Disk,
314    /// The fixtures embedded in the crate, with paths relative to them.
315    Bundled,
316}
317
318impl Source {
319    fn read(self, path: &Path) -> Result<String, Error> {
320        match self {
321            Self::Disk => fs::read_to_string(path).map_err(|source| Error::Io {
322                path: path.to_owned(),
323                source,
324            }),
325            Self::Bundled => Ok(bundled(path).next().map_or("", |(_, c)| c).to_owned()),
326        }
327    }
328
329    fn is_dir(self, path: &Path) -> bool {
330        match self {
331            Self::Disk => path.is_dir(),
332            Self::Bundled => bundled(path).any(|(p, _)| p != path),
333        }
334    }
335
336    /// The entries of a directory by name, without hidden ones like
337    /// `.DS_Store`.
338    fn entries(self, dir: &Path) -> Result<Vec<(String, PathBuf)>, Error> {
339        let mut entries = Vec::new();
340        match self {
341            Self::Disk => {
342                let io_error = |source| Error::Io {
343                    path: dir.to_owned(),
344                    source,
345                };
346                for entry in fs::read_dir(dir).map_err(io_error)? {
347                    let entry = entry.map_err(io_error)?;
348                    let name = entry.file_name().to_string_lossy().into_owned();
349                    if !name.starts_with('.') {
350                        entries.push((name, entry.path()));
351                    }
352                }
353            }
354            Self::Bundled => {
355                let below = |(path, _): (&'static Path, _)| path.strip_prefix(dir).ok();
356                for first in bundled(dir)
357                    .filter_map(below)
358                    .filter_map(|p| p.iter().next())
359                {
360                    let name = first.to_string_lossy().into_owned();
361                    if !entries.iter().any(|(n, _)| *n == name) {
362                        entries.push((name.clone(), dir.join(name)));
363                    }
364                }
365            }
366        }
367        Ok(entries)
368    }
369}
370
371/// The embedded files at or below `path`, with their paths.
372fn bundled(path: &Path) -> impl Iterator<Item = (&'static Path, &'static str)> {
373    BUNDLED
374        .iter()
375        .map(|(p, content)| (Path::new(*p), *content))
376        .filter(move |(p, _)| p.starts_with(path))
377}
378
379fn invalid<E: ToString>(path: &Path) -> impl FnOnce(E) -> Error {
380    let path = path.to_owned();
381    move |error| Error::Invalid {
382        path,
383        reason: error.to_string(),
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn parses_answers() {
393        assert_eq!(
394            answer(r#"{"status": "ok", "out": {"NewEnable": "1"}}"#),
395            Ok(Some(Answer::Ok(BTreeMap::from([(
396                "NewEnable".to_owned(),
397                "1".to_owned()
398            )]))))
399        );
400        assert_eq!(
401            answer(r#"{"status": "fault", "code": 714}"#),
402            Ok(Some(Answer::Fault {
403                code: 714,
404                description: String::new()
405            }))
406        );
407        assert_eq!(
408            answer(r#"{"status": "failed", "error": "timeout"}"#),
409            Ok(None)
410        );
411        for (json, error) in [
412            ("{", "EOF while parsing an object at line 1 column 1"),
413            (r#"{"status": "ok"}"#, "no output arguments"),
414            (
415                r#"{"status": "ok", "out": {"NewEnable": 1}}"#,
416                "NewEnable is not a string",
417            ),
418            (r#"{"status": "fault", "code": 70000}"#, "no error code"),
419            (r#"{"status": "skipped"}"#, "unknown status"),
420        ] {
421            assert_eq!(answer(json), Err(error.to_owned()), "{json}");
422        }
423    }
424}