xui-rs 2.0.0

A modern, typed async Rust SDK for the 3x-ui panel 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
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::Method;
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;

use super::models::{
    ActiveInboundsByGuid, AffectedCount, BulkAdjustRequest, BulkAdjustResult, BulkAttachResult,
    BulkCreateResult, BulkDeleteResult, BulkDetachResult, BulkSetEnabledResult, ClientConfig,
    ClientCreateRequest, ClientDetails, ClientExternalLinkInput, ClientHwidDevice, ClientIpInfo,
    ClientIpsByGuid, ClientMutationStatus, ClientPage, ClientPageRequest, ClientWithAttachments,
    ClientsByGuid, DeletedCount, GroupName, GroupSummary, LastOnlineByEmail,
};
use crate::{
    Client, ClientTraffic, Error, Result, client::AuthenticationScope, response::ApiResponse,
};

const ROOT: &str = "panel/api/clients";

/// Client and client-group endpoints for a [`Client`].
#[derive(Clone, Copy, Debug)]
pub struct ClientsApi<'client> {
    client: &'client Client,
}

impl<'client> ClientsApi<'client> {
    pub(crate) const fn new(client: &'client Client) -> Self {
        Self { client }
    }

    /// Lists all clients with full records, attachments, and traffic.
    ///
    /// # Errors
    ///
    /// Returns an error when the request or response contract fails.
    pub async fn list(self) -> Result<Vec<ClientWithAttachments>> {
        self.get_object("list").await
    }

    /// Lists one filtered page with stable global summary counters.
    ///
    /// # Errors
    ///
    /// Returns an error when query encoding, transport, or decoding fails.
    pub async fn list_paged(self, request: &ClientPageRequest) -> Result<ClientPage> {
        let query = PageQuery::from(request);
        let path = format!("{ROOT}/list/paged");
        let envelope = self
            .client
            .execute_query::<ClientPage, _>(
                Method::GET,
                &path,
                &query,
                AuthenticationScope::PanelApi,
            )
            .await?;
        self.required_object(Method::GET, &path, envelope)
    }

    /// Fetches a client by its unique email/name.
    ///
    /// # Errors
    ///
    /// Returns an error when the client cannot be fetched or decoded.
    pub async fn get(self, email: &str) -> Result<ClientDetails> {
        self.get_object(&format!("get/{}", segment(email))).await
    }

    /// Fetches all clients associated with a positive Telegram user ID.
    ///
    /// # Errors
    ///
    /// Returns an error when the lookup or response decoding fails.
    pub async fn get_by_telegram_id(self, telegram_id: i64) -> Result<Vec<ClientDetails>> {
        self.get_object(&format!("get/tgId/{telegram_id}")).await
    }

    /// Returns one client's shared traffic row.
    ///
    /// # Errors
    ///
    /// Returns an error when traffic cannot be fetched or decoded.
    pub async fn traffic(self, email: &str) -> Result<ClientTraffic> {
        self.get_object(&format!("traffic/{}", segment(email)))
            .await
    }

    /// Returns all share links for a subscription identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when link generation or decoding fails.
    pub async fn subscription_links(self, sub_id: &str) -> Result<Vec<String>> {
        self.get_object(&format!("subLinks/{}", segment(sub_id)))
            .await
    }

    /// Returns all share links for one client across attached inbounds.
    ///
    /// # Errors
    ///
    /// Returns an error when link generation or decoding fails.
    pub async fn links(self, email: &str) -> Result<Vec<String>> {
        self.get_object(&format!("links/{}", segment(email))).await
    }

    /// Lists devices registered against a client's subscription identifier.
    ///
    /// 3x-ui stores only a hash of the raw HWID; this response contains
    /// non-secret metadata and the revocation identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when the request or response contract fails.
    pub async fn hwid_devices(self, email: &str) -> Result<Vec<ClientHwidDevice>> {
        self.post_object(&format!("hwids/{}", segment(email)), None::<&()>)
            .await
    }

