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    /// Signalled (`true`) by `InviteDialogStates::on_terminated` once this
160    /// leg's SIP termination has been recorded. Detached for legs created
161    /// via `new()`; main-leg instances share the ActiveCall-level channel so
162    /// `do_hangup` can wait for the BYE outcome before tearing the session
163    /// down.
164    pub terminated_tx: Arc<tokio::sync::watch::Sender<bool>>,
165}
166
167impl LegShared {
168    pub fn new(ssrc: u32, is_refer: bool, progress: CallProgress) -> Self {
169        Self {
170            ssrc,
171            is_refer,
172            progress: Arc::new(ArcSwap::from_pointee(progress)),
173            extras: Arc::new(ArcSwap::from_pointee(HashMap::new())),
174            terminated_tx: Arc::new(tokio::sync::watch::channel(false).0),
175        }
176    }
177
178    /// Resolves once the leg's SIP termination has been recorded, returning
179    /// immediately when it already has. Never rejects: pair with
180    /// `tokio::time::timeout` for a bounded wait.
181    pub async fn terminated(&self) {
182        let mut rx = self.terminated_tx.subscribe();
183        while !*rx.borrow_and_update() {
184            if rx.changed().await.is_err() {
185                return;
186            }
187        }
188    }
189
190    pub fn update_progress(&self, f: impl Fn(&mut CallProgress)) {
191        self.progress.rcu(|p| {
192            let mut p = CallProgress::clone(p);
193            f(&mut p);
194            p
195        });
196    }
197
198    pub fn set_extra(&self, key: &str, value: Value) {
199        self.extras.rcu(|e| {
200            let mut e = HashMap::clone(e);
201            e.insert(key.to_string(), value.clone());
202            e
203        });
204    }
205
206    pub fn build_hangup_event(&self, track_id: TrackId, initiator: Option<String>) -> SessionEvent {
207        let progress = self.progress.load_full();
208        let extras = self.extras.load_full();
209        build_hangup_event(&progress, &extras, self.is_refer, track_id, initiator)
210    }
211
212    pub fn build_callrecord(&self, app_state: &AppState, call_type: ActiveCallType) -> CallRecord {
213        let session_id = self.progress.load_full().session_id.clone();
214        self.build_callrecord_with_id(app_state, call_type, session_id)
215    }
216
217    pub fn build_callrecord_with_id(
218        &self,
219        app_state: &AppState,
220        call_type: ActiveCallType,
221        session_id: String,
222    ) -> CallRecord {
223        let progress = self.progress.load_full();
224        let extras = self.extras.load_full();
225        build_callrecord(&progress, &extras, None, app_state, session_id, call_type)
226    }
227}
228
229pub fn build_hangup_event(
230    progress: &CallProgress,
231    extras: &HashMap<String, Value>,
232    is_refer: bool,
233    track_id: TrackId,
234    initiator: Option<String>,
235) -> SessionEvent {
236    let from = progress.option.as_ref().and_then(|o| o.caller.as_ref());
237    let to = progress.option.as_ref().and_then(|o| o.callee.as_ref());
238
239    SessionEvent::Hangup {
240        track_id,
241        timestamp: crate::media::get_timestamp(),
242        reason: progress.hangup_reason.as_ref().map(|r| format!("{:?}", r)),
243        initiator,
244        start_time: progress.start_time.unwrap_or_default().to_rfc3339(),
245        answer_time: progress.answer_time.map(|t| t.to_rfc3339()),
246        ringing_time: progress.ring_time.map(|t| t.to_rfc3339()),
247        hangup_time: Utc::now().to_rfc3339(),
248        extra: Some(extras.clone()),
249        from: from.map(|f| f.into()),
250        to: to.map(|f| f.into()),
251        refer: Some(is_refer),
252    }
253}
254
255pub fn build_callrecord(
256    progress: &CallProgress,
257    extras: &HashMap<String, Value>,
258    refer_leg: Option<&LegShared>,
259    app_state: &AppState,
260    session_id: String,
261    call_type: ActiveCallType,
262) -> CallRecord {
263    let option = progress.option.clone().unwrap_or_default();
264    let recorder = if option.recorder.is_some() {
265        let recorder_file = app_state.get_recorder_file(&session_id);
266        if std::path::Path::new(&recorder_file).exists() {
267            let file_size = std::fs::metadata(&recorder_file)
268                .map(|m| m.len())
269                .unwrap_or(0);
270            vec![crate::callrecord::CallRecordMedia {
271                track_id: session_id.clone(),
272                path: recorder_file,
273                size: file_size,
274                extra: None,
275            }]
276        } else {
277            vec![]
278        }
279    } else {
280        vec![]
281    };
282
283    let dump_event_file = app_state.get_dump_events_file(&session_id);
284    let dump_event_file = if std::path::Path::new(&dump_event_file).exists() {
285        Some(dump_event_file)
286    } else {
287        None
288    };
289
290    let refer_callrecord =
291        refer_leg.map(|leg| Box::new(leg.build_callrecord(app_state, ActiveCallType::B2bua)));
292
293    // SIP Call-IDs of every dialog seen for this session (primary leg,
294    // bridge legs, REFER transfer legs) — resolved by the sipflow capture
295    // when enabled, empty otherwise.
296    let sip_call_ids = app_state
297        .sip_flow
298        .as_ref()
299        .map(|flow| flow.get_session_call_ids(&session_id))
300        .unwrap_or_default();
301
302    let caller = option.caller.clone().unwrap_or_default();
303    let callee = option.callee.clone().unwrap_or_default();
304
305    CallRecord {
306        option: Some(option),
307        call_id: session_id,
308        call_type,
309        start_time: progress.start_time.unwrap_or_default(),
310        ring_time: progress.ring_time,
311        answer_time: progress.answer_time,
312        end_time: Utc::now(),
313        caller,
314        callee,
315        hangup_reason: progress.hangup_reason.clone(),
316        hangup_messages: Vec::new(),
317        status_code: progress.last_status_code,
318        extras: Some(extras.clone()),
319        dump_event_file,
320        recorder,
321        refer_callrecord,
322        sip_call_ids,
323    }
324}
325
326pub fn resolve_final_answer(
327    raw: Option<Vec<u8>>,
328    early: Option<&String>,
329) -> Result<(String, bool), &'static str> {
330    match raw {
331        Some(bytes) => {
332            let s = String::from_utf8_lossy(&bytes).to_string();
333            if s.trim().is_empty() {
334                match early {
335                    Some(e) if !e.is_empty() => Ok((e.clone(), true)),
336                    _ => Ok((s, false)),
337                }
338            } else {
339                Ok((s, false))
340            }
341        }
342        None => match early {
343            Some(e) if !e.is_empty() => Ok((e.clone(), true)),
344            _ => Err("no answer received"),
345        },
346    }
347}
348
349pub enum ActorMsg {
350    ReferDone {
351        track_id: TrackId,
352        forward_dtmf: bool,
353        result: Result<String, rsipstack::Error>,
354        /// Final SIP status of the refer leg (200 on success, 408 on
355        /// timeout, ...); reported to the referrer via NOTIFY when this
356        /// transfer was triggered by an incoming REFER.
357        code: Option<u16>,
358    },
359}
360
361pub struct CallRuntime {
362    pub input_timeout_expire: (u64, u32),
363    pub actor_tx: mpsc::Sender<ActorMsg>,
364    pub me: Option<crate::call::active_call::ActiveCallRef>,
365}
366
367impl CallRuntime {
368    pub fn new(actor_tx: mpsc::Sender<ActorMsg>) -> Self {
369        Self {
370            input_timeout_expire: (0, 0),
371            actor_tx,
372            me: None,
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    const EARLY_SDP: &str = "v=0\r\no=- 1000 1 IN IP4 192.168.1.100\r\n";
382
383    #[test]
384    fn early_then_confirmed_progress() {
385        let mut p = CallProgress::default();
386        p.on_early(183);
387        assert!(p.ring_time.is_some());
388        assert_eq!(p.last_status_code, 183);
389
390        p.on_confirmed("dialog-1".to_string());
391        assert_eq!(p.session_id, "dialog-1");
392        assert_eq!(p.last_status_code, 200);
393        assert!(p.answer_time.is_some());
394
395        // A second confirmed must not move answer_time.
396        let first = p.answer_time;
397        p.on_confirmed("dialog-2".to_string());
398        assert_eq!(p.answer_time, first);
399    }
400
401    #[test]
402    fn try_set_answer_keeps_first() {
403        let mut p = CallProgress::default();
404        p.try_set_answer(EARLY_SDP);
405        p.try_set_answer("late");
406        assert_eq!(p.answer.as_deref(), Some(EARLY_SDP));
407    }
408
409    #[test]
410    fn set_hangup_reason_keeps_first() {
411        let mut p = CallProgress::default();
412        p.set_hangup_reason(CallRecordHangupReason::ByCaller);
413        p.set_hangup_reason(CallRecordHangupReason::ByCallee);
414        assert_eq!(p.hangup_reason, Some(CallRecordHangupReason::ByCaller));
415    }
416
417    #[test]
418    fn resolve_final_answer_uses_early_sdp_on_empty_body() {
419        let early = EARLY_SDP.to_string();
420        let (sdp, applied) = resolve_final_answer(Some(vec![]), Some(&early)).unwrap();
421        assert_eq!(sdp, EARLY_SDP);
422        assert!(applied);
423    }
424
425    #[test]
426    fn resolve_final_answer_uses_200ok_body_when_present() {
427        let early = EARLY_SDP.to_string();
428        let (sdp, applied) = resolve_final_answer(Some(b"final".to_vec()), Some(&early)).unwrap();
429        assert_eq!(sdp, "final");
430        assert!(!applied);
431    }
432
433    #[test]
434    fn resolve_final_answer_no_answer_at_all() {
435        assert!(resolve_final_answer(None, None).is_err());
436        assert!(resolve_final_answer(None, Some(&String::new())).is_err());
437    }
438
439    #[test]
440    fn termination_mapping() {
441        let info = CallProgress::termination(Some(&TerminatedReason::UacCancel));
442        assert_eq!((info.status_code, info.initiator), (487, "caller"));
443        assert_eq!(info.hangup_reason, CallRecordHangupReason::Canceled);
444
445        let info = CallProgress::termination(Some(&TerminatedReason::UasDecline));
446        assert_eq!((info.status_code, info.initiator), (603, "callee"));
447        assert_eq!(info.hangup_reason, CallRecordHangupReason::ByCallee);
448
449        let info = CallProgress::termination(None);
450        assert_eq!((info.status_code, info.initiator), (500, "system"));
451        assert_eq!(info.hangup_reason, CallRecordHangupReason::BySystem);
452    }
453
454    #[test]
455    fn leg_shared_extras_rcu() {
456        let leg = LegShared::new(42, false, CallProgress::default());
457        leg.set_extra("k", Value::String("v".into()));
458        assert_eq!(
459            leg.extras.load_full().get("k"),
460            Some(&Value::String("v".into()))
461        );
462    }
463}