Skip to content

Commit b3785c6

Browse files
committed
check for remaining ringing seconds
1 parent 0ae3d80 commit b3785c6

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/calls.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ use crate::param::Param;
1414
use crate::sync::SyncData;
1515
use crate::tools::time;
1616
use anyhow::{anyhow, ensure, Result};
17+
use std::time::Duration;
18+
use tokio::task;
19+
use tokio::time::sleep;
1720

1821
/// How long callee's or caller's phone ring.
1922
///
@@ -43,7 +46,18 @@ pub struct CallInfo {
4346

4447
impl CallInfo {
4548
fn is_stale_call(&self) -> bool {
46-
time() > self.msg.timestamp_sent + RINGING_SECONDS
49+
self.remaining_ring_seconds() <= 0
50+
}
51+
52+
fn remaining_ring_seconds(&self) -> i64 {
53+
let mut remaining_seconds = self.msg.timestamp_sent + RINGING_SECONDS - time();
54+
if remaining_seconds < 0 {
55+
remaining_seconds = 0;
56+
}
57+
if remaining_seconds > RINGING_SECONDS {
58+
remaining_seconds = RINGING_SECONDS;
59+
}
60+
return remaining_seconds;
4761
}
4862
}
4963

@@ -121,6 +135,10 @@ impl Context {
121135
Ok(())
122136
}
123137

138+
async fn emit_end_call_if_unaccepted(wait: u64) {
139+
sleep(Duration::from_secs(wait)).await;
140+
}
141+
124142
pub(crate) async fn handle_call_msg(
125143
&self,
126144
mime_message: &MimeMessage,
@@ -134,6 +152,8 @@ impl Context {
134152
self.emit_event(EventType::IncomingCall {
135153
msg_id: call.msg.id,
136154
});
155+
let wait = call.remaining_ring_seconds();
156+
task::spawn(Context::emit_end_call_if_unaccepted(wait.try_into()?));
137157
}
138158
}
139159
SystemMessage::CallAccepted => {
@@ -429,6 +449,18 @@ mod tests {
429449
..Default::default()
430450
};
431451
assert!(!call_info.is_stale_call());
452+
assert_eq!(call_info.remaining_ring_seconds(), RINGING_SECONDS);
453+
454+
// call started 5 seconds ago, this is not stale as well
455+
let call_info = CallInfo {
456+
msg: Message {
457+
timestamp_sent: time() - 5,
458+
..Default::default()
459+
},
460+
..Default::default()
461+
};
462+
assert!(!call_info.is_stale_call());
463+
assert_eq!(call_info.remaining_ring_seconds(), RINGING_SECONDS - 5);
432464

433465
// a call started one hour ago is clearly stale
434466
let call_info = CallInfo {
@@ -439,6 +471,7 @@ mod tests {
439471
..Default::default()
440472
};
441473
assert!(call_info.is_stale_call());
474+
assert_eq!(call_info.remaining_ring_seconds(), 0);
442475

443476
Ok(())
444477
}

0 commit comments

Comments
 (0)