    /// Clears every registered HWID device for a client.
    ///
    /// # Errors
    ///
    /// Returns an error when the panel cannot clear the registrations.
    pub async fn clear_hwid_devices(self, email: &str) -> Result<()> {
        let suffix = format!("hwids/{}", segment(email));
        let path = format!("{ROOT}/{suffix}");
        self.client
            .execute::<Value, ()>(Method::DELETE, &path, None, AuthenticationScope::PanelApi)
            .await?;
        Ok(())
    }

    /// Revokes one registered HWID device by its database identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when the device does not exist or cannot be revoked.
    pub async fn delete_hwid_device(self, email: &str, id: i64) -> Result<()> {
        let suffix = format!("hwids/{}/{}", segment(email), id);
        let path = format!("{ROOT}/{suffix}");
        self.client
            .execute::<Value, ()>(Method::DELETE, &path, None, AuthenticationScope::PanelApi)
            .await?;
        Ok(())
    }

    /// Creates and attaches a client.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, transport, or decoding fails.
    pub async fn create(self, request: &ClientCreateRequest) -> Result<ClientMutationStatus> {
        self.post_status("add", request).await
    }

    /// Replaces a client's full writable configuration on every attachment.
    ///
    /// Start with [`crate::ClientRecord::to_config`] to preserve fields. The endpoint
    /// is replacement-based, not PATCH.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, transport, or decoding fails.
    pub async fn update(self, email: &str, client: &ClientConfig) -> Result<ClientMutationStatus> {
        self.post_status(&format!("update/{}", segment(email)), client)
            .await
    }

    /// Restricts per-inbound settings replacement to selected attachments.
    ///
    /// Canonical client fields such as group and enabled state remain global.
    /// An empty `inbound_ids` slice has the server's unfiltered update meaning.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, transport, or decoding fails.
    pub async fn update_on_inbounds(
        self,
        email: &str,
        client: &ClientConfig,
        inbound_ids: &[i64],
    ) -> Result<ClientMutationStatus> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Query {
            inbound_ids: String,
        }

