1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use crate::{
    find_in_xml,
    utils::{self, HttpResponseExt, HyperBodyExt},
    Error,
};
use http::Uri;
use roxmltree::{Document, Node};
use ssdp_client::URN;
use std::rc::Rc;

mod action;
mod state_variable;
pub use action::*;
pub use state_variable::*;

/// Service Control Protocol Description.
/// It contains information about a particular service, more specifically its actions and state
/// variables.
#[derive(Debug)]
pub struct SCPD {
    urn: URN,
    state_variables: Vec<Rc<StateVariable>>,
    actions: Vec<Action>,
}
impl SCPD {
    pub fn urn(&self) -> &URN {
        &self.urn
    }
    pub fn state_variables(&self) -> &[Rc<StateVariable>] {
        &self.state_variables
    }
    pub fn actions(&self) -> &[Action] {
        &self.actions
    }

    /// Fetches the SCPD description.
    /// The `urn` has to be provided because it isn't included in the description.
    pub(crate) async fn from_url(url: &Uri, urn: URN) -> Result<Self, Error> {
        let body = hyper::Client::new()
            .get(url.clone())
            .await?
            .err_if_not_200()?
            .into_body()
            .text()
            .await?;
        let body = std::str::from_utf8(&body)?;

        let document = Document::parse(&body)?;
        let scpd = utils::find_root(&document, "scpd", "Service Control Point Definition")?;

        #[allow(non_snake_case)]
        let (state_variables, actions) = find_in_xml! { scpd => serviceStateTable, actionList };

        let state_variables: Vec<_> = state_variables
            .children()
            .filter(Node::is_element)
            .map(StateVariable::from_xml)
            .map(|sv| sv.map(Rc::new))
            .collect::<Result<_, _>>()?;
        let actions = actions
            .children()
            .filter(Node::is_element)
            .map(|node| Action::from_xml(node, &state_variables))
            .collect::<Result<_, _>>()?;

        Ok(Self {
            urn,
            state_variables,
            actions,
        })
    }
}