1use 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
11static BUNDLED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
14
15#[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#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Answer {
33 Ok(BTreeMap<String, String>),
35 Fault { code: u16, description: String },
37}
38
39#[derive(Debug, Clone, Default)]
42pub(crate) struct Recording {
43 pub(crate) once: Option<Answer>,
44 pub(crate) indexed: BTreeMap<u32, Answer>,
45}
46
47#[derive(Debug, Clone)]
68pub struct Fixture {
69 pub(crate) description_xml: String,
70 pub(crate) description: DeviceDescription,
71 pub(crate) scpds: HashMap<String, (String, Scpd)>,
73 pub(crate) recordings: HashMap<(String, String), Recording>,
75 pub(crate) lists: HashMap<String, String>,
77 pub(crate) api: HashMap<String, String>,
80 pub(crate) pages: HashMap<String, String>,
82 pub(crate) stats: HashMap<String, String>,
84}
85
86impl Fixture {
87 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 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 pub fn load(dir: impl AsRef<Path>) -> Result<Self, Error> {
122 Self::read(Source::Disk, dir.as_ref())
123 }
124
125 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 pub fn description(&self) -> &DeviceDescription {
183 &self.description
184 }
185
186 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 #[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 #[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 #[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
241fn 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
269fn 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
281fn 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#[derive(Debug, Clone, Copy)]
311enum Source {
312 Disk,
314 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 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
371fn 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}