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
#![allow(clippy::missing_errors_doc)]

use std::collections::BTreeMap;

use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::Method;
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;

use super::models::{
    ApiTokenCreateRequest, ApiTokenMetadata, ApiTokenScope, BalancerStatus, CreatedApiToken,
    EffectiveDefaults, FactoryDefaults, GeoCategoryPage, GeoEntryPage, GeoFile, GeodataTokenIssue,
    MoveDirection, OutboundDocuments, OutboundSubscription, OutboundSubscriptionInput,
    OutboundTestMode, OutboundTestResult, OutboundTraffic, PanelSettingsUpdate, PanelSettingsView,
    PiaAccount, PiaCountry, PiaKey, PiaServers, RouteTestRequest, RouteTestResult,
    SensitivePayload, SmtpTestResult, UserCredentialsUpdate, WarpRegistration,
    XraySettingsSnapshot,
};
use crate::{
    Client, Error, Result, XrayConfig, client::AuthenticationScope, response::ApiResponse,
};

const SETTINGS_ROOT: &str = "panel/api/setting";
const XRAY_ROOT: &str = "panel/api/xray";

/// Panel settings, credentials, notification tests, and API-token operations.
#[derive(Clone, Copy, Debug)]
pub struct SettingsApi<'client> {
    client: &'client Client,
}

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

    /// Returns the complete browser-safe panel settings view.
    pub async fn all(self) -> Result<PanelSettingsView> {
        self.post_object("all", None::<&()>).await
    }

    /// Sends a test notification through the configured Discord bot.
    pub async fn test_discord(self) -> Result<()> {
        self.post_empty("testDiscord", None::<&()>).await
    }

    /// Returns host-derived effective defaults.
    pub async fn defaults(self) -> Result<EffectiveDefaults> {
        self.post_object("defaultSettings", None::<&()>).await
    }

    /// Returns the source defaults as setting-name/value pairs.
    ///
    pub async fn factory_defaults(self) -> Result<FactoryDefaults> {
        self.post_object("factoryDefaults", None::<&()>).await
    }

    /// Replaces all persisted panel settings.
    pub async fn update(self, update: &PanelSettingsUpdate) -> Result<()> {
        self.post_empty("update", Some(update)).await
    }

    /// Validates a Go regular expression with the panel runtime.
    ///
    pub async fn validate_regex(self, regex: &str) -> Result<()> {
        #[derive(Serialize)]
        struct Body<'a> {
            regex: &'a str,
        }
        self.post_empty("validateRegex", Some(&Body { regex }))
            .await
    }

    /// Replaces the currently authenticated panel user's credentials.
    pub async fn update_user(self, update: &UserCredentialsUpdate) -> Result<()> {
        self.post_empty("updateUser", Some(update)).await
    }

    /// Schedules a panel process restart after the upstream three-second delay.
    pub async fn restart_panel(self) -> Result<()> {
        self.post_empty("restartPanel", None::<&()>).await
    }

    /// Returns the panel's default Xray template.
    pub async fn default_xray_config(self) -> Result<XrayConfig> {
        self.get_object("getDefaultJsonConfig").await
    }

    /// Lists API-token metadata. Plaintext tokens are never included.
    pub async fn api_tokens(self) -> Result<Vec<ApiTokenMetadata>> {
        self.get_object("apiTokens").await
    }

    /// Creates an API token and returns its plaintext exactly once.
    pub async fn create_api_token(
        self,
        request: &ApiTokenCreateRequest,
    ) -> Result<CreatedApiToken> {
        self.post_form_object("apiTokens/create", request).await
    }

    /// Permanently deletes an API token after verifying its expected scope.
    pub async fn delete_api_token(self, id: i64, expected_scope: ApiTokenScope) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body<'a> {
            expected_scope: &'a str,
        }
        self.post_empty(
            &format!("apiTokens/delete/{id}"),
            Some(&Body {
                expected_scope: expected_scope.as_str(),
            }),
        )
        .await
    }

    /// Enables or disables an API token after verifying its expected scope.
    pub async fn set_api_token_enabled(
        self,
        id: i64,
        expected_scope: ApiTokenScope,
        enabled: bool,
    ) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body {
            enabled: bool,
            expected_scope: &'static str,
        }
        self.post_empty(
            &format!("apiTokens/setEnabled/{id}"),
            Some(&Body {
                enabled,
                expected_scope: expected_scope.as_str(),
            }),
        )
        .await
    }

    /// Tests the currently saved SMTP configuration.
    ///
    /// Unlike normal panel envelopes, an SMTP connectivity failure is a typed
    /// successful HTTP response with `success: false` and a diagnostic stage.
    pub async fn test_smtp(self) -> Result<SmtpTestResult> {
        let path = format!("{SETTINGS_ROOT}/testSmtp");
        let result = self
            .client
            .execute_response::<SmtpTestResult, ()>(
                Method::POST,
                &path,
                None,
                AuthenticationScope::PanelApi,
            )
            .await?;
        if !result.success && result.stage.is_empty() {
            return Err(Error::Api {
                method: Method::POST,
                url: Box::new(self.client.endpoint(&path)?),
                message: if result.message.is_empty() {
                    "SMTP test is unavailable".to_owned()
                } else {
                    result.message
                },
            });
        }
        Ok(result)
    }

    /// Sends a Telegram test notification using the saved bot configuration.
    pub async fn test_telegram(self) -> Result<()> {
        self.post_empty("testTgBot", None::<&()>).await
    }

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

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

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