        let suffix = format!("update/{}", segment(email));
        let path = format!("{ROOT}/{suffix}");
        let query = Query {
            inbound_ids: join_numbers(inbound_ids),
        };
        let envelope = self
            .client
            .execute_query_json::<ClientMutationStatus, _, _>(
                Method::POST,
                &path,
                &query,
                client,
                AuthenticationScope::PanelApi,
            )
            .await?;
        Ok(envelope.obj.unwrap_or_default())
    }

    /// Deletes a client from every inbound.
    ///
    /// Set `keep_traffic` to retain its traffic row for a future recreation.
    ///
    /// # Errors
    ///
    /// Returns an error when the panel cannot complete the deletion.
    pub async fn delete(self, email: &str, keep_traffic: bool) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Query {
            keep_traffic: u8,
        }

        let path = format!("{ROOT}/del/{}", segment(email));
        self.client
            .execute_query::<Value, _>(
                Method::POST,
                &path,
                &Query {
                    keep_traffic: u8::from(keep_traffic),
                },
                AuthenticationScope::PanelApi,
            )
            .await?;
        Ok(())
    }

    /// Attaches an existing client to additional inbounds.
    ///
    /// # Errors
    ///
    /// Returns an error when validation or attachment fails.
    pub async fn attach(self, email: &str, inbound_ids: &[i64]) -> Result<ClientMutationStatus> {
        self.post_status(
            &format!("{}/attach", segment(email)),
            &InboundIdsBody { inbound_ids },
        )
        .await
    }

    /// Detaches a client from selected inbounds without deleting its record.
    ///
    /// # Errors
    ///
    /// Returns an error when validation or detachment fails.
    pub async fn detach(self, email: &str, inbound_ids: &[i64]) -> Result<ClientMutationStatus> {
        self.post_status(
            &format!("{}/detach", segment(email)),
            &InboundIdsBody { inbound_ids },
        )
        .await
    }

    /// Replaces all external links and remote subscriptions for a client.
    ///
    /// # Errors
    ///
    /// Returns an error when a link is invalid or replacement fails.
    pub async fn set_external_links(
        self,
        email: &str,
        external_links: &[ClientExternalLinkInput],
    ) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body<'a> {
            external_links: &'a [ClientExternalLinkInput],
        }

        self.post_empty(
            &format!("{}/externalLinks", segment(email)),
            Some(&Body { external_links }),
        )
        .await
    }

    /// Exports every client in the portable create/import shape.
    ///
    /// # Errors
    ///
    /// Returns an error when export or response decoding fails.
    pub async fn export(self) -> Result<Vec<ClientCreateRequest>> {
        self.get_object("export").await
    }

    /// Imports portable client payloads without overwriting existing emails.
    ///
    /// # Errors
    ///
    /// Returns an error when nested JSON encoding, validation, or transport fails.
    pub async fn import(self, clients: &[ClientCreateRequest]) -> Result<BulkCreateResult> {
        #[derive(Serialize)]
        struct Body {
            data: String,
        }

        let data = serde_json::to_string(clients).map_err(|source| Error::Encode {
            operation: "import clients",
            source,
        })?;
        self.post_object("import", Some(&Body { data })).await
    }

    /// Deletes all unattached client records.
    ///
    /// # Errors
    ///
    /// Returns an error when cleanup or decoding fails.
    pub async fn delete_orphans(self) -> Result<DeletedCount> {
        self.post_object::<DeletedCount, ()>("delOrphans", None)
            .await
    }

    /// Resets traffic for every client.
    ///
    /// # Errors
    ///
    /// Returns an error when the reset fails.
    pub async fn reset_all_traffic(self) -> Result<()> {
        self.post_empty::<()>("resetAllTraffics", None).await
    }

    /// Deletes all expired or quota-depleted clients.
    ///
    /// # Errors
    ///
    /// Returns an error when cleanup or decoding fails.
    pub async fn delete_depleted(self) -> Result<DeletedCount> {
        self.post_object::<DeletedCount, ()>("delDepleted", None)
            .await
    }

    /// Applies a signed expiry/quota change and optional typed flow directive.
    ///
    /// The panel deduplicates emails within a request, but separate calls can
    /// apply the same expiry/quota delta again. Inspect both result fields:
    /// a skipped field does not imply that every change for that client failed.
    /// After an ambiguous response, reconcile client and attachment state before
    /// retrying. Cookie-authenticated calls may be replayed once after HTTP 403.
    ///
    /// # Errors
    ///
    /// Returns an error when adjustment or decoding fails. Earlier server-side
    /// changes may already have committed; an error does not guarantee rollback.
    pub async fn bulk_adjust(self, request: &BulkAdjustRequest) -> Result<BulkAdjustResult> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body<'a> {
            emails: &'a [String],
            add_days: i32,
            add_bytes: i64,
            flow: &'static str,
            #[serde(skip_serializing_if = "Option::is_none")]
            limit_hwid: Option<i32>,
            #[serde(skip_serializing_if = "str::is_empty")]
            ad_tag: &'a str,
        }

        self.post_object(
            "bulkAdjust",
            Some(&Body {
                emails: &request.emails,
                add_days: request.add_days,
                add_bytes: request.add_bytes,
                flow: request.flow.as_str(),
                limit_hwid: request.limit_hwid,
                ad_tag: &request.ad_tag,
            }),
        )
        .await
    }

    /// Generates a local Happ Crypt5 link for a client database identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if Happ links are disabled, the client is missing, or transport fails.
    pub async fn happ_link(self, client_id: i64) -> Result<super::HappLink> {
        self.post_object(&format!("happLink/{client_id}"), None::<&()>)
            .await
    }

    /// Enables multiple clients.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_enable(self, emails: &[impl AsRef<str>]) -> Result<BulkSetEnabledResult> {
        let emails = owned_strings(emails);
        self.post_object("bulkEnable", Some(&EmailsBody { emails: &emails }))
            .await
    }

    /// Disables multiple clients.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_disable(self, emails: &[impl AsRef<str>]) -> Result<BulkSetEnabledResult> {
        let emails = owned_strings(emails);
        self.post_object("bulkDisable", Some(&EmailsBody { emails: &emails }))
            .await
    }

    /// Deletes multiple clients.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_delete(
        self,
        emails: &[impl AsRef<str>],
        keep_traffic: bool,
    ) -> Result<BulkDeleteResult> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body<'a> {
            emails: &'a [String],
            keep_traffic: bool,
        }

        let emails = owned_strings(emails);
        self.post_object(
            "bulkDel",
            Some(&Body {
                emails: &emails,
                keep_traffic,
            }),
        )
        .await
    }

    /// Creates multiple clients and reports per-item skips.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_create(self, clients: &[ClientCreateRequest]) -> Result<BulkCreateResult> {
        self.post_object("bulkCreate", Some(clients)).await
    }

    /// Attaches multiple clients to multiple inbounds.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_attach(
        self,
        emails: &[impl AsRef<str>],
        inbound_ids: &[i64],
    ) -> Result<BulkAttachResult> {
        let emails = owned_strings(emails);
        self.post_object(
            "bulkAttach",
            Some(&BulkAttachmentBody {
                emails: &emails,
                inbound_ids,
            }),
        )
        .await
    }

    /// Detaches multiple clients from multiple inbounds.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation or decoding fails.
    pub async fn bulk_detach(
        self,
        emails: &[impl AsRef<str>],
        inbound_ids: &[i64],
    ) -> Result<BulkDetachResult> {
        let emails = owned_strings(emails);
        self.post_object(
            "bulkDetach",
            Some(&BulkAttachmentBody {
                emails: &emails,
                inbound_ids,
            }),
        )
        .await
    }

    /// Resets traffic for multiple clients and returns the affected count.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk reset or decoding fails.
    pub async fn bulk_reset_traffic(self, emails: &[impl AsRef<str>]) -> Result<AffectedCount> {
        let emails = owned_strings(emails);
        self.post_object("bulkResetTraffic", Some(&EmailsBody { emails: &emails }))
            .await
    }

    /// Resets traffic for one client and re-enables it on attached inbounds.
    ///
    /// # Errors
    ///
    /// Returns an error when the reset fails.
    pub async fn reset_traffic(self, email: &str) -> Result<()> {
        self.post_empty::<()>(&format!("resetTraffic/{}", segment(email)), None)
            .await
    }

    /// Replaces one client's upload and download counters.
    ///
    /// # Errors
    ///
    /// Returns an error when the update fails.
    pub async fn update_traffic(self, email: &str, upload: i64, download: i64) -> Result<()> {
        #[derive(Serialize)]
        struct Body {
            upload: i64,
            download: i64,
        }

        self.post_empty(
            &format!("updateTraffic/{}", segment(email)),
            Some(&Body { upload, download }),
        )
        .await
    }

    /// Lists display-ready source IP observations for one client.
    ///
    /// # Errors
    ///
    /// Returns an error when lookup or decoding fails.
    pub async fn ips(self, email: &str) -> Result<Vec<ClientIpInfo>> {
        self.post_object::<Vec<ClientIpInfo>, ()>(&format!("ips/{}", segment(email)), None)
            .await
    }

    /// Clears one client's recorded source IPs.
    ///
    /// # Errors
    ///
    /// Returns an error when cleanup fails.
    pub async fn clear_ips(self, email: &str) -> Result<()> {
        self.post_empty::<()>(&format!("clearIps/{}", segment(email)), None)
            .await
    }

    /// Lists emails currently online across the panel tree.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn onlines(self) -> Result<Vec<String>> {
        self.post_object::<Vec<String>, ()>("onlines", None).await
    }

    /// Lists online emails grouped by stable panel GUID.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn onlines_by_guid(self) -> Result<ClientsByGuid> {
        self.post_object::<ClientsByGuid, ()>("onlinesByGuid", None)
            .await
    }

    /// Returns source-IP observations grouped by panel GUID and email.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn client_ips_by_guid(self) -> Result<ClientIpsByGuid> {
        self.post_object::<ClientIpsByGuid, ()>("clientIpsByGuid", None)
            .await
    }

    /// Returns recently active inbound tags grouped by panel GUID.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn active_inbounds_by_guid(self) -> Result<ActiveInboundsByGuid> {
        self.post_object::<ActiveInboundsByGuid, ()>("activeInbounds", None)
            .await
    }

    /// Returns last-online timestamps keyed by client email.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn last_online(self) -> Result<LastOnlineByEmail> {
        self.post_object::<LastOnlineByEmail, ()>("lastOnline", None)
            .await
    }

    /// Lists all client groups with counts and traffic since group reset.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn groups(self) -> Result<Vec<GroupSummary>> {
        self.get_object("groups").await
    }

    /// Lists emails belonging to one group.
    ///
    /// # Errors
    ///
    /// Returns an error when retrieval or decoding fails.
    pub async fn group_emails(self, name: &str) -> Result<Vec<String>> {
        self.get_object(&format!("groups/{}/emails", segment(name)))
            .await
    }

    /// Creates an empty group placeholder.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, creation, or decoding fails.
    pub async fn create_group(self, name: &str) -> Result<GroupName> {
        #[derive(Serialize)]
        struct Body<'a> {
            name: &'a str,
        }

        self.post_object("groups/create", Some(&Body { name }))
            .await
    }

    /// Renames a group and all client memberships.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, rename, or decoding fails.
    pub async fn rename_group(self, old_name: &str, new_name: &str) -> Result<AffectedCount> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body<'a> {
            old_name: &'a str,
            new_name: &'a str,
        }

        self.post_object("groups/rename", Some(&Body { old_name, new_name }))
            .await
    }

    /// Deletes a group while retaining its clients.
    ///
    /// # Errors
    ///
    /// Returns an error when deletion or decoding fails.
    pub async fn delete_group(self, name: &str) -> Result<AffectedCount> {
        #[derive(Serialize)]
        struct Body<'a> {
            name: &'a str,
        }

        self.post_object("groups/delete", Some(&Body { name }))
            .await
    }

    /// Resets a group's traffic baseline without resetting client counters.
    ///
    /// # Errors
    ///
    /// Returns an error when reset or decoding fails.
    pub async fn reset_group_traffic(self, name: &str) -> Result<GroupName> {
        #[derive(Serialize)]
        struct Body<'a> {
            name: &'a str,
        }

        self.post_object("groups/resetTraffic", Some(&Body { name }))
            .await
    }

    /// Adds multiple clients to a group, creating it if needed.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, update, or decoding fails.
    pub async fn add_to_group(
        self,
        emails: &[impl AsRef<str>],
        group: &str,
    ) -> Result<AffectedCount> {
        #[derive(Serialize)]
        struct Body<'a> {
            emails: &'a [String],
            group: &'a str,
        }

        let emails = owned_strings(emails);
        self.post_object(
            "groups/bulkAdd",
            Some(&Body {
                emails: &emails,
                group,
            }),
        )
        .await
    }

    /// Removes the group label from multiple clients.
    ///
    /// # Errors
    ///
    /// Returns an error when update or decoding fails.
    pub async fn remove_from_group(self, emails: &[impl AsRef<str>]) -> Result<AffectedCount> {
        let emails = owned_strings(emails);
        self.post_object("groups/bulkRemove", Some(&EmailsBody { emails: &emails }))
            .await
    }

    async fn get_object<T>(self, suffix: &str) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let path = format!("{ROOT}/{suffix}");
        let envelope = self
            .client
            .execute::<T, ()>(Method::GET, &path, None, AuthenticationScope::PanelApi)
            .await?;
        self.required_object(Method::GET, &path, envelope)
    }

    async fn post_object<T, B>(self, suffix: &str, body: Option<&B>) -> Result<T>
    where
        T: DeserializeOwned,
        B: Serialize + ?Sized,
    {
        let path = format!("{ROOT}/{suffix}");
        let envelope = self
            .client
            .execute(Method::POST, &path, body, AuthenticationScope::PanelApi)
            .await?;
        self.required_object(Method::POST, &path, envelope)
    }

    async fn post_status<B>(self, suffix: &str, body: &B) -> Result<ClientMutationStatus>
    where
        B: Serialize + ?Sized,
    {
        let path = format!("{ROOT}/{suffix}");
        let envelope = self
            .client
            .execute(
                Method::POST,
                &path,
                Some(body),
                AuthenticationScope::PanelApi,
            )
            .await?;
        Ok(envelope.obj.unwrap_or_default())
    }

    async fn post_empty<B>(self, suffix: &str, body: Option<&B>) -> Result<()>
    where
        B: Serialize + ?Sized,
    {
        let path = format!("{ROOT}/{suffix}");
        self.client
            .execute::<Value, B>(Method::POST, &path, body, AuthenticationScope::PanelApi)
            .await?;
        Ok(())
    }

    fn required_object<T>(self, method: Method, path: &str, envelope: ApiResponse<T>) -> Result<T> {
        let url = self.client.endpoint(path)?;
        envelope.obj.ok_or_else(|| Error::MissingObject {
            method,
            url: Box::new(url),
        })
    }
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct InboundIdsBody<'a> {
    inbound_ids: &'a [i64],
}

