feat(channels): show and hide requests like Teams
- chatsvc ChannelVisibility: favorite, isGeneralChannelFavorite, isfollowed and membership expiration writes in Teams' order - join step skipped for private, explicitly added shared and moderator channels - request builder tests with a canned transport Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,497 @@
1
use serde_json::{Value, json};
2
use session::{Method, Request, Session};
3
4
use crate::error::Result;
5
use crate::members::{threads_url, user_mri};
6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7
use crate::pins::DEFAULT_REGION;
8
9
const FAVORITE_PROPERTY: &str = "favorite";
10
const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";
11
const FOLLOWED_PROPERTY: &str = "isfollowed";
12
const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";
13
const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";
14
const FAVORITE_MODE_MANUAL: &str = "manual";
15
const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum ChannelKind {
19
Standard,
20
Private,
21
Shared,
22
}
23
24
impl ChannelKind {
25
pub fn from_membership_type(membership_type: Option<&str>) -> Self {
26
match membership_type.map(str::to_ascii_lowercase).as_deref() {
27
Some("private") => ChannelKind::Private,
28
Some("shared") => ChannelKind::Shared,
29
_ => ChannelKind::Standard,
30
}
31
}
32
}
33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35
pub struct ChannelTarget<'a> {
36
pub channel_id: &'a str,
37
pub general: bool,
38
pub kind: ChannelKind,
39
}
40
41
/// The own member state of a channel conversation that decides Teams' show and hide steps.
42
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43
pub struct ChannelMembership {
44
pub moderator: bool,
45
pub explicitly_added: bool,
46
pub followed: bool,
47
}
48
49
fn truthy(value: Option<&Value>) -> bool {
50
match value {
51
Some(Value::Bool(flag)) => *flag,
52
Some(Value::String(text)) => !text.is_empty(),
53
Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),
54
Some(Value::Array(_) | Value::Object(_)) => true,
55
_ => false,
56
}
57
}
58
59
pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {
60
let member = conversation.get("memberProperties");
61
ChannelMembership {
62
moderator: truthy(member.and_then(|member| member.get("isModerator"))),
63
explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),
64
followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),
65
}
66
}
67
68
/// Teams joins the user to a standard channel thread before it changes the channel's visibility.
69
pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {
70
let permanently_joined = kind == ChannelKind::Private
71
|| (kind == ChannelKind::Shared && membership.explicitly_added)
72
|| membership.moderator;
73
!permanently_joined
74
}
75
76
pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {
77
if shown {
78
0
79
} else {
80
(now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS
81
}
82
}
83
84
pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {
85
transport: T,
86
conversations_url: String,
87
threads_url: String,
88
}
89
90
impl ChannelVisibility<SessionMessageTransport> {
91
pub fn new(session: &Session) -> Self {
92
ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
93
}
94
}
95
96
impl<T: MessageTransport> ChannelVisibility<T> {
97
pub fn with_transport(transport: T, region: &str) -> Self {
98
ChannelVisibility {
99
transport,
100
conversations_url: format!(
101
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
102
),
103
threads_url: threads_url(region),
104
}
105
}
106
107
pub fn conversation_request(&self, conversation_id: &str) -> Request {
108
Request::get(format!(
109
"{}/{}?view=msnp24Equivalent",
110
self.conversations_url,
111
encode(conversation_id)
112
))
113
}
114
115
fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {
116
Request::with_body(
117
Method::Put,
118
format!(
119
"{}/{}/properties?name={name}",
120
self.conversations_url,
121
encode(conversation_id)
122
),
123
json!({ name: value }),
124
)
125
}
126
127
pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {
128
let mut request =
129
self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));
130
if shown {
131
request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);
132
request
133
.headers
134
.push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));
135
}
136
request
137
}
138
139
pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
140
self.property_request(
141
team_thread_id,
142
GENERAL_FAVORITE_PROPERTY,
143
json!(shown.to_string()),
144
)
145
}
146
147
pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
148
self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))
149
}
150
151
pub fn unfollow_request(&self, channel_id: &str) -> Request {
152
self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))
153
}
154
155
pub fn membership_request(
156
&self,
157
channel_id: &str,
158
own_user_id: &str,
159
shown: bool,
160
now_ms: i64,
161
) -> Request {
162
Request::with_body(
163
Method::Put,
164
format!(
165
"{}/{}/members/{}",
166
self.threads_url,
167
encode(channel_id),
168
user_mri(own_user_id)
169
),
170
json!({ "expiration": membership_expiration(shown, now_ms) }),
171
)
172
}
173
174
/// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.
175
pub fn channel_requests(
176
&self,
177
target: &ChannelTarget<'_>,
178
membership: ChannelMembership,
179
own_user_id: &str,
180
shown: bool,
181
now_ms: i64,
182
) -> Vec<Request> {
183
if target.general {
184
return vec![self.general_favorite_request(target.channel_id, shown)];
185
}
186
let mut requests = Vec::new();
187
if joins_thread(target.kind, membership) {
188
requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));
189
}
190
requests.push(self.favorite_request(target.channel_id, shown));
191
if !shown || membership.followed {
192
requests.push(self.unfollow_request(target.channel_id));
193
}
194
requests
195
}
196
197
pub async fn set_channel_shown(
198
&self,
199
target: &ChannelTarget<'_>,
200
own_user_id: &str,
201
shown: bool,
202
now_ms: i64,
203
) -> Result<()> {
204
let membership = if target.general {
205
ChannelMembership::default()
206
} else {
207
let answer = self
208
.transport
209
.send(self.conversation_request(target.channel_id))
210
.await?;
211
ensure_success(&answer)?;
212
parse_channel_membership(&answer.body)
213
};
214
for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {
215
ensure_success(&self.transport.send(request).await?)?;
216
}
217
Ok(())
218
}
219
220
pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {
221
let answer = self
222
.transport
223
.send(self.team_favorite_request(team_thread_id, shown))
224
.await?;
225
ensure_success(&answer)
226
}
227
}
228
229
#[cfg(test)]
230
mod tests {
231
use std::collections::VecDeque;
232
use std::sync::Mutex;
233
234
use session::ApiResponse;
235
236
use super::*;
237
238
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";
239
const CHANNEL: &str = "19:abc@thread.tacv2";
240
const ENCODED: &str = "19%3Aabc%40thread.tacv2";
241
const NOW_MS: i64 = 1_791_368_000_500;
242
243
struct Canned {
244
requests: Mutex<Vec<Request>>,
245
answers: Mutex<VecDeque<(u16, Value)>>,
246
}
247
248
impl MessageTransport for &Canned {
249
async fn send(&self, request: Request) -> Result<ApiResponse> {
250
self.requests.lock().unwrap().push(request);
251
let (status, body) = self
252
.answers
253
.lock()
254
.unwrap()
255
.pop_front()
256
.unwrap_or((200, Value::Null));
257
Ok(ApiResponse {
258
status,
259
body,
260
retry_after: None,
261
})
262
}
263
}
264
265
fn canned(answers: Vec<(u16, Value)>) -> Canned {
266
Canned {
267
requests: Mutex::new(Vec::new()),
268
answers: Mutex::new(answers.into()),
269
}
270
}
271
272
fn standard() -> ChannelTarget<'static> {
273
ChannelTarget {
274
channel_id: CHANNEL,
275
general: false,
276
kind: ChannelKind::Standard,
277
}
278
}
279
280
fn summary(request: &Request) -> (String, String, Option<Value>) {
281
(
282
request.method.as_str().to_owned(),
283
request.url.clone(),
284
request.body.clone(),
285
)
286
}
287
288
#[test]
289
fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {
290
let transport = canned(Vec::new());
291
let client = ChannelVisibility::with_transport(&transport, "emea");
292
let requests = client.channel_requests(
293
&standard(),
294
ChannelMembership::default(),
295
"user-1",
296
true,
297
NOW_MS,
298
);
299
let summaries: Vec<_> = requests.iter().map(summary).collect();
300
assert_eq!(
301
summaries,
302
vec![
303
(
304
"PUT".to_owned(),
305
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
306
Some(json!({"expiration": 0})),
307
),
308
(
309
"PUT".to_owned(),
310
format!(
311
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"
312
),
313
Some(json!({"favorite": "true"})),
314
),
315
]
316
);
317
assert_eq!(
318
requests[1].headers,
319
vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]
320
);
321
}
322
323
#[test]
324
fn hiding_sets_a_two_week_expiration_and_unfollows() {
325
let transport = canned(Vec::new());
326
let client = ChannelVisibility::with_transport(&transport, "emea");
327
let requests = client.channel_requests(
328
&standard(),
329
ChannelMembership::default(),
330
"8:orgid:user-1",
331
false,
332
NOW_MS,
333
);
334
let summaries: Vec<_> = requests.iter().map(summary).collect();
335
assert_eq!(
336
summaries,
337
vec![
338
(
339
"PUT".to_owned(),
340
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
341
Some(json!({"expiration": 1_791_368_001 + 1_209_600})),
342
),
343
(
344
"PUT".to_owned(),
345
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
346
Some(json!({"favorite": "false"})),
347
),
348
(
349
"PUT".to_owned(),
350
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
351
Some(json!({"isfollowed": false})),
352
),
353
]
354
);
355
assert!(requests[1].headers.is_empty());
356
}
357
358
#[test]
359
fn moderators_and_private_members_skip_the_join_step() {
360
let transport = canned(Vec::new());
361
let client = ChannelVisibility::with_transport(&transport, "emea");
362
let moderator = ChannelMembership {
363
moderator: true,
364
..ChannelMembership::default()
365
};
366
let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);
367
assert_eq!(requests.len(), 1);
368
assert!(requests[0].url.contains("name=favorite"));
369
let private = ChannelTarget {
370
kind: ChannelKind::Private,
371
..standard()
372
};
373
assert!(!joins_thread(private.kind, ChannelMembership::default()));
374
let shared = ChannelMembership {
375
explicitly_added: true,
376
..ChannelMembership::default()
377
};
378
assert!(!joins_thread(ChannelKind::Shared, shared));
379
assert!(joins_thread(
380
ChannelKind::Shared,
381
ChannelMembership::default()
382
));
383
}
384
385
#[test]
386
fn showing_a_followed_channel_also_clears_the_follow() {
387
let transport = canned(Vec::new());
388
let client = ChannelVisibility::with_transport(&transport, "emea");
389
let followed = ChannelMembership {
390
moderator: true,
391
followed: true,
392
..ChannelMembership::default()
393
};
394
let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);
395
assert_eq!(requests.len(), 2);
396
assert!(requests[1].url.ends_with("name=isfollowed"));
397
}
398
399
#[test]
400
fn general_and_team_visibility_write_one_property() {
401
let transport = canned(Vec::new());
402
let client = ChannelVisibility::with_transport(&transport, "emea");
403
let general = ChannelTarget {
404
general: true,
405
..standard()
406
};
407
let requests =
408
client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);
409
assert_eq!(
410
requests.iter().map(summary).collect::<Vec<_>>(),
411
vec![(
412
"PUT".to_owned(),
413
format!(
414
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"
415
),
416
Some(json!({"isGeneralChannelFavorite": "false"})),
417
)]
418
);
419
let team = client.team_favorite_request(CHANNEL, true);
420
assert_eq!(
421
summary(&team),
422
(
423
"PUT".to_owned(),
424
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
425
Some(json!({"favorite": "true"})),
426
)
427
);
428
assert!(team.headers.is_empty());
429
}
430
431
#[test]
432
fn membership_follows_javascript_truthiness() {
433
let membership = parse_channel_membership(&json!({
434
"memberProperties": {"isModerator": true, "explicitlyAdded": "true"},
435
"properties": {"isfollowed": "false"},
436
}));
437
assert_eq!(
438
membership,
439
ChannelMembership {
440
moderator: true,
441
explicitly_added: true,
442
followed: true,
443
}
444
);
445
assert_eq!(
446
parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),
447
ChannelMembership::default()
448
);
449
assert_eq!(
450
ChannelKind::from_membership_type(Some("private")),
451
ChannelKind::Private
452
);
453
assert_eq!(
454
ChannelKind::from_membership_type(None),
455
ChannelKind::Standard
456
);
457
}
458
459
#[tokio::test]
460
async fn set_channel_shown_reads_the_conversation_first() {
461
let transport = canned(vec![(
462
200,
463
json!({"memberProperties": {"isModerator": true}}),
464
)]);
465
let client = ChannelVisibility::with_transport(&transport, "emea");
466
client
467
.set_channel_shown(&standard(), "user-1", false, NOW_MS)
468
.await
469
.unwrap();
470
let urls: Vec<String> = transport
471
.requests
472
.lock()
473
.unwrap()
474
.iter()
475
.map(|request| request.url.clone())
476
.collect();
477
assert_eq!(
478
urls,
479
vec![
480
format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),
481
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
482
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
483
]
484
);
485
}
486
487
#[tokio::test]
488
async fn a_failed_step_stops_the_chain() {
489
let transport = canned(vec![(200, json!({})), (403, json!({}))]);
490
let client = ChannelVisibility::with_transport(&transport, "emea");
491
let outcome = client
492
.set_channel_shown(&standard(), "user-1", true, NOW_MS)
493
.await;
494
assert!(outcome.is_err());
495
assert_eq!(transport.requests.lock().unwrap().len(), 2);
496
}
497
}
@@ -0,0 +1,497 @@1
use serde_json::{Value, json};2
use session::{Method, Request, Session};3
4
use crate::error::Result;5
use crate::members::{threads_url, user_mri};6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};7
use crate::pins::DEFAULT_REGION;8
9
const FAVORITE_PROPERTY: &str = "favorite";10
const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";11
const FOLLOWED_PROPERTY: &str = "isfollowed";12
const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";13
const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";14
const FAVORITE_MODE_MANUAL: &str = "manual";15
const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]18
pub enum ChannelKind {19
Standard,20
Private,21
Shared,22
}23
24
impl ChannelKind {25
pub fn from_membership_type(membership_type: Option<&str>) -> Self {26
match membership_type.map(str::to_ascii_lowercase).as_deref() {27
Some("private") => ChannelKind::Private,28
Some("shared") => ChannelKind::Shared,29
_ => ChannelKind::Standard,30
}31
}32
}33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq)]35
pub struct ChannelTarget<'a> {36
pub channel_id: &'a str,37
pub general: bool,38
pub kind: ChannelKind,39
}40
41
/// The own member state of a channel conversation that decides Teams' show and hide steps.42
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]43
pub struct ChannelMembership {44
pub moderator: bool,45
pub explicitly_added: bool,46
pub followed: bool,47
}48
49
fn truthy(value: Option<&Value>) -> bool {50
match value {51
Some(Value::Bool(flag)) => *flag,52
Some(Value::String(text)) => !text.is_empty(),53
Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),54
Some(Value::Array(_) | Value::Object(_)) => true,55
_ => false,56
}57
}58
59
pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {60
let member = conversation.get("memberProperties");61
ChannelMembership {62
moderator: truthy(member.and_then(|member| member.get("isModerator"))),63
explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),64
followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),65
}66
}67
68
/// Teams joins the user to a standard channel thread before it changes the channel's visibility.69
pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {70
let permanently_joined = kind == ChannelKind::Private71
|| (kind == ChannelKind::Shared && membership.explicitly_added)72
|| membership.moderator;73
!permanently_joined74
}75
76
pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {77
if shown {78
079
} else {80
(now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS81
}82
}83
84
pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {85
transport: T,86
conversations_url: String,87
threads_url: String,88
}89
90
impl ChannelVisibility<SessionMessageTransport> {91
pub fn new(session: &Session) -> Self {92
ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)93
}94
}95
96
impl<T: MessageTransport> ChannelVisibility<T> {97
pub fn with_transport(transport: T, region: &str) -> Self {98
ChannelVisibility {99
transport,100
conversations_url: format!(101
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"102
),103
threads_url: threads_url(region),104
}105
}106
107
pub fn conversation_request(&self, conversation_id: &str) -> Request {108
Request::get(format!(109
"{}/{}?view=msnp24Equivalent",110
self.conversations_url,111
encode(conversation_id)112
))113
}114
115
fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {116
Request::with_body(117
Method::Put,118
format!(119
"{}/{}/properties?name={name}",120
self.conversations_url,121
encode(conversation_id)122
),123
json!({ name: value }),124
)125
}126
127
pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {128
let mut request =129
self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));130
if shown {131
request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);132
request133
.headers134
.push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));135
}136
request137
}138
139
pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {140
self.property_request(141
team_thread_id,142
GENERAL_FAVORITE_PROPERTY,143
json!(shown.to_string()),144
)145
}146
147
pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {148
self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))149
}150
151
pub fn unfollow_request(&self, channel_id: &str) -> Request {152
self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))153
}154
155
pub fn membership_request(156
&self,157
channel_id: &str,158
own_user_id: &str,159
shown: bool,160
now_ms: i64,161
) -> Request {162
Request::with_body(163
Method::Put,164
format!(165
"{}/{}/members/{}",166
self.threads_url,167
encode(channel_id),168
user_mri(own_user_id)169
),170
json!({ "expiration": membership_expiration(shown, now_ms) }),171
)172
}173
174
/// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.175
pub fn channel_requests(176
&self,177
target: &ChannelTarget<'_>,178
membership: ChannelMembership,179
own_user_id: &str,180
shown: bool,181
now_ms: i64,182
) -> Vec<Request> {183
if target.general {184
return vec![self.general_favorite_request(target.channel_id, shown)];185
}186
let mut requests = Vec::new();187
if joins_thread(target.kind, membership) {188
requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));189
}190
requests.push(self.favorite_request(target.channel_id, shown));191
if !shown || membership.followed {192
requests.push(self.unfollow_request(target.channel_id));193
}194
requests195
}196
197
pub async fn set_channel_shown(198
&self,199
target: &ChannelTarget<'_>,200
own_user_id: &str,201
shown: bool,202
now_ms: i64,203
) -> Result<()> {204
let membership = if target.general {205
ChannelMembership::default()206
} else {207
let answer = self208
.transport209
.send(self.conversation_request(target.channel_id))210
.await?;211
ensure_success(&answer)?;212
parse_channel_membership(&answer.body)213
};214
for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {215
ensure_success(&self.transport.send(request).await?)?;216
}217
Ok(())218
}219
220
pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {221
let answer = self222
.transport223
.send(self.team_favorite_request(team_thread_id, shown))224
.await?;225
ensure_success(&answer)226
}227
}228
229
#[cfg(test)]230
mod tests {231
use std::collections::VecDeque;232
use std::sync::Mutex;233
234
use session::ApiResponse;235
236
use super::*;237
238
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";239
const CHANNEL: &str = "19:abc@thread.tacv2";240
const ENCODED: &str = "19%3Aabc%40thread.tacv2";241
const NOW_MS: i64 = 1_791_368_000_500;242
243
struct Canned {244
requests: Mutex<Vec<Request>>,245
answers: Mutex<VecDeque<(u16, Value)>>,246
}247
248
impl MessageTransport for &Canned {249
async fn send(&self, request: Request) -> Result<ApiResponse> {250
self.requests.lock().unwrap().push(request);251
let (status, body) = self252
.answers253
.lock()254
.unwrap()255
.pop_front()256
.unwrap_or((200, Value::Null));257
Ok(ApiResponse {258
status,259
body,260
retry_after: None,261
})262
}263
}264
265
fn canned(answers: Vec<(u16, Value)>) -> Canned {266
Canned {267
requests: Mutex::new(Vec::new()),268
answers: Mutex::new(answers.into()),269
}270
}271
272
fn standard() -> ChannelTarget<'static> {273
ChannelTarget {274
channel_id: CHANNEL,275
general: false,276
kind: ChannelKind::Standard,277
}278
}279
280
fn summary(request: &Request) -> (String, String, Option<Value>) {281
(282
request.method.as_str().to_owned(),283
request.url.clone(),284
request.body.clone(),285
)286
}287
288
#[test]289
fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {290
let transport = canned(Vec::new());291
let client = ChannelVisibility::with_transport(&transport, "emea");292
let requests = client.channel_requests(293
&standard(),294
ChannelMembership::default(),295
"user-1",296
true,297
NOW_MS,298
);299
let summaries: Vec<_> = requests.iter().map(summary).collect();300
assert_eq!(301
summaries,302
vec![303
(304
"PUT".to_owned(),305
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),306
Some(json!({"expiration": 0})),307
),308
(309
"PUT".to_owned(),310
format!(311
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"312
),313
Some(json!({"favorite": "true"})),314
),315
]316
);317
assert_eq!(318
requests[1].headers,319
vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]320
);321
}322
323
#[test]324
fn hiding_sets_a_two_week_expiration_and_unfollows() {325
let transport = canned(Vec::new());326
let client = ChannelVisibility::with_transport(&transport, "emea");327
let requests = client.channel_requests(328
&standard(),329
ChannelMembership::default(),330
"8:orgid:user-1",331
false,332
NOW_MS,333
);334
let summaries: Vec<_> = requests.iter().map(summary).collect();335
assert_eq!(336
summaries,337
vec![338
(339
"PUT".to_owned(),340
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),341
Some(json!({"expiration": 1_791_368_001 + 1_209_600})),342
),343
(344
"PUT".to_owned(),345
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),346
Some(json!({"favorite": "false"})),347
),348
(349
"PUT".to_owned(),350
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),351
Some(json!({"isfollowed": false})),352
),353
]354
);355
assert!(requests[1].headers.is_empty());356
}357
358
#[test]359
fn moderators_and_private_members_skip_the_join_step() {360
let transport = canned(Vec::new());361
let client = ChannelVisibility::with_transport(&transport, "emea");362
let moderator = ChannelMembership {363
moderator: true,364
..ChannelMembership::default()365
};366
let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);367
assert_eq!(requests.len(), 1);368
assert!(requests[0].url.contains("name=favorite"));369
let private = ChannelTarget {370
kind: ChannelKind::Private,371
..standard()372
};373
assert!(!joins_thread(private.kind, ChannelMembership::default()));374
let shared = ChannelMembership {375
explicitly_added: true,376
..ChannelMembership::default()377
};378
assert!(!joins_thread(ChannelKind::Shared, shared));379
assert!(joins_thread(380
ChannelKind::Shared,381
ChannelMembership::default()382
));383
}384
385
#[test]386
fn showing_a_followed_channel_also_clears_the_follow() {387
let transport = canned(Vec::new());388
let client = ChannelVisibility::with_transport(&transport, "emea");389
let followed = ChannelMembership {390
moderator: true,391
followed: true,392
..ChannelMembership::default()393
};394
let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);395
assert_eq!(requests.len(), 2);396
assert!(requests[1].url.ends_with("name=isfollowed"));397
}398
399
#[test]400
fn general_and_team_visibility_write_one_property() {401
let transport = canned(Vec::new());402
let client = ChannelVisibility::with_transport(&transport, "emea");403
let general = ChannelTarget {404
general: true,405
..standard()406
};407
let requests =408
client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);409
assert_eq!(410
requests.iter().map(summary).collect::<Vec<_>>(),411
vec![(412
"PUT".to_owned(),413
format!(414
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"415
),416
Some(json!({"isGeneralChannelFavorite": "false"})),417
)]418
);419
let team = client.team_favorite_request(CHANNEL, true);420
assert_eq!(421
summary(&team),422
(423
"PUT".to_owned(),424
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),425
Some(json!({"favorite": "true"})),426
)427
);428
assert!(team.headers.is_empty());429
}430
431
#[test]432
fn membership_follows_javascript_truthiness() {433
let membership = parse_channel_membership(&json!({434
"memberProperties": {"isModerator": true, "explicitlyAdded": "true"},435
"properties": {"isfollowed": "false"},436
}));437
assert_eq!(438
membership,439
ChannelMembership {440
moderator: true,441
explicitly_added: true,442
followed: true,443
}444
);445
assert_eq!(446
parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),447
ChannelMembership::default()448
);449
assert_eq!(450
ChannelKind::from_membership_type(Some("private")),451
ChannelKind::Private452
);453
assert_eq!(454
ChannelKind::from_membership_type(None),455
ChannelKind::Standard456
);457
}458
459
#[tokio::test]460
async fn set_channel_shown_reads_the_conversation_first() {461
let transport = canned(vec![(462
200,463
json!({"memberProperties": {"isModerator": true}}),464
)]);465
let client = ChannelVisibility::with_transport(&transport, "emea");466
client467
.set_channel_shown(&standard(), "user-1", false, NOW_MS)468
.await469
.unwrap();470
let urls: Vec<String> = transport471
.requests472
.lock()473
.unwrap()474
.iter()475
.map(|request| request.url.clone())476
.collect();477
assert_eq!(478
urls,479
vec![480
format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),481
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),482
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),483
]484
);485
}486
487
#[tokio::test]488
async fn a_failed_step_stops_the_chain() {489
let transport = canned(vec![(200, json!({})), (403, json!({}))]);490
let client = ChannelVisibility::with_transport(&transport, "emea");491
let outcome = client492
.set_channel_shown(&standard(), "user-1", true, NOW_MS)493
.await;494
assert!(outcome.is_err());495
assert_eq!(transport.requests.lock().unwrap().len(), 2);496
}497
}@@ -4,6 +4,7 @@ pub mod calendar;
4
4
pub mod calllog;
5
5
pub mod cards;
6
6
pub mod channel_notifications;
7
pub mod channel_visibility;
7
8
pub mod conversations;
8
9
pub mod drafts;
9
10
pub mod emotions;
@@ -45,6 +46,7 @@ pub use cards::{
45
46
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
46
47
};
47
48
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
49
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
48
50
pub use conversations::{ConversationState, Conversations};
49
51
pub use drafts::{ScheduledDraft, ScheduledDrafts};
50
52
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -4,6 +4,7 @@ pub mod calendar;4
pub mod calllog;4
pub mod calllog;5
pub mod cards;5
pub mod cards;6
pub mod channel_notifications;6
pub mod channel_notifications;7
pub mod channel_visibility;7
pub mod conversations;8
pub mod conversations;8
pub mod drafts;9
pub mod drafts;9
pub mod emotions;10
pub mod emotions;@@ -45,6 +46,7 @@ pub use cards::{45
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,46
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,46
};47
};47
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};48
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};49
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};48
pub use conversations::{ConversationState, Conversations};50
pub use conversations::{ConversationState, Conversations};49
pub use drafts::{ScheduledDraft, ScheduledDrafts};51
pub use drafts::{ScheduledDraft, ScheduledDrafts};50
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};52
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};