Merge pull request #30: fix(calls): play tones on macOS and make the Echo test call connect
@@ -33,8 +33,10 @@ sys-locale = "0.3"
33
33
rust-i18n = "4.2"
34
34
resvg = { version = "0.46", default-features = false, features = ["text"] }
35
35
36
[target.'cfg(target_os = "linux")'.dependencies]
36
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
37
37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
38
39
[target.'cfg(target_os = "linux")'.dependencies]
38
40
x11rb = { version = "0.13", features = ["shape"] }
39
41
40
42
[target.'cfg(windows)'.dependencies]
@@ -33,8 +33,10 @@ sys-locale = "0.3"33
rust-i18n = "4.2"33
rust-i18n = "4.2"34
resvg = { version = "0.46", default-features = false, features = ["text"] }34
resvg = { version = "0.46", default-features = false, features = ["text"] }35
35
36
[target.'cfg(target_os = "linux")'.dependencies]36
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }38
39
[target.'cfg(target_os = "linux")'.dependencies]38
x11rb = { version = "0.13", features = ["shape"] }40
x11rb = { version = "0.13", features = ["shape"] }39
41
40
[target.'cfg(windows)'.dependencies]42
[target.'cfg(windows)'.dependencies]@@ -468,6 +468,9 @@ calls:
468
468
recording_join_failed:
469
469
en: The recording service could not join
470
470
de: Der Aufzeichnungsdienst konnte nicht beitreten
471
echo_test_failed:
472
en: The test call could not start
473
de: Der Testanruf konnte nicht gestartet werden
471
474
captions_join_failed:
472
475
en: The captions service could not join
473
476
de: Der Untertitel-Dienst konnte nicht beitreten
@@ -468,6 +468,9 @@ calls:468
recording_join_failed:468
recording_join_failed:469
en: The recording service could not join469
en: The recording service could not join470
de: Der Aufzeichnungsdienst konnte nicht beitreten470
de: Der Aufzeichnungsdienst konnte nicht beitreten471
echo_test_failed:472
en: The test call could not start473
de: Der Testanruf konnte nicht gestartet werden471
captions_join_failed:474
captions_join_failed:472
en: The captions service could not join475
en: The captions service could not join473
de: Der Untertitel-Dienst konnte nicht beitreten476
de: Der Untertitel-Dienst konnte nicht beitreten@@ -1,4 +1,4 @@
1
//! Linux notification and ringtone playback through the system audio output.
1
//! Linux and macOS notification and ringtone playback through the system audio output.
2
2
use std::io::Cursor;
3
3
use std::sync::atomic::{AtomicBool, Ordering};
4
4
use std::sync::{Arc, Mutex};
@@ -14,27 +14,60 @@ pub fn set_sound_output(device_key: Option<String>) {
14
14
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;
15
15
}
16
16
17
/// True when a call-output key names this cpal device (id, friendly name, or Pulse-style id).
18
pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {
19
let key = key.trim();
20
if key.is_empty() {
21
return false;
22
}
23
if device_id == key || device_name == key {
24
return true;
25
}
26
let key_lower = key.to_ascii_lowercase();
27
let id_lower = device_id.to_ascii_lowercase();
28
let name_lower = device_name.to_ascii_lowercase();
29
id_lower == key_lower
30
|| name_lower == key_lower
31
|| (!key_lower.contains(' ') && id_lower.contains(&key_lower))
32
|| (key_lower.len() >= 4 && name_lower.contains(&key_lower))
33
}
34
17
35
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {
18
36
let chosen = SOUND_OUTPUT
19
37
.lock()
20
38
.unwrap_or_else(|p| p.into_inner())
21
39
.clone();
22
let device = chosen.and_then(|key| {
23
rodio::cpal::default_host()
40
if let Some(key) = chosen.as_ref() {
41
if let Some(device) = rodio::cpal::default_host()
24
42
.output_devices()
25
.ok()?
43
.ok()
44
.into_iter()
45
.flatten()
26
46
.find(|device| {
27
device.id().is_ok_and(|id| id.1 == key)
28
|| device
29
.description()
30
.is_ok_and(|description| description.name() == key)
47
let id = device
48
.id()
49
.ok()
50
.map(|id| id.1)
51
.unwrap_or_default();
52
let name = device
53
.description()
54
.ok()
55
.map(|description| description.name().to_owned())
56
.unwrap_or_default();
57
device_matches_key(&id, &name, key)
31
58
})
32
});
33
if let Some(device) = device {
34
if let Ok(sink) =
35
rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream())
36
59
{
37
return Ok(sink);
60
match rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream())
61
{
62
Ok(sink) => return Ok(sink),
63
Err(error) => crate::diagnostics::record(format!(
64
"sound: selected output {key:?} failed ({error}), using system default"
65
)),
66
}
67
} else {
68
crate::diagnostics::record(format!(
69
"sound: selected output {key:?} not found, using system default"
70
));
38
71
}
39
72
}
40
73
rodio::DeviceSinkBuilder::open_default_sink()
@@ -97,6 +130,20 @@ mod tests {
97
130
assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());
98
131
}
99
132
133
#[test]
134
fn call_output_keys_match_cpal_ids_and_friendly_names() {
135
assert!(device_matches_key("sink-a", "Front Speakers", "Front Speakers"));
136
assert!(device_matches_key("sink-a", "Front Speakers", "sink-a"));
137
assert!(device_matches_key("sink-a", "Front Speakers", "front speakers"));
138
assert!(device_matches_key(
139
"alsa_output.pci-0000_00_1f.3.analog-stereo",
140
"Built-in Audio Analog Stereo",
141
"alsa_output.pci-0000_00_1f.3.analog-stereo"
142
));
143
assert!(!device_matches_key("sink-a", "Front Speakers", "Headphones"));
144
assert!(!device_matches_key("id", "Speaker", ""));
145
}
146
100
147
#[test]
101
148
#[ignore = "plays a short notification on the real default audio output"]
102
149
fn notification_plays_on_default_output() {
@@ -1,4 +1,4 @@1
//! Linux notification and ringtone playback through the system audio output.1
//! Linux and macOS notification and ringtone playback through the system audio output.2
use std::io::Cursor;2
use std::io::Cursor;3
use std::sync::atomic::{AtomicBool, Ordering};3
use std::sync::atomic::{AtomicBool, Ordering};4
use std::sync::{Arc, Mutex};4
use std::sync::{Arc, Mutex};@@ -14,27 +14,60 @@ pub fn set_sound_output(device_key: Option<String>) {14
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;14
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;15
}15
}16
16
17
/// True when a call-output key names this cpal device (id, friendly name, or Pulse-style id).18
pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {19
let key = key.trim();20
if key.is_empty() {21
return false;22
}23
if device_id == key || device_name == key {24
return true;25
}26
let key_lower = key.to_ascii_lowercase();27
let id_lower = device_id.to_ascii_lowercase();28
let name_lower = device_name.to_ascii_lowercase();29
id_lower == key_lower30
|| name_lower == key_lower31
|| (!key_lower.contains(' ') && id_lower.contains(&key_lower))32
|| (key_lower.len() >= 4 && name_lower.contains(&key_lower))33
}34
17
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {35
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {18
let chosen = SOUND_OUTPUT36
let chosen = SOUND_OUTPUT19
.lock()37
.lock()20
.unwrap_or_else(|p| p.into_inner())38
.unwrap_or_else(|p| p.into_inner())21
.clone();39
.clone();22
let device = chosen.and_then(|key| {40
if let Some(key) = chosen.as_ref() {23
rodio::cpal::default_host()41
if let Some(device) = rodio::cpal::default_host()24
.output_devices()42
.output_devices()25
.ok()?43
.ok()44
.into_iter()45
.flatten()26
.find(|device| {46
.find(|device| {27
device.id().is_ok_and(|id| id.1 == key)47
let id = device28
|| device48
.id()29
.description()49
.ok()30
.is_ok_and(|description| description.name() == key)50
.map(|id| id.1)51
.unwrap_or_default();52
let name = device53
.description()54
.ok()55
.map(|description| description.name().to_owned())56
.unwrap_or_default();57
device_matches_key(&id, &name, key)31
})58
})32
});33
if let Some(device) = device {34
if let Ok(sink) =35
rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream())36
{59
{37
return Ok(sink);60
match rodio::DeviceSinkBuilder::from_device(device).and_then(|builder| builder.open_stream())61
{62
Ok(sink) => return Ok(sink),63
Err(error) => crate::diagnostics::record(format!(64
"sound: selected output {key:?} failed ({error}), using system default"65
)),66
}67
} else {68
crate::diagnostics::record(format!(69
"sound: selected output {key:?} not found, using system default"70
));38
}71
}39
}72
}40
rodio::DeviceSinkBuilder::open_default_sink()73
rodio::DeviceSinkBuilder::open_default_sink()@@ -97,6 +130,20 @@ mod tests {97
assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());130
assert!(play(Vec::new(), true, Arc::new(AtomicBool::new(true))).is_ok());98
}131
}99
132
133
#[test]134
fn call_output_keys_match_cpal_ids_and_friendly_names() {135
assert!(device_matches_key("sink-a", "Front Speakers", "Front Speakers"));136
assert!(device_matches_key("sink-a", "Front Speakers", "sink-a"));137
assert!(device_matches_key("sink-a", "Front Speakers", "front speakers"));138
assert!(device_matches_key(139
"alsa_output.pci-0000_00_1f.3.analog-stereo",140
"Built-in Audio Analog Stereo",141
"alsa_output.pci-0000_00_1f.3.analog-stereo"142
));143
assert!(!device_matches_key("sink-a", "Front Speakers", "Headphones"));144
assert!(!device_matches_key("id", "Speaker", ""));145
}146
100
#[test]147
#[test]101
#[ignore = "plays a short notification on the real default audio output"]148
#[ignore = "plays a short notification on the real default audio output"]102
fn notification_plays_on_default_output() {149
fn notification_plays_on_default_output() {@@ -3,7 +3,7 @@ mod windows_impl;
3
3
#[cfg(windows)]
4
4
pub use windows_impl::*;
5
5
6
#[cfg(target_os = "linux")]
6
#[cfg(any(target_os = "linux", target_os = "macos"))]
7
7
mod linux_sound;
8
8
#[cfg(not(windows))]
9
9
mod stub;
@@ -3,7 +3,7 @@ mod windows_impl;3
#[cfg(windows)]3
#[cfg(windows)]4
pub use windows_impl::*;4
pub use windows_impl::*;5
5
6
#[cfg(target_os = "linux")]6
#[cfg(any(target_os = "linux", target_os = "macos"))]7
mod linux_sound;7
mod linux_sound;8
#[cfg(not(windows))]8
#[cfg(not(windows))]9
mod stub;9
mod stub;@@ -88,19 +88,19 @@ pub fn stop_flash(_handle: NativeHandle) {}
88
88
89
89
pub fn set_badge(_handle: NativeHandle, _badge: Option<&Badge>) {}
90
90
91
#[cfg(target_os = "linux")]
91
#[cfg(any(target_os = "linux", target_os = "macos"))]
92
92
pub use super::linux_sound::{play_mp3, play_mp3_until, play_sound, set_sound_output};
93
93
94
#[cfg(not(target_os = "linux"))]
94
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
95
95
pub fn play_sound() {}
96
96
97
#[cfg(not(target_os = "linux"))]
97
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
98
98
pub fn set_sound_output(_device_key: Option<String>) {}
99
99
100
#[cfg(not(target_os = "linux"))]
100
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
101
101
pub fn play_mp3(_bytes: Vec<u8>) {}
102
102
103
#[cfg(not(target_os = "linux"))]
103
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
104
104
pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}
105
105
106
106
pub struct Tray;
@@ -88,19 +88,19 @@ pub fn stop_flash(_handle: NativeHandle) {}88
88
89
pub fn set_badge(_handle: NativeHandle, _badge: Option<&Badge>) {}89
pub fn set_badge(_handle: NativeHandle, _badge: Option<&Badge>) {}90
90
91
#[cfg(target_os = "linux")]91
#[cfg(any(target_os = "linux", target_os = "macos"))]92
pub use super::linux_sound::{play_mp3, play_mp3_until, play_sound, set_sound_output};92
pub use super::linux_sound::{play_mp3, play_mp3_until, play_sound, set_sound_output};93
93
94
#[cfg(not(target_os = "linux"))]94
#[cfg(not(any(target_os = "linux", target_os = "macos")))]95
pub fn play_sound() {}95
pub fn play_sound() {}96
96
97
#[cfg(not(target_os = "linux"))]97
#[cfg(not(any(target_os = "linux", target_os = "macos")))]98
pub fn set_sound_output(_device_key: Option<String>) {}98
pub fn set_sound_output(_device_key: Option<String>) {}99
99
100
#[cfg(not(target_os = "linux"))]100
#[cfg(not(any(target_os = "linux", target_os = "macos")))]101
pub fn play_mp3(_bytes: Vec<u8>) {}101
pub fn play_mp3(_bytes: Vec<u8>) {}102
102
103
#[cfg(not(target_os = "linux"))]103
#[cfg(not(any(target_os = "linux", target_os = "macos")))]104
pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}104
pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}105
105
106
pub struct Tray;106
pub struct Tray;@@ -588,6 +588,10 @@ mod tests {
588
588
let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");
589
589
incoming.progress = Some(Progress::Ringing);
590
590
assert!(!should_ringback(Some(&incoming)));
591
let mut echo = CallModel::test();
592
echo.state = CallState::Connecting;
593
echo.progress = Some(Progress::Calling);
594
assert!(should_ringback(Some(&echo)));
591
595
}
592
596
593
597
#[test]
@@ -588,6 +588,10 @@ mod tests {588
let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");588
let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");589
incoming.progress = Some(Progress::Ringing);589
incoming.progress = Some(Progress::Ringing);590
assert!(!should_ringback(Some(&incoming)));590
assert!(!should_ringback(Some(&incoming)));591
let mut echo = CallModel::test();592
echo.state = CallState::Connecting;593
echo.progress = Some(Progress::Calling);594
assert!(should_ringback(Some(&echo)));591
}595
}592
596
593
#[test]597
#[test]@@ -53,11 +53,11 @@ use crate::notices::{
53
53
CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE,
54
54
CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE,
55
55
CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE,
56
DENY_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,
57
LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,
58
MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,
59
MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,
60
RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,
56
DENY_FAILED_NOTICE, ECHO_TEST_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE,
57
INVITE_PERSON_FAILED_NOTICE, LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE,
58
LOWER_THAT_HAND_FAILED_NOTICE, MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE,
59
MUTE_ALL_FAILED_NOTICE, MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO,
60
ON_HOLD_NOTICE, RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,
61
61
RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,
62
62
REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,
63
63
SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,
@@ -84,7 +84,7 @@ use crate::send_control::{RequestFilter, parse_request};
84
84
use crate::signaling::{
85
85
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
86
86
NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
87
escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,
87
ensure_echo_bot_thread, escalation_answer_body, one_to_one_thread, renegotiation_body,
88
88
};
89
89
use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
90
90
use crate::state::{CallSignal, CallState};
@@ -963,16 +963,13 @@ async fn drive(
963
963
964
964
let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
965
965
let thread_id = control
966
.until_hangup(find_echo_bot_thread(
966
.until_hangup(ensure_echo_bot_thread(
967
967
&inner.session,
968
968
&inner.identity.object_id,
969
969
))
970
970
.await??;
971
timeline.record(
972
"echo bot chat",
973
if thread_id.is_some() { "found" } else { "none" },
974
);
975
thread_id
971
timeline.record("echo bot chat", thread_id.clone());
972
Some(thread_id)
976
973
} else {
977
974
None
978
975
};
@@ -1150,8 +1147,11 @@ async fn drive(
1150
1147
}
1151
1148
_ => setup_step(control, signaling.create_conversation(&invitation)).await?,
1152
1149
};
1153
if spec.is_people() {
1150
// People and the Echo test call share outgoing ringback while connecting.
1151
if spec.is_people() || matches!(spec, CallSpec::Echo) {
1154
1152
control.send(CallUpdate::Progress(Progress::Calling));
1153
}
1154
if spec.is_people() {
1155
1155
if threadless {
1156
1156
outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
1157
1157
}
@@ -1406,6 +1406,8 @@ async fn drive(
1406
1406
let mut deferred_changes: Vec<Change> = Vec::new();
1407
1407
let mut remote_direct_share: Option<String> = None;
1408
1408
let mut sent_replacement: Option<Replacement> = None;
1409
let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1410
let mut echo_add_pending = false;
1409
1411
loop {
1410
1412
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1411
1413
start_camera_pending = false;
@@ -1555,11 +1557,34 @@ async fn drive(
1555
1557
let remote = remote.clone();
1556
1558
let links = links.clone();
1557
1559
let thread_id = echo_thread.clone();
1560
let echo_add_tx = echo_add_tx.clone();
1561
if is_echo {
1562
echo_add_pending = true;
1563
}
1558
1564
tokio::spawn(async move {
1559
1565
if is_echo {
1560
let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await;
1566
let result = remote
1567
.signaling
1568
.add_echo_bot(
1569
&remote.conversation,
1570
&remote.participant,
1571
thread_id.as_deref(),
1572
&links,
1573
)
1574
.await;
1575
let ok = result.is_ok();
1576
let _ = echo_add_tx.send(result);
1577
if !ok {
1578
return;
1579
}
1561
1580
}
1562
let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await;
1581
let _ = remote
1582
.signaling
1583
.update_endpoint_metadata(
1584
&remote.conversation,
1585
&remote.participant,
1586
)
1587
.await;
1563
1588
});
1564
1589
}
1565
1590
MediaAction::Escalate => {
@@ -2052,6 +2077,16 @@ async fn drive(
2052
2077
}
2053
2078
}
2054
2079
}
2080
Some(result) = echo_add_rx.recv(), if echo_add_pending => {
2081
echo_add_pending = false;
2082
if let Err(error) = result {
2083
timeline.record("echo bot add failed", error.to_string());
2084
control.send(CallUpdate::Notice(ECHO_TEST_FAILED_NOTICE.into()));
2085
live.cancel_leave = true;
2086
advance(state, CallSignal::RemoteEnd(EndKind::Unavailable), control);
2087
break;
2088
}
2089
}
2055
2090
Some(event) = current.events.recv() => match event {
2056
2091
PeerEvent::Ice(ice_state) => {
2057
2092
timeline.record("ICE state", format!("{ice_state:?}"));
@@ -53,11 +53,11 @@ use crate::notices::{53
CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE,53
CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE,54
CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE,54
CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE,55
CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE,55
CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE,56
DENY_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,56
DENY_FAILED_NOTICE, ECHO_TEST_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE,57
LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,57
INVITE_PERSON_FAILED_NOTICE, LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE,58
MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,58
LOWER_THAT_HAND_FAILED_NOTICE, MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE,59
MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,59
MUTE_ALL_FAILED_NOTICE, MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO,60
RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,60
ON_HOLD_NOTICE, RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,61
RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,61
RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,62
REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,62
REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,63
SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,63
SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,@@ -84,7 +84,7 @@ use crate::send_control::{RequestFilter, parse_request};84
use crate::signaling::{84
use crate::signaling::{85
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,85
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,86
NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,86
NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,87
escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,87
ensure_echo_bot_thread, escalation_answer_body, one_to_one_thread, renegotiation_body,88
};88
};89
use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};89
use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};90
use crate::state::{CallSignal, CallState};90
use crate::state::{CallSignal, CallState};@@ -963,16 +963,13 @@ async fn drive(963
963
964
let thread_id = if matches!(spec, Some(CallSpec::Echo)) {964
let thread_id = if matches!(spec, Some(CallSpec::Echo)) {965
let thread_id = control965
let thread_id = control966
.until_hangup(find_echo_bot_thread(966
.until_hangup(ensure_echo_bot_thread(967
&inner.session,967
&inner.session,968
&inner.identity.object_id,968
&inner.identity.object_id,969
))969
))970
.await??;970
.await??;971
timeline.record(971
timeline.record("echo bot chat", thread_id.clone());972
"echo bot chat",972
Some(thread_id)973
if thread_id.is_some() { "found" } else { "none" },974
);975
thread_id976
} else {973
} else {977
None974
None978
};975
};@@ -1150,8 +1147,11 @@ async fn drive(1150
}1147
}1151
_ => setup_step(control, signaling.create_conversation(&invitation)).await?,1148
_ => setup_step(control, signaling.create_conversation(&invitation)).await?,1152
};1149
};1153
if spec.is_people() {1150
// People and the Echo test call share outgoing ringback while connecting.1151
if spec.is_people() || matches!(spec, CallSpec::Echo) {1154
control.send(CallUpdate::Progress(Progress::Calling));1152
control.send(CallUpdate::Progress(Progress::Calling));1153
}1154
if spec.is_people() {1155
if threadless {1155
if threadless {1156
outgoing_limit = DIRECT_OUTGOING_TIMEOUT;1156
outgoing_limit = DIRECT_OUTGOING_TIMEOUT;1157
}1157
}@@ -1406,6 +1406,8 @@ async fn drive(1406
let mut deferred_changes: Vec<Change> = Vec::new();1406
let mut deferred_changes: Vec<Change> = Vec::new();1407
let mut remote_direct_share: Option<String> = None;1407
let mut remote_direct_share: Option<String> = None;1408
let mut sent_replacement: Option<Replacement> = None;1408
let mut sent_replacement: Option<Replacement> = None;1409
let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();1410
let mut echo_add_pending = false;1409
loop {1411
loop {1410
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {1412
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {1411
start_camera_pending = false;1413
start_camera_pending = false;@@ -1555,11 +1557,34 @@ async fn drive(1555
let remote = remote.clone();1557
let remote = remote.clone();1556
let links = links.clone();1558
let links = links.clone();1557
let thread_id = echo_thread.clone();1559
let thread_id = echo_thread.clone();1560
let echo_add_tx = echo_add_tx.clone();1561
if is_echo {1562
echo_add_pending = true;1563
}1558
tokio::spawn(async move {1564
tokio::spawn(async move {1559
if is_echo {1565
if is_echo {1560
let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await;1566
let result = remote1567
.signaling1568
.add_echo_bot(1569
&remote.conversation,1570
&remote.participant,1571
thread_id.as_deref(),1572
&links,1573
)1574
.await;1575
let ok = result.is_ok();1576
let _ = echo_add_tx.send(result);1577
if !ok {1578
return;1579
}1561
}1580
}1562
let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await;1581
let _ = remote1582
.signaling1583
.update_endpoint_metadata(1584
&remote.conversation,1585
&remote.participant,1586
)1587
.await;1563
});1588
});1564
}1589
}1565
MediaAction::Escalate => {1590
MediaAction::Escalate => {@@ -2052,6 +2077,16 @@ async fn drive(2052
}2077
}2053
}2078
}2054
}2079
}2080
Some(result) = echo_add_rx.recv(), if echo_add_pending => {2081
echo_add_pending = false;2082
if let Err(error) = result {2083
timeline.record("echo bot add failed", error.to_string());2084
control.send(CallUpdate::Notice(ECHO_TEST_FAILED_NOTICE.into()));2085
live.cancel_leave = true;2086
advance(state, CallSignal::RemoteEnd(EndKind::Unavailable), control);2087
break;2088
}2089
}2055
Some(event) = current.events.recv() => match event {2090
Some(event) = current.events.recv() => match event {2056
PeerEvent::Ice(ice_state) => {2091
PeerEvent::Ice(ice_state) => {2057
timeline.record("ICE state", format!("{ice_state:?}"));2092
timeline.record("ICE state", format!("{ice_state:?}"));@@ -12,6 +12,7 @@ pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";
12
12
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";
13
13
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";
14
14
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";
15
pub const ECHO_TEST_FAILED_NOTICE: &str = "calls.notice.echo_test_failed";
15
16
pub const CAPTIONS_JOIN_FAILED_NOTICE: &str = "calls.notice.captions_join_failed";
16
17
pub const CAPTION_LANGUAGE_FAILED_NOTICE: &str = "calls.notice.caption_language_failed";
17
18
pub const CAMERA_START_NOTICE: &str = "calls.notice.camera_start";
@@ -80,6 +81,7 @@ mod tests {
80
81
RECORDING_JOIN_FAILED_NOTICE,
81
82
"calls.notice.recording_join_failed"
82
83
);
84
assert_eq!(ECHO_TEST_FAILED_NOTICE, "calls.notice.echo_test_failed");
83
85
assert_eq!(
84
86
CAPTIONS_JOIN_FAILED_NOTICE,
85
87
"calls.notice.captions_join_failed"
@@ -12,6 +12,7 @@ pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";12
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";12
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";13
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";13
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";14
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";14
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";15
pub const ECHO_TEST_FAILED_NOTICE: &str = "calls.notice.echo_test_failed";15
pub const CAPTIONS_JOIN_FAILED_NOTICE: &str = "calls.notice.captions_join_failed";16
pub const CAPTIONS_JOIN_FAILED_NOTICE: &str = "calls.notice.captions_join_failed";16
pub const CAPTION_LANGUAGE_FAILED_NOTICE: &str = "calls.notice.caption_language_failed";17
pub const CAPTION_LANGUAGE_FAILED_NOTICE: &str = "calls.notice.caption_language_failed";17
pub const CAMERA_START_NOTICE: &str = "calls.notice.camera_start";18
pub const CAMERA_START_NOTICE: &str = "calls.notice.camera_start";@@ -80,6 +81,7 @@ mod tests {80
RECORDING_JOIN_FAILED_NOTICE,81
RECORDING_JOIN_FAILED_NOTICE,81
"calls.notice.recording_join_failed"82
"calls.notice.recording_join_failed"82
);83
);84
assert_eq!(ECHO_TEST_FAILED_NOTICE, "calls.notice.echo_test_failed");83
assert_eq!(85
assert_eq!(84
CAPTIONS_JOIN_FAILED_NOTICE,86
CAPTIONS_JOIN_FAILED_NOTICE,85
"calls.notice.captions_join_failed"87
"calls.notice.captions_join_failed"@@ -190,6 +190,12 @@ pub fn routed_url(url: &str) -> Result<String> {
190
190
191
191
const FAILURE_BODY_CHARS: usize = 240;
192
192
193
/// Status plus a short body excerpt for the timeline and `Error::Signaling`.
194
pub(crate) fn signaling_failure_detail(status: u16, body: &str) -> String {
195
let reason: String = body.chars().take(FAILURE_BODY_CHARS).collect();
196
format!("HTTP {status} {reason}")
197
}
198
193
199
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194
200
pub enum LeaveReason {
195
201
Hangup,
@@ -301,21 +307,14 @@ impl Signaling {
301
307
) -> Result<ApiResponse> {
302
308
request.url = routed_url(&request.url)?;
303
309
let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
304
self.timeline
305
.record(label, format!("HTTP {}", response.status));
306
if !response.is_success() {
307
let reason: String = response
308
.body
309
.to_string()
310
.chars()
311
.take(FAILURE_BODY_CHARS)
312
.collect();
313
return Err(Error::Signaling(format!(
314
"{label} answered HTTP {} {reason}",
315
response.status
316
)));
310
if response.is_success() {
311
self.timeline
312
.record(label, format!("HTTP {}", response.status));
313
return Ok(response);
317
314
}
318
Ok(response)
315
let detail = signaling_failure_detail(response.status, &response.body.to_string());
316
self.timeline.record(label, detail.clone());
317
Err(Error::Signaling(format!("{label} answered {detail}")))
319
318
}
320
319
321
320
async fn send(
@@ -510,21 +509,7 @@ impl Signaling {
510
509
thread_id: Option<&str>,
511
510
callbacks: &CallbackLinks,
512
511
) -> Result<()> {
513
let body = json!({
514
"disableUnmute": false,
515
"participants": {
516
"from": from.wire(),
517
"to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
518
},
519
"participantInvitationData": {},
520
"replacementDetails": null,
521
"groupContext": null,
522
"groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),
523
"links": {
524
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
525
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),
526
},
527
});
512
let body = echo_bot_add_body(from, thread_id, callbacks);
528
513
let url = conversation.link("addParticipantAndModality")?;
529
514
self.post_json("POST add (echo bot)", url, body).await
530
515
}
@@ -1479,6 +1464,28 @@ pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
1479
1464
})
1480
1465
}
1481
1466
1467
pub(crate) fn echo_bot_add_body(
1468
from: &Participant,
1469
thread_id: Option<&str>,
1470
callbacks: &CallbackLinks,
1471
) -> Value {
1472
json!({
1473
"disableUnmute": false,
1474
"participants": {
1475
"from": from.wire(),
1476
"to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
1477
},
1478
"participantInvitationData": {},
1479
"replacementDetails": null,
1480
"groupContext": null,
1481
"groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),
1482
"links": {
1483
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
1484
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),
1485
},
1486
})
1487
}
1488
1482
1489
/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
1483
1490
pub async fn find_echo_bot_thread(
1484
1491
session: &Session,
@@ -1501,6 +1508,29 @@ pub async fn find_echo_bot_thread(
1501
1508
Ok(None)
1502
1509
}
1503
1510
1511
/// Finds the Echo bot 1:1 chat or creates it so `add_echo_bot` can send `groupChat`.
1512
pub async fn ensure_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<String> {
1513
if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? {
1514
return Ok(thread_id);
1515
}
1516
let self_mri = format!("8:orgid:{self_object_id}");
1517
match chatsvc::ThreadMembers::with_region(session, CHATSVC_REGION)
1518
.create_one_to_one(&[self_mri, ECHO_BOT_MRI.to_owned()])
1519
.await
1520
{
1521
Ok(thread_id) => Ok(thread_id),
1522
Err(error) => {
1523
// Create may succeed without a parseable id; the unique roster is still findable.
1524
if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? {
1525
return Ok(thread_id);
1526
}
1527
Err(Error::Signaling(format!(
1528
"echo bot chat create failed: {error}"
1529
)))
1530
}
1531
}
1532
}
1533
1504
1534
#[cfg(test)]
1505
1535
mod tests {
1506
1536
use super::*;
@@ -1620,6 +1650,24 @@ mod tests {
1620
1650
assert!(routed_url("https://.skype.com/x").is_err());
1621
1651
}
1622
1652
1653
#[test]
1654
fn signaling_failure_detail_keeps_status_and_a_short_body() {
1655
let detail = signaling_failure_detail(400, &"x".repeat(300));
1656
assert!(detail.starts_with("HTTP 400 "));
1657
assert_eq!(detail.chars().count(), "HTTP 400 ".chars().count() + FAILURE_BODY_CHARS);
1658
}
1659
1660
#[test]
1661
fn echo_bot_add_body_carries_the_group_chat_thread() {
1662
let body = echo_bot_add_body(&from(), Some("19:me_bot@unq.gbl.spaces"), &callbacks());
1663
assert_eq!(body["groupChat"]["threadId"], "19:me_bot@unq.gbl.spaces");
1664
assert_eq!(body["groupChat"]["messageId"], Value::Null);
1665
assert_eq!(body["participants"]["to"][0]["id"], ECHO_BOT_MRI);
1666
assert!(!body["groupChat"].is_null());
1667
let without = echo_bot_add_body(&from(), None, &callbacks());
1668
assert_eq!(without["groupChat"], Value::Null);
1669
}
1670
1623
1671
#[test]
1624
1672
fn echo_body_matches_the_captured_test_call_shape() {
1625
1673
let body = body_for(&InviteTarget::Echo);
@@ -190,6 +190,12 @@ pub fn routed_url(url: &str) -> Result<String> {190
190
191
const FAILURE_BODY_CHARS: usize = 240;191
const FAILURE_BODY_CHARS: usize = 240;192
192
193
/// Status plus a short body excerpt for the timeline and `Error::Signaling`.194
pub(crate) fn signaling_failure_detail(status: u16, body: &str) -> String {195
let reason: String = body.chars().take(FAILURE_BODY_CHARS).collect();196
format!("HTTP {status} {reason}")197
}198
193
#[derive(Debug, Clone, Copy, PartialEq, Eq)]199
#[derive(Debug, Clone, Copy, PartialEq, Eq)]194
pub enum LeaveReason {200
pub enum LeaveReason {195
Hangup,201
Hangup,@@ -301,21 +307,14 @@ impl Signaling {301
) -> Result<ApiResponse> {307
) -> Result<ApiResponse> {302
request.url = routed_url(&request.url)?;308
request.url = routed_url(&request.url)?;303
let response = session.batch(&[request], &ic3_scope()).await?.remove(0);309
let response = session.batch(&[request], &ic3_scope()).await?.remove(0);304
self.timeline310
if response.is_success() {305
.record(label, format!("HTTP {}", response.status));311
self.timeline306
if !response.is_success() {312
.record(label, format!("HTTP {}", response.status));307
let reason: String = response313
return Ok(response);308
.body309
.to_string()310
.chars()311
.take(FAILURE_BODY_CHARS)312
.collect();313
return Err(Error::Signaling(format!(314
"{label} answered HTTP {} {reason}",315
response.status316
)));317
}314
}318
Ok(response)315
let detail = signaling_failure_detail(response.status, &response.body.to_string());316
self.timeline.record(label, detail.clone());317
Err(Error::Signaling(format!("{label} answered {detail}")))319
}318
}320
319
321
async fn send(320
async fn send(@@ -510,21 +509,7 @@ impl Signaling {510
thread_id: Option<&str>,509
thread_id: Option<&str>,511
callbacks: &CallbackLinks,510
callbacks: &CallbackLinks,512
) -> Result<()> {511
) -> Result<()> {513
let body = json!({512
let body = echo_bot_add_body(from, thread_id, callbacks);514
"disableUnmute": false,515
"participants": {516
"from": from.wire(),517
"to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],518
},519
"participantInvitationData": {},520
"replacementDetails": null,521
"groupContext": null,522
"groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),523
"links": {524
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),525
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),526
},527
});528
let url = conversation.link("addParticipantAndModality")?;513
let url = conversation.link("addParticipantAndModality")?;529
self.post_json("POST add (echo bot)", url, body).await514
self.post_json("POST add (echo bot)", url, body).await530
}515
}@@ -1479,6 +1464,28 @@ pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {1479
})1464
})1480
}1465
}1481
1466
1467
pub(crate) fn echo_bot_add_body(1468
from: &Participant,1469
thread_id: Option<&str>,1470
callbacks: &CallbackLinks,1471
) -> Value {1472
json!({1473
"disableUnmute": false,1474
"participants": {1475
"from": from.wire(),1476
"to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],1477
},1478
"participantInvitationData": {},1479
"replacementDetails": null,1480
"groupContext": null,1481
"groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),1482
"links": {1483
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),1484
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),1485
},1486
})1487
}1488
1482
/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.1489
/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.1483
pub async fn find_echo_bot_thread(1490
pub async fn find_echo_bot_thread(1484
session: &Session,1491
session: &Session,@@ -1501,6 +1508,29 @@ pub async fn find_echo_bot_thread(1501
Ok(None)1508
Ok(None)1502
}1509
}1503
1510
1511
/// Finds the Echo bot 1:1 chat or creates it so `add_echo_bot` can send `groupChat`.1512
pub async fn ensure_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<String> {1513
if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? {1514
return Ok(thread_id);1515
}1516
let self_mri = format!("8:orgid:{self_object_id}");1517
match chatsvc::ThreadMembers::with_region(session, CHATSVC_REGION)1518
.create_one_to_one(&[self_mri, ECHO_BOT_MRI.to_owned()])1519
.await1520
{1521
Ok(thread_id) => Ok(thread_id),1522
Err(error) => {1523
// Create may succeed without a parseable id; the unique roster is still findable.1524
if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? {1525
return Ok(thread_id);1526
}1527
Err(Error::Signaling(format!(1528
"echo bot chat create failed: {error}"1529
)))1530
}1531
}1532
}1533
1504
#[cfg(test)]1534
#[cfg(test)]1505
mod tests {1535
mod tests {1506
use super::*;1536
use super::*;@@ -1620,6 +1650,24 @@ mod tests {1620
assert!(routed_url("https://.skype.com/x").is_err());1650
assert!(routed_url("https://.skype.com/x").is_err());1621
}1651
}1622
1652
1653
#[test]1654
fn signaling_failure_detail_keeps_status_and_a_short_body() {1655
let detail = signaling_failure_detail(400, &"x".repeat(300));1656
assert!(detail.starts_with("HTTP 400 "));1657
assert_eq!(detail.chars().count(), "HTTP 400 ".chars().count() + FAILURE_BODY_CHARS);1658
}1659
1660
#[test]1661
fn echo_bot_add_body_carries_the_group_chat_thread() {1662
let body = echo_bot_add_body(&from(), Some("19:me_bot@unq.gbl.spaces"), &callbacks());1663
assert_eq!(body["groupChat"]["threadId"], "19:me_bot@unq.gbl.spaces");1664
assert_eq!(body["groupChat"]["messageId"], Value::Null);1665
assert_eq!(body["participants"]["to"][0]["id"], ECHO_BOT_MRI);1666
assert!(!body["groupChat"].is_null());1667
let without = echo_bot_add_body(&from(), None, &callbacks());1668
assert_eq!(without["groupChat"], Value::Null);1669
}1670
1623
#[test]1671
#[test]1624
fn echo_body_matches_the_captured_test_call_shape() {1672
fn echo_body_matches_the_captured_test_call_shape() {1625
let body = body_for(&InviteTarget::Echo);1673
let body = body_for(&InviteTarget::Echo);@@ -104,7 +104,38 @@ pub fn create_group_request(region: &str, user_ids: &[String], topic: Option<&st
104
104
)
105
105
}
106
106
107
/// 1:1 chat (person or bot): unique roster so Teams can address it as `groupChat` on a call.
108
pub fn create_one_to_one_request(region: &str, member_mris: &[String]) -> Request {
109
let members: Vec<Value> = member_mris
110
.iter()
111
.map(|mri| json!({"id": user_mri(mri), "role": MEMBER_ROLE}))
112
.collect();
113
Request::with_body(
114
Method::Post,
115
threads_url(region),
116
json!({
117
"members": members,
118
"properties": {
119
"threadType": "chat",
120
"fixedRoster": true,
121
"uniquerosterthread": true,
122
"chatFilesIndexId": "2",
123
},
124
}),
125
)
126
}
127
107
128
fn created_thread_id(body: &Value) -> Option<String> {
129
if let Some(id) = body.get("id").and_then(Value::as_str).filter(|id| id.starts_with("19:")) {
130
return Some(id.to_owned());
131
}
132
if let Some(id) = body
133
.get("threadId")
134
.and_then(Value::as_str)
135
.filter(|id| id.starts_with("19:"))
136
{
137
return Some(id.to_owned());
138
}
108
139
let location = body.get("location")?.as_str()?;
109
140
let last = location.split('?').next()?.rsplit('/').next()?;
110
141
let decoded = percent_encoding::percent_decode_str(last)
@@ -149,7 +180,11 @@ pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
149
180
150
181
impl ThreadMembers<SessionMessageTransport> {
151
182
pub fn new(session: &Session) -> Self {
152
ThreadMembers::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
183
Self::with_region(session, DEFAULT_REGION)
184
}
185
186
pub fn with_region(session: &Session, region: &str) -> Self {
187
ThreadMembers::with_transport(SessionMessageTransport::new(session), region)
153
188
}
154
189
}
155
190
@@ -186,6 +221,20 @@ impl<T: MessageTransport> ThreadMembers<T> {
186
221
.ok_or_else(|| Error::UnexpectedAnswer("thread creation has no location".into()))
187
222
}
188
223
224
/// Teams' `createThread` for a 1:1 unique-roster chat; answers with the new thread id.
225
pub async fn create_one_to_one(&self, member_mris: &[String]) -> Result<String> {
226
let request = create_one_to_one_request(&self.region, member_mris);
227
let answer = self.transport.send(request).await?;
228
ensure_success(&answer)?;
229
created_thread_id(&answer.body).ok_or_else(|| {
230
Error::UnexpectedAnswer(format!(
231
"thread creation has no location (HTTP {} {})",
232
answer.status,
233
answer.body
234
))
235
})
236
}
237
189
238
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
190
239
let request = topic_request(&self.region, thread_id, topic);
191
240
ensure_success(&self.transport.send(request).await?)
@@ -215,6 +264,36 @@ mod tests {
215
264
created_thread_id(&json!({"location": "https://x/v1/threads/oops"})),
216
265
None
217
266
);
267
assert_eq!(
268
created_thread_id(&json!({"id": "19:me_bot@unq.gbl.spaces"})).as_deref(),
269
Some("19:me_bot@unq.gbl.spaces")
270
);
271
assert_eq!(
272
created_thread_id(&json!({"threadId": "19:me_bot@unq.gbl.spaces"})).as_deref(),
273
Some("19:me_bot@unq.gbl.spaces")
274
);
275
}
276
277
#[test]
278
fn a_one_to_one_thread_is_a_unique_roster_chat() {
279
let request = create_one_to_one_request(
280
"emea",
281
&[
282
"me".into(),
283
"28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0".into(),
284
],
285
);
286
let body = request.body.unwrap();
287
assert_eq!(body["properties"]["fixedRoster"], true);
288
assert_eq!(body["properties"]["uniquerosterthread"], true);
289
assert_eq!(
290
body["members"][0],
291
json!({"id": "8:orgid:me", "role": "Admin"})
292
);
293
assert_eq!(
294
body["members"][1],
295
json!({"id": "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0", "role": "Admin"})
296
);
218
297
}
219
298
220
299
use std::sync::Mutex;
@@ -104,7 +104,38 @@ pub fn create_group_request(region: &str, user_ids: &[String], topic: Option<&st104
)104
)105
}105
}106
106
107
/// 1:1 chat (person or bot): unique roster so Teams can address it as `groupChat` on a call.108
pub fn create_one_to_one_request(region: &str, member_mris: &[String]) -> Request {109
let members: Vec<Value> = member_mris110
.iter()111
.map(|mri| json!({"id": user_mri(mri), "role": MEMBER_ROLE}))112
.collect();113
Request::with_body(114
Method::Post,115
threads_url(region),116
json!({117
"members": members,118
"properties": {119
"threadType": "chat",120
"fixedRoster": true,121
"uniquerosterthread": true,122
"chatFilesIndexId": "2",123
},124
}),125
)126
}127
107
fn created_thread_id(body: &Value) -> Option<String> {128
fn created_thread_id(body: &Value) -> Option<String> {129
if let Some(id) = body.get("id").and_then(Value::as_str).filter(|id| id.starts_with("19:")) {130
return Some(id.to_owned());131
}132
if let Some(id) = body133
.get("threadId")134
.and_then(Value::as_str)135
.filter(|id| id.starts_with("19:"))136
{137
return Some(id.to_owned());138
}108
let location = body.get("location")?.as_str()?;139
let location = body.get("location")?.as_str()?;109
let last = location.split('?').next()?.rsplit('/').next()?;140
let last = location.split('?').next()?.rsplit('/').next()?;110
let decoded = percent_encoding::percent_decode_str(last)141
let decoded = percent_encoding::percent_decode_str(last)@@ -149,7 +180,11 @@ pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {149
180
150
impl ThreadMembers<SessionMessageTransport> {181
impl ThreadMembers<SessionMessageTransport> {151
pub fn new(session: &Session) -> Self {182
pub fn new(session: &Session) -> Self {152
ThreadMembers::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)183
Self::with_region(session, DEFAULT_REGION)184
}185
186
pub fn with_region(session: &Session, region: &str) -> Self {187
ThreadMembers::with_transport(SessionMessageTransport::new(session), region)153
}188
}154
}189
}155
190
@@ -186,6 +221,20 @@ impl<T: MessageTransport> ThreadMembers<T> {186
.ok_or_else(|| Error::UnexpectedAnswer("thread creation has no location".into()))221
.ok_or_else(|| Error::UnexpectedAnswer("thread creation has no location".into()))187
}222
}188
223
224
/// Teams' `createThread` for a 1:1 unique-roster chat; answers with the new thread id.225
pub async fn create_one_to_one(&self, member_mris: &[String]) -> Result<String> {226
let request = create_one_to_one_request(&self.region, member_mris);227
let answer = self.transport.send(request).await?;228
ensure_success(&answer)?;229
created_thread_id(&answer.body).ok_or_else(|| {230
Error::UnexpectedAnswer(format!(231
"thread creation has no location (HTTP {} {})",232
answer.status,233
answer.body234
))235
})236
}237
189
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {238
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {190
let request = topic_request(&self.region, thread_id, topic);239
let request = topic_request(&self.region, thread_id, topic);191
ensure_success(&self.transport.send(request).await?)240
ensure_success(&self.transport.send(request).await?)@@ -215,6 +264,36 @@ mod tests {215
created_thread_id(&json!({"location": "https://x/v1/threads/oops"})),264
created_thread_id(&json!({"location": "https://x/v1/threads/oops"})),216
None265
None217
);266
);267
assert_eq!(268
created_thread_id(&json!({"id": "19:me_bot@unq.gbl.spaces"})).as_deref(),269
Some("19:me_bot@unq.gbl.spaces")270
);271
assert_eq!(272
created_thread_id(&json!({"threadId": "19:me_bot@unq.gbl.spaces"})).as_deref(),273
Some("19:me_bot@unq.gbl.spaces")274
);275
}276
277
#[test]278
fn a_one_to_one_thread_is_a_unique_roster_chat() {279
let request = create_one_to_one_request(280
"emea",281
&[282
"me".into(),283
"28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0".into(),284
],285
);286
let body = request.body.unwrap();287
assert_eq!(body["properties"]["fixedRoster"], true);288
assert_eq!(body["properties"]["uniquerosterthread"], true);289
assert_eq!(290
body["members"][0],291
json!({"id": "8:orgid:me", "role": "Admin"})292
);293
assert_eq!(294
body["members"][1],295
json!({"id": "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0", "role": "Admin"})296
);218
}297
}219
298
220
use std::sync::Mutex;299
use std::sync::Mutex;@@ -225,7 +225,10 @@
225
225
let body = text;
226
226
try { body = text ? JSON.parse(text) : null; } catch (error) {}
227
227
const location = response.headers.get('Location');
228
if (body === null && location) body = {location};
228
if (location) {
229
if (body === null || body === '') body = {location};
230
else if (typeof body === 'object' && body.location == null) body.location = location;
231
}
229
232
return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
230
233
} catch (error) {
231
234
return {status: 0, body: String(error)};
@@ -225,7 +225,10 @@225
let body = text;225
let body = text;226
try { body = text ? JSON.parse(text) : null; } catch (error) {}226
try { body = text ? JSON.parse(text) : null; } catch (error) {}227
const location = response.headers.get('Location');227
const location = response.headers.get('Location');228
if (body === null && location) body = {location};228
if (location) {229
if (body === null || body === '') body = {location};230
else if (typeof body === 'object' && body.location == null) body.location = location;231
}229
return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};232
return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};230
} catch (error) {233
} catch (error) {231
return {status: 0, body: String(error)};234
return {status: 0, body: String(error)};@@ -206,11 +206,20 @@ impl NativeHttp {
206
206
.and_then(|value| value.to_str().ok())
207
207
.map(str::to_owned);
208
208
let text = response.text().await?;
209
let body = if text.is_empty() {
210
location.map_or(Value::Null, |location| json!({ "location": location }))
209
let mut body = if text.is_empty() {
210
Value::Null
211
211
} else {
212
212
serde_json::from_str(&text).unwrap_or(Value::String(text))
213
213
};
214
if let Some(location) = location {
215
match &mut body {
216
Value::Null => body = json!({ "location": location }),
217
Value::Object(map) if !map.contains_key("location") => {
218
map.insert("location".into(), Value::String(location));
219
}
220
_ => {}
221
}
222
}
214
223
Ok(ApiResponse {
215
224
status,
216
225
body,
@@ -206,11 +206,20 @@ impl NativeHttp {206
.and_then(|value| value.to_str().ok())206
.and_then(|value| value.to_str().ok())207
.map(str::to_owned);207
.map(str::to_owned);208
let text = response.text().await?;208
let text = response.text().await?;209
let body = if text.is_empty() {209
let mut body = if text.is_empty() {210
location.map_or(Value::Null, |location| json!({ "location": location }))210
Value::Null211
} else {211
} else {212
serde_json::from_str(&text).unwrap_or(Value::String(text))212
serde_json::from_str(&text).unwrap_or(Value::String(text))213
};213
};214
if let Some(location) = location {215
match &mut body {216
Value::Null => body = json!({ "location": location }),217
Value::Object(map) if !map.contains_key("location") => {218
map.insert("location".into(), Value::String(location));219
}220
_ => {}221
}222
}214
Ok(ApiResponse {223
Ok(ApiResponse {215
status,224
status,216
body,225
body,