#[derive(Serialize)]
struct EmailsBody<'a> {
    emails: &'a [String],
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BulkAttachmentBody<'a> {
    emails: &'a [String],
    inbound_ids: &'a [i64],
}

fn owned_strings(values: &[impl AsRef<str>]) -> Vec<String> {
    values
        .iter()
        .map(|value| value.as_ref().to_owned())
        .collect()
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PageQuery {
    page: u32,
    page_size: u16,
    #[serde(skip_serializing_if = "String::is_empty")]
    search: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    filter: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    protocol: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    inbound: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    sort: Option<&'static str>,
    order: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    expiry_from: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    expiry_to: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    usage_from: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    usage_to: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    auto_renew: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    has_tg_id: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    has_comment: Option<&'static str>,
    #[serde(skip_serializing_if = "String::is_empty")]
    group: String,
}

impl From<&ClientPageRequest> for PageQuery {
    fn from(request: &ClientPageRequest) -> Self {
        Self {
            page: request.page,
            page_size: request.page_size,
            search: request.search.clone(),
            filter: request
                .statuses
                .iter()
                .map(|status| status.as_str())
                .collect::<Vec<_>>()
                .join(","),
            protocol: request
                .protocols
                .iter()
                .map(|protocol| protocol.as_str())
                .collect::<Vec<_>>()
                .join(","),
            inbound: join_numbers(&request.inbound_ids),
            sort: request.sort.map(super::models::ClientSort::as_str),
            order: request.order.as_str(),
            expiry_from: request.expiry_from,
            expiry_to: request.expiry_to,
            usage_from: request.usage_from,
            usage_to: request.usage_to,
            auto_renew: request
                .auto_renew
                .map(|value| if value { "on" } else { "off" }),
            has_tg_id: request
                .has_telegram_id
                .map(|value| if value { "yes" } else { "no" }),
            has_comment: request
                .has_comment
                .map(|value| if value { "yes" } else { "no" }),
            group: request.groups.join(","),
        }
    }
}

fn segment(value: &str) -> String {
    utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
}

fn join_numbers(values: &[i64]) -> String {
    values
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(",")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ClientSort, ClientStatusFilter, InboundProtocol, SortOrder};

    #[test]
    fn path_segments_encode_reserved_and_unicode_characters() {
        assert_eq!(
            segment("alice+ops@example.com/a b"),
            "alice%2Bops%40example%2Ecom%2Fa%20b"
        );
        assert_eq!(segment("группа"), "%D0%B3%D1%80%D1%83%D0%BF%D0%BF%D0%B0");
    }

    /// Checks that typed page filters serialize to the query names and values accepted by 3x-ui.
    #[test]
    fn page_request_uses_actual_v385_query_vocabulary() {
        let request = ClientPageRequest {
            statuses: vec![ClientStatusFilter::Online, ClientStatusFilter::Expiring],
            protocols: vec![InboundProtocol::Vless],
            inbound_ids: vec![3, 5],
            sort: Some(ClientSort::LastOnline),
            order: SortOrder::Descending,
            auto_renew: Some(true),
            has_telegram_id: Some(false),
            groups: vec!["Tier A".to_owned(), "Internal".to_owned()],
            ..ClientPageRequest::default()
        };
        let value = serde_json::to_value(PageQuery::from(&request)).unwrap();
        assert_eq!(value["filter"], "online,expiring");
        assert_eq!(value["protocol"], "vless");
        assert_eq!(value["inbound"], "3,5");
        assert_eq!(value["sort"], "lastOnline");
        assert_eq!(value["order"], "descend");
        assert_eq!(value["autoRenew"], "on");
        assert_eq!(value["hasTgId"], "no");
        assert_eq!(value["group"], "Tier A,Internal");
    }
}