1
+use std::time::{SystemTime, UNIX_EPOCH};
2
+
3
+use reqwest::Method;
4
+use serde::Serialize;
5
+use serde_json::Value;
6
+
7
+use crate::auth::Credentials;
8
+use crate::error::{Error, Result};
9
+use crate::sign::{new_nonce, SignedHeaders};
10
+
11
+pub const API_ROOT: &str = "https://global.developer.mi.com";
12
+/// Order query. Needs allowlisting: email overseas-dev@xiaomi.com. At most one
13
+/// request a second and 30 days per query.
14
+pub const ORDER_QUERY_PATH: &str = "/third-api/order/v1/query";
15
+/// The APK upload address. Named in Xiaomi's header page as the GET example;
16
+/// its response shape is not public.
17
+pub const UPLOAD_URL_PATH: &str = "/third-api/apk/v1/getUploadUrl";
18
+
19
+/// Body of the order query. Lists are comma-separated, as the API takes them.
20
+#[derive(Debug, Clone, Serialize)]
21
+#[serde(rename_all = "camelCase")]
22
+pub struct OrderQuery {
23
+ pub pkgs: String,
24
+ #[serde(skip_serializing_if = "Option::is_none")]
25
+ pub regions: Option<String>,
26
+ /// 1 click to pay, 2 paid, 3 closed, 4 refund pending, 5 refund started,
27
+ /// 6 refunded.
28
+ #[serde(skip_serializing_if = "Option::is_none")]
29
+ pub pay_status: Option<String>,
30
+ /// 0 normal, 1 test, 2 promotion, 3 incentive.
31
+ #[serde(skip_serializing_if = "Option::is_none")]
32
+ pub pay_type: Option<i64>,
33
+ pub start_timestamp: u64,
34
+ pub end_timestamp: u64,
35
+}
36
+
37
+/// Longest window the order query accepts.
38
+pub const ORDER_QUERY_MAX_SECS: u64 = 30 * 24 * 60 * 60;
39
+
40
+impl OrderQuery {
41
+ /// The checks GetApps would otherwise answer with a 400.
42
+ pub fn validate(&self) -> std::result::Result<(), String> {
43
+ if self.pkgs.trim().is_empty() {
44
+ return Err("at least one package is required".into());
45
+ }
46
+ if self.end_timestamp <= self.start_timestamp {
47
+ return Err("the end time must be after the start time".into());
48
+ }
49
+ if self.end_timestamp - self.start_timestamp > ORDER_QUERY_MAX_SECS {
50
+ return Err("the window is longer than 30 days".into());
51
+ }
52
+ Ok(())
53
+ }
54
+}
55
+
56
+/// A prepared request: what would be sent, for `--dry-run`. Holds the
57
+/// signature, never the secret.
58
+#[derive(Debug, Clone)]
59
+pub struct Prepared {
60
+ pub method: Method,
61
+ pub url: String,
62
+ pub headers: SignedHeaders,
63
+ pub body: Option<String>,
64
+}
65
+
66
+impl Prepared {
67
+ /// What `--dry-run` prints: the method, URL, headers, canonical string
68
+ /// and body. The `Authorization` value is withheld: it is valid for 30
69
+ /// minutes.
70
+ pub fn describe(&self) -> Value {
71
+ let headers: serde_json::Map<String, Value> = self
72
+ .headers
73
+ .pairs()
74
+ .iter()
75
+ .map(|(name, value)| {
76
+ let shown = if *name == "Authorization" {
77
+ "<signature withheld>"
78
+ } else {
79
+ value
80
+ };
81
+ (name.to_string(), Value::String(shown.to_string()))
82
+ })
83
+ .collect();
84
+ serde_json::json!({
85
+ "method": self.method.as_str(),
86
+ "url": self.url,
87
+ "headers": headers,
88
+ "canonical": self.headers.canonical,
89
+ "body": self.body,
90
+ })
91
+ }
92
+}
93
+
94
+pub struct XiaomiClient {
95
+ http: reqwest::Client,
96
+ credentials: Credentials,
97
+ root: String,
98
+}
99
+
100
+impl XiaomiClient {
101
+ pub fn new(credentials: Credentials) -> Self {
102
+ Self {
103
+ http: reqwest::Client::new(),
104
+ credentials,
105
+ root: API_ROOT.to_string(),
106
+ }
107
+ }
108
+
109
+ /// Point at another host, for tests against a local server.
110
+ pub fn with_root(mut self, root: impl Into<String>) -> Self {
111
+ self.root = root.into();
112
+ self
113
+ }
114
+
115
+ pub fn package(&self) -> &str {
116
+ &self.credentials.package
117
+ }
118
+
119
+ /// Sign a request without sending it. `body` is serialized once here, and
120
+ /// those exact bytes are both hashed and sent.
121
+ pub fn prepare(
122
+ &self,
123
+ method: Method,
124
+ path: &str,
125
+ body: Option<&impl Serialize>,
126
+ ) -> Result<Prepared> {
127
+ let body = body.map(serde_json::to_string).transpose()?;
128
+ let timestamp = SystemTime::now()
129
+ .duration_since(UNIX_EPOCH)
130
+ .map(|d| d.as_secs())
131
+ .unwrap_or_default();
132
+ let headers = SignedHeaders::new(
133
+ &self.credentials,
134
+ method.as_str(),
135
+ path,
136
+ body.as_deref().map(str::as_bytes),
137
+ timestamp,
138
+ new_nonce(),
139
+ );
140
+ Ok(Prepared {
141
+ method,
142
+ url: format!("{}{path}", self.root),
143
+ headers,
144
+ body,
145
+ })
146
+ }
147
+
148
+ /// Send a prepared request and return the envelope's `data`. An HTTP error
149
+ /// or an envelope `code` other than 200 is an error carrying Xiaomi's
150
+ /// message.
151
+ pub async fn send(&self, prepared: Prepared) -> Result<Value> {
152
+ let mut request = self
153
+ .http
154
+ .request(prepared.method, &prepared.url)
155
+ .header("Content-Type", "application/json");
156
+ for (name, value) in prepared.headers.pairs() {
157
+ request = request.header(name, value);
158
+ }
159
+ if let Some(body) = prepared.body {
160
+ request = request.body(body);
161
+ }
162
+ let response = request.send().await?;
163
+ let status = response.status();
164
+ let text = response.text().await.unwrap_or_default();
165
+ if !status.is_success() {
166
+ return Err(Error::Http2xx {
167
+ status: status.as_u16(),
168
+ detail: text,
169
+ });
170
+ }
171
+ unwrap_envelope(serde_json::from_str(&text)?)
172
+ }
173
+
174
+ pub fn orders_request(&self, query: &OrderQuery) -> Result<Prepared> {
175
+ self.prepare(Method::POST, ORDER_QUERY_PATH, Some(query))
176
+ }
177
+
178
+ pub fn upload_url_request(&self) -> Result<Prepared> {
179
+ self.prepare(Method::GET, UPLOAD_URL_PATH, None::<&()>)
180
+ }
181
+}
182
+
183
+/// `{"code": 200, "msg": …, "data": …}` → `data`. Any other code is an error.
184
+pub(crate) fn unwrap_envelope(envelope: Value) -> Result<Value> {
185
+ let code = envelope.get("code").and_then(Value::as_i64).unwrap_or(-1);
186
+ if code == 200 {
187
+ return Ok(envelope.get("data").cloned().unwrap_or(Value::Null));
188
+ }
189
+ Err(Error::Api {
190
+ code,
191
+ msg: envelope
192
+ .get("msg")
193
+ .and_then(Value::as_str)
194
+ .unwrap_or("no message")
195
+ .to_string(),
196
+ })
197
+}
198
+
199
+#[cfg(test)]
200
+mod tests {
201
+ use super::*;
202
+ use serde_json::json;
203
+
204
+ fn query() -> OrderQuery {
205
+ OrderQuery {
206
+ pkgs: "com.example.app".into(),
207
+ regions: None,
208
+ pay_status: Some("2,6".into()),
209
+ pay_type: None,
210
+ start_timestamp: 1_701_084_799,
211
+ end_timestamp: 1_702_684_799,
212
+ }
213
+ }
214
+
215
+ #[test]
216
+ fn order_body_is_camel_case_and_skips_unset() {
217
+ let body = serde_json::to_value(query()).unwrap();
218
+ assert_eq!(
219
+ body,
220
+ json!({"pkgs":"com.example.app","payStatus":"2,6",
221
+ "startTimestamp":1_701_084_799u64,"endTimestamp":1_702_684_799u64})
222
+ );
223
+ }
224
+
225
+ #[test]
226
+ fn order_window_is_checked() {
227
+ assert!(query().validate().is_ok());
228
+ let mut q = query();
229
+ q.end_timestamp = q.start_timestamp;
230
+ assert!(q.validate().is_err());
231
+ q.end_timestamp = q.start_timestamp + ORDER_QUERY_MAX_SECS + 1;
232
+ assert!(q.validate().unwrap_err().contains("30 days"));
233
+ }
234
+
235
+ #[test]
236
+ fn envelope_200_yields_data() {
237
+ let data = unwrap_envelope(json!({"code":200,"msg":"ok","data":[1]})).unwrap();
238
+ assert_eq!(data, json!([1]));
239
+ }
240
+
241
+ #[test]
242
+ fn envelope_error_keeps_code_and_message() {
243
+ let e = unwrap_envelope(json!({"code":1002,"msg":"Signature mismatch!"})).unwrap_err();
244
+ assert!(matches!(e, Error::Api { code: 1002, ref msg } if msg == "Signature mismatch!"));
245
+ }
246
+
247
+ #[test]
248
+ fn prepare_hashes_the_bytes_it_sends() {
249
+ let credentials = Credentials::new("1", "secret", "com.example.app", "a@b", "2", "3");
250
+ let client = XiaomiClient::new(credentials);
251
+ let p = client
252
+ .prepare(Method::POST, ORDER_QUERY_PATH, Some(&query()))
253
+ .unwrap();
254
+ let body = p.body.unwrap();
255
+ let md5 = crate::sign::body_md5(body.as_bytes());
256
+ assert!(p
257
+ .headers
258
+ .canonical
259
+ .starts_with(&format!("POST{md5}AppId:1")));
260
+ assert!(p.headers.canonical.ends_with(ORDER_QUERY_PATH));
261
+ assert_eq!(p.url, format!("{API_ROOT}{ORDER_QUERY_PATH}"));
262
+ }
263
+}