xui-rs 2.0.1

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
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! Inbound configuration, traffic, fallback, import, and lifecycle APIs.

use std::fmt;

use reqwest::Method;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;

use crate::{Client, Error, Result, client::AuthenticationScope, response::ApiResponse};

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

/// Xray protocols accepted by 3x-ui v3.8.5 inbound endpoints.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum InboundProtocol {
    /// `VMess`.
    Vmess,
    /// VLESS.
    Vless,
    /// Trojan.
    Trojan,
    /// Shadowsocks.
    Shadowsocks,
    /// `WireGuard`.
    Wireguard,
    /// Hysteria (including Hysteria 2 through stream settings).
    Hysteria,
    /// HTTP proxy.
    Http,
    /// Mixed HTTP/SOCKS proxy.
    Mixed,
    /// Tunnel.
    Tunnel,
    /// TUN interface.
    Tun,
    /// `MTProto` proxy.
    Mtproto,
    /// Embedded `AmneziaWG` tunnel.
    Amneziawg,
    /// TUIC v5 through the bundled sidecar.
    Tuic,
}

impl InboundProtocol {
    /// Returns the protocol name used by 3x-ui and Xray.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Vmess => "vmess",
            Self::Vless => "vless",
            Self::Trojan => "trojan",
            Self::Shadowsocks => "shadowsocks",
            Self::Wireguard => "wireguard",
            Self::Hysteria => "hysteria",
            Self::Http => "http",
            Self::Mixed => "mixed",
            Self::Tunnel => "tunnel",
            Self::Tun => "tun",
            Self::Mtproto => "mtproto",
            Self::Amneziawg => "amneziawg",
            Self::Tuic => "tuic",
        }
    }
}

/// Schedule used to reset an inbound's traffic counters.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum TrafficReset {
    /// Never reset counters automatically.
    #[default]
    Never,
    /// Reset every hour.
    Hourly,
    /// Reset every day.
    Daily,
    /// Reset every week.
    Weekly,
    /// Reset every month.
    Monthly,
}

/// Strategy used to choose the public address in generated share links.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ShareAddressStrategy {
    /// Prefer the hosting node's public address.
    #[default]
    Node,
    /// Use the inbound listen address.
    Listen,
    /// Use the explicitly configured share address.
    Custom,
}

/// Per-client traffic state returned with an inbound.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTraffic {
    /// Database row identifier.
    pub id: i64,
    /// Parent inbound identifier.
    pub inbound_id: i64,
    /// Whether this client is enabled.
    pub enable: bool,
    /// Globally unique client email/name.
    pub email: String,
    /// Protocol client identifier, when applicable.
    #[serde(default)]
    pub uuid: String,
    /// Subscription identifier.
    #[serde(default)]
    pub sub_id: String,
    /// Uploaded bytes.
    pub up: i64,
    /// Downloaded bytes.
    pub down: i64,
    /// Expiration timestamp in milliseconds, or zero when unlimited.
    pub expiry_time: i64,
    /// Traffic limit in bytes, or zero when unlimited.
    pub total: i64,
    /// Client traffic reset policy encoded by the panel.
    pub reset: i32,
    /// Most recent online timestamp in milliseconds.
    pub last_online: i64,
    /// Most recent subscription fetch timestamp in milliseconds.
    #[serde(default)]
    pub last_sub_fetch: i64,
    /// Calendar renewal day; zero selects interval-based renewal.
    #[serde(default)]
    pub reset_day: i32,
    /// Maximum number of automatic renewals; zero is unlimited.
    #[serde(default)]
    pub reset_max: i32,
    /// Number of automatic renewals already applied.
    #[serde(default)]
    pub reset_count: i32,
}

impl fmt::Debug for ClientTraffic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ClientTraffic")
            .field("id", &self.id)
            .field("inbound_id", &self.inbound_id)
            .field("enable", &self.enable)
            .field("email", &self.email)
            .field("uuid", &"[REDACTED]")
            .field("sub_id", &"[REDACTED]")
            .field("up", &self.up)
            .field("down", &self.down)
            .field("expiry_time", &self.expiry_time)
            .field("total", &self.total)
            .field("reset", &self.reset)
            .field("last_online", &self.last_online)
            .field("last_sub_fetch", &self.last_sub_fetch)
            .field("reset_day", &self.reset_day)
            .field("reset_max", &self.reset_max)
            .field("reset_count", &self.reset_count)
            .finish()
    }
}

