Skip to main content

imessage_database/util/
platform.rs

1/*!
2 Platform detection for Messages database paths.
3*/
4
5use std::{fmt::Display, path::Path};
6
7use crate::{
8    error::table::{TableConnectError, TableError},
9    tables::table::DEFAULT_PATH_IOS,
10    util::path_hint::{Presence, diagnose, presence},
11};
12
13/// Platform that produced the Messages database.
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub enum Platform {
16    /// macOS Messages database.
17    #[allow(non_camel_case_types)]
18    macOS,
19    /// iOS backup containing a Messages database.
20    #[allow(non_camel_case_types)]
21    iOS,
22}
23
24impl Platform {
25    /// Detect whether a path points to an iOS backup root or a macOS database.
26    ///
27    /// Require a Messages database at [`DEFAULT_PATH_IOS`] before accepting an iOS backup root;
28    /// any other directory is [`MissingBackupDatabase`](TableConnectError::MissingBackupDatabase).
29    /// Return an error for a missing or inaccessible path, with hints from the surrounding
30    /// filesystem when available. Treat files as macOS database inputs; validate their contents
31    /// with [`get_connection`](crate::tables::table::get_connection).
32    pub fn determine(db_path: &Path) -> Result<Self, TableError> {
33        // iOS inputs must be backup roots, not the nested database path.
34        if db_path.ends_with(DEFAULT_PATH_IOS) {
35            return Err(TableError::CannotConnect(TableConnectError::NotBackupRoot));
36        }
37
38        let connect_error = match presence(db_path) {
39            Err(why) => TableConnectError::Inaccessible(db_path.to_path_buf(), why),
40            Ok(Presence::Missing) => {
41                TableConnectError::DoesNotExist(db_path.to_path_buf(), diagnose(db_path))
42            }
43            Ok(Presence::Directory) => {
44                let messages_db = db_path.join(DEFAULT_PATH_IOS);
45                match presence(&messages_db) {
46                    Ok(Presence::File) => return Ok(Self::iOS),
47                    Err(why) => TableConnectError::Inaccessible(messages_db, why),
48                    Ok(_) => TableConnectError::MissingBackupDatabase(
49                        db_path.to_path_buf(),
50                        diagnose(db_path),
51                    ),
52                }
53            }
54            Ok(Presence::File | Presence::Other) => return Ok(Self::macOS),
55        };
56        Err(TableError::CannotConnect(connect_error))
57    }
58
59    /// Parse a platform name from CLI input.
60    #[must_use]
61    pub fn from_cli(platform: &str) -> Option<Self> {
62        match platform.to_lowercase().as_str() {
63            "macos" => Some(Self::macOS),
64            "ios" => Some(Self::iOS),
65            _ => None,
66        }
67    }
68}
69
70impl Default for Platform {
71    /// The default Platform is [`Platform::macOS`].
72    fn default() -> Self {
73        Self::macOS
74    }
75}
76
77impl Display for Platform {
78    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Platform::macOS => write!(fmt, "macOS"),
81            Platform::iOS => write!(fmt, "iOS"),
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use std::{
89        env::temp_dir,
90        fs::{File, create_dir_all, remove_dir_all},
91        path::PathBuf,
92        process,
93    };
94
95    use crate::{
96        error::table::{TableConnectError, TableError},
97        tables::table::DEFAULT_PATH_IOS,
98        util::platform::Platform,
99    };
100
101    fn scratch(label: &str) -> PathBuf {
102        let path = temp_dir().join(format!(
103            "imessage-database-platform-{}-{label}",
104            process::id()
105        ));
106        let _ = remove_dir_all(&path);
107        create_dir_all(&path).unwrap();
108        path
109    }
110
111    #[test]
112    fn detects_backup_root() {
113        let dir = scratch("root");
114        let messages_db = dir.join(DEFAULT_PATH_IOS);
115        create_dir_all(messages_db.parent().unwrap()).unwrap();
116        File::create(&messages_db).unwrap();
117
118        assert_eq!(Platform::determine(&dir).unwrap(), Platform::iOS);
119
120        remove_dir_all(&dir).unwrap();
121    }
122
123    #[test]
124    fn file_is_macos() {
125        let dir = scratch("file");
126        let file = dir.join("chat.db");
127        File::create(&file).unwrap();
128
129        assert_eq!(Platform::determine(&file).unwrap(), Platform::macOS);
130
131        remove_dir_all(&dir).unwrap();
132    }
133
134    #[test]
135    fn missing_path_is_an_error() {
136        let dir = scratch("missing");
137
138        assert!(matches!(
139            Platform::determine(&dir.join("absent")),
140            Err(TableError::CannotConnect(TableConnectError::DoesNotExist(
141                _,
142                _
143            )))
144        ));
145
146        remove_dir_all(&dir).unwrap();
147    }
148
149    #[test]
150    fn directory_without_backup_is_an_error() {
151        let dir = scratch("plain-dir");
152
153        assert!(matches!(
154            Platform::determine(&dir),
155            Err(TableError::CannotConnect(
156                TableConnectError::MissingBackupDatabase(_, _)
157            ))
158        ));
159
160        remove_dir_all(&dir).unwrap();
161    }
162
163    #[test]
164    fn backup_without_messages_database_names_the_backup() {
165        let dir = scratch("backup-no-messages");
166        File::create(dir.join("Manifest.db")).unwrap();
167
168        let error = Platform::determine(&dir).unwrap_err().to_string();
169        assert!(error.contains("contains no Messages database"), "{error}");
170        assert!(error.contains("is an iOS backup"), "{error}");
171
172        remove_dir_all(&dir).unwrap();
173    }
174
175    #[test]
176    fn can_parse_macos_any_case() {
177        assert!(matches!(Platform::from_cli("macos"), Some(Platform::macOS)));
178        assert!(matches!(Platform::from_cli("MACOS"), Some(Platform::macOS)));
179        assert!(matches!(Platform::from_cli("MacOS"), Some(Platform::macOS)));
180    }
181
182    #[test]
183    fn can_parse_ios_any_case() {
184        assert!(matches!(Platform::from_cli("ios"), Some(Platform::iOS)));
185        assert!(matches!(Platform::from_cli("IOS"), Some(Platform::iOS)));
186        assert!(matches!(Platform::from_cli("iOS"), Some(Platform::iOS)));
187    }
188
189    #[test]
190    fn cant_parse_invalid() {
191        assert!(Platform::from_cli("mac").is_none());
192        assert!(Platform::from_cli("iphone").is_none());
193        assert!(Platform::from_cli("").is_none());
194    }
195
196    #[test]
197    fn cant_build_ends_with_ios_backup() {
198        let path = std::path::PathBuf::from(DEFAULT_PATH_IOS);
199        assert!(Platform::determine(&path).is_err());
200    }
201}