cal_core/device/
digit_router.rs

1use crate::device::device::Connector;
2use crate::router_option::RouterOption;
3use crate::{ConnectState, FlowState};
4use serde::{Deserialize, Serialize};
5use std::fmt::{Debug, Formatter};
6
7#[derive(Serialize, Deserialize, Clone)]
8#[serde(rename_all = "camelCase")]
9pub struct DigitRouter {
10    pub text: String,
11    #[serde(rename = "ttsLanguage")]
12    #[serde(default = "crate::device::shared::build_tts_voice")]
13    pub tts_voice: String,
14    #[serde(default = "crate::device::shared::build_finish_key")]
15    pub finish_on_key: String,
16    #[serde(default = "crate::device::shared::build_connect_to")]
17    pub connect_to: String,
18    #[serde(default)]
19    pub options: Vec<RouterOption>,
20    #[serde(default = "crate::device::shared::build_digit_timeout")]
21    pub timeout: u8,
22    #[serde(default = "crate::device::shared::build_max_digits")]
23    pub max_digits: u8,
24}
25
26impl DigitRouter {
27    fn get_opts(&mut self) -> Vec<RouterOption> {
28        let opts = &mut self.options.clone();
29        opts.sort_by_key(|o| o.option.chars().count());
30        opts.reverse();
31        opts.clone()
32    }
33}
34
35impl Connector for DigitRouter {
36    fn get_connect_to(&mut self, state: &mut FlowState) -> ConnectState {
37        match &state.get_digits() {
38            Some(d) => self
39                .get_opts()
40                .iter()
41                .find(|o| o.option.eq(d.as_str()))
42                .map(|o| {
43                    ConnectState::matched(
44                        &o.connect_to.to_string(),
45                        Some(d.to_string()),
46                        Some(o.option.clone()),
47                    )
48                })
49                .unwrap_or_else(|| {
50                    ConnectState::default(&self.connect_to.to_string(), Some(d.to_string()))
51                }),
52            None => ConnectState::default(
53                &self.connect_to.to_string(),
54                Some(self.connect_to.to_string()),
55            ),
56        }
57    }
58}
59
60impl Debug for DigitRouter {
61    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62        f.debug_struct("DigitRouter")
63            .field("text", &self.text)
64            .field("tts_voice", &self.tts_voice)
65            .field("finish_on_key", &self.finish_on_key)
66            .field("connect_to", &self.connect_to)
67            .field("options", &self.options)
68            .field("timeout", &self.timeout)
69            .field("max_digits", &self.max_digits)
70            .finish()
71    }
72}