/// Complete writable configuration accepted by create, update, and import.
///
/// Use [`InboundConfig::new`] for safe panel defaults. Convert a fetched
/// [`Inbound`] with [`Inbound::to_config`] before replacing it through
/// [`InboundsApi::update`]. The open-ended JSON fields intentionally mirror
/// Xray's protocol-specific configuration fragments.
#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InboundConfig {
    /// Uploaded bytes to seed during import.
    pub up: i64,
    /// Downloaded bytes to seed during import.
    pub down: i64,
    /// Traffic limit in bytes, or zero when unlimited.
    pub total: i64,
    /// Human-readable label.
    pub remark: String,
    /// Position in subscription output; negatives are allowed, and zero normalizes to one.
    pub sub_sort_index: i32,
    /// Whether the inbound is enabled.
    pub enable: bool,
    /// Disables client flow values when generating subscription links.
    #[serde(default)]
    pub disable_flow: bool,
    /// Expiration timestamp in milliseconds, or zero when unlimited.
    pub expiry_time: i64,
    /// Automatic traffic reset schedule.
    pub traffic_reset: TrafficReset,
    /// Day of month used by monthly reset schedules.
    pub traffic_reset_day: u8,
    /// Most recent automatic reset timestamp in milliseconds.
    pub last_traffic_reset_time: i64,
    /// Per-client traffic rows preserved by imports.
    #[serde(default)]
    pub client_stats: Vec<ClientTraffic>,
    /// Local listen address, or an empty string for all interfaces.
    pub listen: String,
    /// Listen port; zero lets compatible server flows choose it.
    pub port: u16,
    /// Xray inbound protocol.
    pub protocol: InboundProtocol,
    /// Protocol-specific Xray settings object.
    pub settings: Value,
    /// Transport and security settings object.
    pub stream_settings: Value,
    /// Stable Xray tag; leave empty on create to let 3x-ui generate it.
    pub tag: String,
    /// Xray sniffing settings object.
    pub sniffing: Value,
    /// Hosting node identifier, or `None` for the local panel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<i64>,
    /// Public share-address selection strategy.
    pub share_addr_strategy: ShareAddressStrategy,
    /// Explicit share address used with the custom strategy.
    pub share_addr: String,
}

impl InboundConfig {
    /// Creates an enabled configuration with unlimited traffic and safe panel defaults.
    pub fn new(protocol: InboundProtocol, port: u16) -> Self {
        Self {
            up: 0,
            down: 0,
            total: 0,
            remark: String::new(),
            sub_sort_index: 1,
            enable: true,
            disable_flow: false,
            expiry_time: 0,
            traffic_reset: TrafficReset::Never,
            traffic_reset_day: 1,
            last_traffic_reset_time: 0,
            client_stats: Vec::new(),
            listen: String::new(),
            port,
            protocol,
            settings: Value::Object(serde_json::Map::new()),
            stream_settings: Value::Object(serde_json::Map::new()),
            tag: String::new(),
            sniffing: Value::Object(serde_json::Map::new()),
            node_id: None,
            share_addr_strategy: ShareAddressStrategy::Node,
            share_addr: String::new(),
        }
    }
}

impl fmt::Debug for InboundConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InboundConfig")
            .field("up", &self.up)
            .field("down", &self.down)
            .field("total", &self.total)
            .field("remark", &self.remark)
            .field("sub_sort_index", &self.sub_sort_index)
            .field("enable", &self.enable)
            .field("disable_flow", &self.disable_flow)
            .field("expiry_time", &self.expiry_time)
            .field("traffic_reset", &self.traffic_reset)
            .field("traffic_reset_day", &self.traffic_reset_day)
            .field("last_traffic_reset_time", &self.last_traffic_reset_time)
            .field("client_stats", &self.client_stats)
            .field("listen", &self.listen)
            .field("port", &self.port)
            .field("protocol", &self.protocol)
            .field("settings", &"[REDACTED]")
            .field("stream_settings", &"[REDACTED]")
            .field("tag", &self.tag)
            .field("sniffing", &"[REDACTED]")
            .field("node_id", &self.node_id)
            .field("share_addr_strategy", &self.share_addr_strategy)
            .field("share_addr", &self.share_addr)
            .finish()
    }
}

