rsipstack/sip/headers/typed/
diversion.rs1use super::parse_helpers::{param_value, parse_display_uri_params_str, split_comma_entries};
2use crate::prelude::*;
3use crate::sip::{uri::Param, Error, Header, Uri};
4
5#[derive(Debug, PartialEq, Eq, Clone)]
12pub enum DiversionReason {
13 Unknown,
14 UserBusy,
15 NoAnswer,
16 Redirected,
17 Unconditional,
18 TimeOfDay,
19 Deflection,
20 FollowMe,
21 OutOfService,
22 Away,
23 Other(String),
24}
25
26impl DiversionReason {
27 pub fn parse(s: &str) -> Self {
28 let lower = s.trim().to_ascii_lowercase();
29 match lower.as_str() {
30 "unknown" => Self::Unknown,
31 "user-busy" | "busy" => Self::UserBusy,
32 "no-answer" => Self::NoAnswer,
33 "redirected" => Self::Redirected,
34 "unconditional" => Self::Unconditional,
35 "time-of-day" => Self::TimeOfDay,
36 "deflection" => Self::Deflection,
37 "follow-me" => Self::FollowMe,
38 "out-of-service" => Self::OutOfService,
39 "away" => Self::Away,
40 _ => Self::Other(lower),
41 }
42 }
43
44 pub fn as_str(&self) -> &str {
45 match self {
46 Self::Unknown => "unknown",
47 Self::UserBusy => "user-busy",
48 Self::NoAnswer => "no-answer",
49 Self::Redirected => "redirected",
50 Self::Unconditional => "unconditional",
51 Self::TimeOfDay => "time-of-day",
52 Self::Deflection => "deflection",
53 Self::FollowMe => "follow-me",
54 Self::OutOfService => "out-of-service",
55 Self::Away => "away",
56 Self::Other(v) => v.as_str(),
57 }
58 }
59}
60
61impl core::fmt::Display for DiversionReason {
62 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
63 write!(f, "{}", self.as_str())
64 }
65}
66
67#[derive(Debug, PartialEq, Eq, Clone)]
73pub struct DiversionEntry {
74 pub uri: Uri,
77 pub reason: Option<DiversionReason>,
78 pub counter: Option<u32>,
81 pub privacy: Option<String>,
83 pub ext: Vec<Param>,
85}
86
87#[derive(Debug, PartialEq, Eq, Clone)]
93pub struct Diversion {
94 pub entries: Vec<DiversionEntry>,
95}
96
97impl DiversionEntry {
98 pub fn parse(s: &str) -> Result<Self, Error> {
99 let (_, uri, params) = parse_display_uri_params_str(s)?;
100 let counter = param_value(¶ms, "counter").and_then(|v| v.parse::<u32>().ok());
101 let mut entry = DiversionEntry {
102 uri,
103 reason: param_value(¶ms, "reason").map(|v| DiversionReason::parse(&v)),
104 counter,
105 privacy: param_value(¶ms, "privacy"),
106 ext: Vec::new(),
107 };
108 for p in params {
109 if let Param::Other(n, _) = &p {
110 let name = n.value();
111 if name.eq_ignore_ascii_case("reason")
112 || name.eq_ignore_ascii_case("counter")
113 || name.eq_ignore_ascii_case("privacy")
114 {
115 continue;
116 }
117 }
118 entry.ext.push(p);
119 }
120 Ok(entry)
121 }
122
123 pub fn with_uri(mut self, uri: Uri) -> Self {
124 self.uri = uri;
125 self
126 }
127
128 pub fn with_reason(mut self, reason: DiversionReason) -> Self {
129 self.reason = Some(reason);
130 self
131 }
132
133 pub fn with_counter(mut self, counter: u32) -> Self {
134 self.counter = Some(counter);
135 self
136 }
137
138 pub fn with_privacy(mut self, privacy: impl Into<String>) -> Self {
139 self.privacy = Some(privacy.into());
140 self
141 }
142}
143
144impl Diversion {
145 pub fn parse(s: &str) -> Result<Self, Error> {
147 let entries = split_comma_entries(s)
148 .into_iter()
149 .map(|v| DiversionEntry::parse(&v))
150 .collect::<Result<Vec<_>, _>>()?;
151 Ok(Self { entries })
152 }
153
154 pub fn from_entries(entries: Vec<DiversionEntry>) -> Self {
156 Self { entries }
157 }
158}
159
160impl core::fmt::Display for DiversionEntry {
161 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
162 write!(f, "<{}>", self.uri)?;
163 if let Some(reason) = &self.reason {
164 write!(f, ";reason={}", reason)?;
165 }
166 if let Some(counter) = &self.counter {
167 write!(f, ";counter={}", counter)?;
168 }
169 if let Some(privacy) = &self.privacy {
170 write!(f, ";privacy={}", privacy)?;
171 }
172 for p in &self.ext {
173 write!(f, "{}", p)?;
174 }
175 Ok(())
176 }
177}
178
179impl core::fmt::Display for Diversion {
180 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
181 let items = self
182 .entries
183 .iter()
184 .map(|e| e.to_string())
185 .collect::<Vec<_>>()
186 .join(", ");
187 write!(f, "{}", items)
188 }
189}
190
191impl core::convert::From<Diversion> for String {
192 fn from(h: Diversion) -> String {
193 h.to_string()
194 }
195}
196
197impl core::convert::From<Diversion> for Header {
198 fn from(h: Diversion) -> Header {
199 Header::Diversion(crate::sip::headers::Diversion::new(h.to_string()))
200 }
201}
202
203impl<'a> super::TypedHeader<'a> for Diversion {}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn parse_single_entry() {
211 let h = Diversion::parse("<sip:diverted@bcn.example.com>").unwrap();
212 assert_eq!(h.entries.len(), 1);
213 assert_eq!(h.entries[0].uri.to_string(), "sip:diverted@bcn.example.com");
214 assert!(h.entries[0].reason.is_none());
215 assert!(h.entries[0].counter.is_none());
216 assert!(h.entries[0].privacy.is_none());
217 assert!(h.entries[0].ext.is_empty());
218 }
219
220 #[test]
221 fn parse_with_params() {
222 let h = Diversion::parse(
223 "<sip:22334459@bcn.example.com>;reason=no-answer;counter=1;privacy=full",
224 )
225 .unwrap();
226 let e = &h.entries[0];
227 assert_eq!(e.reason.as_ref(), Some(&DiversionReason::NoAnswer));
228 assert_eq!(e.counter, Some(1));
229 assert_eq!(e.privacy.as_deref(), Some("full"));
230 }
231
232 #[test]
233 fn parse_comma_joined_entries() {
234 let h = Diversion::parse(
235 "<sip:first@example.com>;reason=unconditional;counter=1,\
236 <sip:second@example.com>;reason=user-busy;counter=2",
237 )
238 .unwrap();
239 assert_eq!(h.entries.len(), 2);
240 assert_eq!(
241 h.entries[0].reason.as_ref(),
242 Some(&DiversionReason::Unconditional)
243 );
244 assert_eq!(
245 h.entries[1].reason.as_ref(),
246 Some(&DiversionReason::UserBusy)
247 );
248 assert_eq!(h.entries[1].counter, Some(2));
249 }
250
251 #[test]
252 fn legacy_busy_canonicalized() {
253 let h = Diversion::parse("<sip:a@example.com>;reason=busy").unwrap();
254 assert_eq!(
255 h.entries[0].reason.as_ref(),
256 Some(&DiversionReason::UserBusy)
257 );
258 assert!(h.to_string().contains("reason=user-busy"));
259 }
260
261 #[test]
262 fn unknown_reason_preserved() {
263 let h = Diversion::parse("<sip:a@example.com>;reason=deflection-cfvl").unwrap();
264 assert_eq!(
265 h.entries[0].reason.as_ref(),
266 Some(&DiversionReason::Other("deflection-cfvl".into()))
267 );
268 assert!(h.to_string().contains("reason=deflection-cfvl"));
269 }
270
271 #[test]
272 fn all_standard_reasons() {
273 for (wire, expected) in [
274 ("unknown", DiversionReason::Unknown),
275 ("user-busy", DiversionReason::UserBusy),
276 ("no-answer", DiversionReason::NoAnswer),
277 ("redirected", DiversionReason::Redirected),
278 ("unconditional", DiversionReason::Unconditional),
279 ("time-of-day", DiversionReason::TimeOfDay),
280 ("deflection", DiversionReason::Deflection),
281 ("follow-me", DiversionReason::FollowMe),
282 ("out-of-service", DiversionReason::OutOfService),
283 ("away", DiversionReason::Away),
284 ] {
285 let h = Diversion::parse(&format!("<sip:a@example.com>;reason={}", wire)).unwrap();
286 assert_eq!(h.entries[0].reason, Some(expected));
287 }
288 }
289
290 #[test]
291 fn ext_params_preserved() {
292 let h = Diversion::parse("<sip:a@example.com>;reason=no-answer;foo=bar").unwrap();
293 assert_eq!(h.entries[0].ext.len(), 1);
294 assert!(h.to_string().contains("foo=bar"));
295 }
296
297 #[test]
298 fn display_roundtrip() {
299 let s = "<sip:first@example.com>;reason=unconditional;counter=1;privacy=off,\
300 <sip:second@example.com>;reason=no-answer;counter=2;privacy=full";
301 let h = Diversion::parse(s).unwrap();
302 let h2 = Diversion::parse(&h.to_string()).unwrap();
303 assert_eq!(h, h2);
304 }
305
306 #[test]
307 fn tel_uri_entry() {
308 let h = Diversion::parse("<tel:+15551234567>;reason=user-busy").unwrap();
309 assert_eq!(h.entries[0].uri.to_string(), "tel:+15551234567");
310 assert_eq!(h.entries[0].reason, Some(DiversionReason::UserBusy));
311 }
312
313 #[test]
314 fn builder_helpers() {
315 use crate::sip::uri::parse_uri;
316 let e = DiversionEntry::parse("<sip:bob@example.com>")
317 .unwrap()
318 .with_reason(DiversionReason::NoAnswer)
319 .with_counter(1)
320 .with_privacy("off");
321 assert_eq!(
322 e.to_string(),
323 "<sip:bob@example.com>;reason=no-answer;counter=1;privacy=off"
324 );
325 assert!(parse_uri("sip:bob@example.com").is_ok());
327 }
328}