twiml/
gather.rs

1use crate::*;
2use xml::{
3    writer::{EventWriter, XmlEvent},
4    EmitterConfig,
5};
6
7#[derive(Debug)]
8pub struct Gather<'a> {
9    method: Method,
10    action: Option<&'a str>,
11    key: char,
12    timeout: usize,
13    body: GatherBody<'a>,
14}
15
16#[derive(Debug)]
17enum GatherBody<'a> {
18    Nil,
19    Say(Say<'a>),
20    Play(Play<'a>),
21    Redirect(Redirect<'a>),
22}
23
24impl<'a> Default for Gather<'a> {
25    fn default() -> Self {
26        Gather {
27            body: GatherBody::Nil,
28            method: Method::Post,
29            key: '#',
30            action: None,
31            timeout: 5,
32        }
33    }
34}
35
36impl<'a> Gather<'a> {
37    pub fn say<S: Into<Say<'a>>>(mut self, say: S) -> Self {
38        self.body = GatherBody::Say(say.into());
39        self
40    }
41
42    pub fn play<P: Into<Play<'a>>>(mut self, play: P) -> Self {
43        self.body = GatherBody::Play(play.into());
44        self
45    }
46
47    pub fn redirect<R: Into<Redirect<'a>>>(mut self, redirect: R) -> Self {
48        self.body = GatherBody::Redirect(redirect.into());
49        self
50    }
51
52    pub fn method(mut self, method: Method) -> Self {
53        self.method = method;
54        self
55    }
56
57    pub fn finish_on_key(mut self, key: char) -> Self {
58        self.key = key;
59        self
60    }
61
62    pub fn timeout(mut self, timeout: usize) -> Self {
63        self.timeout = timeout;
64        self
65    }
66}
67
68impl<'a> Twiml for Gather<'a> {
69    fn write<W: Write>(&self, w: &mut EventWriter<W>) -> TwimlResult<()> {
70        let timeout = self.timeout.to_string();
71        let key = self.key.to_string();
72        let el = XmlEvent::start_element("Gather")
73            .attr("method", self.method.to_str())
74            .attr("timeout", &timeout)
75            .attr("finishOnKey", &key);
76        if let Some(action) = self.action {
77            w.write(el.attr("action", action))?;
78        } else {
79            w.write(el)?;
80        }
81        match self.body {
82            GatherBody::Nil => {}
83            GatherBody::Play(ref val) => val.write(w)?,
84            GatherBody::Say(ref val) => val.write(w)?,
85            GatherBody::Redirect(ref val) => val.write(w)?,
86        }
87
88        w.write(XmlEvent::end_element())?;
89        Ok(())
90    }
91
92    fn build(&self) -> TwimlResult<String> {
93        // Create a buffer and serialize our nodes into it
94        let mut writer = Vec::with_capacity(30);
95        {
96            let mut w = EmitterConfig::new()
97                .write_document_declaration(false)
98                .create_writer(&mut writer);
99
100            self.write(&mut w)?;
101        }
102        Ok(String::from_utf8(writer)?)
103    }
104}