/// Metadata describing a master inbound used by a fallback child.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FallbackParent {
    /// Master inbound identifier.
    pub master_id: i64,
    /// Match path on the master.
    #[serde(default)]
    pub path: String,
}

/// Full inbound record returned by 3x-ui.
#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Inbound {
    /// Inbound identifier.
    pub id: i64,
    /// Writable configuration and current traffic state.
    #[serde(flatten)]
    pub config: InboundConfig,
    /// GUID of the node where the inbound originated.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub origin_node_guid: String,
    /// Master relationship when this inbound is used as a fallback.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback_parent: Option<FallbackParent>,
}

impl Inbound {
    /// Clones the complete writable payload for update or import.
    pub fn to_config(&self) -> InboundConfig {
        self.config.clone()
    }

    /// Consumes the response and returns its writable payload.
    pub fn into_config(self) -> InboundConfig {
        self.config
    }
}

impl fmt::Debug for Inbound {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Inbound")
            .field("id", &self.id)
            .field("config", &self.config)
            .field("origin_node_guid", &self.origin_node_guid)
            .field("fallback_parent", &self.fallback_parent)
            .finish()
    }
}

/// Lightweight inbound projection used by picker UIs.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InboundOption {
    /// Inbound identifier.
    pub id: i64,
    /// Human-readable label.
    pub remark: String,
    /// Stable Xray tag.
    pub tag: String,
    /// Xray inbound protocol.
    pub protocol: InboundProtocol,
    /// Listen port.
    pub port: u16,
    /// Whether the inbound is enabled.
    pub enable: bool,
    /// Whether the transport supports VLESS Vision flow.
    pub tls_flow_capable: bool,
    /// Shadowsocks method, when applicable.
    #[serde(default)]
    pub ss_method: String,
    /// `WireGuard` public key, when applicable.
    #[serde(default)]
    pub wg_public_key: String,
    /// `WireGuard` MTU, when applicable.
    #[serde(default)]
    pub wg_mtu: u32,
    /// `WireGuard` DNS value, when applicable.
    #[serde(default)]
    pub wg_dns: String,
    /// `MTProto` domain, when applicable.
    #[serde(default)]
    pub mtproto_domain: String,
    /// Hosting node identifier.
    #[serde(default)]
    pub node_id: Option<i64>,
    /// Hosting node's externally reachable address.
    #[serde(default)]
    pub node_address: String,
    /// Local listen address.
    #[serde(default)]
    pub listen: String,
    /// Explicit public share address.
    #[serde(default)]
    pub share_addr: String,
    /// Share-address strategy, when populated by the panel.
    #[serde(default)]
    pub share_addr_strategy: Option<ShareAddressStrategy>,
    /// Complete `AmneziaWG` server settings, when applicable.
    #[serde(default)]
    pub awg_server: Option<AmneziaWgServerSettings>,
    /// Transport network, when supplied by the panel.
    #[serde(default)]
    pub network: String,
    /// Transport security, when supplied by the panel.
    #[serde(default)]
    pub security: String,
    /// Complete TUIC sidecar settings, when applicable.
    #[serde(default)]
    pub tuic_server: Option<TuicServerSettings>,
}

