mattermost-tui 1.1.1

Keyboard-driven terminal client for Mattermost
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Mattermost REST client with automatic re-login.
//!
//! Everything it does is a read except `view`, `create_post`, `edit_post`, `delete_post`,
//! `react`, `unreact`, `create_direct`, `join`, `leave`, `set_status`, `pin` and `unpin`.

/// Wire types of the REST API.
pub mod types;

use std::sync::{Mutex, PoisonError};

use reqwest::{Method, RequestBuilder, Response, StatusCode};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::config::Credentials;
use types::{
    CategoryList, Channel, ChannelId, ChannelMember, Post, PostId, PostList, Reaction, Status,
    Team, TeamId, User, UserId, UserStatus,
};

/// Everything that can go wrong talking to a server.
#[derive(Debug, Error)]
pub enum Error {
    /// The request failed before a usable answer came back.
    #[error("request failed: {0}")]
    Http(#[from] reqwest::Error),
    /// The server answered with an error status.
    #[error("server answered {status}: {message}")]
    Status { status: u16, message: String },
    /// The server refused the login or password.
    #[error("login refused: {0}")]
    Login(String),
    /// The account has MFA enabled and no valid code was given.
    #[error("a multi-factor code is required")]
    MfaRequired,
    /// A successful login did not carry a session token.
    #[error("the server sent no session token")]
    NoToken,
}

#[derive(Deserialize)]
struct AppError {
    #[serde(default)]
    id: String,
    #[serde(default)]
    message: String,
}

#[derive(Serialize)]
struct LoginBody<'a> {
    login_id: &'a str,
    password: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    token: Option<&'a str>,
}

/// A connection to one server.
#[derive(Debug)]
pub struct Client {
    http: reqwest::Client,
    base: String,
    credentials: Credentials,
    token: Mutex<String>,
}

impl Client {
    /// Opens a session, logging in with a password or taking the token as is.
    ///
    /// # Errors
    /// Fails when the server is unreachable or refuses the login, with
    /// [`Error::MfaRequired`] when a code is needed.
    pub async fn connect(
        url: &str,
        credentials: Credentials,
        mfa: Option<&str>,
    ) -> Result<Self, Error> {
        let http = reqwest::Client::builder()
            .user_agent(concat!("mm/", env!("CARGO_PKG_VERSION")))
            .build()?;
        let base = format!("{}/api/v4", url.trim_end_matches('/'));
        let token = match &credentials {
            Credentials::Password { login, password } => {
                login_token(&http, &base, login, password, mfa).await?
            }
            Credentials::Token(token) => token.clone(),
        };
        Ok(Self {
            http,
            base,
            credentials,
            token: Mutex::new(token),
        })
    }

