1use crate::{CallOption, ReferOption, media::recorder::RecorderOption, synthesis::SynthesisOption};
2use serde::{Deserialize, Serialize};
3use serde_with::skip_serializing_none;
4use std::{
5 collections::HashMap,
6 sync::{Arc, Mutex},
7};
8
9pub mod active_call;
10pub mod refer_headers;
11pub mod sip;
12pub mod state;
13pub mod tracks;
14pub use active_call::ActiveCall;
15pub use active_call::ActiveCallRef;
16pub use active_call::ActiveCallType;
17pub use refer_headers::{PassThroughReferHeaders, ReferHeaderContext, ReferHeaderResolver};
18
19pub type CommandSender = tokio::sync::broadcast::Sender<Command>;
20pub type CommandReceiver = tokio::sync::broadcast::Receiver<Command>;
21
22#[skip_serializing_none]
24#[derive(Debug, Deserialize, Serialize, Clone)]
25#[serde(
26 tag = "command",
27 rename_all = "camelCase",
28 rename_all_fields = "camelCase"
29)]
30pub enum Command {
31 Invite {
32 option: CallOption,
33 },
34 Accept {
35 option: CallOption,
36 },
37 Reject {
38 reason: String,
39 code: Option<u32>,
40 },
41 Ringing {
42 recorder: Option<RecorderOption>,
43 early_media: Option<bool>,
44 ringtone: Option<String>,
45 },
46 Tts {
47 text: String,
48 speaker: Option<String>,
49 play_id: Option<String>,
51 auto_hangup: Option<bool>,
53 streaming: Option<bool>,
57 end_of_stream: Option<bool>,
59 option: Option<SynthesisOption>,
60 wait_input_timeout: Option<u32>,
61 base64: Option<bool>,
63 cache_key: Option<String>,
65 },
66 Play {
67 url: String,
68 play_id: Option<String>,
69 auto_hangup: Option<bool>,
70 wait_input_timeout: Option<u32>,
71 offset_ms: Option<u32>,
72 },
73 Dtmf {
78 digit: char,
79 duration_ms: Option<u32>,
81 play_id: Option<String>,
82 },
83 Interrupt {
84 graceful: Option<bool>,
85 fade_out_ms: Option<u32>,
86 },
87 Pause {},
88 Resume {},
89 Hangup {
90 reason: Option<String>,
91 initiator: Option<String>,
92 headers: Option<HashMap<String, String>>,
93 refer: Option<bool>,
94 },
95 Refer {
96 caller: String,
97 callee: String,
99 options: Option<ReferOption>,
100 },
101 Message {
102 body: String,
104 content_type: Option<String>,
106 headers: Option<HashMap<String, String>>,
108 refer: Option<bool>,
110 },
111 Bridge {
116 target_session_id: String,
118 },
119 Unbridge {
121 target_session_id: String,
123 },
124 Mute {
125 track_id: Option<String>,
126 },
127 Unmute {
128 track_id: Option<String>,
129 },
130 History {
131 speaker: String,
132 text: String,
133 },
134 Custom {
135 sender: Option<String>,
136 data: serde_json::Value,
137 },
138 AddIceCandidate {
140 candidate: String,
141 sdp_mid: Option<String>,
142 sdp_mline_index: Option<u32>,
143 },
144 Renegotiate {
148 offer: String,
149 },
150}
151
152#[derive(Debug)]
154pub struct RoutingState {
155 round_robin_counters: Arc<Mutex<HashMap<String, usize>>>,
157}
158
159impl Default for RoutingState {
160 fn default() -> Self {
161 Self::new()
162 }
163}
164
165impl RoutingState {
166 pub fn new() -> Self {
167 Self {
168 round_robin_counters: Arc::new(Mutex::new(HashMap::new())),
169 }
170 }
171
172 pub fn next_round_robin_index(&self, destination_key: &str, trunk_count: usize) -> usize {
174 if trunk_count == 0 {
175 return 0;
176 }
177
178 let mut counters = self.round_robin_counters.lock().unwrap();
179 let counter = counters
180 .entry(destination_key.to_string())
181 .or_insert_with(|| 0);
182 let r = *counter % trunk_count;
183 *counter += 1;
184 return r;
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::Command;
191
192 #[test]
193 fn diagnostic_commands_omit_sip_password() {
194 assert!(format!("{:?}", crate::SipOption::default()).contains("password: None"));
195 let sip = serde_json::json!({"username": "alice", "password": "dummy-sip-secret"});
196 for value in [
197 serde_json::json!({"command": "invite", "option": {"sip": sip}}),
198 serde_json::json!({"command": "accept", "option": {"sip": sip}}),
199 serde_json::json!({"command": "refer", "caller": "a", "callee": "b", "options": {"sip": sip}}),
200 ] {
201 let command: Command = serde_json::from_value(value).unwrap();
202 let debug = format!("{command:?}");
203 assert!(debug.contains("alice"));
204 assert!(debug.contains(r#"password: Some("***")"#));
205 assert!(!debug.contains("dummy-sip-secret"));
206 let serialized = serde_json::to_value(&command).unwrap();
207 let sip = match command {
208 Command::Invite { option } | Command::Accept { option } => option.sip.unwrap(),
209 Command::Refer { options, .. } => options.unwrap().sip.unwrap(),
210 _ => unreachable!(),
211 };
212 assert_eq!(sip.password.as_deref(), Some("dummy-sip-secret"));
213 let options = serialized.get("option").or_else(|| serialized.get("options")).unwrap();
214 assert!(options["sip"].get("password").is_none());
215 assert_eq!(options["sip"]["username"], "alice");
216 }
217 }
218
219 #[test]
220 fn message_command_deserializes_body() {
221 let command: Command = serde_json::from_value(serde_json::json!({
222 "command": "message",
223 "body": "customer_id=12345",
224 "contentType": "text/plain"
225 }))
226 .unwrap();
227
228 assert!(matches!(
229 command,
230 Command::Message {
231 body,
232 content_type: Some(content_type),
233 ..
234 } if body == "customer_id=12345" && content_type == "text/plain"
235 ));
236 }
237
238 #[test]
239 fn dtmf_command_deserializes() {
240 let command: Command = serde_json::from_value(serde_json::json!({
241 "command": "dtmf",
242 "digit": "#",
243 "durationMs": 80,
244 "playId": "notify"
245 }))
246 .unwrap();
247
248 assert!(matches!(
249 command,
250 Command::Dtmf {
251 digit: '#',
252 duration_ms: Some(80),
253 play_id: Some(play_id),
254 } if play_id == "notify"
255 ));
256
257 assert!(
259 serde_json::from_value::<Command>(serde_json::json!({
260 "command": "dtmf",
261 "digit": "12"
262 }))
263 .is_err()
264 );
265 }
266
267 #[test]
268 fn message_command_deserializes_legacy_text() {
269 let command: Command = serde_json::from_value(serde_json::json!({
270 "command": "message",
271 "body": "customer_id=12345"
272 }))
273 .unwrap();
274
275 assert!(matches!(
276 command,
277 Command::Message { body, .. } if body == "customer_id=12345"
278 ));
279 }
280
281 #[test]
282 fn message_command_serializes_body() {
283 let command = Command::Message {
284 body: "customer_id=12345".to_string(),
285 content_type: None,
286 headers: None,
287 refer: None,
288 };
289 let value = serde_json::to_value(command).unwrap();
290
291 assert_eq!(value["body"], "customer_id=12345");
292 assert!(value.get("text").is_none());
293 }
294}