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 message_command_deserializes_body() {
194 let command: Command = serde_json::from_value(serde_json::json!({
195 "command": "message",
196 "body": "customer_id=12345",
197 "contentType": "text/plain"
198 }))
199 .unwrap();
200
201 assert!(matches!(
202 command,
203 Command::Message {
204 body,
205 content_type: Some(content_type),
206 ..
207 } if body == "customer_id=12345" && content_type == "text/plain"
208 ));
209 }
210
211 #[test]
212 fn dtmf_command_deserializes() {
213 let command: Command = serde_json::from_value(serde_json::json!({
214 "command": "dtmf",
215 "digit": "#",
216 "durationMs": 80,
217 "playId": "notify"
218 }))
219 .unwrap();
220
221 assert!(matches!(
222 command,
223 Command::Dtmf {
224 digit: '#',
225 duration_ms: Some(80),
226 play_id: Some(play_id),
227 } if play_id == "notify"
228 ));
229
230 assert!(
232 serde_json::from_value::<Command>(serde_json::json!({
233 "command": "dtmf",
234 "digit": "12"
235 }))
236 .is_err()
237 );
238 }
239
240 #[test]
241 fn message_command_deserializes_legacy_text() {
242 let command: Command = serde_json::from_value(serde_json::json!({
243 "command": "message",
244 "body": "customer_id=12345"
245 }))
246 .unwrap();
247
248 assert!(matches!(
249 command,
250 Command::Message { body, .. } if body == "customer_id=12345"
251 ));
252 }
253
254 #[test]
255 fn message_command_serializes_body() {
256 let command = Command::Message {
257 body: "customer_id=12345".to_string(),
258 content_type: None,
259 headers: None,
260 refer: None,
261 };
262 let value = serde_json::to_value(command).unwrap();
263
264 assert_eq!(value["body"], "customer_id=12345");
265 assert!(value.get("text").is_none());
266 }
267}