    /// The reader's own account.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn me(&self) -> Result<User, Error> {
        self.fetch(Method::GET, "/users/me", &[], None::<&()>).await
    }

    /// The teams the reader belongs to.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn teams(&self) -> Result<Vec<Team>, Error> {
        self.fetch(Method::GET, "/users/me/teams", &[], None::<&()>)
            .await
    }

    /// The reader's channels in a team, including direct and group messages.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn channels(&self, team: &TeamId) -> Result<Vec<Channel>, Error> {
        let path = format!("/users/me/teams/{}/channels", team.0);
        self.fetch(Method::GET, &path, &[], None::<&()>).await
    }

    /// The reader's memberships in a team, which hold the unread counts.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn members(&self, team: &TeamId) -> Result<Vec<ChannelMember>, Error> {
        let path = format!("/users/me/teams/{}/channels/members", team.0);
        self.fetch(Method::GET, &path, &[], None::<&()>).await
    }

    /// The sidebar categories of a team, which say which channels are shown.
    ///
    /// # Errors
    /// Fails on network or server errors, and on servers older than 5.26.
    pub async fn categories(&self, team: &TeamId) -> Result<CategoryList, Error> {
        let path = format!("/users/me/teams/{}/channels/categories", team.0);
        self.fetch(Method::GET, &path, &[], None::<&()>).await
    }

    /// Marks a channel as viewed, which is the only thing besides logging in that changes the server.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn view(&self, channel: &ChannelId, prev: Option<&ChannelId>) -> Result<(), Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            channel_id: &'a str,
            prev_channel_id: &'a str,
        }
        let body = Body {
            channel_id: &channel.0,
            prev_channel_id: prev.map_or("", |p| p.0.as_str()),
        };
        let _: serde_json::Value = self
            .fetch(Method::POST, "/channels/members/me/view", &[], Some(&body))
            .await?;
        Ok(())
    }

    /// Creates a post, as a reply in the thread of `root` when there is one.
    ///
    /// # Errors
    /// Fails on network or server errors, for example a message that is too long.
    pub async fn create_post(
        &self,
        channel: &ChannelId,
        message: &str,
        root: Option<&PostId>,
    ) -> Result<Post, Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            channel_id: &'a str,
            message: &'a str,
            root_id: &'a str,
        }
        let body = Body {
            channel_id: &channel.0,
            message,
            root_id: root.map_or("", |r| r.0.as_str()),
        };
        self.fetch(Method::POST, "/posts", &[], Some(&body)).await
    }

    /// Replaces the text of one of the reader's posts.
    ///
    /// # Errors
    /// Fails on network or server errors, and when the server does not allow the edit.
    pub async fn edit_post(&self, id: &PostId, message: &str) -> Result<Post, Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            message: &'a str,
        }
        let path = format!("/posts/{}/patch", id.0);
        self.fetch(Method::PUT, &path, &[], Some(&Body { message }))
            .await
    }

    /// Deletes one of the reader's posts.
    ///
    /// # Errors
    /// Fails on network or server errors, and when the server does not allow the deletion.
    pub async fn delete_post(&self, id: &PostId) -> Result<(), Error> {
        let path = format!("/posts/{}", id.0);
        let _: serde_json::Value = self.fetch(Method::DELETE, &path, &[], None::<&()>).await?;
        Ok(())
    }

    /// Adds the reader's reaction to a post.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn react(
        &self,
        user: &UserId,
        post: &PostId,
        emoji: &str,
    ) -> Result<Reaction, Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            user_id: &'a str,
            post_id: &'a str,
            emoji_name: &'a str,
        }
        let body = Body {
            user_id: &user.0,
            post_id: &post.0,
            emoji_name: emoji,
        };
        self.fetch(Method::POST, "/reactions", &[], Some(&body))
            .await
    }

    /// Takes the reader's reaction off a post.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn unreact(&self, user: &UserId, post: &PostId, emoji: &str) -> Result<(), Error> {
        let path = format!("/users/{}/posts/{}/reactions/{emoji}", user.0, post.0);
        let _: serde_json::Value = self.fetch(Method::DELETE, &path, &[], None::<&()>).await?;
        Ok(())
    }

    /// Opens the direct conversation between two users, which posts nothing.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn create_direct(&self, me: &UserId, other: &UserId) -> Result<Channel, Error> {
        let ids = [&me.0, &other.0];
        self.fetch(Method::POST, "/channels/direct", &[], Some(&ids))
            .await
    }

    /// Makes the reader a member of a channel.
    ///
    /// # Errors
    /// Fails on network or server errors, and when the channel cannot be joined.
    pub async fn join(&self, channel: &ChannelId, user: &UserId) -> Result<(), Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            user_id: &'a str,
        }
        let path = format!("/channels/{}/members", channel.0);
        let body = Body { user_id: &user.0 };
        let _: serde_json::Value = self.fetch(Method::POST, &path, &[], Some(&body)).await?;
        Ok(())
    }

    /// Takes the reader out of a channel.
    ///
    /// # Errors
    /// Fails on network or server errors, and when the channel cannot be left.
    pub async fn leave(&self, channel: &ChannelId, user: &UserId) -> Result<(), Error> {
        let path = format!("/channels/{}/members/{}", channel.0, user.0);
        let _: serde_json::Value = self.fetch(Method::DELETE, &path, &[], None::<&()>).await?;
        Ok(())
    }

    /// Sets the presence of the reader.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn set_status(&self, user: &UserId, status: Status) -> Result<(), Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            user_id: &'a str,
            status: &'a str,
        }
        let path = format!("/users/{}/status", user.0);
        let body = Body {
            user_id: &user.0,
            status: status.word(),
        };
        let _: serde_json::Value = self.fetch(Method::PUT, &path, &[], Some(&body)).await?;
        Ok(())
    }

    /// Pins a post to its channel, or unpins it.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn pin(&self, post: &PostId, pinned: bool) -> Result<(), Error> {
        let path = format!("/posts/{}/{}", post.0, if pinned { "pin" } else { "unpin" });
        let _: serde_json::Value = self.fetch(Method::POST, &path, &[], None::<&()>).await?;
        Ok(())
    }

    /// The account with this username.
    ///
    /// # Errors
    /// Fails on network or server errors, and when nobody has that name.
    pub async fn user_named(&self, name: &str) -> Result<User, Error> {
        let path = format!("/users/username/{name}");
        self.fetch(Method::GET, &path, &[], None::<&()>).await
    }

    /// A channel of a team by its name in the address.
    ///
    /// # Errors
    /// Fails on network or server errors, and when the team has no such channel.
    pub async fn channel_named(&self, team: &TeamId, name: &str) -> Result<Channel, Error> {
        let path = format!("/teams/{}/channels/name/{name}", team.0);
        self.fetch(Method::GET, &path, &[], None::<&()>).await
    }

    /// The first 200 members of a channel.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn channel_users(&self, channel: &ChannelId) -> Result<Vec<User>, Error> {
        let query = [
            ("in_channel", channel.0.clone()),
            ("per_page", "200".to_owned()),
        ];
        self.fetch(Method::GET, "/users", &query, None::<&()>).await
    }

    /// Whether each of the users is around.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn statuses(&self, ids: &[UserId]) -> Result<Vec<UserStatus>, Error> {
        self.fetch(Method::POST, "/users/status/ids", &[], Some(ids))
            .await
    }

    /// The content of an attached file.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn download(&self, file: &str) -> Result<Vec<u8>, Error> {
        let path = format!("/files/{file}");
        let resp = self.answer(Method::GET, &path, &[], None::<&()>).await?;
        Ok(resp.bytes().await?.to_vec())
    }

    /// Any read-only answer as it came, for the trace asked for with `MM_DEBUG`.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn inspect(&self, path: &str) -> Result<serde_json::Value, Error> {
        self.fetch(Method::GET, path, &[], None::<&()>).await
    }

    /// A page of posts, newest first, optionally those older than `before`.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn posts(
        &self,
        channel: &ChannelId,
        before: Option<&PostId>,
        per_page: u32,
    ) -> Result<PostList, Error> {
        let mut query = vec![("per_page", per_page.to_string())];
        if let Some(before) = before {
            query.push(("before", before.0.clone()));
        }
        let path = format!("/channels/{}/posts", channel.0);
        self.fetch(Method::GET, &path, &query, None::<&()>).await
    }

    /// Resolves user ids into accounts.
    ///
    /// # Errors
    /// Fails on network or server errors.
    pub async fn users(&self, ids: &[UserId]) -> Result<Vec<User>, Error> {
        self.fetch(Method::POST, "/users/ids", &[], Some(ids)).await
    }

    async fn fetch<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, String)],
        body: Option<&(impl Serialize + ?Sized)>,
    ) -> Result<T, Error> {
        Ok(self.answer(method, path, query, body).await?.json().await?)
    }

    async fn answer(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, String)],
        body: Option<&(impl Serialize + ?Sized)>,
    ) -> Result<Response, Error> {
        let url = format!("{}{path}", self.base);
        let build = |token: String| {
            let req = self
                .http
                .request(method.clone(), &url)
                .query(query)
                .bearer_auth(token);
            match body {
                Some(body) => req.json(body),
                None => req,
            }
        };
        let mut resp = send(build(self.token())).await?;
        if resp.status() == StatusCode::UNAUTHORIZED && self.relogin().await? {
            resp = send(build(self.token())).await?;
        }
        if resp.status().is_success() {
            return Ok(resp);
        }
        Err(status_error(resp).await)
    }

    /// Logs in again after the session expired; false when there is no password to do it with.
    ///
    /// # Errors
    /// Fails when the server refuses the login.
    pub async fn relogin(&self) -> Result<bool, Error> {
        let Credentials::Password { login, password } = &self.credentials else {
            return Ok(false);
        };
        let token = login_token(&self.http, &self.base, login, password, None).await?;
        *self.token.lock().unwrap_or_else(PoisonError::into_inner) = token;
        Ok(true)
    }

    /// The address of the event stream.
    pub fn ws_url(&self) -> String {
        let (secure, rest) = match self.base.strip_prefix("https://") {
            Some(rest) => (true, rest),
            None => (false, self.base.trim_start_matches("http://")),
        };
        format!("{}://{rest}/websocket", if secure { "wss" } else { "ws" })
    }

    /// The current session token.
    pub fn token(&self) -> String {
        self.token
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
}