/// Xray template, integration, routing-test, and outbound-subscription operations.
#[derive(Clone, Copy, Debug)]
pub struct XraySettingsApi<'client> {
    client: &'client Client,
}

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

    /// Returns the default Xray template.
    pub async fn default_config(self) -> Result<XrayConfig> {
        self.get_object("getDefaultJsonConfig").await
    }

    /// Returns cumulative traffic for every outbound.
    pub async fn outbounds_traffic(self) -> Result<Vec<OutboundTraffic>> {
        self.get_object("getOutboundsTraffic").await
    }

    /// Returns the most recent Xray startup or reload result.
    pub async fn xray_result(self) -> Result<String> {
        self.get_object("getXrayResult").await
    }

    /// Returns and decodes the panel's nested-string Xray settings response.
    pub async fn settings(self) -> Result<XraySettingsSnapshot> {
        let path = format!("{XRAY_ROOT}/");
        let envelope = self
            .client
            .execute::<String, ()>(Method::POST, &path, None, AuthenticationScope::PanelApi)
            .await?;
        let raw = required_object(self.client, Method::POST, &path, envelope)?;
        let url = self.client.endpoint(&path)?;
        serde_json::from_str(&raw).map_err(|source| Error::Decode {
            method: Method::POST,
            url: Box::new(url),
            source,
        })
    }

    /// Replaces the Xray template and outbound-test URL, serializing JSON automatically.
    pub async fn update(self, config: &XrayConfig, outbound_test_url: &str) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            xray_setting: String,
            outbound_test_url: &'a str,
        }
        let xray_setting = serde_json::to_string(config).map_err(|source| Error::Encode {
            operation: "update Xray settings",
            source,
        })?;
        self.post_form_empty(
            "update",
            &Form {
                xray_setting,
                outbound_test_url,
            },
        )
        .await
    }

    /// Returns stored WARP account data.
    pub async fn warp_data(self) -> Result<SensitivePayload> {
        self.integration("warp", "data", None::<&()>).await
    }
    /// Deletes stored WARP account data.
    pub async fn delete_warp(self) -> Result<()> {
        self.integration_empty("warp", "del", None::<&()>).await
    }
    /// Returns generated WARP Xray configuration.
    pub async fn warp_config(self) -> Result<SensitivePayload> {
        self.integration("warp", "config", None::<&()>).await
    }
    /// Registers WARP using optional existing key material.
    pub async fn register_warp(self, registration: &WarpRegistration) -> Result<SensitivePayload> {
        self.integration("warp", "reg", Some(registration)).await
    }
    /// Rotates the WARP address immediately.
    pub async fn change_warp_ip(self) -> Result<SensitivePayload> {
        self.integration("warp", "changeIp", None::<&()>).await
    }
    /// Applies a WARP license string.
    pub async fn set_warp_license(self, license: &str) -> Result<SensitivePayload> {
        #[derive(Serialize)]
        struct Form<'a> {
            license: &'a str,
        }
        self.integration("warp", "license", Some(&Form { license }))
            .await
    }
    /// Sets the automatic WARP rotation interval.
    pub async fn set_warp_update_interval(self, interval: u32) -> Result<()> {
        #[derive(Serialize)]
        struct Form {
            interval: u32,
        }
        self.integration_empty("warp", "interval", Some(&Form { interval }))
            .await
    }

    /// Returns `NordVPN` countries.
    pub async fn nord_countries(self) -> Result<SensitivePayload> {
        self.integration("nord", "countries", None::<&()>).await
    }
    /// Returns `NordVPN` servers for a country identifier.
    pub async fn nord_servers(self, country_id: &str) -> Result<SensitivePayload> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            country_id: &'a str,
        }
        self.integration("nord", "servers", Some(&Form { country_id }))
            .await
    }
    /// Exchanges a `NordVPN` access token for credentials.
    pub async fn register_nord(self, token: &str) -> Result<SensitivePayload> {
        #[derive(Serialize)]
        struct Form<'a> {
            token: &'a str,
        }
        self.integration("nord", "reg", Some(&Form { token })).await
    }
    /// Stores a `NordVPN` private key.
    pub async fn set_nord_key(self, key: &str) -> Result<SensitivePayload> {
        #[derive(Serialize)]
        struct Form<'a> {
            key: &'a str,
        }
        self.integration("nord", "setKey", Some(&Form { key }))
            .await
    }
    /// Returns stored `NordVPN` data.
    pub async fn nord_data(self) -> Result<SensitivePayload> {
        self.integration("nord", "data", None::<&()>).await
    }
    /// Deletes stored `NordVPN` data.
    pub async fn delete_nord(self) -> Result<()> {
        self.integration_empty("nord", "del", None::<&()>).await
    }

    /// Returns PIA countries from the provider's signed server list.
    pub async fn pia_countries(self) -> Result<Vec<PiaCountry>> {
        self.integration("pia", "countries", None::<&()>).await
    }

    /// Returns PIA `WireGuard` servers for a country code.
    pub async fn pia_servers(self, country_code: &str) -> Result<PiaServers> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            country_code: &'a str,
        }
        self.integration("pia", "servers", Some(&Form { country_code }))
            .await
    }

    /// Signs in to PIA and stores the resulting account data.
    pub async fn register_pia(self, username: &str, password: &str) -> Result<PiaAccount> {
        #[derive(Serialize)]
        struct Form<'a> {
            username: &'a str,
            password: &'a str,
        }
        self.integration("pia", "reg", Some(&Form { username, password }))
            .await
    }

    /// Returns the stored PIA account hint.
    pub async fn pia_data(self) -> Result<PiaAccount> {
        self.integration("pia", "data", None::<&()>).await
    }

    /// Deletes stored PIA credentials.
    pub async fn delete_pia(self) -> Result<()> {
        self.integration_empty("pia", "del", None::<&()>).await
    }

    /// Registers a PIA `WireGuard` key against the selected server.
    pub async fn add_pia_key(self, hostname: &str) -> Result<PiaKey> {
        #[derive(Serialize)]
        struct Form<'a> {
            hostname: &'a str,
        }
        self.integration("pia", "addKey", Some(&Form { hostname }))
            .await
    }

    /// Lists geosite and geoip databases from Xray's active asset directory.
    pub async fn geodata_files(self) -> Result<Vec<GeoFile>> {
        self.get_object("geodata/files").await
    }

    /// Returns one filtered page of categories from a geodata database.
    pub async fn geodata_categories(
        self,
        file: &str,
        query: &str,
        offset: u32,
        limit: u16,
    ) -> Result<GeoCategoryPage> {
        #[derive(Serialize)]
        struct Query<'a> {
            file: &'a str,
            q: &'a str,
            offset: u32,
            limit: u16,
        }
        let path = format!("{XRAY_ROOT}/geodata/categories");
        let envelope = self
            .client
            .execute_query::<GeoCategoryPage, _>(
                Method::GET,
                &path,
                &Query {
                    file,
                    q: query,
                    offset,
                    limit,
                },
                AuthenticationScope::PanelApi,
            )
            .await?;
        required_object(self.client, Method::GET, &path, envelope)
    }

    /// Returns one filtered page of rules inside a geodata category.
    pub async fn geodata_entries(
        self,
        file: &str,
        code: &str,
        query: &str,
        offset: u32,
        limit: u16,
    ) -> Result<GeoEntryPage> {
        #[derive(Serialize)]
        struct Query<'a> {
            file: &'a str,
            code: &'a str,
            q: &'a str,
            offset: u32,
            limit: u16,
        }
        let path = format!("{XRAY_ROOT}/geodata/entries");
        let envelope = self
            .client
            .execute_query::<GeoEntryPage, _>(
                Method::GET,
                &path,
                &Query {
                    file,
                    code,
                    q: query,
                    offset,
                    limit,
                },
                AuthenticationScope::PanelApi,
            )
            .await?;
        required_object(self.client, Method::GET, &path, envelope)
    }

    /// Validates up to 500 geosite or geoip routing tokens.
    pub async fn validate_geodata_tokens(
        self,
        ip: bool,
        tokens: &[impl AsRef<str>],
    ) -> Result<Vec<GeodataTokenIssue>> {
        #[derive(Serialize)]
        struct Form<'a> {
            kind: &'a str,
            tokens: String,
        }
        let tokens = tokens
            .iter()
            .map(AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(",");
        self.post_form_object(
            "geodata/validate",
            &Form {
                kind: if ip { "ip" } else { "site" },
                tokens,
            },
        )
        .await
    }

    /// Resets traffic counters for one outbound tag.
    pub async fn reset_outbound_traffic(self, tag: &str) -> Result<()> {
        #[derive(Serialize)]
        struct Form<'a> {
            tag: &'a str,
        }
        self.post_form_empty("resetOutboundsTraffic", &Form { tag })
            .await
    }

    /// Tests one outbound, automatically encoding nested Xray JSON.
    pub async fn test_outbound(
        self,
        outbound: &Value,
        all_outbounds: Option<&[Value]>,
        mode: OutboundTestMode,
    ) -> Result<OutboundTestResult> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            outbound: &'a str,
            all_outbounds: &'a str,
            mode: &'a str,
        }

        let outbound = encode_json("test outbound", outbound)?;
        let all_outbounds = encode_optional_json("test outbound dependencies", all_outbounds)?;
        self.post_form_object(
            "testOutbound",
            &Form {
                outbound: &outbound,
                all_outbounds: &all_outbounds,
                mode: mode.as_str(),
            },
        )
        .await
    }

    /// Tests up to 50 outbounds in one shared Xray instance.
    pub async fn test_outbounds(
        self,
        outbounds: &[Value],
        all_outbounds: Option<&[Value]>,
        mode: OutboundTestMode,
    ) -> Result<Vec<OutboundTestResult>> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            outbounds: &'a str,
            all_outbounds: &'a str,
            mode: &'a str,
        }

        let outbounds = encode_json("test outbounds", outbounds)?;
        let all_outbounds = encode_optional_json("test outbound dependencies", all_outbounds)?;
        self.post_form_object(
            "testOutbounds",
            &Form {
                outbounds: &outbounds,
                all_outbounds: &all_outbounds,
                mode: mode.as_str(),
            },
        )
        .await
    }

    /// Returns live status for comma-separated balancer tags.
    pub async fn balancer_status(
        self,
        tags: &[impl AsRef<str>],
    ) -> Result<BTreeMap<String, BalancerStatus>> {
        #[derive(Serialize)]
        struct Form {
            tags: String,
        }
        let tags = tags.iter().map(AsRef::as_ref).collect::<Vec<_>>().join(",");
        self.post_form_object("balancerStatus", &Form { tags })
            .await
    }

    /// Forces a balancer target, or clears the override when `target` is empty.
    pub async fn set_balancer_override(self, tag: &str, target: &str) -> Result<()> {
        #[derive(Serialize)]
        struct Form<'a> {
            tag: &'a str,
            target: &'a str,
        }
        self.post_form_empty("balancerOverride", &Form { tag, target })
            .await
    }

    /// Asks the running Xray router how it would route a synthetic connection.
    pub async fn test_route(self, request: &RouteTestRequest) -> Result<RouteTestResult> {
        self.post_form_object("routeTest", request).await
    }

    /// Lists stored remote outbound subscriptions.
    pub async fn outbound_subscriptions(self) -> Result<Vec<OutboundSubscription>> {
        self.get_object("outbound-subs").await
    }
    /// Creates a remote outbound subscription.
    pub async fn create_outbound_subscription(
        self,
        input: &OutboundSubscriptionInput,
    ) -> Result<OutboundSubscription> {
        self.post_form_object("outbound-subs", input).await
    }
    /// Refreshes and returns parsed outbounds for a subscription.
    pub async fn refresh_outbound_subscription(self, id: i64) -> Result<OutboundDocuments> {
        self.post_form_object(&format!("outbound-subs/{id}/refresh"), &())
            .await
    }
    /// Moves a subscription up or down in merge order.
    pub async fn move_outbound_subscription(self, id: i64, direction: MoveDirection) -> Result<()> {
        #[derive(Serialize)]
        struct Form<'a> {
            dir: &'a str,
        }
        self.post_form_empty(
            &format!("outbound-subs/{id}/move"),
            &Form {
                dir: direction.as_str(),
            },
        )
        .await
    }
    /// Replaces a stored outbound subscription.
    pub async fn update_outbound_subscription(
        self,
        id: i64,
        input: &OutboundSubscriptionInput,
    ) -> Result<()> {
        self.post_form_empty(&format!("outbound-subs/{id}"), input)
            .await
    }
    /// Deletes a subscription with HTTP DELETE.
    pub async fn delete_outbound_subscription(self, id: i64) -> Result<()> {
        let path = format!("{XRAY_ROOT}/outbound-subs/{id}");
        self.client
            .execute::<Value, ()>(Method::DELETE, &path, None, AuthenticationScope::PanelApi)
            .await?;
        Ok(())
    }
    /// Deletes a subscription through the POST compatibility alias.
    pub async fn delete_outbound_subscription_via_post(self, id: i64) -> Result<()> {
        self.post_form_empty(&format!("outbound-subs/{id}/del"), &())
            .await
    }
    /// Fetches and parses a remote subscription without retaining it.
    pub async fn parse_outbound_subscription(
        self,
        url: &str,
        allow_private: bool,
        allow_insecure: bool,
    ) -> Result<OutboundDocuments> {
        self.parse_outbound_subscription_with_user_agent(url, allow_private, allow_insecure, "")
            .await
    }

    /// Fetches a remote subscription with a custom user agent without retaining it.
    pub async fn parse_outbound_subscription_with_user_agent(
        self,
        url: &str,
        allow_private: bool,
        allow_insecure: bool,
        user_agent: &str,
    ) -> Result<OutboundDocuments> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Form<'a> {
            url: &'a str,
            allow_private: bool,
            allow_insecure: bool,
            user_agent: &'a str,
        }
        self.post_form_object(
            "outbound-subs/parse",
            &Form {
                url,
                allow_private,
                allow_insecure,
                user_agent,
            },
        )
        .await
    }

    async fn integration<T, B>(self, family: &str, action: &str, form: Option<&B>) -> Result<T>
    where
        T: DeserializeOwned,
        B: Serialize + ?Sized,
    {
        let path = format!("{XRAY_ROOT}/{family}/{}", segment(action));
        let envelope = match form {
            Some(form) => {
                self.client
                    .execute_form(Method::POST, &path, form, AuthenticationScope::PanelApi)
                    .await?
            }
            None => {
                self.client
                    .execute::<T, ()>(Method::POST, &path, None, AuthenticationScope::PanelApi)
                    .await?
            }
        };
        required_object(self.client, Method::POST, &path, envelope)
    }

    async fn integration_empty<B>(self, family: &str, action: &str, form: Option<&B>) -> Result<()>
    where
        B: Serialize + ?Sized,
    {
        let path = format!("{XRAY_ROOT}/{family}/{}", segment(action));
        match form {
            Some(form) => {
                self.client
                    .execute_form::<Value, _>(
                        Method::POST,
                        &path,
                        form,
                        AuthenticationScope::PanelApi,
                    )
                    .await?;
            }
            None => {
                self.client
                    .execute::<Value, ()>(Method::POST, &path, None, AuthenticationScope::PanelApi)
                    .await?;
            }
        }
        Ok(())
    }

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

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

    async fn post_form_empty<B>(self, suffix: &str, form: &B) -> Result<()>
    where
        B: Serialize + ?Sized,
    {
        let path = format!("{XRAY_ROOT}/{suffix}");
        self.client
            .execute_form::<Value, _>(Method::POST, &path, form, AuthenticationScope::PanelApi)
            .await?;
        Ok(())
    }
}

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

fn encode_json<T: Serialize + ?Sized>(operation: &'static str, value: &T) -> Result<String> {
    serde_json::to_string(value).map_err(|source| Error::Encode { operation, source })
}

fn encode_optional_json<T: Serialize + ?Sized>(
    operation: &'static str,
    value: Option<&T>,
) -> Result<String> {
    value.map_or_else(|| Ok(String::new()), |value| encode_json(operation, value))
}

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