zulip-api 0.0.8

Client library for interacting with the Zulip API
Documentation
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! Zulip API client.

use crate::api::{ApiKey, User};
use crate::error::Error;
use crate::result::Result;
use crate::{
    delete_message, edit_message, emoji_reaction, fetch_api_key, get_file_temporary_url,
    get_message, get_message_history, get_messages, get_read_receipts, mark_all_as_read,
    mark_stream_as_read, mark_topic_as_read, matches_narrow, register, render, report_message,
    send_message, update_message_flags, update_message_flags_narrow, upload_file, version,
};

mod endpoint;
mod tus;

pub use endpoint::Endpoint;

/// Represents the HTTP request timeout.
pub const TIMEOUT: u64 = 5;

/// Represents the main client for interacting with Zulip servers.
#[derive(Clone, Debug)]
pub struct Client {
    http: reqwest::Client,
    url: hyper::Uri,
    user: User,
    key: ApiKey,
}

impl Client {
    /// Creates a new [Client] from the provided Zulip server URL.
    pub fn new(url: hyper::Uri, user: User, key: ApiKey) -> Result<Self> {
        Ok(Self {
            http: Self::http_client()?,
            url,
            user,
            key,
        })
    }

    /// Builder function that sets the HTTP client.
    pub fn with_http(self, http: reqwest::Client) -> Self {
        Self { http, ..self }
    }

    /// Attempts to read [Client] configuration from a `zuliprc` INI file.
    pub fn from_zuliprc(path: &str) -> Result<Self> {
        let cfg = ini!(path);

        let url = cfg["api"]["site"]
            .as_deref()
            .ok_or(Error::io_other("missing zuliprc `site`"))
            .and_then(|u| u.parse().map_err(|err| Error::io_other(format!("{err}"))))?;

        let user = cfg["api"]["email"]
            .as_deref()
            .map(User::from)
            .ok_or(Error::io_other("missing zuliprc `email`"))?;

        let key = cfg["api"]["key"]
            .as_deref()
            .map(ApiKey::from)
            .ok_or(Error::io_other("missing zuliprc `key`"))?;

        Self::new(url, user, key)
    }

    /// Creates a HTTP client for making requests to the Zulip API server.
    pub fn http_client() -> Result<reqwest::Client> {
        let builder = reqwest::Client::builder().user_agent(Self::user_agent());

        #[cfg(target_family = "wasm")]
        {
            builder.build().map_err(Error::from)
        }
        #[cfg(all(not(target_family = "wasm"), feature = "dev"))]
        {
            builder
                .danger_accept_invalid_certs(true)
                .timeout(std::time::Duration::from_secs(TIMEOUT))
                .use_rustls_tls()
                .build()
                .map_err(Error::from)
        }
        #[cfg(all(not(target_family = "wasm"), not(feature = "dev")))]
        {
            builder
                .timeout(std::time::Duration::from_secs(TIMEOUT))
                .use_rustls_tls()
                .build()
                .map_err(Error::from)
        }
    }

    /// Gets the [Client]'s `UserAgent`.
    pub fn user_agent() -> String {
        format!("ZulipRust/{}", version())
    }

    /// Gets the `Authorization` header.
    pub fn auth_header(&self) -> String {
        use base64::{Base64, Encoding};

        let b64 = Base64::encode_string(
            format!("{}:{}", self.user.as_str(), self.key.as_str()).as_bytes(),
        );

        format!("Basic {b64}")
    }

    /// Loads a page from the Zulip.
    ///
    /// - `path`: optional path of the page to load, empty string loads the base path
    pub async fn load_page(&self, path: &str) -> Result<String> {
        let url = if path.is_empty() {
            self.base_url()
        } else {
            format!("{}/{path}", self.base_url())
        };

        let res = self
            .http
            .get(url)
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Send message response: {body}");

        Ok(body.into())
    }