/// Server-side settings embedded in an `AmneziaWG` inbound.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct AmneziaWgServerSettings {
    /// Server tunnel private key.
    pub private_key: String,
    /// Server tunnel public key.
    pub public_key: String,
    /// IPv4 subnet address.
    pub subnet_ip: String,
    /// IPv4 subnet prefix length.
    pub subnet_cidr: u8,
    /// Primary DNS server offered to clients.
    pub primary_dns: String,
    /// Secondary DNS server offered to clients.
    pub secondary_dns: String,
    /// Tunnel MTU.
    pub mtu: i32,
    /// Preferred external interface.
    pub external_interface: String,
    /// Enables IPv6 tunnel addressing.
    pub ipv6_enabled: bool,
    /// IPv6 subnet.
    pub ipv6_subnet: String,
    /// Preferred external IPv6 interface.
    pub ipv6_external_interface: String,
    /// Legacy routing flag retained by 3x-ui for stored configurations.
    pub route_through_xray: bool,
    /// `AmneziaWG` junk packet count.
    pub jc: i32,
    /// Minimum junk packet size.
    pub jmin: i32,
    /// Maximum junk packet size.
    pub jmax: i32,
    /// Obfuscation header value.
    pub s1: i32,
    /// Obfuscation header value.
    pub s2: i32,
    /// Obfuscation header value.
    pub s3: i32,
    /// Obfuscation header value.
    pub s4: i32,
    /// Magic header value.
    pub h1: String,
    /// Magic header value.
    pub h2: String,
    /// Magic header value.
    pub h3: String,
    /// Magic header value.
    pub h4: String,
    /// Init packet signature value.
    pub i1: String,
    /// Response packet signature value.
    pub i2: String,
    /// Under-load packet signature value.
    pub i3: String,
    /// Transport packet signature value.
    pub i4: String,
    /// Additional transport signature value.
    pub i5: String,
    /// Rekey interval accepted by `AmneziaWG`.
    pub rekey_after_time: String,
    /// Rekey timeout accepted by `AmneziaWG`.
    pub rekey_timeout: String,
    /// Reject-after interval accepted by `AmneziaWG`.
    pub reject_after_time: String,
    /// Keepalive timeout accepted by `AmneziaWG`.
    pub keepalive_timeout: String,
    /// Maximum handshake attempts accepted by `AmneziaWG`.
    pub max_handshake_attempts: String,
    /// Enables randomized trailer bytes.
    pub random_trailers: bool,
    /// Disables `AmneziaWG` cookies.
    pub disable_cookies: bool,
    /// Base64 header-protection key for `AmneziaWG` 3.0.
    pub header_protection_key: String,
    /// Padding range for `AmneziaWG` 3.0.
    pub content_padding_addition: String,
}

/// A persisted fallback rule attached to a master inbound.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InboundFallback {
    /// Fallback row identifier.
    pub id: i64,
    /// Master inbound identifier.
    pub master_id: i64,
    /// Child inbound identifier.
    pub child_id: i64,
    /// Optional SNI/server name match.
    pub name: String,
    /// Optional ALPN match.
    pub alpn: String,
    /// Optional path match.
    pub path: String,
    /// Explicit Xray destination, or empty to derive it from the child.
    pub dest: String,
    /// PROXY protocol version.
    pub xver: i32,
    /// Stable ordering value.
    pub sort_order: i32,
}

/// Input used when atomically replacing a master's fallback rules.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FallbackInput {
    /// Child inbound identifier.
    pub child_id: i64,
    /// Optional SNI/server name match.
    pub name: String,
    /// Optional ALPN match.
    pub alpn: String,
    /// Optional path match.
    pub path: String,
    /// Explicit Xray destination, or empty to derive it from the child.
    pub dest: String,
    /// PROXY protocol version.
    pub xver: i32,
    /// Stable ordering value.
    pub sort_order: i32,
}

/// An inbound that could not be deleted by a bulk operation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct SkippedInbound {
    /// Inbound identifier.
    pub id: i64,
    /// Server-provided failure reason.
    pub reason: String,
}

/// Result of deleting multiple inbounds.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct BulkDeleteInboundsResult {
    /// Number of deleted inbounds.
    pub deleted: u64,
    /// Per-inbound failures; other inbounds were still processed.
    #[serde(default)]
    pub skipped: Vec<SkippedInbound>,
}

/// A client that could not be deleted by a bulk operation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct SkippedClient {
    /// Client email/name.
    pub email: String,
    /// Server-provided failure reason.
    pub reason: String,
}

/// Result of deleting all clients from one inbound.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct BulkDeleteClientsResult {
    /// Number of deleted clients.
    pub deleted: u64,
    /// Per-client failures; other clients were still processed.
    #[serde(default)]
    pub skipped: Vec<SkippedClient>,
}

/// Minimal per-client aggregate consumed by traffic synchronization.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTrafficUsage {
    /// Client email/name known to the receiving panel.
    pub email: String,
    /// Aggregated uploaded bytes.
    pub up: i64,
    /// Aggregated downloaded bytes.
    pub down: i64,
}

/// Traffic snapshot pushed from a master panel.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrafficPushRequest {
    /// Stable GUID of the sending master panel.
    pub master_guid: String,
    /// Aggregated per-client usage rows.
    pub traffics: Vec<ClientTrafficUsage>,
}

impl TrafficPushRequest {
    /// Creates a traffic snapshot for a master panel.
    pub fn new(master_guid: impl Into<String>, traffics: Vec<ClientTrafficUsage>) -> Self {
        Self {
            master_guid: master_guid.into(),
            traffics,
        }
    }
}

