use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use serde_json::Value;
use tr064::{DeviceDescription, Scpd};
static BUNDLED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("cannot read {}", path.display())]
Io {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("{} is not valid: {reason}", path.display())]
Invalid { path: PathBuf, reason: String },
#[error("no fixture {0} comes with fritz-sim")]
Unknown(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
Ok(BTreeMap<String, String>),
Fault { code: u16, description: String },
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Recording {
pub(crate) once: Option<Answer>,
pub(crate) indexed: BTreeMap<u32, Answer>,
}
#[derive(Debug, Clone)]
pub struct Fixture {
pub(crate) description_xml: String,
pub(crate) description: DeviceDescription,
pub(crate) scpds: HashMap<String, (String, Scpd)>,
pub(crate) recordings: HashMap<(String, String), Recording>,
pub(crate) lists: HashMap<String, String>,
pub(crate) api: HashMap<String, String>,
pub(crate) pages: HashMap<String, String>,
pub(crate) stats: HashMap<String, String>,
}
impl Fixture {
pub fn bundled(name: &str) -> Result<Self, Error> {
if !Self::bundled_names().iter().any(|n| n == name) {
return Err(Error::Unknown(name.to_owned()));
}
Self::read(Source::Bundled, Path::new(name))
}
pub fn bundled_names() -> Vec<String> {
let mut names: Vec<String> = BUNDLED
.iter()
.filter_map(|(path, _)| {
let mut parts = path.splitn(3, '/');
Some(format!("{}/{}", parts.next()?, parts.next()?))
})
.collect();
names.dedup();
names
}
pub fn load(dir: impl AsRef<Path>) -> Result<Self, Error> {
Self::read(Source::Disk, dir.as_ref())
}
fn read(source: Source, dir: &Path) -> Result<Self, Error> {
let read = |path: &Path| source.read(path);
let entries = |dir: &Path| source.entries(dir);
let path = dir.join("tr64desc.xml");
let description_xml = read(&path)?;
let description = DeviceDescription::parse(&description_xml).map_err(invalid(&path))?;
let mut scpds = HashMap::new();
for (name, path) in entries(&dir.join("scpd"))? {
let xml = read(&path)?;
let scpd = Scpd::parse(&xml).map_err(invalid(&path))?;
scpds.insert(name, (xml, scpd));
}
let mut recordings: HashMap<_, Recording> = HashMap::new();
for (service, service_dir) in entries(&dir.join("responses"))? {
for (name, path) in entries(&service_dir)? {
let Some(stem) = name.strip_suffix(".json") else {
continue;
};
let (action, index) = match stem.split_once('@') {
Some((action, index)) => {
let index = index.parse().map_err(invalid(&path))?;
(action, Some(index))
}
None => (stem, None),
};
let Some(answer) = answer(&read(&path)?).map_err(invalid(&path))? else {
continue;
};
let recording = recordings
.entry((service.clone(), action.to_owned()))
.or_default();
match index {
Some(index) => {
recording.indexed.insert(index, answer);
}
None => recording.once = Some(answer),
}
}
}
let lists = by_stem(source, &dir.join("lists"))?;
let stats = by_stem(source, &dir.join("homeauto"))?;
let api = tree(source, &dir.join("api"), "/api")?;
let pages = tree(source, &dir.join("data"), "")?;
Ok(Self {
description_xml,
description,
scpds,
recordings,
lists,
api,
pages,
stats,
})
}
pub fn description(&self) -> &DeviceDescription {
&self.description
}
pub fn answer(&self, service: &str, action: &str, index: Option<u32>) -> Option<&Answer> {
let recording = self
.recordings
.get(&(service.to_owned(), action.to_owned()))?;
match index {
Some(index) => recording.indexed.get(&index),
None => recording.once.as_ref(),
}
}
#[must_use]
pub fn with_answer(
mut self,
service: &str,
action: &str,
index: Option<u32>,
answer: Answer,
) -> Self {
let recording = self
.recordings
.entry((service.to_owned(), action.to_owned()))
.or_default();
match index {
Some(index) => {
recording.indexed.insert(index, answer);
}
None => recording.once = Some(answer),
}
self
}
#[must_use]
pub fn with_page(mut self, name: &str, json: impl Into<String>) -> Self {
self.pages.insert(format!("/{name}"), json.into());
self
}
#[must_use]
pub fn with_api(mut self, path: &str, json: impl Into<String>) -> Self {
self.api.insert(path.to_owned(), json.into());
self
}
}
fn answer(json: &str) -> Result<Option<Answer>, String> {
let value: Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
match value["status"].as_str() {
Some("ok") => {
let out = value["out"].as_object().ok_or("no output arguments")?;
out.iter()
.map(|(name, value)| {
let value = value.as_str().ok_or(format!("{name} is not a string"))?;
Ok((name.clone(), value.to_owned()))
})
.collect::<Result<_, String>>()
.map(|out| Some(Answer::Ok(out)))
}
Some("fault") => {
let code = value["code"].as_u64().and_then(|c| u16::try_from(c).ok());
Ok(Some(Answer::Fault {
code: code.ok_or("no error code")?,
description: value["description"].as_str().unwrap_or_default().to_owned(),
}))
}
Some("failed") => Ok(None),
_ => Err("unknown status".to_owned()),
}
}
fn by_stem(source: Source, dir: &Path) -> Result<HashMap<String, String>, Error> {
let mut found = HashMap::new();
if source.is_dir(dir) {
for (name, path) in source.entries(dir)? {
let name = name.split_once('.').map_or(name.as_str(), |(stem, _)| stem);
found.insert(name.to_owned(), source.read(&path)?);
}
}
Ok(found)
}
fn tree(source: Source, dir: &Path, prefix: &str) -> Result<HashMap<String, String>, Error> {
let mut found = HashMap::new();
if source.is_dir(dir) {
documents(source, dir, prefix, &mut found)?;
}
Ok(found)
}
fn documents(
source: Source,
dir: &Path,
prefix: &str,
found: &mut HashMap<String, String>,
) -> Result<(), Error> {
for (name, path) in source.entries(dir)? {
if source.is_dir(&path) {
documents(source, &path, &format!("{prefix}/{name}"), found)?;
} else if let Some(stem) = name.strip_suffix(".json") {
found.insert(format!("{prefix}/{stem}"), source.read(&path)?);
}
}
Ok(())
}
#[derive(Debug, Clone, Copy)]
enum Source {
Disk,
Bundled,
}
impl Source {
fn read(self, path: &Path) -> Result<String, Error> {
match self {
Self::Disk => fs::read_to_string(path).map_err(|source| Error::Io {
path: path.to_owned(),
source,
}),
Self::Bundled => Ok(bundled(path).next().map_or("", |(_, c)| c).to_owned()),
}
}
fn is_dir(self, path: &Path) -> bool {
match self {
Self::Disk => path.is_dir(),
Self::Bundled => bundled(path).any(|(p, _)| p != path),
}
}
fn entries(self, dir: &Path) -> Result<Vec<(String, PathBuf)>, Error> {
let mut entries = Vec::new();
match self {
Self::Disk => {
let io_error = |source| Error::Io {
path: dir.to_owned(),
source,
};
for entry in fs::read_dir(dir).map_err(io_error)? {
let entry = entry.map_err(io_error)?;
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with('.') {
entries.push((name, entry.path()));
}
}
}
Self::Bundled => {
let below = |(path, _): (&'static Path, _)| path.strip_prefix(dir).ok();
for first in bundled(dir)
.filter_map(below)
.filter_map(|p| p.iter().next())
{
let name = first.to_string_lossy().into_owned();
if !entries.iter().any(|(n, _)| *n == name) {
entries.push((name.clone(), dir.join(name)));
}
}
}
}
Ok(entries)
}
}
fn bundled(path: &Path) -> impl Iterator<Item = (&'static Path, &'static str)> {
BUNDLED
.iter()
.map(|(p, content)| (Path::new(*p), *content))
.filter(move |(p, _)| p.starts_with(path))
}
fn invalid<E: ToString>(path: &Path) -> impl FnOnce(E) -> Error {
let path = path.to_owned();
move |error| Error::Invalid {
path,
reason: error.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_answers() {
assert_eq!(
answer(r#"{"status": "ok", "out": {"NewEnable": "1"}}"#),
Ok(Some(Answer::Ok(BTreeMap::from([(
"NewEnable".to_owned(),
"1".to_owned()
)]))))
);
assert_eq!(
answer(r#"{"status": "fault", "code": 714}"#),
Ok(Some(Answer::Fault {
code: 714,
description: String::new()
}))
);
assert_eq!(
answer(r#"{"status": "failed", "error": "timeout"}"#),
Ok(None)
);
for (json, error) in [
("{", "EOF while parsing an object at line 1 column 1"),
(r#"{"status": "ok"}"#, "no output arguments"),
(
r#"{"status": "ok", "out": {"NewEnable": 1}}"#,
"NewEnable is not a string",
),
(r#"{"status": "fault", "code": 70000}"#, "no error code"),
(r#"{"status": "skipped"}"#, "unknown status"),
] {
assert_eq!(answer(json), Err(error.to_owned()), "{json}");
}
}
}