active_call/useragent/
registration.rs1use anyhow::Result;
2use rsipstack::dialog::{authenticate::Credential, registration::Registration};
3use rsipstack::rsip::{HostWithPort, Response, StatusCodeKind, Transport};
4use rsipstack::transport::SipAddr;
5use serde::{Deserialize, Serialize};
6use std::time::Instant;
7use tokio_util::sync::CancellationToken;
8use tracing::{debug, warn};
9
10use super::public_address::{normalize_transport, should_update_address};
11
12#[derive(Debug, Deserialize, Clone, Serialize)]
13pub struct UserCredential {
14 pub username: String,
15 pub auth_username: Option<String>,
18 pub password: String,
19 pub realm: Option<String>,
20}
21
22#[derive(Debug, Deserialize, Clone, Serialize)]
23pub struct RegisterOption {
24 pub server: String,
25 pub username: String,
26 pub display_name: Option<String>,
27 pub disabled: Option<bool>,
28 pub credential: Option<UserCredential>,
29}
30
31impl From<UserCredential> for Credential {
32 fn from(val: UserCredential) -> Self {
33 Credential {
34 username: val.username,
35 auth_username: val.auth_username,
36 password: val.password,
37 realm: val.realm,
38 }
39 }
40}
41
42impl RegisterOption {
43 pub fn aor(&self) -> String {
44 format!("{}@{}", self.username, self.server)
45 }
46}
47
48pub struct RegistrationHandle {
49 pub registration: Registration,
50 pub option: RegisterOption,
51 pub cancel_token: CancellationToken,
52 pub start_time: Instant,
53 pub last_update: Instant,
54 pub last_response: Option<Response>,
55}
56
57impl RegistrationHandle {
58 pub fn should_retry_registration_now(
59 &self,
60 local_addr: &SipAddr,
61 current_contact_address: &HostWithPort,
62 discovered_public_address: Option<&HostWithPort>,
63 ) -> bool {
64 if normalize_transport(local_addr.r#type.as_ref()) != Transport::Udp {
65 return false;
66 }
67
68 discovered_public_address
69 .is_some_and(|address| should_update_address(current_contact_address, address))
70 }
71
72 pub async fn do_register(
73 &mut self,
74 sip_server: &rsipstack::rsip::Uri,
75 expires: Option<u32>,
76 contact: &rsipstack::rsip::typed::Contact,
77 ) -> Result<(u32, Option<HostWithPort>)> {
78 self.registration.contact = Some(contact.clone());
79 let resp = match self
80 .registration
81 .register(sip_server.clone(), expires)
82 .await
83 .map_err(|e| anyhow::anyhow!("Registration failed: {}", e))
84 {
85 Ok(resp) => resp,
86 Err(e) => {
87 warn!("registration failed: {}", e);
88 return Err(anyhow::anyhow!("Registration failed: {}", e));
89 }
90 };
91 debug!(
92 user = self.option.aor(),
93 "registration response: {:?}", resp
94 );
95 match resp.status_code().kind() {
96 StatusCodeKind::Successful => {
97 self.last_update = Instant::now();
98 self.last_response = Some(resp);
99 Ok((
100 self.registration.expires(),
101 self.registration.public_address.clone(),
102 ))
103 }
104 _ => Err(anyhow::anyhow!("{:?}", resp.reason_phrase())),
105 }
106 }
107}