/// Inbound management endpoints for a [`Client`].
#[derive(Clone, Copy, Debug)]
pub struct InboundsApi<'client> {
    client: &'client Client,
}

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

    /// Returns all inbounds with complete client configuration.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response violates the
    /// v3.8.5 contract.
    pub async fn list(self) -> Result<Vec<Inbound>> {
        self.get_object("list").await
    }

    /// Returns all inbounds with slimmed `settings.clients` entries.
    ///
    /// The outer response remains [`Inbound`]; protocol-specific client JSON
    /// contains only the fields selected by 3x-ui's slim endpoint.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response is invalid.
    pub async fn list_slim(self) -> Result<Vec<Inbound>> {
        self.get_object("list/slim").await
    }

    /// Returns lightweight inbound options for selectors and dashboards.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response is invalid.
    pub async fn options(self) -> Result<Vec<InboundOption>> {
        self.get_object("options").await
    }

    /// Returns every generated inbound share link.
    ///
    /// An empty panel encodes its nil Go slice as `obj: null`; the SDK
    /// normalizes that response to an empty vector.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response is invalid.
    pub async fn all_links(self) -> Result<Vec<String>> {
        let path = format!("{ROOT}/allLinks");
        let envelope = self
            .client
            .execute::<Vec<String>, ()>(Method::GET, &path, None, AuthenticationScope::PanelApi)
            .await?;
        Ok(envelope.obj.unwrap_or_default())
    }

    /// Fetches one inbound by identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response is invalid.
    pub async fn get(self, id: i64) -> Result<Inbound> {
        self.get_object(&format!("get/{id}")).await
    }

    /// Creates a new inbound.
    ///
    /// # Errors
    ///
    /// Returns an error when validation fails, the request fails, or the
    /// response is invalid.
    pub async fn create(self, inbound: &InboundConfig) -> Result<Inbound> {
        self.post_object("add", Some(inbound)).await
    }

    /// Permanently deletes one inbound and returns its identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when deletion fails or the response is invalid.
    pub async fn delete(self, id: i64) -> Result<i64> {
        self.post_object::<i64, ()>(&format!("del/{id}"), None)
            .await
    }

    /// Deletes multiple inbounds, retaining per-item failure reports.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation itself fails or its response
    /// is invalid.
    pub async fn delete_many(self, ids: &[i64]) -> Result<BulkDeleteInboundsResult> {
        #[derive(Serialize)]
        struct Body<'a> {
            ids: &'a [i64],
        }

        self.post_object("bulkDel", Some(&Body { ids })).await
    }

    /// Replaces an inbound's complete writable configuration.
    ///
    /// Start from [`Inbound::to_config`] when editing an existing inbound;
    /// 3x-ui's update endpoint is a replacement operation rather than PATCH.
    ///
    /// # Errors
    ///
    /// Returns an error when validation fails, the request fails, or the
    /// response is invalid.
    pub async fn update(self, id: i64, inbound: &InboundConfig) -> Result<Inbound> {
        self.post_object(&format!("update/{id}"), Some(inbound))
            .await
    }

    /// Enables or disables an inbound without sending its large settings JSON.
    ///
    /// # Errors
    ///
    /// Returns an error when the panel cannot persist or apply the change.
    pub async fn set_enabled(self, id: i64, enable: bool) -> Result<()> {
        #[derive(Serialize)]
        struct Body {
            enable: bool,
        }

        self.post_empty(&format!("setEnable/{id}"), Some(&Body { enable }))
            .await
    }

    /// Changes only the inbound's nonzero subscription ordering index (negatives allowed).
    ///
    /// This avoids replacing large protocol settings and potentially writing
    /// a stale client list during a concurrent edit.
    ///
    /// # Errors
    ///
    /// Returns an error when the index is invalid or cannot be persisted.
    pub async fn set_subscription_sort_index(self, id: i64, sub_sort_index: i32) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Body {
            sub_sort_index: i32,
        }

        self.post_empty(
            &format!("{id}/subSortIndex"),
            Some(&Body { sub_sort_index }),
        )
        .await
    }

    /// Resets all traffic counters for one inbound.
    ///
    /// # Errors
    ///
    /// Returns an error when the panel cannot reset the counters.
    pub async fn reset_traffic(self, id: i64) -> Result<()> {
        self.post_empty::<()>(&format!("{id}/resetTraffic"), None)
            .await
    }

    /// Deletes every client attached to one inbound.
    ///
    /// # Errors
    ///
    /// Returns an error when the bulk operation itself fails or its response
    /// is invalid.
    pub async fn delete_all_clients(self, id: i64) -> Result<BulkDeleteClientsResult> {
        self.post_object::<BulkDeleteClientsResult, ()>(&format!("{id}/delAllClients"), None)
            .await
    }

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

    /// Imports a complete inbound configuration using the panel's form endpoint.
    ///
    /// Unlike [`InboundsApi::create`], this preserves supplied client traffic
    /// rows while resetting panel-local database identifiers.
    ///
    /// # Errors
    ///
    /// Returns an error when JSON/form encoding, validation, transport, or
    /// response decoding fails.
    pub async fn import(self, inbound: &InboundConfig) -> Result<Inbound> {
        #[derive(Serialize)]
        struct Form<'a> {
            data: &'a str,
        }

        let data = serde_json::to_string(inbound).map_err(|source| Error::Encode {
            operation: "import inbound",
            source,
        })?;
        let path = format!("{ROOT}/import");
        let envelope = self
            .client
            .execute_form::<Inbound, _>(
                Method::POST,
                &path,
                &Form { data: &data },
                AuthenticationScope::PanelApi,
            )
            .await?;
        self.required_object(Method::POST, &path, envelope)
    }

    /// Pushes a master's aggregate client traffic snapshot.
    ///
    /// # Errors
    ///
    /// Returns an error when the receiving panel rejects the snapshot.
    pub async fn push_client_traffic(self, traffic: &TrafficPushRequest) -> Result<()> {
        self.post_empty("pushClientTraffics", Some(traffic)).await
    }

    /// Returns fallback rules attached to a master inbound.
    ///
    /// # Errors
    ///
    /// Returns an error when the request fails or the response is invalid.
    pub async fn fallbacks(self, id: i64) -> Result<Vec<InboundFallback>> {
        self.get_object(&format!("{id}/fallbacks")).await
    }

    /// Atomically replaces every fallback rule on a master inbound.
    ///
    /// # Errors
    ///
    /// Returns an error when validation or replacement fails.
    pub async fn set_fallbacks(self, id: i64, fallbacks: &[FallbackInput]) -> Result<()> {
        #[derive(Serialize)]
        struct Body<'a> {
            fallbacks: &'a [FallbackInput],
        }

        self.post_empty(&format!("{id}/fallbacks"), Some(&Body { fallbacks }))
            .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_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),
        })
    }
}