async fn send(req: RequestBuilder) -> Result<Response, Error> {
    Ok(req.send().await?)
}

async fn status_error(resp: Response) -> Error {
    let status = resp.status().as_u16();
    let message = match resp.json::<AppError>().await {
        Ok(e) => e.message,
        Err(_) => String::new(),
    };
    Error::Status { status, message }
}

async fn login_token(
    http: &reqwest::Client,
    base: &str,
    login: &str,
    password: &str,
    mfa: Option<&str>,
) -> Result<String, Error> {
    let body = LoginBody {
        login_id: login,
        password,
        token: mfa,
    };
    let resp = http
        .post(format!("{base}/users/login"))
        .json(&body)
        .send()
        .await?;
    if resp.status().is_success() {
        let token = resp.headers().get("token").and_then(|v| v.to_str().ok());
        return token.map(str::to_owned).ok_or(Error::NoToken);
    }
    let status = resp.status();
    let err = resp.json::<AppError>().await.unwrap_or(AppError {
        id: String::new(),
        message: String::new(),
    });
    if err.id.contains("mfa") {
        return Err(Error::MfaRequired);
    }
    if status.is_client_error() {
        return Err(Error::Login(err.message));
    }
    Err(Error::Status {
        status: status.as_u16(),
        message: err.message,
    })
}

