Merge remote-tracking branch 'origin/main' into fix/badge-count
@@ -31,15 +31,24 @@ async fn main() {
31
31
);
32
32
println!(
33
33
"# with thread: {}",
34
events.iter().filter(|event| event.thread_id.is_some()).count()
34
events
35
.iter()
36
.filter(|event| event.thread_id.is_some())
37
.count()
35
38
);
36
39
println!(
37
40
"# with organizer name: {}",
38
events.iter().filter(|event| event.organizer_name.is_some()).count()
41
events
42
.iter()
43
.filter(|event| event.organizer_name.is_some())
44
.count()
39
45
);
40
46
println!(
41
47
"# not responded: {}, cancelled: {}, all day: {}",
42
events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
48
events
49
.iter()
50
.filter(|event| event.response == chatsvc::ResponseType::NotResponded)
51
.count(),
43
52
events.iter().filter(|event| event.cancelled).count(),
44
53
events.iter().filter(|event| event.all_day).count()
45
54
);
@@ -31,15 +31,24 @@ async fn main() {31
);31
);32
println!(32
println!(33
"# with thread: {}",33
"# with thread: {}",34
events.iter().filter(|event| event.thread_id.is_some()).count()34
events35
.iter()36
.filter(|event| event.thread_id.is_some())37
.count()35
);38
);36
println!(39
println!(37
"# with organizer name: {}",40
"# with organizer name: {}",38
events.iter().filter(|event| event.organizer_name.is_some()).count()41
events42
.iter()43
.filter(|event| event.organizer_name.is_some())44
.count()39
);45
);40
println!(46
println!(41
"# not responded: {}, cancelled: {}, all day: {}",47
"# not responded: {}, cancelled: {}, all day: {}",42
events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),48
events49
.iter()50
.filter(|event| event.response == chatsvc::ResponseType::NotResponded)51
.count(),43
events.iter().filter(|event| event.cancelled).count(),52
events.iter().filter(|event| event.cancelled).count(),44
events.iter().filter(|event| event.all_day).count()53
events.iter().filter(|event| event.all_day).count()45
);54
);@@ -1,6 +1,8 @@
1
1
use std::time::Duration;
2
2
3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3
use chatsvc::{
4
ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,
5
};
4
6
use session::{DEFAULT_ENDPOINT, Session};
5
7
6
8
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);
8
10
9
11
#[tokio::main]
10
12
async fn main() {
11
let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
13
let user_id = std::env::args()
14
.nth(1)
15
.expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12
16
let inactive_wait = std::env::args()
13
17
.nth(2)
14
18
.and_then(|value| value.parse().ok())
@@ -21,11 +25,20 @@ async fn main() {
21
25
initially_active: true,
22
26
..RealtimeConfig::default()
23
27
};
24
let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
28
let mut realtime = Realtime::start_with(&session, config)
29
.await
30
.expect("realtime start");
25
31
let endpoint_id = wait_for_endpoint(&mut realtime).await;
26
32
println!("# trouter connected");
27
33
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
34
println!(
35
"register: {}",
36
outcome(
37
presence
38
.register_endpoint(&endpoint_id, ActivityReporting::Transport)
39
.await
40
)
41
);
29
42
realtime.resend_activity();
30
43
println!("# sent active");
31
44
tokio::time::sleep(SETTLE).await;
@@ -36,8 +49,14 @@ async fn main() {
36
49
tokio::time::sleep(inactive_wait).await;
37
50
print_own_presence(&presence, &user_id).await;
38
51
39
println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40
println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
52
println!(
53
"http report inactive: {}",
54
outcome(presence.report_activity(&endpoint_id, false).await)
55
);
56
println!(
57
"unregister: {}",
58
outcome(presence.unregister_endpoint(&endpoint_id).await)
59
);
41
60
realtime.stop().await;
42
61
println!("# stopped");
43
62
}
@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
49
68
while let Some(event) = realtime.recv().await {
50
69
match event {
51
70
RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
71
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {
72
connected = true
73
}
53
74
_ => {}
54
75
}
55
76
if connected && let Some(endpoint_id) = endpoint_id.take() {
@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
58
79
}
59
80
panic!("realtime closed before connecting");
60
81
};
61
tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
82
tokio::time::timeout(CONNECT_TIMEOUT, wait)
83
.await
84
.expect("trouter did not connect")
62
85
}
63
86
64
87
async fn print_own_presence(presence: &PresenceService, user_id: &str) {
@@ -1,6 +1,8 @@1
use std::time::Duration;1
use std::time::Duration;2
2
3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};3
use chatsvc::{4
ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,5
};4
use session::{DEFAULT_ENDPOINT, Session};6
use session::{DEFAULT_ENDPOINT, Session};5
7
6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);8
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);8
10
9
#[tokio::main]11
#[tokio::main]10
async fn main() {12
async fn main() {11
let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");13
let user_id = std::env::args()14
.nth(1)15
.expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");12
let inactive_wait = std::env::args()16
let inactive_wait = std::env::args()13
.nth(2)17
.nth(2)14
.and_then(|value| value.parse().ok())18
.and_then(|value| value.parse().ok())@@ -21,11 +25,20 @@ async fn main() {21
initially_active: true,25
initially_active: true,22
..RealtimeConfig::default()26
..RealtimeConfig::default()23
};27
};24
let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");28
let mut realtime = Realtime::start_with(&session, config)29
.await30
.expect("realtime start");25
let endpoint_id = wait_for_endpoint(&mut realtime).await;31
let endpoint_id = wait_for_endpoint(&mut realtime).await;26
println!("# trouter connected");32
println!("# trouter connected");27
33
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));34
println!(35
"register: {}",36
outcome(37
presence38
.register_endpoint(&endpoint_id, ActivityReporting::Transport)39
.await40
)41
);29
realtime.resend_activity();42
realtime.resend_activity();30
println!("# sent active");43
println!("# sent active");31
tokio::time::sleep(SETTLE).await;44
tokio::time::sleep(SETTLE).await;@@ -36,8 +49,14 @@ async fn main() {36
tokio::time::sleep(inactive_wait).await;49
tokio::time::sleep(inactive_wait).await;37
print_own_presence(&presence, &user_id).await;50
print_own_presence(&presence, &user_id).await;38
51
39
println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));52
println!(40
println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));53
"http report inactive: {}",54
outcome(presence.report_activity(&endpoint_id, false).await)55
);56
println!(57
"unregister: {}",58
outcome(presence.unregister_endpoint(&endpoint_id).await)59
);41
realtime.stop().await;60
realtime.stop().await;42
println!("# stopped");61
println!("# stopped");43
}62
}@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {49
while let Some(event) = realtime.recv().await {68
while let Some(event) = realtime.recv().await {50
match event {69
match event {51
RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),70
RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),52
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,71
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {72
connected = true73
}53
_ => {}74
_ => {}54
}75
}55
if connected && let Some(endpoint_id) = endpoint_id.take() {76
if connected && let Some(endpoint_id) = endpoint_id.take() {@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {58
}79
}59
panic!("realtime closed before connecting");80
panic!("realtime closed before connecting");60
};81
};61
tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")82
tokio::time::timeout(CONNECT_TIMEOUT, wait)83
.await84
.expect("trouter did not connect")62
}85
}63
86
64
async fn print_own_presence(presence: &PresenceService, user_id: &str) {87
async fn print_own_presence(presence: &PresenceService, user_id: &str) {@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {
19
19
_ => "*",
20
20
})
21
21
.collect();
22
let host_kind = without_scheme
23
.split('/')
24
.next()
25
.map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
22
let host_kind = without_scheme.split('/').next().map_or("?", |host| {
23
if host.ends_with("-my.sharepoint.com") {
24
"<tenant>-my.sharepoint.com"
25
} else {
26
"other"
27
}
28
});
26
29
format!("{host_kind}/{}", shape.join("/"))
27
30
}
28
31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {
30
33
match error {
31
34
TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32
35
"HTTP {status} code {}",
33
body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
36
body.pointer("/error/code")
37
.and_then(serde_json::Value::as_str)
38
.unwrap_or("-")
39
),
40
TranscriptError::Request(other) => format!(
41
"request {}",
42
other.to_string().chars().take(60).collect::<String>()
34
43
),
35
TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36
44
other => format!("{other:?}"),
37
45
}
38
46
}
39
47
40
48
fn magic(bytes: &[u8]) -> String {
41
let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
49
let start = bytes
50
.strip_prefix(b"\xEF\xBB\xBF".as_slice())
51
.unwrap_or(bytes);
42
52
if start.starts_with(b"WEBVTT") {
43
53
format!("WEBVTT (bom {})", start.len() != bytes.len())
44
54
} else if bytes.starts_with(b"PK\x03\x04") {
@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {
51
61
#[tokio::main]
52
62
async fn main() {
53
63
let mut arguments = std::env::args().skip(1);
54
let Some(thread_file) = arguments.next() else { usage() };
64
let Some(thread_file) = arguments.next() else {
65
usage()
66
};
55
67
let delete = arguments.any(|argument| argument == "--delete");
56
let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
68
let thread_id = std::fs::read_to_string(&thread_file)
69
.expect("thread file")
70
.trim()
71
.to_owned();
57
72
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58
73
let session = Session::connect(&endpoint).await.expect("browser");
59
74
let recap = Recap::new(&session);
@@ -76,7 +91,9 @@ async fn main() {
76
91
host_and_path_shape(&occurrence.recording_url)
77
92
);
78
93
}
79
let Some(occurrence) = occurrences.first() else { return };
94
let Some(occurrence) = occurrences.first() else {
95
return;
96
};
80
97
81
98
let details = match recap.details(occurrence).await {
82
99
Ok(details) => details,
@@ -89,7 +106,9 @@ async fn main() {
89
106
"# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90
107
details.audio_only,
91
108
details.duration_seconds,
92
details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
109
details
110
.expires_at
111
.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93
112
details.transcript_id.is_some(),
94
113
host_and_path_shape(&details.item_url)
95
114
);
@@ -99,8 +118,14 @@ async fn main() {
99
118
"# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100
119
turns.len(),
101
120
turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102
turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
103
turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
121
turns
122
.iter()
123
.map(|turn| turn.text.split_whitespace().count())
124
.sum::<usize>(),
125
turns
126
.iter()
127
.map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128
.collect::<Vec<_>>()
104
129
),
105
130
Err(error) => println!("# transcript: error {}", error_shape(&error)),
106
131
}
@@ -123,7 +148,11 @@ async fn main() {
123
148
text.contains("word/document.xml")
124
149
);
125
150
}
126
Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
151
Err(error) => println!(
152
"# transcript file {}: error {}",
153
format.query(),
154
error_shape(&error)
155
),
127
156
}
128
157
}
129
158
let _ = std::fs::remove_dir_all(&directory);
@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {19
_ => "*",19
_ => "*",20
})20
})21
.collect();21
.collect();22
let host_kind = without_scheme22
let host_kind = without_scheme.split('/').next().map_or("?", |host| {23
.split('/')23
if host.ends_with("-my.sharepoint.com") {24
.next()24
"<tenant>-my.sharepoint.com"25
.map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });25
} else {26
"other"27
}28
});26
format!("{host_kind}/{}", shape.join("/"))29
format!("{host_kind}/{}", shape.join("/"))27
}30
}28
31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {30
match error {33
match error {31
TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(34
TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(32
"HTTP {status} code {}",35
"HTTP {status} code {}",33
body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")36
body.pointer("/error/code")37
.and_then(serde_json::Value::as_str)38
.unwrap_or("-")39
),40
TranscriptError::Request(other) => format!(41
"request {}",42
other.to_string().chars().take(60).collect::<String>()34
),43
),35
TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),36
other => format!("{other:?}"),44
other => format!("{other:?}"),37
}45
}38
}46
}39
47
40
fn magic(bytes: &[u8]) -> String {48
fn magic(bytes: &[u8]) -> String {41
let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);49
let start = bytes50
.strip_prefix(b"\xEF\xBB\xBF".as_slice())51
.unwrap_or(bytes);42
if start.starts_with(b"WEBVTT") {52
if start.starts_with(b"WEBVTT") {43
format!("WEBVTT (bom {})", start.len() != bytes.len())53
format!("WEBVTT (bom {})", start.len() != bytes.len())44
} else if bytes.starts_with(b"PK\x03\x04") {54
} else if bytes.starts_with(b"PK\x03\x04") {@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {51
#[tokio::main]61
#[tokio::main]52
async fn main() {62
async fn main() {53
let mut arguments = std::env::args().skip(1);63
let mut arguments = std::env::args().skip(1);54
let Some(thread_file) = arguments.next() else { usage() };64
let Some(thread_file) = arguments.next() else {65
usage()66
};55
let delete = arguments.any(|argument| argument == "--delete");67
let delete = arguments.any(|argument| argument == "--delete");56
let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();68
let thread_id = std::fs::read_to_string(&thread_file)69
.expect("thread file")70
.trim()71
.to_owned();57
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());72
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());58
let session = Session::connect(&endpoint).await.expect("browser");73
let session = Session::connect(&endpoint).await.expect("browser");59
let recap = Recap::new(&session);74
let recap = Recap::new(&session);@@ -76,7 +91,9 @@ async fn main() {76
host_and_path_shape(&occurrence.recording_url)91
host_and_path_shape(&occurrence.recording_url)77
);92
);78
}93
}79
let Some(occurrence) = occurrences.first() else { return };94
let Some(occurrence) = occurrences.first() else {95
return;96
};80
97
81
let details = match recap.details(occurrence).await {98
let details = match recap.details(occurrence).await {82
Ok(details) => details,99
Ok(details) => details,@@ -89,7 +106,9 @@ async fn main() {89
"# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",106
"# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",90
details.audio_only,107
details.audio_only,91
details.duration_seconds,108
details.duration_seconds,92
details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),109
details110
.expires_at111
.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),93
details.transcript_id.is_some(),112
details.transcript_id.is_some(),94
host_and_path_shape(&details.item_url)113
host_and_path_shape(&details.item_url)95
);114
);@@ -99,8 +118,14 @@ async fn main() {99
"# transcript: {} turns, {} with speaker, {} words, spans {:?}",118
"# transcript: {} turns, {} with speaker, {} words, spans {:?}",100
turns.len(),119
turns.len(),101
turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),120
turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),102
turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),121
turns103
turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()122
.iter()123
.map(|turn| turn.text.split_whitespace().count())124
.sum::<usize>(),125
turns126
.iter()127
.map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))128
.collect::<Vec<_>>()104
),129
),105
Err(error) => println!("# transcript: error {}", error_shape(&error)),130
Err(error) => println!("# transcript: error {}", error_shape(&error)),106
}131
}@@ -123,7 +148,11 @@ async fn main() {123
text.contains("word/document.xml")148
text.contains("word/document.xml")124
);149
);125
}150
}126
Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),151
Err(error) => println!(152
"# transcript file {}: error {}",153
format.query(),154
error_shape(&error)155
),127
}156
}128
}157
}129
let _ = std::fs::remove_dir_all(&directory);158
let _ = std::fs::remove_dir_all(&directory);@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};
4
4
#[tokio::main]
5
5
async fn main() {
6
6
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7
let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());
7
let needle = std::env::args()
8
.nth(1)
9
.unwrap_or_else(|| "Lunch".to_owned());
8
10
let session = Session::connect(&endpoint).await.expect("browser");
9
11
let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
10
let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");
11
let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);
12
let scope = Scope::new(
13
"https://chatsvcagg.teams.microsoft.com",
14
"user_impersonation",
15
);
16
let answer = session
17
.batch(&[Request::get(url)], &scope)
18
.await
19
.expect("csa")
20
.remove(0);
12
21
println!("# status {}", answer.status);
13
for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {
14
for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {
15
let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();
22
for team in answer
23
.body
24
.get("teams")
25
.and_then(Value::as_array)
26
.into_iter()
27
.flatten()
28
{
29
for channel in team
30
.get("channels")
31
.and_then(Value::as_array)
32
.into_iter()
33
.flatten()
34
{
35
let name = channel
36
.get("displayName")
37
.and_then(Value::as_str)
38
.unwrap_or_default();
16
39
if !name.contains(&needle) {
17
40
continue;
18
41
}
19
42
println!("channel {name}");
20
for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {
43
for tab in channel
44
.get("tabs")
45
.and_then(Value::as_array)
46
.into_iter()
47
.flatten()
48
{
21
49
let mut shown = tab.clone();
22
50
if let Some(object) = shown.as_object_mut() {
23
51
object.retain(|key, _| key != "replyChainId");
24
52
}
25
println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());
53
println!(
54
" {}",
55
serde_json::to_string(&shown)
56
.unwrap_or_default()
57
.chars()
58
.take(1500)
59
.collect::<String>()
60
);
26
61
}
27
62
}
28
63
}
@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};4
#[tokio::main]4
#[tokio::main]5
async fn main() {5
async fn main() {6
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());6
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());7
let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());7
let needle = std::env::args()8
.nth(1)9
.unwrap_or_else(|| "Lunch".to_owned());8
let session = Session::connect(&endpoint).await.expect("browser");10
let session = Session::connect(&endpoint).await.expect("browser");9
let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";11
let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";10
let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");12
let scope = Scope::new(11
let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);13
"https://chatsvcagg.teams.microsoft.com",14
"user_impersonation",15
);16
let answer = session17
.batch(&[Request::get(url)], &scope)18
.await19
.expect("csa")20
.remove(0);12
println!("# status {}", answer.status);21
println!("# status {}", answer.status);13
for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {22
for team in answer14
for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {23
.body15
let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();24
.get("teams")25
.and_then(Value::as_array)26
.into_iter()27
.flatten()28
{29
for channel in team30
.get("channels")31
.and_then(Value::as_array)32
.into_iter()33
.flatten()34
{35
let name = channel36
.get("displayName")37
.and_then(Value::as_str)38
.unwrap_or_default();16
if !name.contains(&needle) {39
if !name.contains(&needle) {17
continue;40
continue;18
}41
}19
println!("channel {name}");42
println!("channel {name}");20
for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {43
for tab in channel44
.get("tabs")45
.and_then(Value::as_array)46
.into_iter()47
.flatten()48
{21
let mut shown = tab.clone();49
let mut shown = tab.clone();22
if let Some(object) = shown.as_object_mut() {50
if let Some(object) = shown.as_object_mut() {23
object.retain(|key, _| key != "replyChainId");51
object.retain(|key, _| key != "replyChainId");24
}52
}25
println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());53
println!(54
" {}",55
serde_json::to_string(&shown)56
.unwrap_or_default()57
.chars()58
.take(1500)59
.collect::<String>()60
);26
}61
}27
}62
}28
}63
}@@ -8,14 +8,31 @@ async fn main() {
8
8
let pins = Pins::new(&session);
9
9
match pins.folders().await {
10
10
Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
11
Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),
11
Err(error) => println!(
12
"# folders failed: {}",
13
error.to_string().chars().take(160).collect::<String>()
14
),
12
15
}
13
16
match pins.pinned_channels().await {
14
17
Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
15
Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),
18
Err(error) => println!(
19
"# pinned channels failed: {}",
20
error.to_string().chars().take(160).collect::<String>()
21
),
16
22
}
17
23
match pins.team_layout().await {
18
Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),
19
Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),
24
Ok(layout) => println!(
25
"# team layout ok: {} teams, {} tabs",
26
layout.len(),
27
layout
28
.iter()
29
.flat_map(|team| team.channels.iter())
30
.map(|channel| channel.tabs.len())
31
.sum::<usize>()
32
),
33
Err(error) => println!(
34
"# team layout failed: {}",
35
error.to_string().chars().take(160).collect::<String>()
36
),
20
37
}
21
38
}
@@ -8,14 +8,31 @@ async fn main() {8
let pins = Pins::new(&session);8
let pins = Pins::new(&session);9
match pins.folders().await {9
match pins.folders().await {10
Ok(folders) => println!("# folders ok: {}", folders.folders.len()),10
Ok(folders) => println!("# folders ok: {}", folders.folders.len()),11
Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),11
Err(error) => println!(12
"# folders failed: {}",13
error.to_string().chars().take(160).collect::<String>()14
),12
}15
}13
match pins.pinned_channels().await {16
match pins.pinned_channels().await {14
Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),17
Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),15
Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),18
Err(error) => println!(19
"# pinned channels failed: {}",20
error.to_string().chars().take(160).collect::<String>()21
),16
}22
}17
match pins.team_layout().await {23
match pins.team_layout().await {18
Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),24
Ok(layout) => println!(19
Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),25
"# team layout ok: {} teams, {} tabs",26
layout.len(),27
layout28
.iter()29
.flat_map(|team| team.channels.iter())30
.map(|channel| channel.tabs.len())31
.sum::<usize>()32
),33
Err(error) => println!(34
"# team layout failed: {}",35
error.to_string().chars().take(160).collect::<String>()36
),20
}37
}21
}38
}@@ -304,7 +304,14 @@ mod tests {
304
304
let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
305
305
assert_eq!(
306
306
hidden,
307
[Some(true), Some(false), Some(true), None, Some(true), Some(true)]
307
[
308
Some(true),
309
Some(false),
310
Some(true),
311
None,
312
Some(true),
313
Some(true)
314
]
308
315
);
309
316
}
310
317
@@ -304,7 +304,14 @@ mod tests {304
let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();304
let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();305
assert_eq!(305
assert_eq!(306
hidden,306
hidden,307
[Some(true), Some(false), Some(true), None, Some(true), Some(true)]307
[308
Some(true),309
Some(false),310
Some(true),311
None,312
Some(true),313
Some(true)314
]308
);315
);309
}316
}310
317
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
57
57
.into_iter()
58
58
.flatten()
59
59
.filter_map(|message| {
60
let message_id = match message.get("id")? {
61
Value::String(text) if !text.is_empty() => text.clone(),
62
Value::Number(number) => number.to_string(),
63
_ => return None,
64
};
60
let message_id = crate::json_id::id_text(message.get("id")?)?;
65
61
Some(MessageEmotions {
66
62
message_id,
67
63
reactions: reactions(message.pointer("/properties/emotions")),
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {57
.into_iter()57
.into_iter()58
.flatten()58
.flatten()59
.filter_map(|message| {59
.filter_map(|message| {60
let message_id = match message.get("id")? {60
let message_id = crate::json_id::id_text(message.get("id")?)?;61
Value::String(text) if !text.is_empty() => text.clone(),62
Value::Number(number) => number.to_string(),63
_ => return None,64
};65
Some(MessageEmotions {61
Some(MessageEmotions {66
message_id,62
message_id,67
reactions: reactions(message.pointer("/properties/emotions")),63
reactions: reactions(message.pointer("/properties/emotions")),@@ -0,0 +1,42 @@
1
use serde_json::{Number, Value};
2
3
pub(crate) fn id_text(value: &Value) -> Option<String> {
4
match value {
5
Value::String(text) if !text.is_empty() => Some(text.clone()),
6
Value::Number(number) => Some(integer_text(number)),
7
_ => None,
8
}
9
}
10
11
fn integer_text(number: &Number) -> String {
12
match number.as_f64() {
13
Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {
14
format!("{float:.0}")
15
}
16
_ => number.to_string(),
17
}
18
}
19
20
#[cfg(test)]
21
mod tests {
22
use serde_json::json;
23
24
use super::*;
25
26
#[test]
27
fn float_ids_read_as_integers() {
28
assert_eq!(
29
id_text(&json!(1783430602049.0)).as_deref(),
30
Some("1783430602049")
31
);
32
assert_eq!(
33
id_text(&json!(1783430602049u64)).as_deref(),
34
Some("1783430602049")
35
);
36
assert_eq!(
37
id_text(&json!("1783430602049")).as_deref(),
38
Some("1783430602049")
39
);
40
assert_eq!(id_text(&json!("")), None);
41
}
42
}
@@ -0,0 +1,42 @@1
use serde_json::{Number, Value};2
3
pub(crate) fn id_text(value: &Value) -> Option<String> {4
match value {5
Value::String(text) if !text.is_empty() => Some(text.clone()),6
Value::Number(number) => Some(integer_text(number)),7
_ => None,8
}9
}10
11
fn integer_text(number: &Number) -> String {12
match number.as_f64() {13
Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {14
format!("{float:.0}")15
}16
_ => number.to_string(),17
}18
}19
20
#[cfg(test)]21
mod tests {22
use serde_json::json;23
24
use super::*;25
26
#[test]27
fn float_ids_read_as_integers() {28
assert_eq!(29
id_text(&json!(1783430602049.0)).as_deref(),30
Some("1783430602049")31
);32
assert_eq!(33
id_text(&json!(1783430602049u64)).as_deref(),34
Some("1783430602049")35
);36
assert_eq!(37
id_text(&json!("1783430602049")).as_deref(),38
Some("1783430602049")39
);40
assert_eq!(id_text(&json!("")), None);41
}42
}@@ -8,6 +8,7 @@ pub mod emotions;
8
8
mod error;
9
9
pub mod forward;
10
10
pub mod gifs;
11
mod json_id;
11
12
pub mod language_settings;
12
13
pub mod links;
13
14
mod mask;
@@ -16,10 +17,10 @@ pub mod pins;
16
17
pub mod presence;
17
18
pub mod reactions;
18
19
pub mod read_horizon;
19
pub mod recap;
20
20
pub mod realtime;
21
pub mod recording_policy;
21
pub mod recap;
22
22
pub mod receipts;
23
pub mod recording_policy;
23
24
pub mod saved;
24
25
pub mod settings;
25
26
pub mod sound_settings;
@@ -29,8 +30,8 @@ pub mod translate;
29
30
pub mod window;
30
31
31
32
pub use calendar::{
32
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,
33
meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
33
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
34
ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34
35
};
35
36
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36
37
pub use cards::{
@@ -38,8 +39,8 @@ pub use cards::{
38
39
};
39
40
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40
41
pub use conversations::{ConversationState, Conversations};
41
pub use read_horizon::ReadHorizon;
42
42
pub use drafts::{ScheduledDraft, ScheduledDrafts};
43
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
43
44
pub use error::{Error, Result};
44
45
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45
46
pub use gifs::{Gif, Gifs};
@@ -47,7 +48,6 @@ pub use language_settings::{
47
48
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48
49
parse_language_settings, target_patch,
49
50
};
50
pub use recording_policy::{RecordingPolicy, parse_recording_policy};
51
51
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
52
52
pub use mask::mask_conversation_id;
53
53
pub use messages::{ConversationRef, Messages};
@@ -56,23 +56,27 @@ pub use pins::{
56
56
PinnedMessage, Pins, TeamLayout,
57
57
};
58
58
pub use presence::{
59
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
60
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
59
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
60
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
61
61
};
62
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
63
pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
62
pub use reactions::{
63
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
64
reaction_key, reaction_keys,
65
};
66
pub use read_horizon::ReadHorizon;
64
67
pub use realtime::{
65
68
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
66
69
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
67
70
TypingEvent,
68
71
};
69
pub use receipts::{MemberHorizon, Receipts};
70
pub use saved::SavedMessage;
71
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
72
72
pub use recap::{
73
73
Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
74
74
days_until_expiry,
75
75
};
76
pub use receipts::{MemberHorizon, Receipts};
77
pub use recording_policy::{RecordingPolicy, parse_recording_policy};
78
pub use saved::SavedMessage;
79
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
76
80
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
77
81
pub use translate::{
78
82
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
@@ -8,6 +8,7 @@ pub mod emotions;8
mod error;8
mod error;9
pub mod forward;9
pub mod forward;10
pub mod gifs;10
pub mod gifs;11
mod json_id;11
pub mod language_settings;12
pub mod language_settings;12
pub mod links;13
pub mod links;13
mod mask;14
mod mask;@@ -16,10 +17,10 @@ pub mod pins;16
pub mod presence;17
pub mod presence;17
pub mod reactions;18
pub mod reactions;18
pub mod read_horizon;19
pub mod read_horizon;19
pub mod recap;20
pub mod realtime;20
pub mod realtime;21
pub mod recording_policy;21
pub mod recap;22
pub mod receipts;22
pub mod receipts;23
pub mod recording_policy;23
pub mod saved;24
pub mod saved;24
pub mod settings;25
pub mod settings;25
pub mod sound_settings;26
pub mod sound_settings;@@ -29,8 +30,8 @@ pub mod translate;29
pub mod window;30
pub mod window;30
31
31
pub use calendar::{32
pub use calendar::{32
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,33
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,33
meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,34
ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,34
};35
};35
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};36
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};36
pub use cards::{37
pub use cards::{@@ -38,8 +39,8 @@ pub use cards::{38
};39
};39
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};40
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};40
pub use conversations::{ConversationState, Conversations};41
pub use conversations::{ConversationState, Conversations};41
pub use read_horizon::ReadHorizon;42
pub use drafts::{ScheduledDraft, ScheduledDrafts};42
pub use drafts::{ScheduledDraft, ScheduledDrafts};43
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};43
pub use error::{Error, Result};44
pub use error::{Error, Result};44
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};45
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};45
pub use gifs::{Gif, Gifs};46
pub use gifs::{Gif, Gifs};@@ -47,7 +48,6 @@ pub use language_settings::{47
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,48
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,48
parse_language_settings, target_patch,49
parse_language_settings, target_patch,49
};50
};50
pub use recording_policy::{RecordingPolicy, parse_recording_policy};51
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};51
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};52
pub use mask::mask_conversation_id;52
pub use mask::mask_conversation_id;53
pub use messages::{ConversationRef, Messages};53
pub use messages::{ConversationRef, Messages};@@ -56,23 +56,27 @@ pub use pins::{56
PinnedMessage, Pins, TeamLayout,56
PinnedMessage, Pins, TeamLayout,57
};57
};58
pub use presence::{58
pub use presence::{59
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,59
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,60
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,60
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,61
};61
};62
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};62
pub use reactions::{63
pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};63
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,64
reaction_key, reaction_keys,65
};66
pub use read_horizon::ReadHorizon;64
pub use realtime::{67
pub use realtime::{65
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,68
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,66
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,69
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,67
TypingEvent,70
TypingEvent,68
};71
};69
pub use receipts::{MemberHorizon, Receipts};70
pub use saved::SavedMessage;71
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};72
pub use recap::{72
pub use recap::{73
Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,73
Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,74
days_until_expiry,74
days_until_expiry,75
};75
};76
pub use receipts::{MemberHorizon, Receipts};77
pub use recording_policy::{RecordingPolicy, parse_recording_policy};78
pub use saved::SavedMessage;79
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};76
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};80
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};77
pub use translate::{81
pub use translate::{78
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,82
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {
24
24
number
25
25
.as_f64()
26
26
.filter(|float| float.is_finite() && float.fract() == 0.0)
27
.filter(|float| {
28
*float >= i64::MIN as f64 && *float < i64::MAX as f64
29
})
27
.filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)
30
28
.map(|float| float as i64)
31
29
}),
32
30
Value::String(text) => text.trim().parse::<i64>().ok(),
@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {24
number24
number25
.as_f64()25
.as_f64()26
.filter(|float| float.is_finite() && float.fract() == 0.0)26
.filter(|float| float.is_finite() && float.fract() == 0.0)27
.filter(|float| {27
.filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)28
*float >= i64::MIN as f64 && *float < i64::MAX as f6429
})30
.map(|float| float as i64)28
.map(|float| float as i64)31
}),29
}),32
Value::String(text) => text.trim().parse::<i64>().ok(),30
Value::String(text) => text.trim().parse::<i64>().ok(),@@ -297,7 +297,11 @@ mod tests {
297
297
.collect();
298
298
assert_eq!(
299
299
names,
300
["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]
300
[
301
"Lunch Order Board \u{1F37D}\u{FE0F}",
302
"100% done",
303
"Bad%FFbytes"
304
]
301
305
);
302
306
}
303
307
@@ -297,7 +297,11 @@ mod tests {297
.collect();297
.collect();298
assert_eq!(298
assert_eq!(299
names,299
names,300
["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]300
[301
"Lunch Order Board \u{1F37D}\u{FE0F}",302
"100% done",303
"Bad%FFbytes"304
]301
);305
);302
}306
}303
307
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {
147
147
self.send(request, &url).await.map(drop)
148
148
}
149
149
150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
150
pub async fn register_endpoint(
151
&self,
152
endpoint_id: &str,
153
reporting: ActivityReporting,
154
) -> Result<()> {
151
155
let url = format!("{BASE_URL}/me/endpoints/");
152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
156
let mut request =
157
Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153
158
request.headers = endpoint_headers(endpoint_id);
154
159
self.send(request, &url).await.map(drop)
155
160
}
@@ -502,7 +507,10 @@ mod tests {
502
507
#[tokio::test]
503
508
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504
509
let service = service(200, Value::Null);
505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
510
service
511
.register_endpoint("epid-1", ActivityReporting::Transport)
512
.await
513
.unwrap();
506
514
let (request, scope) = only_request(&service);
507
515
assert_eq!(request.method, Method::Put);
508
516
assert_eq!(
@@ -533,7 +541,10 @@ mod tests {
533
541
#[tokio::test]
534
542
async fn register_endpoint_can_switch_to_direct_reporting() {
535
543
let service = service(200, Value::Null);
536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
544
service
545
.register_endpoint("epid-1", ActivityReporting::Direct)
546
.await
547
.unwrap();
537
548
let (request, _) = only_request(&service);
538
549
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539
550
}
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {147
self.send(request, &url).await.map(drop)147
self.send(request, &url).await.map(drop)148
}148
}149
149
150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {150
pub async fn register_endpoint(151
&self,152
endpoint_id: &str,153
reporting: ActivityReporting,154
) -> Result<()> {151
let url = format!("{BASE_URL}/me/endpoints/");155
let url = format!("{BASE_URL}/me/endpoints/");152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));156
let mut request =157
Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));153
request.headers = endpoint_headers(endpoint_id);158
request.headers = endpoint_headers(endpoint_id);154
self.send(request, &url).await.map(drop)159
self.send(request, &url).await.map(drop)155
}160
}@@ -502,7 +507,10 @@ mod tests {502
#[tokio::test]507
#[tokio::test]503
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {508
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {504
let service = service(200, Value::Null);509
let service = service(200, Value::Null);505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();510
service511
.register_endpoint("epid-1", ActivityReporting::Transport)512
.await513
.unwrap();506
let (request, scope) = only_request(&service);514
let (request, scope) = only_request(&service);507
assert_eq!(request.method, Method::Put);515
assert_eq!(request.method, Method::Put);508
assert_eq!(516
assert_eq!(@@ -533,7 +541,10 @@ mod tests {533
#[tokio::test]541
#[tokio::test]534
async fn register_endpoint_can_switch_to_direct_reporting() {542
async fn register_endpoint_can_switch_to_direct_reporting() {535
let service = service(200, Value::Null);543
let service = service(200, Value::Null);536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();544
service545
.register_endpoint("epid-1", ActivityReporting::Direct)546
.await547
.unwrap();537
let (request, _) = only_request(&service);548
let (request, _) = only_request(&service);538
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");549
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");539
}550
}@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
180
180
activity: if entry.out_of_office {
181
181
Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
182
182
} else {
183
entry.activity.map(bounded).filter(|value| !value.is_empty())
183
entry
184
.activity
185
.map(bounded)
186
.filter(|value| !value.is_empty())
184
187
},
185
188
})
186
189
})
@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {180
activity: if entry.out_of_office {180
activity: if entry.out_of_office {181
Some(OUT_OF_OFFICE_ACTIVITY.to_owned())181
Some(OUT_OF_OFFICE_ACTIVITY.to_owned())182
} else {182
} else {183
entry.activity.map(bounded).filter(|value| !value.is_empty())183
entry184
.activity185
.map(bounded)186
.filter(|value| !value.is_empty())184
},187
},185
})188
})186
})189
})@@ -13,11 +13,11 @@ use session::Session;
13
13
use tokio::sync::{Notify, mpsc, oneshot, watch};
14
14
use tokio::task::JoinHandle;
15
15
16
pub use callback::{CallbackReplier, TrouterCallback};
16
17
pub use event::{
17
18
EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18
19
TrouterEndpoint, TypingEvent, decode_payload,
19
20
};
20
pub use callback::{CallbackReplier, TrouterCallback};
21
21
pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22
22
23
23
use crate::error::Result;
@@ -13,11 +13,11 @@ use session::Session;13
use tokio::sync::{Notify, mpsc, oneshot, watch};13
use tokio::sync::{Notify, mpsc, oneshot, watch};14
use tokio::task::JoinHandle;14
use tokio::task::JoinHandle;15
15
16
pub use callback::{CallbackReplier, TrouterCallback};16
pub use event::{17
pub use event::{17
EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,18
EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,18
TrouterEndpoint, TypingEvent, decode_payload,19
TrouterEndpoint, TypingEvent, decode_payload,19
};20
};20
pub use callback::{CallbackReplier, TrouterCallback};21
pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};21
pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};22
22
23
use crate::error::Result;23
use crate::error::Result;@@ -34,9 +34,13 @@ impl PageScript {
34
34
let mut worker_source = WORKER_TEMPLATE
35
35
.replace("ed(DEFAULT_GLOBAL_NAME), "ed(&names.global))
36
36
.replace("ed(DEFAULT_BINDING_NAME), "ed(&names.binding))
37
.replace("ed(DEFAULT_EPID_KEY), "ed(&names.endpoint_storage_key));
37
.replace(
38
"ed(DEFAULT_EPID_KEY),
39
"ed(&names.endpoint_storage_key),
40
);
38
41
if config.forward_callbacks {
39
worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
42
worker_source =
43
worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
40
44
}
41
45
if config.ringable {
42
46
worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
@@ -90,7 +94,10 @@ pub(super) struct Attached {
90
94
stop_expression: String,
91
95
}
92
96
93
pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {
97
pub(super) async fn attach(
98
session: &Session,
99
script: &PageScript,
100
) -> crate::error::Result<Attached> {
94
101
let (control, events) = session.subscribe(App::Teams).await?;
95
102
control.enable_events().await?;
96
103
control.add_binding(&script.binding_name).await?;
@@ -378,11 +385,9 @@ mod tests {
378
385
fn ensure_body_embeds_the_worker_once_before_the_call() {
379
386
let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
380
387
assert!(ensure_body.starts_with("(() => {"));
381
assert!(
382
ensure_body
383
.trim_end()
384
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
385
);
388
assert!(ensure_body.trim_end().ends_with(
389
"window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
390
));
386
391
assert_eq!(ensure_body.matches("const VERSION").count(), 1);
387
392
}
388
393
@@ -399,9 +404,20 @@ mod tests {
399
404
};
400
405
let script = PageScript::new(&config);
401
406
assert!(!script.worker_source.contains("__chatsvc"));
402
assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));
403
assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));
404
assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");
407
assert!(
408
script
409
.worker_source
410
.contains("const GLOBAL_NAME = '__callingTrouter';")
411
);
412
assert!(
413
script
414
.worker_source
415
.contains("const FORWARD_CALLBACKS = true;")
416
);
417
assert_eq!(
418
script.stop_expression(),
419
"window.__callingTrouter ? window.__callingTrouter.stop() : null"
420
);
405
421
let default_script = PageScript::new(&RealtimeConfig::default());
406
422
assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
407
423
}
@@ -416,9 +432,21 @@ mod tests {
416
432
let quiet = PageScript::new(&RealtimeConfig::default());
417
433
assert!(quiet.worker_source.contains(REGISTRATION_OFF));
418
434
for script in [ringable, quiet] {
419
assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
420
assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
421
assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
435
assert!(
436
script
437
.worker_source
438
.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439
);
440
assert!(
441
script
442
.worker_source
443
.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444
);
445
assert!(
446
script
447
.worker_source
448
.contains("RINGABLE ? {productContext: ''} : {}")
449
);
422
450
}
423
451
}
424
452
}
@@ -34,9 +34,13 @@ impl PageScript {34
let mut worker_source = WORKER_TEMPLATE34
let mut worker_source = WORKER_TEMPLATE35
.replace("ed(DEFAULT_GLOBAL_NAME), "ed(&names.global))35
.replace("ed(DEFAULT_GLOBAL_NAME), "ed(&names.global))36
.replace("ed(DEFAULT_BINDING_NAME), "ed(&names.binding))36
.replace("ed(DEFAULT_BINDING_NAME), "ed(&names.binding))37
.replace("ed(DEFAULT_EPID_KEY), "ed(&names.endpoint_storage_key));37
.replace(38
"ed(DEFAULT_EPID_KEY),39
"ed(&names.endpoint_storage_key),40
);38
if config.forward_callbacks {41
if config.forward_callbacks {39
worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");42
worker_source =43
worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");40
}44
}41
if config.ringable {45
if config.ringable {42
worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");46
worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");@@ -90,7 +94,10 @@ pub(super) struct Attached {90
stop_expression: String,94
stop_expression: String,91
}95
}92
96
93
pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {97
pub(super) async fn attach(98
session: &Session,99
script: &PageScript,100
) -> crate::error::Result<Attached> {94
let (control, events) = session.subscribe(App::Teams).await?;101
let (control, events) = session.subscribe(App::Teams).await?;95
control.enable_events().await?;102
control.enable_events().await?;96
control.add_binding(&script.binding_name).await?;103
control.add_binding(&script.binding_name).await?;@@ -378,11 +385,9 @@ mod tests {378
fn ensure_body_embeds_the_worker_once_before_the_call() {385
fn ensure_body_embeds_the_worker_once_before_the_call() {379
let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();386
let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();380
assert!(ensure_body.starts_with("(() => {"));387
assert!(ensure_body.starts_with("(() => {"));381
assert!(388
assert!(ensure_body.trim_end().ends_with(382
ensure_body389
"window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"383
.trim_end()390
));384
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")385
);386
assert_eq!(ensure_body.matches("const VERSION").count(), 1);391
assert_eq!(ensure_body.matches("const VERSION").count(), 1);387
}392
}388
393
@@ -399,9 +404,20 @@ mod tests {399
};404
};400
let script = PageScript::new(&config);405
let script = PageScript::new(&config);401
assert!(!script.worker_source.contains("__chatsvc"));406
assert!(!script.worker_source.contains("__chatsvc"));402
assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));407
assert!(403
assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));408
script404
assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");409
.worker_source410
.contains("const GLOBAL_NAME = '__callingTrouter';")411
);412
assert!(413
script414
.worker_source415
.contains("const FORWARD_CALLBACKS = true;")416
);417
assert_eq!(418
script.stop_expression(),419
"window.__callingTrouter ? window.__callingTrouter.stop() : null"420
);405
let default_script = PageScript::new(&RealtimeConfig::default());421
let default_script = PageScript::new(&RealtimeConfig::default());406
assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));422
assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));407
}423
}@@ -416,9 +432,21 @@ mod tests {416
let quiet = PageScript::new(&RealtimeConfig::default());432
let quiet = PageScript::new(&RealtimeConfig::default());417
assert!(quiet.worker_source.contains(REGISTRATION_OFF));433
assert!(quiet.worker_source.contains(REGISTRATION_OFF));418
for script in [ringable, quiet] {434
for script in [ringable, quiet] {419
assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));435
assert!(420
assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));436
script421
assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));437
.worker_source438
.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")439
);440
assert!(441
script442
.worker_source443
.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")444
);445
assert!(446
script447
.worker_source448
.contains("RINGABLE ? {productContext: ''} : {}")449
);422
}450
}423
}451
}424
}452
}@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {
344
344
}
345
345
Err(error) => return Err(error),
346
346
};
347
let Some(report_id) = reports
348
.pointer("/value/0/id")
349
.and_then(Value::as_str)
350
else {
347
let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {
351
348
return Ok(Attendance::TurnedOff);
352
349
};
353
350
let report = self
@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {
386
383
.pointer("/parentReference/driveId")
387
384
.and_then(Value::as_str)?;
388
385
let item_id = item.get("id").and_then(Value::as_str)?;
389
Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))
386
Some(format!(
387
"{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388
))
390
389
}
391
390
392
391
fn decode_binary(body: &Value) -> Option<Vec<u8>> {
@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>
443
442
.into_iter()
444
443
.flatten()
445
444
.filter(|message| {
446
message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")
445
message.get("messagetype").and_then(Value::as_str)
446
== Some("RichText/Media_CallRecording")
447
447
})
448
448
.filter_map(|message| message.get("content").and_then(Value::as_str))
449
449
.filter(|content| content.contains(AUDIO_ONLY_MARKER))
@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {
505
505
}
506
506
507
507
pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508
let stamp = listing_json
509
.pointer("/fields/_ExpirationDate")?
510
.as_str()?;
508
let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
511
509
DateTime::parse_from_rfc3339(stamp)
512
510
.ok()
513
511
.map(|stamp| stamp.with_timezone(&Utc))
@@ -589,10 +587,7 @@ mod tests {
589
587
use super::*;
590
588
591
589
fn fixture(name: &str) -> Value {
592
let path = format!(
593
"{}/tests/fixtures/recap/{name}",
594
env!("CARGO_MANIFEST_DIR")
595
);
590
let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
596
591
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
597
592
}
598
593
@@ -602,7 +597,10 @@ mod tests {
602
597
assert_eq!(occurrences.len(), 2);
603
598
assert_eq!(occurrences[0].message_id, "2002");
604
599
assert_eq!(occurrences[0].duration_seconds, Some(1832));
605
assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));
600
assert_eq!(
601
occurrences[0].organizer_id.as_deref(),
602
Some("user-organizer")
603
);
606
604
assert_eq!(occurrences[1].message_id, "2001");
607
605
assert_eq!(occurrences[1].duration_seconds, None);
608
606
}
@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {344
}344
}345
Err(error) => return Err(error),345
Err(error) => return Err(error),346
};346
};347
let Some(report_id) = reports347
let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {348
.pointer("/value/0/id")349
.and_then(Value::as_str)350
else {351
return Ok(Attendance::TurnedOff);348
return Ok(Attendance::TurnedOff);352
};349
};353
let report = self350
let report = self@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {386
.pointer("/parentReference/driveId")383
.pointer("/parentReference/driveId")387
.and_then(Value::as_str)?;384
.and_then(Value::as_str)?;388
let item_id = item.get("id").and_then(Value::as_str)?;385
let item_id = item.get("id").and_then(Value::as_str)?;389
Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))386
Some(format!(387
"{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"388
))390
}389
}391
390
392
fn decode_binary(body: &Value) -> Option<Vec<u8>> {391
fn decode_binary(body: &Value) -> Option<Vec<u8>> {@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>443
.into_iter()442
.into_iter()444
.flatten()443
.flatten()445
.filter(|message| {444
.filter(|message| {446
message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")445
message.get("messagetype").and_then(Value::as_str)446
== Some("RichText/Media_CallRecording")447
})447
})448
.filter_map(|message| message.get("content").and_then(Value::as_str))448
.filter_map(|message| message.get("content").and_then(Value::as_str))449
.filter(|content| content.contains(AUDIO_ONLY_MARKER))449
.filter(|content| content.contains(AUDIO_ONLY_MARKER))@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {505
}505
}506
506
507
pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {507
pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {508
let stamp = listing_json508
let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;509
.pointer("/fields/_ExpirationDate")?510
.as_str()?;511
DateTime::parse_from_rfc3339(stamp)509
DateTime::parse_from_rfc3339(stamp)512
.ok()510
.ok()513
.map(|stamp| stamp.with_timezone(&Utc))511
.map(|stamp| stamp.with_timezone(&Utc))@@ -589,10 +587,7 @@ mod tests {589
use super::*;587
use super::*;590
588
591
fn fixture(name: &str) -> Value {589
fn fixture(name: &str) -> Value {592
let path = format!(590
let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));593
"{}/tests/fixtures/recap/{name}",594
env!("CARGO_MANIFEST_DIR")595
);596
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()591
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()597
}592
}598
593
@@ -602,7 +597,10 @@ mod tests {602
assert_eq!(occurrences.len(), 2);597
assert_eq!(occurrences.len(), 2);603
assert_eq!(occurrences[0].message_id, "2002");598
assert_eq!(occurrences[0].message_id, "2002");604
assert_eq!(occurrences[0].duration_seconds, Some(1832));599
assert_eq!(occurrences[0].duration_seconds, Some(1832));605
assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));600
assert_eq!(601
occurrences[0].organizer_id.as_deref(),602
Some("user-organizer")603
);606
assert_eq!(occurrences[1].message_id, "2001");604
assert_eq!(occurrences[1].message_id, "2001");607
assert_eq!(occurrences[1].duration_seconds, None);605
assert_eq!(occurrences[1].duration_seconds, None);608
}606
}@@ -24,11 +24,7 @@ pub struct SavedMessage {
24
24
}
25
25
26
26
fn text_or_number(value: &Value, key: &str) -> Option<String> {
27
match value.get(key)? {
28
Value::String(text) if !text.is_empty() => Some(text.clone()),
29
Value::Number(number) => Some(number.to_string()),
30
_ => None,
31
}
27
crate::json_id::id_text(value.get(key)?)
32
28
}
33
29
34
30
fn activity_of(message: &Value) -> Option<Value> {
@@ -24,11 +24,7 @@ pub struct SavedMessage {24
}24
}25
25
26
fn text_or_number(value: &Value, key: &str) -> Option<String> {26
fn text_or_number(value: &Value, key: &str) -> Option<String> {27
match value.get(key)? {27
crate::json_id::id_text(value.get(key)?)28
Value::String(text) if !text.is_empty() => Some(text.clone()),29
Value::Number(number) => Some(number.to_string()),30
_ => None,31
}32
}28
}33
29
34
fn activity_of(message: &Value) -> Option<Value> {30
fn activity_of(message: &Value) -> Option<Value> {@@ -217,8 +217,14 @@ mod tests {
217
217
218
218
#[test]
219
219
fn skin_tone_is_read_from_the_string_property() {
220
assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));
221
assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);
220
assert_eq!(
221
parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
222
Some(2)
223
);
224
assert_eq!(
225
parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
226
None
227
);
222
228
assert_eq!(parse_skin_tone(&json!({})), None);
223
229
}
224
230
@@ -217,8 +217,14 @@ mod tests {217
217
218
#[test]218
#[test]219
fn skin_tone_is_read_from_the_string_property() {219
fn skin_tone_is_read_from_the_string_property() {220
assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));220
assert_eq!(221
assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);221
parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),222
Some(2)223
);224
assert_eq!(225
parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),226
None227
);222
assert_eq!(parse_skin_tone(&json!({})), None);228
assert_eq!(parse_skin_tone(&json!({})), None);223
}229
}224
230
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(
148
148
));
149
149
}
150
150
if previous.urgent_sound != updated.urgent_sound {
151
changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
151
changes.push((
152
TOAST_SETTINGS,
153
URGENT_SOUND,
154
switch_value(updated.urgent_sound),
155
));
152
156
}
153
157
if previous.urgent_sound_type != updated.urgent_sound_type {
154
158
changes.push((
@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {
200
204
json!({"voiceAdminSettings": true})
201
205
}
202
206
203
pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
204
{
207
pub struct SoundSettingsClient<
208
P: MessageTransport = SessionMessageTransport,
209
M: CsaTransport = SessionTransport,
210
> {
205
211
properties: UserSettings<P>,
206
212
middle_tier: M,
207
213
middle_tier_url: String,
@@ -356,9 +362,12 @@ mod tests {
356
362
sound_when_busy: false,
357
363
..previous.clone()
358
364
};
359
let merged: Value =
360
serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
361
.unwrap();
365
let merged: Value = serde_json::from_str(&merge_sound_settings(
366
&properties(personal),
367
&previous,
368
&updated,
369
))
370
.unwrap();
362
371
assert_eq!(
363
372
merged,
364
373
json!({
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(148
));148
));149
}149
}150
if previous.urgent_sound != updated.urgent_sound {150
if previous.urgent_sound != updated.urgent_sound {151
changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));151
changes.push((152
TOAST_SETTINGS,153
URGENT_SOUND,154
switch_value(updated.urgent_sound),155
));152
}156
}153
if previous.urgent_sound_type != updated.urgent_sound_type {157
if previous.urgent_sound_type != updated.urgent_sound_type {154
changes.push((158
changes.push((@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {200
json!({"voiceAdminSettings": true})204
json!({"voiceAdminSettings": true})201
}205
}202
206
203
pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>207
pub struct SoundSettingsClient<204
{208
P: MessageTransport = SessionMessageTransport,209
M: CsaTransport = SessionTransport,210
> {205
properties: UserSettings<P>,211
properties: UserSettings<P>,206
middle_tier: M,212
middle_tier: M,207
middle_tier_url: String,213
middle_tier_url: String,@@ -356,9 +362,12 @@ mod tests {356
sound_when_busy: false,362
sound_when_busy: false,357
..previous.clone()363
..previous.clone()358
};364
};359
let merged: Value =365
let merged: Value = serde_json::from_str(&merge_sound_settings(360
serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))366
&properties(personal),361
.unwrap();367
&previous,368
&updated,369
))370
.unwrap();362
assert_eq!(371
assert_eq!(363
merged,372
merged,364
json!({373
json!({@@ -315,7 +315,10 @@ mod tests {
315
315
format!("{}.mp3", ringtone.name().to_lowercase())
316
316
);
317
317
}
318
assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
318
assert_eq!(
319
Ringtone::from_name("wishgranted"),
320
Some(Ringtone::WishGranted)
321
);
319
322
assert_eq!(Ringtone::from_name("Chime"), None);
320
323
assert_eq!(Ringtone::Ring.label(), "Default");
321
324
}
@@ -315,7 +315,10 @@ mod tests {315
format!("{}.mp3", ringtone.name().to_lowercase())315
format!("{}.mp3", ringtone.name().to_lowercase())316
);316
);317
}317
}318
assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));318
assert_eq!(319
Ringtone::from_name("wishgranted"),320
Some(Ringtone::WishGranted)321
);319
assert_eq!(Ringtone::from_name("Chime"), None);322
assert_eq!(Ringtone::from_name("Chime"), None);320
assert_eq!(Ringtone::Ring.label(), "Default");323
assert_eq!(Ringtone::Ring.label(), "Default");321
}324
}@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {
38
38
}
39
39
40
40
fn message_id(message: &Value) -> Option<String> {
41
match message.get("id")? {
42
Value::String(text) if !text.is_empty() => Some(text.clone()),
43
Value::Number(number) => Some(number.to_string()),
44
_ => None,
45
}
41
crate::json_id::id_text(message.get("id")?)
46
42
}
47
43
48
44
fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {38
}38
}39
39
40
fn message_id(message: &Value) -> Option<String> {40
fn message_id(message: &Value) -> Option<String> {41
match message.get("id")? {41
crate::json_id::id_text(message.get("id")?)42
Value::String(text) if !text.is_empty() => Some(text.clone()),43
Value::Number(number) => Some(number.to_string()),44
_ => None,45
}46
}42
}47
43
48
fn cursor_of(body: &Value, link_key: &str) -> Option<String> {44
fn cursor_of(body: &Value, link_key: &str) -> Option<String> {