/// TUIC v5 server settings, using the sidecar's `snake_case` wire names.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct TuicServerSettings {
    /// Certificate file path.
    pub certificate: String,
    /// Private-key file path.
    pub private_key: String,
    /// Congestion control algorithm, such as `bbr`.
    pub congestion_control: String,
    /// Advertised ALPN protocols.
    pub alpn: Vec<String>,
    /// UDP relay mode, such as `native`.
    pub udp_relay_mode: String,
    /// Enables zero-RTT handshakes.
    pub zero_rtt_handshake: bool,
    /// Sidecar log level.
    pub log_level: String,
    /// Maximum idle duration in seconds.
    pub max_idle_time: i32,
    /// Authentication timeout in seconds.
    pub authentication_timeout: i32,
    /// Maximum relayed UDP packet size in bytes.
    pub max_udp_relay_packet_size: i32,
    /// TLS server name.
    pub sni: String,
}

impl fmt::Debug for TuicServerSettings {
    /// Formats TUIC transport settings while redacting the private key and omitting other details.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TuicServerSettings")
            .field("private_key", &"[REDACTED]")
            .field("congestion_control", &self.congestion_control)
            .field("alpn", &self.alpn)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::*;

    const SDK_ROUTES: &[(&str, &str, Option<&str>)] = &[
        (
            "get",
            "/panel/api/inbounds/list",
            Some("get_panel_api_inbounds_list"),
        ),
        (
            "get",
            "/panel/api/inbounds/list/slim",
            Some("get_panel_api_inbounds_list_slim"),
        ),
        (
            "get",
            "/panel/api/inbounds/options",
            Some("get_panel_api_inbounds_options"),
        ),
        (
            "get",
            "/panel/api/inbounds/allLinks",
            Some("get_panel_api_inbounds_allLinks"),
        ),
        (
            "get",
            "/panel/api/inbounds/get/{id}",
            Some("get_panel_api_inbounds_get_id"),
        ),
        (
            "get",
            "/panel/api/inbounds/{id}/fallbacks",
            Some("get_panel_api_inbounds_id_fallbacks"),
        ),
        (
            "post",
            "/panel/api/inbounds/add",
            Some("post_panel_api_inbounds_add"),
        ),
        (
            "post",
            "/panel/api/inbounds/del/{id}",
            Some("post_panel_api_inbounds_del_id"),
        ),
        (
            "post",
            "/panel/api/inbounds/bulkDel",
            Some("post_panel_api_inbounds_bulkDel"),
        ),
        (
            "post",
            "/panel/api/inbounds/update/{id}",
            Some("post_panel_api_inbounds_update_id"),
        ),
        (
            "post",
            "/panel/api/inbounds/setEnable/{id}",
            Some("post_panel_api_inbounds_setEnable_id"),
        ),
        (
            "post",
            "/panel/api/inbounds/{id}/subSortIndex",
            Some("post_panel_api_inbounds_id_subSortIndex"),
        ),
        (
            "post",
            "/panel/api/inbounds/{id}/resetTraffic",
            Some("post_panel_api_inbounds_id_resetTraffic"),
        ),
        (
            "post",
            "/panel/api/inbounds/{id}/delAllClients",
            Some("post_panel_api_inbounds_id_delAllClients"),
        ),
        (
            "post",
            "/panel/api/inbounds/resetAllTraffics",
            Some("post_panel_api_inbounds_resetAllTraffics"),
        ),
        (
            "post",
            "/panel/api/inbounds/import",
            Some("post_panel_api_inbounds_import"),
        ),
        (
            "post",
            "/panel/api/inbounds/{id}/fallbacks",
            Some("post_panel_api_inbounds_id_fallbacks"),
        ),
        (
            "post",
            "/panel/api/inbounds/pushClientTraffics",
            Some("post_panel_api_inbounds_pushClientTraffics"),
        ),
    ];

