Skip to main content

instapi360_cloud/
client.rs

1//! The HTTP client: header assembly, signed request dispatch, envelope
2//! decoding, and the account/media/download endpoint methods.
3
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
8use reqwest::Method;
9use serde::de::DeserializeOwned;
10use serde_json::Value;
11
12use crate::config::ClientConfig;
13use crate::error::{Error, Result};
14use crate::model::*;
15use crate::session::Session;
16use crate::signing::Signer;
17
18/// A "pc"+32-hex trace id, derived from a per-request seed (splitmix64 twice).
19fn trace_hex(seed: u64) -> String {
20    let mut x = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
21    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
22    let a = x ^ (x >> 31);
23    let mut y = a.wrapping_add(0x9E37_79B9_7F4A_7C15);
24    y = (y ^ (y >> 30)).wrapping_mul(0x94D0_49BB_1331_11EB);
25    let b = y ^ (y >> 29);
26    format!("{a:016x}{b:016x}")
27}
28
29/// Async client for the Insta360 cloud API.
30#[derive(Clone)]
31pub struct Client {
32    http: reqwest::Client,
33    cfg: ClientConfig,
34    /// Retained for the share-link endpoints (the only ones that HMAC-sign).
35    #[allow(dead_code)]
36    signer: Signer,
37    /// Account/app API host (`/account/*`, `/app/*`).
38    base: String,
39    /// Cloud media API host (`/cloud/service/*`) — a different host.
40    cloud_base: String,
41    nonce_seed: std::sync::Arc<AtomicU64>,
42}
43
44impl Client {
45    /// Construct a client from config. Fails only if the TLS/HTTP stack can't
46    /// be built.
47    pub fn new(cfg: ClientConfig) -> Result<Self> {
48        let http = reqwest::Client::builder()
49            .user_agent(cfg.user_agent.clone())
50            .build()?;
51        let signer = Signer::new(&cfg);
52        let base = cfg.region.openapi_base().to_string();
53        let cloud_base = cfg.region.cloud_base().to_string();
54        Ok(Client {
55            http,
56            signer,
57            base,
58            cloud_base,
59            cfg,
60            nonce_seed: std::sync::Arc::new(AtomicU64::new(0)),
61        })
62    }
63
64    /// Access the underlying reqwest client (used by the download path for the
65    /// OSS GET, which is *not* an API-signed request).
66    pub fn http(&self) -> &reqwest::Client {
67        &self.http
68    }
69
70    #[allow(dead_code)]
71    fn now_unix() -> i64 {
72        SystemTime::now()
73            .duration_since(UNIX_EPOCH)
74            .map(|d| d.as_secs() as i64)
75            .unwrap_or(0)
76    }
77
78    /// Assemble the standard identity + auth + signing headers for an API call.
79    fn build_headers(&self, session: Option<&Session>) -> Result<HeaderMap> {
80        let mut h = HeaderMap::new();
81        let mut put = |name: &str, val: &str| -> Result<()> {
82            if val.is_empty() {
83                return Ok(());
84            }
85            let n = HeaderName::from_bytes(name.as_bytes())
86                .map_err(|e| Error::Signing(format!("bad header name {name}: {e}")))?;
87            let v = HeaderValue::from_str(val)
88                .map_err(|e| Error::Signing(format!("bad header value for {name}: {e}")))?;
89            h.insert(n, v);
90            Ok(())
91        };
92
93        // Client identity — header names/values taken verbatim from the live
94        // desktop app's outgoing requests (recovered from process memory).
95        put("app_version", &self.cfg.app_version)?;
96        put("app_traffic", &self.cfg.app_traffic)?;
97        put("X-Equipment-Code", &self.cfg.equipment_code)?;
98        put("x-insta360-platform", self.cfg.platform.header_value())?; // "pc/windows"
99        put("X-Language", &self.cfg.language)?;
100        put("X-MainLand", self.cfg.region.mainland_flag())?;
101        put("Referer", "https://cloud.insta360.com/")?;
102        // Trace id format observed: "pc" + 32 lowercase hex.
103        let seed = self.nonce_seed.fetch_add(1, Ordering::Relaxed);
104        put("X-Insta360-Trace-Id", &format!("pc{}", trace_hex(seed)))?;
105
106        // Auth. The desktop app sends the session JWT in the `Authentication`
107        // header; some endpoints also accept `X-User-Token`. Send both so we
108        // work regardless of which the endpoint checks.
109        if let Some(s) = session {
110            put("Authentication", &s.user_token)?;
111            put("X-User-Token", &s.user_token)?;
112        }
113
114        Ok(h)
115    }
116
117    /// Send a JSON API request and decode the `data` payload from the envelope.
118    async fn request<T: DeserializeOwned>(
119        &self,
120        method: Method,
121        url: &str,
122        session: Option<&Session>,
123        query: &[(&str, String)],
124        body: Option<Value>,
125    ) -> Result<T> {
126        let headers = self.build_headers(session)?;
127        let mut req = self.http.request(method, url).headers(headers);
128        if !query.is_empty() {
129            req = req.query(query);
130        }
131        if let Some(b) = body {
132            req = req.json(&b);
133        }
134        let resp = req.send().await?;
135        let status = resp.status();
136        let text = resp.text().await?;
137
138        if status == reqwest::StatusCode::UNAUTHORIZED {
139            return Err(Error::Auth(format!("401 from {url}")));
140        }
141
142        let env: Envelope<T> = serde_json::from_str(&text).map_err(|e| Error::Api {
143            code: status.as_u16() as i64,
144            message: format!(
145                "bad response from {url} (http {status}): {e}; body: {}",
146                text.chars().take(200).collect::<String>()
147            ),
148        })?;
149
150        if !env.is_ok() {
151            let code = env.code.unwrap_or(-1);
152            // The API uses a dedicated code for token expiry; treat as auth.
153            let msg = env.message.unwrap_or_default();
154            if code == 401 || msg.to_lowercase().contains("token") {
155                return Err(Error::Auth(format!("api code {code}: {msg}")));
156            }
157            return Err(Error::Api { code, message: msg });
158        }
159
160        env.data.ok_or_else(|| Error::Api {
161            code: 0,
162            message: "empty data".into(),
163        })
164    }
165
166    // ----- account -----
167
168    /// Fetch the authenticated profile
169    /// (`GET openapi-*/account/v2/getProfile`). The account API lives on the
170    /// openapi host; `data` nests the profile under `account`.
171    pub async fn profile(&self, session: &Session) -> Result<Profile> {
172        let url = format!("{}/account/v2/getProfile", self.base);
173        let raw: Value = self
174            .request(Method::GET, &url, Some(session), &[], None)
175            .await?;
176        let obj = raw.get("account").unwrap_or(&raw);
177        // Parse leniently — the account object carries overlapping name-ish keys
178        // (name/nickname/…) that trip serde's alias de-dup, so pick by hand.
179        Ok(Profile {
180            user_id: as_str(obj, &["userId", "ins_user_id", "id", "accountId", "openId"]),
181            email: as_str(obj, &["userEmail", "email", "bindEmail"]),
182            name: as_str(
183                obj,
184                &["nickName", "nickname", "userName", "username", "name"],
185            ),
186        })
187    }
188
189    /// Renew the session (`GET openapi-*/account/v2/refreshToken`).
190    ///
191    /// The current token authenticates the call and the API mints a fresh one
192    /// in `data.token` — no separate refresh token is required, so a session can
193    /// be rolled forward indefinitely as long as it is renewed before it lapses.
194    pub async fn refresh(&self, session: &Session) -> Result<Session> {
195        #[derive(serde::Deserialize)]
196        struct RefreshData {
197            token: String,
198        }
199        let url = format!("{}/account/v2/refreshToken", self.base);
200        let d: RefreshData = self
201            .request(Method::GET, &url, Some(session), &[], None)
202            .await?;
203        let expires_at = jwt_exp(&d.token);
204        Ok(Session {
205            user_token: d.token,
206            refresh_token: session.refresh_token.clone(),
207            expires_at,
208            user_id: session.user_id.clone(),
209        })
210    }
211
212    // ----- media listing -----
213
214    /// List cloud media, one page
215    /// (`GET service-*/cloud/service/media/view/list?pageNumber&pageSize`).
216    pub async fn list_media(&self, session: &Session, cursor: PageCursor) -> Result<MediaPage> {
217        let url = format!("{}/cloud/service/media/view/list", self.cloud_base);
218        let q = [
219            ("pageNumber", cursor.page.to_string()),
220            ("pageSize", cursor.count.to_string()),
221        ];
222        let raw: Value = self
223            .request(Method::GET, &url, Some(session), &q, None)
224            .await?;
225        parse_media_page(&raw, &cursor)
226    }
227
228    /// Fetch full detail for one media item
229    /// (`GET service-*/cloud/service/media/view/detail?mediaId`).
230    pub async fn media_detail(&self, session: &Session, id: &MediaId) -> Result<Media> {
231        let url = format!("{}/cloud/service/media/view/detail", self.cloud_base);
232        let q = [("mediaId", id.0.clone())];
233        let raw: Value = self
234            .request(Method::GET, &url, Some(session), &q, None)
235            .await?;
236        parse_media(&raw).ok_or_else(|| Error::Api {
237            code: 0,
238            message: "detail had no media".into(),
239        })
240    }
241
242    /// Resolve the signed CDN download URL(s) for a media item
243    /// (`GET service-*/cloud/service/media/download?mediaId`). Returns one
244    /// [`FilePart`] per file (the response's `data.paths[]`).
245    ///
246    /// The `resourceKey` URLs are short-lived (~24h) — download promptly.
247    pub async fn resolve_download(&self, session: &Session, id: &MediaId) -> Result<Vec<FilePart>> {
248        let url = format!("{}/cloud/service/media/download", self.cloud_base);
249        let q = [("mediaId", id.0.clone())];
250        let raw: Value = self
251            .request(Method::GET, &url, Some(session), &q, None)
252            .await?;
253        let parts = parse_file_parts(&raw);
254        if parts.is_empty() {
255            return Err(Error::Api {
256                code: 0,
257                message: "download response had no file parts".into(),
258            });
259        }
260        Ok(parts)
261    }
262}
263
264// ----- lenient JSON parsers (shapes vary across API versions) -----
265
266fn as_u64(v: &Value, keys: &[&str]) -> Option<u64> {
267    for k in keys {
268        if let Some(n) = v.get(k) {
269            if let Some(u) = n.as_u64() {
270                return Some(u);
271            }
272            if let Some(s) = n.as_str() {
273                if let Ok(u) = s.parse() {
274                    return Some(u);
275                }
276            }
277        }
278    }
279    None
280}
281
282fn as_str(v: &Value, keys: &[&str]) -> Option<String> {
283    for k in keys {
284        if let Some(s) = v.get(k).and_then(|x| x.as_str()) {
285            return Some(s.to_string());
286        }
287    }
288    None
289}
290
291fn jwt_payload(token: &str) -> Option<Value> {
292    use base64::Engine;
293    let payload = token.split('.').nth(1)?;
294    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
295        .decode(payload)
296        .ok()?;
297    serde_json::from_slice(&bytes).ok()
298}
299
300/// Decode a JWT's `exp` (unix seconds) without verifying the signature.
301pub fn jwt_exp(token: &str) -> Option<i64> {
302    jwt_payload(token)?.get("exp").and_then(|x| x.as_i64())
303}
304
305/// If `token` looks like an Insta360 **session** token (a JWT whose payload
306/// carries `openId`), return its `exp` (unix seconds). Used to pick the real
307/// session token out of arbitrary strings scraped from a browser session.
308pub fn session_token_exp(token: &str) -> Option<i64> {
309    let p = jwt_payload(token)?;
310    if p.get("openId").is_some() {
311        p.get("exp").and_then(|x| x.as_i64())
312    } else {
313        None
314    }
315}
316
317fn classify(media_type: Option<&str>, name: &str) -> MediaKind {
318    let lower = name.to_lowercase();
319    if lower.ends_with(".insv") {
320        return MediaKind::Insv360;
321    }
322    if lower.ends_with(".insp") || lower.ends_with(".jpg") || lower.ends_with(".dng") {
323        return MediaKind::Photo;
324    }
325    if lower.ends_with(".mp4") {
326        return MediaKind::FlatVideo;
327    }
328    match media_type {
329        Some(t) if t.contains("photo") || t.contains("image") => MediaKind::Photo,
330        Some(t) if t.contains("video") => MediaKind::FlatVideo,
331        _ => MediaKind::Other,
332    }
333}
334
335/// Extract the file parts from a media/detail/download JSON object.
336fn parse_file_parts(v: &Value) -> Vec<FilePart> {
337    // `paths` is the download-resolve shape ([{index,name,size,url}]); the
338    // others cover detail/upload variants.
339    let arr = [
340        "paths",
341        "files",
342        "fileList",
343        "mediaUploadRespList",
344        "downloadList",
345    ]
346    .iter()
347    .find_map(|k| v.get(k).and_then(|x| x.as_array()))
348    // Some responses nest under `data`.
349    .or_else(|| {
350        v.get("data").and_then(|d| {
351            ["paths", "files", "fileList"]
352                .iter()
353                .find_map(|k| d.get(k).and_then(|x| x.as_array()))
354        })
355    });
356
357    if let Some(items) = arr {
358        return items
359            .iter()
360            .filter_map(|it| {
361                let url = as_str(it, &["download_url", "downloadUrl", "url", "downloadPath"])?;
362                let name = as_str(it, &["fileName", "file_name", "name"])
363                    .unwrap_or_else(|| url.rsplit('/').next().unwrap_or("part").to_string());
364                let size = as_u64(it, &["fileSize", "size", "mediaSize"]).unwrap_or(0);
365                let md5 = as_str(it, &["md5", "fileMd5", "coverMd5"]);
366                Some(FilePart {
367                    file_name: name,
368                    size,
369                    url,
370                    md5,
371                })
372            })
373            .collect();
374    }
375
376    // Single-file shape: a bare download_url on the object itself.
377    if let Some(url) = as_str(v, &["download_url", "downloadUrl", "url", "downloadPath"]) {
378        let name = as_str(v, &["mediaName", "fileName", "name"])
379            .unwrap_or_else(|| url.rsplit('/').next().unwrap_or("media").to_string());
380        let size = as_u64(v, &["downOriginalSize", "fileSize", "mediaSize"]).unwrap_or(0);
381        let md5 = as_str(v, &["md5", "coverMd5"]);
382        return vec![FilePart {
383            file_name: name,
384            size,
385            url,
386            md5,
387        }];
388    }
389
390    Vec::new()
391}
392
393/// Parse a single media object (list/detail item, field names from the live API).
394fn parse_media(v: &Value) -> Option<Media> {
395    let id = as_str(v, &["mediaId", "id", "uuid"])?;
396    let name = as_str(v, &["mediaName", "name", "fileName"]).unwrap_or_else(|| id.clone());
397    let media_type = as_str(v, &["mediaType", "type"]);
398    let kind = classify(media_type.as_deref(), &name);
399    let size = as_u64(
400        v,
401        &["mediaSize", "downOriginalSize", "fileSize", "file_size"],
402    )
403    .unwrap_or(0);
404    // Times are unix milliseconds in this API (e.g. createTime 1787429512249).
405    let time = as_u64(
406        v,
407        &["createTime", "mediaTime", "create_time", "upload_time_s"],
408    )
409    .map(|u| {
410        if u > 1_000_000_000_000 {
411            (u / 1000) as i64
412        } else {
413            u as i64
414        }
415    });
416    let camera = as_str(v, &["cameraType", "camera_name", "cameraName", "camera"]);
417
418    // Prefer the download-resolve `paths` (with URLs); otherwise synthesize
419    // name-only parts from `fileItems` (array of filenames) so the part count
420    // and multi-file grouping are correct even in a plain listing.
421    let mut parts = parse_file_parts(v);
422    if parts.is_empty() {
423        if let Some(items) = v.get("fileItems").and_then(|x| x.as_array()) {
424            parts = items
425                .iter()
426                .filter_map(|x| x.as_str())
427                .map(|n| FilePart {
428                    file_name: n.to_string(),
429                    size: 0,
430                    url: String::new(),
431                    md5: None,
432                })
433                .collect();
434        }
435    }
436    Some(Media {
437        id: MediaId(id),
438        name,
439        kind,
440        size_original: size,
441        time_unix: time,
442        camera,
443        parts,
444    })
445}
446
447/// Parse a list response into a page.
448fn parse_media_page(v: &Value, cursor: &PageCursor) -> Result<MediaPage> {
449    let arr = ["list", "mediaVos", "mediaInfos", "medias", "items"]
450        .iter()
451        .find_map(|k| v.get(k).and_then(|x| x.as_array()))
452        .cloned()
453        .or_else(|| v.as_array().cloned())
454        .unwrap_or_default();
455
456    let items: Vec<Media> = arr.iter().filter_map(parse_media).collect();
457    let total = as_u64(v, &["total_count", "totalCount", "total", "count"]);
458    let got_so_far = (cursor.page as u64) * (cursor.count as u64);
459    let next = match total {
460        Some(t) if got_so_far < t && !items.is_empty() => Some(cursor.next()),
461        None if items.len() as u32 == cursor.count => Some(cursor.next()),
462        _ => None,
463    };
464    Ok(MediaPage { items, total, next })
465}