Skip to main content

active_call/
lib.rs

1use anyhow::Result;
2use rsipstack::dialog::{authenticate::Credential, invitation::InviteOption};
3use serde::{Deserialize, Serialize};
4use serde_with::skip_serializing_none;
5use std::collections::HashMap;
6
7use crate::{
8    media::{
9        ambiance::AmbianceOption, recorder::RecorderOption, track::media_pass::MediaPassOption,
10        vad::VADOption,
11    },
12    synthesis::SynthesisOption,
13    transcription::TranscriptionOption,
14};
15
16pub mod app;
17pub mod call;
18pub mod callrecord;
19pub mod config;
20pub mod event;
21pub mod handler;
22pub mod locator;
23pub mod media;
24pub mod net_tool;
25
26#[cfg(feature = "offline")]
27pub mod offline;
28
29pub mod playbook;
30pub mod synthesis;
31pub mod transcription;
32pub mod useragent;
33
34#[derive(Debug, Deserialize, Serialize, Default, Clone)]
35#[serde(default)]
36pub struct SipOption {
37    pub username: Option<String>,
38    pub password: Option<String>,
39    pub realm: Option<String>,
40    pub contact: Option<String>,
41    pub headers: Option<HashMap<String, String>>,
42    pub hangup_headers: Option<HashMap<String, String>>,
43}
44
45#[skip_serializing_none]
46#[derive(Debug, Deserialize, Serialize, Clone)]
47#[serde(rename_all = "camelCase")]
48pub struct CallOption {
49    pub denoise: Option<bool>,
50    pub offer: Option<String>,
51    pub callee: Option<String>,
52    pub caller: Option<String>,
53    pub recorder: Option<RecorderOption>,
54    pub vad: Option<VADOption>,
55    pub asr: Option<TranscriptionOption>,
56    pub tts: Option<SynthesisOption>,
57    pub media_pass: Option<MediaPassOption>,
58    // handshake timeout in seconds
59    pub handshake_timeout: Option<u64>,
60    pub enable_ipv6: Option<bool>,
61    pub inactivity_timeout: Option<u64>, // inactivity timeout in seconds
62    pub sip: Option<SipOption>,
63    pub extra: Option<HashMap<String, String>>,
64    pub codec: Option<String>, // pcmu, pcma, g722, pcm, only for websocket call
65    pub ambiance: Option<AmbianceOption>,
66    pub eou: Option<EouOption>,
67    pub realtime: Option<RealtimeOption>,
68    pub subscribe: Option<bool>,
69}
70
71impl Default for CallOption {
72    fn default() -> Self {
73        Self {
74            denoise: None,
75            offer: None,
76            callee: None,
77            caller: None,
78            recorder: None,
79            asr: None,
80            vad: None,
81            tts: None,
82            media_pass: None,
83            handshake_timeout: None,
84            inactivity_timeout: Some(50), // default 50 seconds
85            enable_ipv6: None,
86            sip: None,
87            extra: None,
88            codec: None,
89            ambiance: None,
90            eou: None,
91            realtime: None,
92            subscribe: None,
93        }
94    }
95}
96
97impl CallOption {
98    pub fn check_default(&mut self) {
99        if let Some(tts) = &mut self.tts {
100            tts.check_default();
101        }
102        if let Some(asr) = &mut self.asr {
103            asr.check_default();
104        }
105        if let Some(realtime) = &mut self.realtime {
106            realtime.check_default();
107        }
108    }
109
110    pub fn build_invite_option(&self) -> Result<InviteOption> {
111        let mut invite_option = InviteOption::default();
112        if let Some(offer) = &self.offer {
113            invite_option.offer = Some(offer.clone().into());
114        }
115        if let Some(callee) = &self.callee {
116            invite_option.callee = callee.clone().try_into()?;
117        }
118        let caller_uri = if let Some(caller) = &self.caller {
119            // Ensure caller URI has proper sip: scheme
120            if caller.starts_with("sip:") || caller.starts_with("sips:") {
121                caller.clone()
122            } else {
123                format!("sip:{}", caller)
124            }
125        } else if let Some(username) = self.sip.as_ref().and_then(|sip| sip.username.as_ref()) {
126            // If caller is not specified but we have SIP credentials, use username as caller
127            // If realm is available, use it, otherwise use local IP
128            let domain = self
129                .sip
130                .as_ref()
131                .and_then(|sip| sip.realm.as_ref())
132                .map(|s| s.as_str())
133                .unwrap_or("127.0.0.1");
134            format!("sip:{}@{}", username, domain)
135        } else {
136            // Default to a valid SIP URI if nothing is specified
137            "sip:active-call@127.0.0.1".to_string()
138        };
139        invite_option.caller = caller_uri.try_into()?;
140
141        if let Some(sip) = &self.sip {
142            invite_option.credential = Some(Credential {
143                username: sip.username.clone().unwrap_or_default(),
144                password: sip.password.clone().unwrap_or_default(),
145                realm: sip.realm.clone(),
146            });
147            invite_option.headers = sip.headers.as_ref().map(|h| {
148                h.iter()
149                    .map(|(k, v)| rsip::Header::Other(k.clone(), v.clone()))
150                    .collect::<Vec<_>>()
151            });
152            sip.contact.as_ref().map(|c| match c.clone().try_into() {
153                Ok(u) => {
154                    invite_option.contact = u;
155                }
156                Err(_) => {}
157            });
158        }
159        Ok(invite_option)
160    }
161}
162
163#[skip_serializing_none]
164#[derive(Debug, Deserialize, Serialize, Clone)]
165#[serde(rename_all = "camelCase")]
166pub struct ReferOption {
167    pub denoise: Option<bool>,
168    pub timeout: Option<u32>,
169    pub moh: Option<String>,
170    pub asr: Option<TranscriptionOption>,
171    /// hangup after the call is ended
172    pub auto_hangup: Option<bool>,
173    pub sip: Option<SipOption>,
174}
175
176#[skip_serializing_none]
177#[derive(Clone, Debug, Deserialize, Serialize, Default)]
178#[serde(rename_all = "camelCase")]
179pub struct EouOption {
180    pub r#type: Option<String>,
181    pub endpoint: Option<String>,
182    #[serde(alias = "apiKey")]
183    pub secret_key: Option<String>,
184    pub secret_id: Option<String>,
185    /// max timeout in milliseconds
186    pub timeout: Option<u32>,
187    pub extra: Option<HashMap<String, String>>,
188}
189
190#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
191pub enum RealtimeType {
192    #[serde(rename = "openai")]
193    OpenAI,
194    #[serde(rename = "azure")]
195    Azure,
196    Other(String),
197}
198
199impl<'de> Deserialize<'de> for RealtimeType {
200    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
201    where
202        D: serde::Deserializer<'de>,
203    {
204        let value = String::deserialize(deserializer)?;
205        match value.as_str() {
206            "openai" => Ok(RealtimeType::OpenAI),
207            "azure" => Ok(RealtimeType::Azure),
208            _ => Ok(RealtimeType::Other(value)),
209        }
210    }
211}
212
213#[skip_serializing_none]
214#[derive(Clone, Debug, Deserialize, Serialize, Default)]
215#[serde(rename_all = "camelCase")]
216pub struct RealtimeOption {
217    pub provider: Option<RealtimeType>,
218    pub model: Option<String>,
219    #[serde(alias = "apiKey")]
220    pub secret_key: Option<String>,
221    pub secret_id: Option<String>,
222    pub endpoint: Option<String>,
223    pub turn_detection: Option<serde_json::Value>,
224    pub tools: Option<Vec<serde_json::Value>>,
225    pub extra: Option<HashMap<String, String>>,
226}
227
228impl RealtimeOption {
229    pub fn check_default(&mut self) {
230        if self.secret_key.is_none() {
231            self.secret_key = std::env::var("OPENAI_API_KEY").ok();
232        }
233    }
234}
235
236pub type Spawner = fn(
237    std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
238) -> tokio::task::JoinHandle<()>;
239static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
240
241pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
242    EXTERNAL_SPAWNER.set(spawner)
243}
244
245pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
246where
247    F: std::future::Future<Output = ()> + Send + 'static,
248{
249    if let Some(spawner) = EXTERNAL_SPAWNER.get() {
250        spawner(Box::pin(future))
251    } else {
252        tokio::spawn(future)
253    }
254}