    /// Compares the SDK route inventory with both tagged `OpenAPI` operations and Go-router snapshots.
    /// Source-only routes are checked separately so omissions in `OpenAPI` cannot hide SDK gaps.
    #[test]
    fn sdk_covers_openapi_and_source_routes() {
        let openapi: Value =
            serde_json::from_str(include_str!("../spec/3x-ui-v3.8.5.openapi.json")).unwrap();
        let paths = openapi["paths"].as_object().unwrap();
        let http_methods = [
            "get", "post", "put", "patch", "delete", "head", "options", "trace",
        ];
        let operation_count = paths
            .values()
            .filter_map(Value::as_object)
            .flat_map(serde_json::Map::keys)
            .filter(|method| http_methods.contains(&method.as_str()))
            .count();
        assert_eq!(operation_count, 193, "vendored OpenAPI changed");

        let documented = paths
            .iter()
            .flat_map(|(path, item)| {
                item.as_object().into_iter().flat_map(move |operations| {
                    operations
                        .iter()
                        .filter(|(_, operation)| {
                            operation["tags"]
                                .as_array()
                                .is_some_and(|tags| tags.iter().any(|tag| tag == "Inbounds"))
                        })
                        .map(move |(method, operation)| {
                            (
                                method.as_str(),
                                path.as_str(),
                                operation["operationId"].as_str().unwrap(),
                            )
                        })
                })
            })
            .collect::<BTreeSet<_>>();
        let implemented_openapi = SDK_ROUTES
            .iter()
            .filter_map(|(method, path, operation)| {
                operation.map(|operation| (*method, *path, operation))
            })
            .collect::<BTreeSet<_>>();
        assert_eq!(documented, implemented_openapi);

        let source: Value =
            serde_json::from_str(include_str!("../spec/3x-ui-v3.8.5.inbounds-routes.json"))
                .unwrap();
        let source_routes = source["routes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|route| {
                (
                    route["method"].as_str().unwrap(),
                    route["path"].as_str().unwrap(),
                )
            })
            .collect::<BTreeSet<_>>();
        let implemented_routes = SDK_ROUTES
            .iter()
            .map(|(method, path, _)| (*method, *path))
            .collect::<BTreeSet<_>>();
        assert_eq!(source_routes, implemented_routes);
    }

    #[test]
    fn defaults_match_server_normalization() {
        let config = InboundConfig::new(InboundProtocol::Vless, 443);
        assert!(config.enable);
        assert_eq!(config.sub_sort_index, 1);
        assert_eq!(config.traffic_reset, TrafficReset::Never);
        assert_eq!(config.traffic_reset_day, 1);
        assert_eq!(config.share_addr_strategy, ShareAddressStrategy::Node);
    }

    #[test]
    fn sensitive_xray_values_are_redacted_from_debug() {
        let mut config = InboundConfig::new(InboundProtocol::Trojan, 443);
        config.settings = serde_json::json!({"clients": [{"password": "secret"}]});
        config.stream_settings = serde_json::json!({"privateKey": "private-secret"});
        let output = format!("{config:?}");
        assert!(!output.contains("secret"));
        assert!(!output.contains("private-secret"));
    }

    /// Checks that `WireGuard` and remote-node option fields decode into their typed SDK fields.
    #[test]
    fn actual_v385_option_extensions_are_typed() {
        let option: InboundOption = serde_json::from_value(serde_json::json!({
            "id": 7,
            "remark": "wg",
            "tag": "in-wg",
            "protocol": "wireguard",
            "port": 51820,
            "enable": true,
            "tlsFlowCapable": false,
            "ssMethod": "",
            "wgPublicKey": "public",
            "wgMtu": 1420,
            "wgDns": "1.1.1.1",
            "nodeId": 3,
            "nodeAddress": "node.example.com",
            "shareAddrStrategy": "node"
        }))
        .unwrap();

        assert_eq!(option.wg_mtu, 1420);
        assert_eq!(option.node_id, Some(3));
        assert_eq!(option.node_address, "node.example.com");
    }

    #[test]
    fn config_round_trips_nested_xray_json() {
        let mut config = InboundConfig::new(InboundProtocol::Vmess, 20_000);
        config.settings = serde_json::json!({"clients": [{"id": "client-secret"}]});
        let value = serde_json::to_value(&config).unwrap();
        let decoded: InboundConfig = serde_json::from_value(value.clone()).unwrap();
        assert_eq!(decoded, config);
        assert!(value["settings"].is_object());
    }

    /// Pins each inbound protocol to its Xray wire name, including the TUIC sidecar.
    #[test]
    fn every_inbound_protocol_has_the_exact_xray_name() {
        assert_eq!(
            [
                InboundProtocol::Vmess,
                InboundProtocol::Vless,
                InboundProtocol::Trojan,
                InboundProtocol::Shadowsocks,
                InboundProtocol::Wireguard,
                InboundProtocol::Hysteria,
                InboundProtocol::Http,
                InboundProtocol::Mixed,
                InboundProtocol::Tunnel,
                InboundProtocol::Tun,
                InboundProtocol::Mtproto,
                InboundProtocol::Amneziawg,
                InboundProtocol::Tuic,
            ]
            .map(InboundProtocol::as_str),
            [
                "vmess",
                "vless",
                "trojan",
                "shadowsocks",
                "wireguard",
                "hysteria",
                "http",
                "mixed",
                "tunnel",
                "tun",
                "mtproto",
                "amneziawg",
                "tuic",
            ]
        );
    }

    #[test]
    fn traffic_and_inbound_debug_redact_client_credentials() {
        let traffic: ClientTraffic = serde_json::from_value(serde_json::json!({
            "id": 1,
            "inboundId": 7,
            "enable": true,
            "email": "alice",
            "uuid": "traffic-uuid-secret",
            "subId": "traffic-sub-secret",
            "up": 10,
            "down": 20,
            "expiryTime": 0,
            "total": 100,
            "reset": 0,
            "lastOnline": 30
        }))
        .unwrap();
        let output = format!("{traffic:?}");
        assert!(output.contains("alice"));
        assert!(!output.contains("traffic-uuid-secret"));
        assert!(!output.contains("traffic-sub-secret"));

        let mut config = InboundConfig::new(InboundProtocol::Vless, 443);
        config.remark = "production".into();
        let inbound = Inbound {
            id: 7,
            config: config.clone(),
            origin_node_guid: "node-guid".into(),
            fallback_parent: Some(FallbackParent {
                master_id: 3,
                path: "/fallback".into(),
            }),
        };
        assert_eq!(inbound.to_config(), config);
        assert!(format!("{inbound:?}").contains("node-guid"));
        assert_eq!(inbound.into_config(), config);
    }
}