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