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 sip;
11pub mod state;
12pub mod tracks;
13pub use active_call::ActiveCall;
14pub use active_call::ActiveCallRef;
15pub use active_call::ActiveCallType;
16
17pub type CommandSender = tokio::sync::broadcast::Sender<Command>;
18pub type CommandReceiver = tokio::sync::broadcast::Receiver<Command>;
19
20#[skip_serializing_none]
22#[derive(Debug, Deserialize, Serialize, Clone)]
23#[serde(
24 tag = "command",
25 rename_all = "camelCase",
26 rename_all_fields = "camelCase"
27)]
28pub enum Command {
29 Invite {
30 option: CallOption,
31 },
32 Accept {
33 option: CallOption,
34 },
35 Reject {
36 reason: String,
37 code: Option<u32>,
38 },
39 Ringing {
40 recorder: Option<RecorderOption>,
41 early_media: Option<bool>,
42 ringtone: Option<String>,
43 },
44 Tts {
45 text: String,
46 speaker: Option<String>,
47 play_id: Option<String>,
49 auto_hangup: Option<bool>,
51 streaming: Option<bool>,
55 end_of_stream: Option<bool>,
57 option: Option<SynthesisOption>,
58 wait_input_timeout: Option<u32>,
59 base64: Option<bool>,
61 cache_key: Option<String>,
63 },
64 Play {
65 url: String,
66 play_id: Option<String>,
67 auto_hangup: Option<bool>,
68 wait_input_timeout: Option<u32>,
69 offset_ms: Option<u32>,
70 },
71 Dtmf {
76 digit: char,
77 duration_ms: Option<u32>,
79 play_id: Option<String>,
80 },
81 Interrupt {
82 graceful: Option<bool>,
83 fade_out_ms: Option<u32>,
84 },
85 Pause {},
86 Resume {},
87 Hangup {
88 reason: Option<String>,
89 initiator: Option<String>,
90 headers: Option<HashMap<String, String>>,
91 refer: Option<bool>,
92 },
93 Refer {
94 caller: String,
95 callee: String,
97 options: Option<ReferOption>,
98 },
99 Message {
100 body: String,
102 content_type: Option<String>,
104 headers: Option<HashMap<String, String>>,
106 refer: Option<bool>,
108 },
109 Bridge {
114 target_session_id: String,
116 },
117 Unbridge {
119 target_session_id: String,
121 },
122 Mute {
123 track_id: Option<String>,
124 },
125 Unmute {
126 track_id: Option<String>,
127 },
128 History {
129 speaker: String,
130 text: String,
131 },
132 Custom {
133 sender: Option<String>,
134 data: serde_json::Value,
135 },
136 AddIceCandidate {
138 candidate: String,
139 sdp_mid: Option<String>,
140 sdp_mline_index: Option<u32>,
141 },
142 Renegotiate {
146 offer: String,
147 },
148}
149
150#[derive(Debug)]
152pub struct RoutingState {
153 round_robin_counters: Arc<Mutex<HashMap<String, usize>>>,
155}
156
157impl Default for RoutingState {
158 fn default() -> Self {
159 Self::new()
160 }
161}
162
163impl RoutingState {
164 pub fn new() -> Self {
165 Self {
166 round_robin_counters: Arc::new(Mutex::new(HashMap::new())),
167 }
168 }
169
170 pub fn next_round_robin_index(&self, destination_key: &str, trunk_count: usize) -> usize {
172 if trunk_count == 0 {
173 return 0;
174 }
175
176 let mut counters = self.round_robin_counters.lock().unwrap();
177 let counter = counters
178 .entry(destination_key.to_string())
179 .or_insert_with(|| 0);
180 let r = *counter % trunk_count;
181 *counter += 1;
182 return r;
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::Command;
189
190 #[test]
191 fn message_command_deserializes_body() {
192 let command: Command = serde_json::from_value(serde_json::json!({
193 "command": "message",
194 "body": "customer_id=12345",
195 "contentType": "text/plain"
196 }))
197 .unwrap();
198
199 assert!(matches!(
200 command,
201 Command::Message {
202 body,
203 content_type: Some(content_type),
204 ..
205 } if body == "customer_id=12345" && content_type == "text/plain"
206 ));
207 }
208
209 #[test]
210 fn dtmf_command_deserializes() {
211 let command: Command = serde_json::from_value(serde_json::json!({
212 "command": "dtmf",
213 "digit": "#",
214 "durationMs": 80,
215 "playId": "notify"
216 }))
217 .unwrap();
218
219 assert!(matches!(
220 command,
221 Command::Dtmf {
222 digit: '#',
223 duration_ms: Some(80),
224 play_id: Some(play_id),
225 } if play_id == "notify"
226 ));
227
228 assert!(
230 serde_json::from_value::<Command>(serde_json::json!({
231 "command": "dtmf",
232 "digit": "12"
233 }))
234 .is_err()
235 );
236 }
237
238 #[test]
239 fn message_command_deserializes_legacy_text() {
240 let command: Command = serde_json::from_value(serde_json::json!({
241 "command": "message",
242 "body": "customer_id=12345"
243 }))
244 .unwrap();
245
246 assert!(matches!(
247 command,
248 Command::Message { body, .. } if body == "customer_id=12345"
249 ));
250 }
251
252 #[test]
253 fn message_command_serializes_body() {
254 let command = Command::Message {
255 body: "customer_id=12345".to_string(),
256 content_type: None,
257 headers: None,
258 refer: None,
259 };
260 let value = serde_json::to_value(command).unwrap();
261
262 assert_eq!(value["body"], "customer_id=12345");
263 assert!(value.get("text").is_none());
264 }
265}