Skip to main content

mobiler_core/
device.rs

1//! Structured device details (`cx.device_info`), for support and bug reports.
2
3use facet::Facet;
4use serde::{Deserialize, Serialize};
5
6use crate::PluginResponse;
7
8/// The phone's OS version and model, from the built-in `device` capability's `info` op. Read-only
9/// and non-identifying: no serial, advertising id or user-set device name. A field the shell can't
10/// know is empty (`0` for `os_api_level`); the web shell knows none of them.
11#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
12#[repr(C)]
13pub struct DeviceInfo {
14    /// `"13"` (Android `Build.VERSION.RELEASE`) / `"17.5"` (iOS `systemVersion`).
15    pub os_version: String,
16    /// Android `Build.VERSION.SDK_INT`; `0` elsewhere.
17    pub os_api_level: u32,
18    /// `"samsung"` / `"Apple"`.
19    pub manufacturer: String,
20    /// `"SM-A325F"` (Android `Build.MODEL`) / `"iPhone15,2"` (iOS hardware identifier).
21    pub model: String,
22}
23
24impl DeviceInfo {
25    /// Serialize for a `PluginResponse.output` (crux's FFI format, like [`crate::HttpOutcome`]).
26    pub fn encode(&self) -> Vec<u8> {
27        use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
28        let mut buffer = Vec::new();
29        BincodeFfiFormat::serialize(&mut buffer, self).expect("encode DeviceInfo");
30        buffer
31    }
32
33    /// Decode a shell's `device`/`info` payload.
34    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
35        use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
36        BincodeFfiFormat::deserialize(bytes).map_err(|e| e.to_string())
37    }
38}
39
40/// `Some` for a shell that answered; `None` when it refused (`ok: false`, e.g. a shell that
41/// predates `info`) or sent something undecodable.
42pub(crate) fn from_response(r: &PluginResponse) -> Option<DeviceInfo> {
43    if !r.ok {
44        return None;
45    }
46    DeviceInfo::decode(&r.output).ok()
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    fn sample() -> DeviceInfo {
54        DeviceInfo { os_version: "13".into(), os_api_level: 33, manufacturer: "samsung".into(), model: "SM-A325F".into() }
55    }
56
57    #[test]
58    fn device_info_round_trips() {
59        assert_eq!(DeviceInfo::decode(&sample().encode()), Ok(sample()));
60    }
61
62    #[test]
63    fn a_refused_or_garbled_reply_is_none() {
64        assert_eq!(from_response(&PluginResponse { ok: true, output: sample().encode() }), Some(sample()));
65        assert_eq!(from_response(&PluginResponse { ok: false, output: b"unknown op".to_vec() }), None);
66        assert_eq!(from_response(&PluginResponse { ok: true, output: vec![] }), None);
67    }
68}