    /// Sends a message to the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::send_message;
    /// use zulip_api::message::{MessageTo, MessageType};
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = send_message::Request::new()
    ///     .with_msg_type(MessageType::Channel)
    ///     .with_topic("test topic")
    ///     .with_to(MessageTo::ChannelName("general".into()))
    ///     .with_content("test message".to_string());
    ///
    /// let res = client.send_message(&req).await.unwrap();
    ///
    /// println!("Send message response: {res:?}");
    /// # };
    /// ```
    pub async fn send_message(
        &self,
        msg: &send_message::Request,
    ) -> Result<send_message::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::SendMessage))
            .header("Authorization", self.auth_header())
            .form(msg)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Send message response: {body}");

        serde_json::from_str::<send_message::Response>(body).map_err(Error::from)
    }

    /// Gets a list of messages from the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::get_messages;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = get_messages::Request::new();
    /// let res = client.get_messages(&req).await.unwrap();
    ///
    /// println!("Get messages response: {res:?}");
    /// # };
    /// ```
    pub async fn get_messages(
        &self,
        req: &get_messages::Request,
    ) -> Result<get_messages::Response> {
        let res = self
            .http
            .get(self.endpoint(Endpoint::GetMessages))
            .header("Authorization", self.auth_header())
            .query(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Get messages response: {body}");

        serde_json::from_str::<get_messages::Response>(body).map_err(Error::from)
    }

    /// Uploads a file to the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::upload_file;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = upload_file::Request::new().with_file_path("/path/to/file.txt");
    /// let res = client.upload_file(&req).await.unwrap();
    ///
    /// println!("Upload file response: {res}");
    /// # };
    /// ```
    pub async fn upload_file(&self, req: &upload_file::Request) -> Result<upload_file::Response> {
        let file_path = req.file_path();
        let md = std::fs::metadata(file_path)?;
        let file_len = md.len() as usize;
        let max_file_len = upload_file::LARGE_FILE;

        if file_len >= max_file_len {
            self.tus_create_and_upload(file_path).await
        } else {
            log::debug!("Sending {file_path}, length: {file_len} using the normal upload");

            let form = reqwest::multipart::Form::new()
                .file("filename", file_path)
                .await?;

            let res = self
                .http
                .post(self.endpoint(Endpoint::UploadFile))
                .header("Authorization", self.auth_header())
                .multipart(form)
                .send()
                .await?;

            let bytes = res.bytes().await?;
            let body = str::from_utf8(&bytes[..])?;

            log::debug!("Upload file response: {body}");

            serde_json::from_str::<upload_file::Response>(body).map_err(Error::from)
        }
    }

    /// Get a temporary URL for access to an [uploaded file](https://zulip.com/api/upload-file) that doesn't require authentication.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::{get_file_temporary_url, upload_file};
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = upload_file::Request::new().with_file_path("/path/to/file.txt");
    /// let res = client.upload_file(&req).await.unwrap();
    ///
    /// println!("Upload file response: {res}");
    ///
    /// let req = get_file_temporary_url::Request::new()
    ///     .with_realm_id(res.realm_id().unwrap())
    ///     .with_filename(res.filename_path().unwrap());
    ///
    /// let res = client.get_file_temporary_url(&req).await.unwrap();
    ///
    /// println!("Get file temporary URL response: {res}");
    /// # };
    /// ```
    pub async fn get_file_temporary_url(
        &self,
        req: &get_file_temporary_url::Request,
    ) -> Result<get_file_temporary_url::Response> {
        let endpoint = self.endpoint(Endpoint::UploadFile);
        let realm_id = req.realm_id();
        let filename = req.filename();

        let res = self
            .http
            .get(format!("{endpoint}/{realm_id}/{filename}"))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Upload file response: {body}");

        serde_json::from_str::<get_file_temporary_url::Response>(body).map_err(Error::from)
    }

    /// Edit a message on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::edit_message;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = edit_message::Request::new()
    ///     .with_message_id(1)
    ///     .with_content("edited content");
    ///
    /// let res = client.edit_message(&req).await.unwrap();
    ///
    /// println!("Edit message response: {res:?}");
    /// # };
    /// ```
    pub async fn edit_message(
        &self,
        req: &edit_message::Request,
    ) -> Result<edit_message::Response> {
        let endpoint = self.endpoint(Endpoint::EditMessage);
        let msg_id = req.message_id();

        let res = self
            .http
            .patch(format!("{endpoint}/{msg_id}"))
            .header("Authorization", self.auth_header())
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Edit message response: {body}");

        serde_json::from_str::<edit_message::Response>(body).map_err(Error::from)
    }

    /// Delete a message on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::delete_message;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = delete_message::Request::new()
    ///     .with_message_id(1);
    ///
    /// let res = client.delete_message(&req).await.unwrap();
    ///
    /// println!("Delete message response: {res:?}");
    /// # };
    /// ```
    pub async fn delete_message(
        &self,
        req: &delete_message::Request,
    ) -> Result<delete_message::Response> {
        let endpoint = self.endpoint(Endpoint::DeleteMessage);
        let msg_id = req.message_id();

        let res = self
            .http
            .delete(format!("{endpoint}/{msg_id}"))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Delete message response: {body}");

        serde_json::from_str::<delete_message::Response>(body).map_err(Error::from)
    }

    /// Gets a message on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::get_message;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = get_message::Request::new()
    ///     .with_message_id(1);
    ///
    /// let res = client.get_message(&req).await.unwrap();
    ///
    /// println!("Get message response: {res:?}");
    /// # };
    /// ```
    pub async fn get_message(&self, req: &get_message::Request) -> Result<get_message::Response> {
        let endpoint = self.endpoint(Endpoint::GetMessage);
        let msg_id = req.message_id();

        let res = self
            .http
            .get(format!("{endpoint}/{msg_id}"))
            .header("Authorization", self.auth_header())
            .query(&req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Get message response: {body}");

        serde_json::from_str::<get_message::Response>(body).map_err(Error::from)
    }

    /// Gets a message edit history on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::get_message_history;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = get_message_history::Request::new()
    ///     .with_message_id(1);
    ///
    /// let res = client.get_message_history(&req).await.unwrap();
    ///
    /// println!("Get message history response: {res:?}");
    /// # };
    /// ```
    pub async fn get_message_history(
        &self,
        req: &get_message_history::Request,
    ) -> Result<get_message_history::Response> {
        let endpoint = self.endpoint(Endpoint::GetMessageHistory);
        let msg_id = req.message_id();

        let res = self
            .http
            .get(format!("{endpoint}/{msg_id}/history"))
            .header("Authorization", self.auth_header())
            .query(&req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Get message history response: {body}");

        serde_json::from_str::<get_message_history::Response>(body).map_err(Error::from)
    }

    /// Reports a message for moderation on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::{report_message, ReportType};
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = report_message::Request::new()
    ///     .with_message_id(1)
    ///     .with_report_type(ReportType::Other)
    ///     .with_description("This message insults and mocks Frodo, which is against the code of conduct.");
    ///
    /// let res = client.report_message(&req).await.unwrap();
    ///
    /// println!("Report message response: {res:?}");
    /// # };
    /// ```
    pub async fn report_message(
        &self,
        req: &report_message::Request,
    ) -> Result<report_message::Response> {
        let endpoint = self.endpoint(Endpoint::ReportMessage);
        let msg_id = req.message_id();

        let mut form = reqwest::multipart::Form::new().text("report_type", req.report_type());

        if let Some(description) = req.description() {
            form = form.text("description", description.to_string());
        }

        let res = self
            .http
            .post(format!("{endpoint}/{msg_id}/report"))
            .header("Authorization", self.auth_header())
            .multipart(form)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Get message response: {body}");

        serde_json::from_str::<report_message::Response>(body).map_err(Error::from)
    }

    /// Gets narrow matches on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::filter::{Narrow, Operand, Operator};
    /// use zulip_api::matches_narrow;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let msg_ids = [1u64];
    /// let narrow = [Narrow::new()
    ///     .with_operator(Operator::Has)
    ///     .with_operand(Operand::text("link"))];
    ///
    /// let req = matches_narrow::Request::new()
    ///     .with_msg_ids(msg_ids.as_ref())
    ///     .with_narrow(narrow.as_ref());
    ///
    /// let res = client.matches_narrow(&req).await.unwrap();
    ///
    /// println!("Matches narrow response: {res:?}");
    /// # };
    /// ```
    pub async fn matches_narrow(
        &self,
        req: &matches_narrow::Request,
    ) -> Result<matches_narrow::Response> {
        let res = self
            .http
            .get(self.endpoint(Endpoint::MatchesNarrow))
            .header("Authorization", self.auth_header())
            .query(&[("msg_ids", serde_json::to_string(req.msg_ids())?)])
            .query(&[("narrow", serde_json::to_string(req.narrow())?)])
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Matches narrow response: {body}");

        serde_json::from_str::<matches_narrow::Response>(body).map_err(Error::from)
    }

    /// Adds an emoji reaction to a message on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::emoji_reaction;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = emoji_reaction::Request::new()
    ///     .with_message_id(1)
    ///     .with_emoji_name("+1");
    ///
    /// let res = client.add_reaction(&req).await.unwrap();
    ///
    /// println!("Add emoji reaction response: {res:?}");
    /// # };
    /// ```
    pub async fn add_reaction(
        &self,
        req: &emoji_reaction::Request,
    ) -> Result<emoji_reaction::Response> {
        let url = format!(
            "{}/{}/reactions",
            self.endpoint(Endpoint::Reaction),
            req.message_id()
        );

        let res = self
            .http
            .post(url)
            .header("Authorization", self.auth_header())
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Add emoji reaction response: {body}");

        serde_json::from_str::<emoji_reaction::Response>(body).map_err(Error::from)
    }

    /// Removes an emoji reaction from a message on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::emoji_reaction;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = emoji_reaction::Request::new()
    ///     .with_message_id(1)
    ///     .with_emoji_name("+1");
    ///
    /// let res = client.remove_reaction(&req).await.unwrap();
    ///
    /// println!("Remove emoji reaction response: {res:?}");
    /// # };
    /// ```
    pub async fn remove_reaction(
        &self,
        req: &emoji_reaction::Request,
    ) -> Result<emoji_reaction::Response> {
        let url = format!(
            "{}/{}/reactions",
            self.endpoint(Endpoint::Reaction),
            req.message_id()
        );

        let res = self
            .http
            .delete(url)
            .header("Authorization", self.auth_header())
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Remove emoji reaction response: {body}");

        serde_json::from_str::<emoji_reaction::Response>(body).map_err(Error::from)
    }

    /// Renders a message from the Zulip server into HTML.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::render;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = render::Request::new()
    ///     .with_content("test message");
    ///
    /// let res = client.render(&req).await.unwrap();
    ///
    /// println!("Render response: {res:?}");
    /// # };
    /// ```
    pub async fn render(&self, req: &render::Request) -> Result<render::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::Render))
            .header("Authorization", self.auth_header())
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Render response: {body}");

        serde_json::from_str::<render::Response>(body).map_err(Error::from)
    }

    /// Update message flags on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::{update_message_flags, Flag, Operation};
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = update_message_flags::Request::new()
    ///     .with_messages([1u64].as_ref())
    ///     .with_op(Operation::Add)
    ///     .with_flag(Flag::Read);
    ///
    /// let res = client.update_message_flags(&req).await.unwrap();
    ///
    /// println!("Update message flags response: {res}");
    /// # };
    /// ```
    pub async fn update_message_flags(
        &self,
        req: &update_message_flags::Request,
    ) -> Result<update_message_flags::Response> {
        let form = reqwest::multipart::Form::new()
            .text("messages", serde_json::to_string(req.messages())?)
            .text("op", req.op().as_str())
            .text("flag", req.flag().as_str());

        let res = self
            .http
            .post(self.endpoint(Endpoint::UpdateMessageFlags))
            .header("Authorization", self.auth_header())
            .multipart(form)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Update message flags response: {body}");

        serde_json::from_str::<update_message_flags::Response>(body).map_err(Error::from)
    }

    /// Update message flags for a narrow on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::{update_message_flags_narrow, Flag, Operation};
    /// use zulip_api::filter::{Anchor, Narrow};
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = update_message_flags_narrow::Request::new()
    ///     .with_anchor(Anchor::new())
    ///     .with_include_anchor(true)
    ///     .with_num_before(1)
    ///     .with_num_after(1)
    ///     .with_narrow(vec![Narrow::new()])
    ///     .with_op(Operation::Add)
    ///     .with_flag(Flag::Read);
    ///
    /// let res = client.update_message_flags_narrow(&req).await.unwrap();
    ///
    /// println!("Update message flags for narrow response: {res}");
    /// # };
    /// ```
    pub async fn update_message_flags_narrow(
        &self,
        req: &update_message_flags_narrow::Request,
    ) -> Result<update_message_flags_narrow::Response> {
        let mut form = reqwest::multipart::Form::new()
            .text("anchor", serde_json::to_string(&req.anchor())?)
            .text("num_before", format!("{}", req.num_before()))
            .text("num_after", format!("{}", req.num_after()))
            .text("narrow", serde_json::to_string(req.narrow())?)
            .text("op", req.op().as_str())
            .text("flag", req.flag().as_str());

        if let Some(include_anchor) = req.include_anchor() {
            form = form.text("include_anchor", format!("{include_anchor}"));
        }

        let res = self
            .http
            .post(self.endpoint(Endpoint::UpdateMessageFlagsNarrow))
            .header("Authorization", self.auth_header())
            .multipart(form)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Update message flags for narrow response: {body}");

        serde_json::from_str::<update_message_flags_narrow::Response>(body).map_err(Error::from)
    }

    /// Marks all messages as read on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let res = client.mark_all_as_read().await.unwrap();
    ///
    /// println!("Mark all as read response: {res:?}");
    /// # };
    /// ```
    pub async fn mark_all_as_read(&self) -> Result<mark_all_as_read::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::MarkAllAsRead))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Mark all as read response: {body}");

        serde_json::from_str::<mark_all_as_read::Response>(body).map_err(Error::from)
    }

    /// Marks all messages in a channel as read on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::mark_stream_as_read;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = mark_stream_as_read::Request::new().with_stream_id(1);
    ///
    /// let res = client.mark_stream_as_read(&req).await.unwrap();
    ///
    /// println!("Mark stream as read response: {res:?}");
    /// # };
    /// ```
    pub async fn mark_stream_as_read(
        &self,
        req: &mark_stream_as_read::Request,
    ) -> Result<mark_stream_as_read::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::MarkStreamAsRead))
            .header("Authorization", self.auth_header())
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Mark stream as read response: {body}");

        serde_json::from_str::<mark_stream_as_read::Response>(body).map_err(Error::from)
    }

    /// Marks all messages in a topic as read on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::mark_topic_as_read;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = mark_topic_as_read::Request::new()
    ///     .with_stream_id(1)
    ///     .with_topic_name("test topic");
    ///
    /// let res = client.mark_topic_as_read(&req).await.unwrap();
    ///
    /// println!("Mark topic as read response: {res:?}");
    /// # };
    /// ```
    pub async fn mark_topic_as_read(
        &self,
        req: &mark_topic_as_read::Request,
    ) -> Result<mark_topic_as_read::Response> {
        let form = reqwest::multipart::Form::new()
            .text("stream_id", format!("{}", req.stream_id()))
            .text("topic_name", req.topic_name().to_string());

        let res = self
            .http
            .post(self.endpoint(Endpoint::MarkTopicAsRead))
            .header("Authorization", self.auth_header())
            .multipart(form)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Mark topic as read response: {body}");

        serde_json::from_str::<mark_topic_as_read::Response>(body).map_err(Error::from)
    }

    /// Gets a message's read receipts on the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::get_read_receipts;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = get_read_receipts::Request::new()
    ///     .with_message_id(1);
    ///
    /// let res = client.get_read_receipts(&req).await.unwrap();
    ///
    /// println!("Get read receipts response: {res:?}");
    /// # };
    /// ```
    pub async fn get_read_receipts(
        &self,
        req: &get_read_receipts::Request,
    ) -> Result<get_read_receipts::Response> {
        let endpoint = self.endpoint(Endpoint::GetMessage);
        let msg_id = req.message_id();

        let res = self
            .http
            .get(format!("{endpoint}/{msg_id}/read_receipts"))
            .header("Authorization", self.auth_header())
            .query(&req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Get read receipts response: {body}");

        serde_json::from_str::<get_read_receipts::Response>(body).map_err(Error::from)
    }

    /// Registers an event queue with the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::register;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let req = register::Request::new();
    ///
    /// let res = client.register(&req).await.unwrap();
    ///
    /// println!("Register response: {res:?}");
    /// # };
    /// ```
    pub async fn register(&self, req: &register::Request) -> Result<register::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::Register))
            .header("Authorization", self.auth_header())
            .json(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Register response: {body}");

        serde_json::from_str::<register::Response>(body).map_err(Error::from)
    }

    /// Fetches a user's API key using a username-password authentication method with the Zulip server.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use zulip_api::client::Client;
    /// use zulip_api::fetch_api_key;
    ///
    /// # async {
    /// let client = Client::from_zuliprc(".zuliprc").unwrap();
    ///
    /// let algo = jwt::Algorithm::HS256;
    /// let key = jwt::EncodingKey::from_base64_secret("MWFlMTgyZjg3NzM1MzMyYmUxNDEwYWMyM2RlMDRkNzRlOWIwNmI4Mjc2YjQwMmZmYWMzNjllNTA5ZThiN2I0Mg==").unwrap();
    /// let email = fetch_api_key::Email::new("user@example.dev");
    /// let password = fetch_api_key::Password::new("super_secret_password");
    /// let req = fetch_api_key::Request::create(algo, &key, &email, &password).unwrap();
    ///
    /// let res = client.fetch_api_key(&req).await.unwrap();
    ///
    /// println!("Fetch API key response: {res:?}");
    /// # };
    /// ```
    pub async fn fetch_api_key(
        &self,
        req: &fetch_api_key::Request,
    ) -> Result<fetch_api_key::Response> {
        let res = self
            .http
            .post(self.endpoint(Endpoint::FetchApiKey))
            .form(req)
            .send()
            .await?;

        let bytes = res.bytes().await?;
        let body = str::from_utf8(&bytes[..])?;

        log::debug!("Fetch API key response: {body}");

        serde_json::from_str::<fetch_api_key::Response>(body).map_err(Error::from)
    }

    /// Gets the URL for the provided [Endpoint].
    pub fn endpoint(&self, endpoint: Endpoint) -> String {
        let scheme = self.scheme();
        let host = self.host();

        self.port()
            .map(|port| format!("{scheme}://{host}:{port}/{endpoint}"))
            .unwrap_or_else(|| format!("{scheme}://{host}/{endpoint}"))
    }

    /// Gets the base URL for the Zulip API server.
    pub fn base_url(&self) -> String {
        let scheme = self.scheme();
        let host = self.host();

        self.port()
            .map(|port| format!("{scheme}://{host}:{port}"))
            .unwrap_or_else(|| format!("{scheme}://{host}"))
    }

    /// Gets the Zulip server's URL scheme.
    pub(crate) fn scheme(&self) -> &str {
        self.url.scheme_str().unwrap_or("http")
    }

    /// Gets the Zulip server's URL host.
    pub(crate) fn host(&self) -> &str {
        self.url.host().unwrap_or("chat.zulip.org")
    }

    /// Gets the Zulip server's URL port.
    pub(crate) fn port(&self) -> Option<u16> {
        self.url.port_u16()
    }
}