#[cfg(test)]
mod tests {
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;

    fn password() -> Credentials {
        Credentials::Password {
            login: "paul".into(),
            password: "hunter2".into(),
        }
    }

    fn login_ok(token: &str) -> Mock {
        Mock::given(method("POST"))
            .and(path("/api/v4/users/login"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("Token", token)
                    .set_body_json(serde_json::json!({"id": "u1", "username": "paul"})),
            )
    }

    fn me_ok(token: &str) -> Mock {
        Mock::given(method("GET"))
            .and(path("/api/v4/users/me"))
            .and(header("authorization", format!("Bearer {token}").as_str()))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "u1", "username": "paul"})),
            )
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn login_takes_token_from_header() {
        let server = MockServer::start().await;
        login_ok("tok1").mount(&server).await;
        me_ok("tok1").mount(&server).await;
        let client = Client::connect(&server.uri(), password(), None)
            .await
            .unwrap();
        assert_eq!(client.me().await.unwrap().username, "paul");
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn mfa_is_reported() {
        let server = MockServer::start().await;
        Mock::given(path("/api/v4/users/login"))
            .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
                "id": "mfa.validate_token.authenticate.app_error",
                "message": "Invalid MFA token."
            })))
            .mount(&server)
            .await;
        let err = Client::connect(&server.uri(), password(), None)
            .await
            .unwrap_err();
        assert!(matches!(err, Error::MfaRequired));
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn bad_password_is_refused() {
        let server = MockServer::start().await;
        Mock::given(path("/api/v4/users/login"))
            .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
                "id": "api.user.login.invalid_credentials_email_username",
                "message": "Enter a valid email or username."
            })))
            .mount(&server)
            .await;
        let err = Client::connect(&server.uri(), password(), None)
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Login(_)));
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn expired_session_logs_in_again() {
        let server = MockServer::start().await;
        login_ok("tok1").up_to_n_times(1).mount(&server).await;
        login_ok("tok2").mount(&server).await;
        Mock::given(path("/api/v4/users/me"))
            .and(header("authorization", "Bearer tok1"))
            .respond_with(ResponseTemplate::new(401))
            .mount(&server)
            .await;
        me_ok("tok2").mount(&server).await;
        let client = Client::connect(&server.uri(), password(), None)
            .await
            .unwrap();
        assert_eq!(client.me().await.unwrap().username, "paul");
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn second_rejection_is_an_error() {
        let server = MockServer::start().await;
        login_ok("tok1").mount(&server).await;
        Mock::given(path("/api/v4/users/me"))
            .respond_with(ResponseTemplate::new(401))
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), password(), None)
            .await
            .unwrap();
        assert!(matches!(
            client.me().await,
            Err(Error::Status { status: 401, .. })
        ));
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn token_is_used_without_login() {
        let server = MockServer::start().await;
        me_ok("pat").mount(&server).await;
        let client = Client::connect(&server.uri(), Credentials::Token("pat".into()), None)
            .await
            .unwrap();
        assert_eq!(client.me().await.unwrap().id, UserId("u1".into()));
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn view_sends_the_channel_and_the_previous_one() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v4/channels/members/me/view"))
            .and(wiremock::matchers::body_json(
                serde_json::json!({"channel_id": "c2", "prev_channel_id": "c1"}),
            ))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"status": "OK", "last_viewed_at_times": {}})),
            )
            .expect(1)
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        client
            .view(&ChannelId("c2".into()), Some(&ChannelId("c1".into())))
            .await
            .unwrap();
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn posts_ask_for_the_page_before_a_post() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v4/channels/c1/posts"))
            .and(wiremock::matchers::query_param("before", "p9"))
            .and(wiremock::matchers::query_param("per_page", "20"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"order": [], "posts": {}})),
            )
            .expect(1)
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        let list = client
            .posts(&ChannelId("c1".into()), Some(&PostId("p9".into())), 20)
            .await
            .unwrap();
        assert!(list.order.is_empty());
    }

    fn post_json(id: &str) -> serde_json::Value {
        serde_json::json!({"id": id, "create_at": 1, "user_id": "u1", "channel_id": "c1", "message": "hi"})
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn writing_calls_send_the_documented_bodies() {
        use wiremock::matchers::body_json;
        let server = MockServer::start().await;
        for (verb, route, body) in [
            (
                "POST",
                "/api/v4/posts",
                serde_json::json!({"channel_id": "c1", "message": "hi", "root_id": ""}),
            ),
            (
                "POST",
                "/api/v4/posts",
                serde_json::json!({"channel_id": "c1", "message": "re", "root_id": "p0"}),
            ),
            (
                "PUT",
                "/api/v4/posts/p1/patch",
                serde_json::json!({"message": "fix"}),
            ),
        ] {
            Mock::given(method(verb))
                .and(path(route))
                .and(body_json(body))
                .respond_with(ResponseTemplate::new(200).set_body_json(post_json("p1")))
                .expect(1)
                .mount(&server)
                .await;
        }
        Mock::given(method("DELETE"))
            .and(path("/api/v4/posts/p1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"status": "OK"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        let channel = ChannelId("c1".into());
        client.create_post(&channel, "hi", None).await.unwrap();
        client
            .create_post(&channel, "re", Some(&PostId("p0".into())))
            .await
            .unwrap();
        client.edit_post(&PostId("p1".into()), "fix").await.unwrap();
        client.delete_post(&PostId("p1".into())).await.unwrap();
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn reactions_and_presence_calls_send_the_documented_requests() {
        use wiremock::matchers::{body_json, query_param};
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v4/reactions"))
            .and(body_json(
                serde_json::json!({"user_id": "u1", "post_id": "p1", "emoji_name": "+1"}),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"user_id": "u1", "post_id": "p1", "emoji_name": "+1"}),
            ))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("DELETE"))
            .and(path("/api/v4/users/u1/posts/p1/reactions/+1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"status": "OK"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/api/v4/users"))
            .and(query_param("in_channel", "c1"))
            .and(query_param("per_page", "200"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"id": "u2", "username": "ana"}])),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v4/users/status/ids"))
            .and(body_json(serde_json::json!(["u2"])))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!([{"user_id": "u2", "status": "away", "last_activity_at": 1}]),
            ))
            .expect(1)
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        let (me, post) = (UserId("u1".into()), PostId("p1".into()));
        assert_eq!(
            client.react(&me, &post, "+1").await.unwrap().emoji_name,
            "+1"
        );
        client.unreact(&me, &post, "+1").await.unwrap();
        let users = client.channel_users(&ChannelId("c1".into())).await.unwrap();
        assert_eq!(users[0].username, "ana");
        let statuses = client.statuses(&[UserId("u2".into())]).await.unwrap();
        assert_eq!(statuses[0].status, "away");
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn users_posts_ids() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v4/users/ids"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"id": "u2", "username": "ana"}])),
            )
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        let users = client.users(&[UserId("u2".into())]).await.unwrap();
        assert_eq!(users[0].username, "ana");
    }

    #[ignore = "needs a local socket"]
    #[tokio::test]
    async fn a_file_comes_down_as_bytes() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v4/files/f1"))
            .and(header("authorization", "Bearer t"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![0u8, 159, 146, 150]))
            .mount(&server)
            .await;
        let client = Client::connect(&server.uri(), Credentials::Token("t".into()), None)
            .await
            .unwrap();
        assert_eq!(client.download("f1").await.unwrap(), [0, 159, 146, 150]);
        assert!(client.download("missing").await.is_err());
    }
}