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    let caller = option.caller.clone().unwrap_or_default();
272    let callee = option.callee.clone().unwrap_or_default();
273
274    CallRecord {
275        option: Some(option),
276        call_id: session_id,
277        call_type,
278        start_time: progress.start_time.unwrap_or_default(),
279        ring_time: progress.ring_time,
280        answer_time: progress.answer_time,
281        end_time: Utc::now(),
282        caller,
283        callee,
284        hangup_reason: progress.hangup_reason.clone(),
285        hangup_messages: Vec::new(),
286        status_code: progress.last_status_code,
287        extras: Some(extras.clone()),
288        dump_event_file,
289        recorder,
290        refer_callrecord,
291    }
292}
293
294pub fn resolve_final_answer(
295    raw: Option<Vec<u8>>,
296    early: Option<&String>,
297) -> Result<(String, bool), &'static str> {
298    match raw {
299        Some(bytes) => {
300            let s = String::from_utf8_lossy(&bytes).to_string();
301            if s.trim().is_empty() {
302                match early {
303                    Some(e) if !e.is_empty() => Ok((e.clone(), true)),
304                    _ => Ok((s, false)),
305                }
306            } else {
307                Ok((s, false))
308            }
309        }
310        None => match early {
311            Some(e) if !e.is_empty() => Ok((e.clone(), true)),
312            _ => Err("no answer received"),
313        },
314    }
315}
316
317pub enum ActorMsg {
318    ReferDone {
319        track_id: TrackId,
320        forward_dtmf: bool,
321        result: Result<String, rsipstack::Error>,
322        /// Final SIP status of the refer leg (200 on success, 408 on
323        /// timeout, ...); reported to the referrer via NOTIFY when this
324        /// transfer was triggered by an incoming REFER.
325        code: Option<u16>,
326    },
327}
328
329pub struct CallRuntime {
330    pub input_timeout_expire: (u64, u32),
331    pub actor_tx: mpsc::Sender<ActorMsg>,
332    pub me: Option<crate::call::active_call::ActiveCallRef>,
333}
334
335impl CallRuntime {
336    pub fn new(actor_tx: mpsc::Sender<ActorMsg>) -> Self {
337        Self {
338            input_timeout_expire: (0, 0),
339            actor_tx,
340            me: None,
341        }
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    const EARLY_SDP: &str = "v=0\r\no=- 1000 1 IN IP4 192.168.1.100\r\n";
350
351    #[test]
352    fn early_then_confirmed_progress() {
353        let mut p = CallProgress::default();
354        p.on_early(183);
355        assert!(p.ring_time.is_some());
356        assert_eq!(p.last_status_code, 183);
357
358        p.on_confirmed("dialog-1".to_string());
359        assert_eq!(p.session_id, "dialog-1");
360        assert_eq!(p.last_status_code, 200);
361        assert!(p.answer_time.is_some());
362
363        // A second confirmed must not move answer_time.
364        let first = p.answer_time;
365        p.on_confirmed("dialog-2".to_string());
366        assert_eq!(p.answer_time, first);
367    }
368
369    #[test]
370    fn try_set_answer_keeps_first() {
371        let mut p = CallProgress::default();
372        p.try_set_answer(EARLY_SDP);
373        p.try_set_answer("late");
374        assert_eq!(p.answer.as_deref(), Some(EARLY_SDP));
375    }
376
377    #[test]
378    fn set_hangup_reason_keeps_first() {
379        let mut p = CallProgress::default();
380        p.set_hangup_reason(CallRecordHangupReason::ByCaller);
381        p.set_hangup_reason(CallRecordHangupReason::ByCallee);
382        assert_eq!(p.hangup_reason, Some(CallRecordHangupReason::ByCaller));
383    }
384
385    #[test]
386    fn resolve_final_answer_uses_early_sdp_on_empty_body() {
387        let early = EARLY_SDP.to_string();
388        let (sdp, applied) = resolve_final_answer(Some(vec![]), Some(&early)).unwrap();
389        assert_eq!(sdp, EARLY_SDP);
390        assert!(applied);
391    }
392
393    #[test]
394    fn resolve_final_answer_uses_200ok_body_when_present() {
395        let early = EARLY_SDP.to_string();
396        let (sdp, applied) = resolve_final_answer(Some(b"final".to_vec()), Some(&early)).unwrap();
397        assert_eq!(sdp, "final");
398        assert!(!applied);
399    }
400
401    #[test]
402    fn resolve_final_answer_no_answer_at_all() {
403        assert!(resolve_final_answer(None, None).is_err());
404        assert!(resolve_final_answer(None, Some(&String::new())).is_err());
405    }
406
407    #[test]
408    fn termination_mapping() {
409        let info = CallProgress::termination(Some(&TerminatedReason::UacCancel));
410        assert_eq!((info.status_code, info.initiator), (487, "caller"));
411        assert_eq!(info.hangup_reason, CallRecordHangupReason::Canceled);
412
413        let info = CallProgress::termination(Some(&TerminatedReason::UasDecline));
414        assert_eq!((info.status_code, info.initiator), (603, "callee"));
415        assert_eq!(info.hangup_reason, CallRecordHangupReason::ByCallee);
416
417        let info = CallProgress::termination(None);
418        assert_eq!((info.status_code, info.initiator), (500, "system"));
419        assert_eq!(info.hangup_reason, CallRecordHangupReason::BySystem);
420    }
421
422    #[test]
423    fn leg_shared_extras_rcu() {
424        let leg = LegShared::new(42, false, CallProgress::default());
425        leg.set_extra("k", Value::String("v".into()));
426        assert_eq!(
427            leg.extras.load_full().get("k"),
428            Some(&Value::String("v".into()))
429        );
430    }
431}