Skip to main content

active_call/call/
state.rs

1use crate::CallOption;
2use crate::app::AppState;
3use crate::call::active_call::ActiveCallType;
4use crate::callrecord::{CallRecord, CallRecordHangupReason};
5use crate::event::SessionEvent;
6use crate::media::TrackId;
7use arc_swap::ArcSwap;
8use chrono::{DateTime, Utc};
9use rsipstack::dialog::dialog::TerminatedReason;
10use serde_json::Value;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::mpsc;
14
15pub type Extras = Arc<ArcSwap<HashMap<String, Value>>>;
16
17#[derive(Clone, Debug, Default)]
18pub struct CallProgress {
19    pub session_id: String,
20    pub start_time: Option<DateTime<Utc>>,
21    pub ring_time: Option<DateTime<Utc>>,
22    pub answer_time: Option<DateTime<Utc>>,
23    pub answer: Option<String>,
24    pub last_status_code: u16,
25    pub hangup_reason: Option<CallRecordHangupReason>,
26    pub option: Option<CallOption>,
27    /// Set on a superseded INVITE-mode bridge leg after a successful
28    /// auto-refer transfer: its termination is an internal replace, so no
29    /// Hangup event is reported to the client and it must not tear the
30    /// session down.
31    pub superseded: bool,
32}
33
34impl CallProgress {
35    pub fn on_early(&mut self, code: u16) {
36        self.ring_time.get_or_insert_with(Utc::now);
37        self.last_status_code = code;
38    }
39
40    pub fn on_confirmed(&mut self, session_id: String) {
41        self.session_id = session_id;
42        self.answer_time.get_or_insert_with(Utc::now);
43        self.last_status_code = 200;
44    }
45
46    pub fn on_answered(&mut self) {
47        self.answer_time.get_or_insert_with(Utc::now);
48        self.last_status_code = 200;
49    }
50
51    pub fn try_set_answer(&mut self, sdp: &str) {
52        if self.answer.is_none() {
53            self.answer = Some(sdp.to_string());
54        }
55    }
56
57    pub fn set_hangup_reason(&mut self, reason: CallRecordHangupReason) {
58        if self.hangup_reason.is_none() {
59            self.hangup_reason = Some(reason);
60        }
61    }
62
63    pub fn merge_option(&self, mut option: CallOption) -> CallOption {
64        if let Some(existing) = &self.option {
65            if option.asr.is_none() {
66                option.asr = existing.asr.clone();
67            }
68            if option.tts.is_none() {
69                option.tts = existing.tts.clone();
70            }
71            if option.vad.is_none() {
72                option.vad = existing.vad.clone();
73            }
74            if option.denoise.is_none() {
75                option.denoise = existing.denoise;
76            }
77            if option.agc.is_none() {
78                option.agc = existing.agc.clone();
79            }
80            if option.recorder.is_none() {
81                option.recorder = existing.recorder.clone();
82            }
83            if option.eou.is_none() {
84                option.eou = existing.eou.clone();
85            }
86            if option.extra.is_none() {
87                option.extra = existing.extra.clone();
88            }
89            if option.ambiance.is_none() {
90                option.ambiance = existing.ambiance.clone();
91            }
92            if option.ringback_detection.is_none() {
93                option.ringback_detection = existing.ringback_detection.clone();
94            }
95            if option.monitor.is_none() {
96                option.monitor = existing.monitor.clone();
97            }
98        }
99        option
100    }
101
102    pub fn termination(reason: Option<&TerminatedReason>) -> TerminationInfo {
103        match reason {
104            Some(TerminatedReason::UacCancel) => {
105                TerminationInfo::new(487, CallRecordHangupReason::Canceled, "caller")
106            }
107            Some(TerminatedReason::UacBye) => {
108                TerminationInfo::new(200, CallRecordHangupReason::ByCaller, "caller")
109            }
110            Some(TerminatedReason::UacBusy) => {
111                TerminationInfo::new(486, CallRecordHangupReason::ByCaller, "caller")
112            }
113            Some(TerminatedReason::UasBye) => {
114                TerminationInfo::new(200, CallRecordHangupReason::ByCallee, "callee")
115            }
116            Some(TerminatedReason::UasBusy) => {
117                TerminationInfo::new(486, CallRecordHangupReason::ByCallee, "callee")
118            }
119            Some(TerminatedReason::UasDecline) => {
120                TerminationInfo::new(603, CallRecordHangupReason::ByCallee, "callee")
121            }
122            Some(TerminatedReason::UacOther(code)) => {
123                TerminationInfo::new(code.code(), CallRecordHangupReason::ByCaller, "system")
124            }
125            Some(TerminatedReason::UasOther(code)) => {
126                TerminationInfo::new(code.code(), CallRecordHangupReason::ByCallee, "system")
127            }
128            _ => TerminationInfo::new(500, CallRecordHangupReason::BySystem, "system"),
129        }
130    }
131}
132
133pub struct TerminationInfo {
134    pub status_code: u16,
135    pub hangup_reason: CallRecordHangupReason,
136    pub initiator: &'static str,
137}
138
139impl TerminationInfo {
140    fn new(
141        status_code: u16,
142        hangup_reason: CallRecordHangupReason,
143        initiator: &'static str,
144    ) -> Self {
145        Self {
146            status_code,
147            hangup_reason,
148            initiator,
149        }
150    }
151}
152
153#[derive(Clone)]
154pub struct LegShared {
155    pub ssrc: u32,
156    pub is_refer: bool,
157    pub progress: Arc<ArcSwap<CallProgress>>,
158    pub extras: Extras,
159}
160
161impl LegShared {
162    pub fn new(ssrc: u32, is_refer: bool, progress: CallProgress) -> Self {
163        Self {
164            ssrc,
165            is_refer,
166            progress: Arc::new(ArcSwap::from_pointee(progress)),
167            extras: Arc::new(ArcSwap::from_pointee(HashMap::new())),
168        }
169    }
170
171    pub fn update_progress(&self, f: impl Fn(&mut CallProgress)) {
172        self.progress.rcu(|p| {
173            let mut p = CallProgress::clone(p);
174            f(&mut p);
175            p
176        });
177    }
178
179    pub fn set_extra(&self, key: &str, value: Value) {
180        self.extras.rcu(|e| {
181            let mut e = HashMap::clone(e);
182            e.insert(key.to_string(), value.clone());
183            e
184        });
185    }
186
187    pub fn build_hangup_event(&self, track_id: TrackId, initiator: Option<String>) -> SessionEvent {
188        let progress = self.progress.load_full();
189        let extras = self.extras.load_full();
190        build_hangup_event(&progress, &extras, self.is_refer, track_id, initiator)
191    }
192
193    pub fn build_callrecord(&self, app_state: &AppState, call_type: ActiveCallType) -> CallRecord {
194        let session_id = self.progress.load_full().session_id.clone();
195        self.build_callrecord_with_id(app_state, call_type, session_id)
196    }
197
198    pub fn build_callrecord_with_id(
199        &self,
200        app_state: &AppState,
201        call_type: ActiveCallType,
202        session_id: String,
203    ) -> CallRecord {
204        let progress = self.progress.load_full();
205        let extras = self.extras.load_full();
206        build_callrecord(&progress, &extras, None, app_state, session_id, call_type)
207    }
208}
209
210pub fn build_hangup_event(
211    progress: &CallProgress,
212    extras: &HashMap<String, Value>,
213    is_refer: bool,
214    track_id: TrackId,
215    initiator: Option<String>,
216) -> SessionEvent {
217    let from = progress.option.as_ref().and_then(|o| o.caller.as_ref());
218    let to = progress.option.as_ref().and_then(|o| o.callee.as_ref());
219
220    SessionEvent::Hangup {
221        track_id,
222        timestamp: crate::media::get_timestamp(),
223        reason: progress.hangup_reason.as_ref().map(|r| format!("{:?}", r)),
224        initiator,
225        start_time: progress.start_time.unwrap_or_default().to_rfc3339(),
226        answer_time: progress.answer_time.map(|t| t.to_rfc3339()),
227        ringing_time: progress.ring_time.map(|t| t.to_rfc3339()),
228        hangup_time: Utc::now().to_rfc3339(),
229        extra: Some(extras.clone()),
230        from: from.map(|f| f.into()),
231        to: to.map(|f| f.into()),
232        refer: Some(is_refer),
233    }
234}
235
236pub fn build_callrecord(
237    progress: &CallProgress,
238    extras: &HashMap<String, Value>,
239    refer_leg: Option<&LegShared>,
240    app_state: &AppState,
241    session_id: String,
242    call_type: ActiveCallType,
243) -> CallRecord {
244    let option = progress.option.clone().unwrap_or_default();
245    let recorder = if option.recorder.is_some() {
246        let recorder_file = app_state.get_recorder_file(&session_id);
247        if std::path::Path::new(&recorder_file).exists() {
248            let file_size = std::fs::metadata(&recorder_file)
249                .map(|m| m.len())
250                .unwrap_or(0);
251            vec![crate::callrecord::CallRecordMedia {
252                track_id: session_id.clone(),
253                path: recorder_file,
254                size: file_size,
255                extra: None,
256            }]
257        } else {
258            vec![]
259        }
260    } else {
261        vec![]
262    };
263
264    let dump_event_file = app_state.get_dump_events_file(&session_id);
265    let dump_event_file = if std::path::Path::new(&dump_event_file).exists() {
266        Some(dump_event_file)
267    } else {
268        None
269    };
270
271    let refer_callrecord =
272        refer_leg.map(|leg| Box::new(leg.build_callrecord(app_state, ActiveCallType::B2bua)));
273
274    // SIP Call-IDs of every dialog seen for this session (primary leg,
275    // bridge legs, REFER transfer legs) — resolved by the sipflow capture
276    // when enabled, empty otherwise.
277    let sip_call_ids = app_state
278        .sip_flow
279        .as_ref()
280        .map(|flow| flow.get_session_call_ids(&session_id))
281        .unwrap_or_default();
282
283    let caller = option.caller.clone().unwrap_or_default();
284    let callee = option.callee.clone().unwrap_or_default();
285
286    CallRecord {
287        option: Some(option),
288        call_id: session_id,
289        call_type,
290        start_time: progress.start_time.unwrap_or_default(),
291        ring_time: progress.ring_time,
292        answer_time: progress.answer_time,
293        end_time: Utc::now(),
294        caller,
295        callee,
296        hangup_reason: progress.hangup_reason.clone(),
297        hangup_messages: Vec::new(),
298        status_code: progress.last_status_code,
299        extras: Some(extras.clone()),
300        dump_event_file,
301        recorder,
302        refer_callrecord,
303        sip_call_ids,
304    }
305}
306
307pub fn resolve_final_answer(
308    raw: Option<Vec<u8>>,
309    early: Option<&String>,
310) -> Result<(String, bool), &'static str> {
311    match raw {
312        Some(bytes) => {
313            let s = String::from_utf8_lossy(&bytes).to_string();
314            if s.trim().is_empty() {
315                match early {
316                    Some(e) if !e.is_empty() => Ok((e.clone(), true)),
317                    _ => Ok((s, false)),
318                }
319            } else {
320                Ok((s, false))
321            }
322        }
323        None => match early {
324            Some(e) if !e.is_empty() => Ok((e.clone(), true)),
325            _ => Err("no answer received"),
326        },
327    }
328}
329
330pub enum ActorMsg {
331    ReferDone {
332        track_id: TrackId,
333        forward_dtmf: bool,
334        result: Result<String, rsipstack::Error>,
335        /// Final SIP status of the refer leg (200 on success, 408 on
336        /// timeout, ...); reported to the referrer via NOTIFY when this
337        /// transfer was triggered by an incoming REFER.
338        code: Option<u16>,
339    },
340}
341
342pub struct CallRuntime {
343    pub input_timeout_expire: (u64, u32),
344    pub actor_tx: mpsc::Sender<ActorMsg>,
345    pub me: Option<crate::call::active_call::ActiveCallRef>,
346}
347
348impl CallRuntime {
349    pub fn new(actor_tx: mpsc::Sender<ActorMsg>) -> Self {
350        Self {
351            input_timeout_expire: (0, 0),
352            actor_tx,
353            me: None,
354        }
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    const EARLY_SDP: &str = "v=0\r\no=- 1000 1 IN IP4 192.168.1.100\r\n";
363
364    #[test]
365    fn early_then_confirmed_progress() {
366        let mut p = CallProgress::default();
367        p.on_early(183);
368        assert!(p.ring_time.is_some());
369        assert_eq!(p.last_status_code, 183);
370
371        p.on_confirmed("dialog-1".to_string());
372        assert_eq!(p.session_id, "dialog-1");
373        assert_eq!(p.last_status_code, 200);
374        assert!(p.answer_time.is_some());
375
376        // A second confirmed must not move answer_time.
377        let first = p.answer_time;
378        p.on_confirmed("dialog-2".to_string());
379        assert_eq!(p.answer_time, first);
380    }
381
382    #[test]
383    fn try_set_answer_keeps_first() {
384        let mut p = CallProgress::default();
385        p.try_set_answer(EARLY_SDP);
386        p.try_set_answer("late");
387        assert_eq!(p.answer.as_deref(), Some(EARLY_SDP));
388    }
389
390    #[test]
391    fn set_hangup_reason_keeps_first() {
392        let mut p = CallProgress::default();
393        p.set_hangup_reason(CallRecordHangupReason::ByCaller);
394        p.set_hangup_reason(CallRecordHangupReason::ByCallee);
395        assert_eq!(p.hangup_reason, Some(CallRecordHangupReason::ByCaller));
396    }
397
398    #[test]
399    fn resolve_final_answer_uses_early_sdp_on_empty_body() {
400        let early = EARLY_SDP.to_string();
401        let (sdp, applied) = resolve_final_answer(Some(vec![]), Some(&early)).unwrap();
402        assert_eq!(sdp, EARLY_SDP);
403        assert!(applied);
404    }
405
406    #[test]
407    fn resolve_final_answer_uses_200ok_body_when_present() {
408        let early = EARLY_SDP.to_string();
409        let (sdp, applied) = resolve_final_answer(Some(b"final".to_vec()), Some(&early)).unwrap();
410        assert_eq!(sdp, "final");
411        assert!(!applied);
412    }
413
414    #[test]
415    fn resolve_final_answer_no_answer_at_all() {
416        assert!(resolve_final_answer(None, None).is_err());
417        assert!(resolve_final_answer(None, Some(&String::new())).is_err());
418    }
419
420    #[test]
421    fn termination_mapping() {
422        let info = CallProgress::termination(Some(&TerminatedReason::UacCancel));
423        assert_eq!((info.status_code, info.initiator), (487, "caller"));
424        assert_eq!(info.hangup_reason, CallRecordHangupReason::Canceled);
425
426        let info = CallProgress::termination(Some(&TerminatedReason::UasDecline));
427        assert_eq!((info.status_code, info.initiator), (603, "callee"));
428        assert_eq!(info.hangup_reason, CallRecordHangupReason::ByCallee);
429
430        let info = CallProgress::termination(None);
431        assert_eq!((info.status_code, info.initiator), (500, "system"));
432        assert_eq!(info.hangup_reason, CallRecordHangupReason::BySystem);
433    }
434
435    #[test]
436    fn leg_shared_extras_rcu() {
437        let leg = LegShared::new(42, false, CallProgress::default());
438        leg.set_extra("k", Value::String("v".into()));
439        assert_eq!(
440            leg.extras.load_full().get("k"),
441            Some(&Value::String("v".into()))
442        );
443    }
444}