Skip to main content

imessage_database/tables/
handle.rs

1/*!
2 This module represents common (but not all) columns in the `handle` table.
3*/
4
5use rusqlite::{CachedStatement, Connection, Result, Row};
6use std::collections::{BTreeSet, HashMap, HashSet};
7
8use crate::{
9    error::table::TableError,
10    tables::{
11        diagnostic::HandleDiagnostic,
12        table::{Cacheable, HANDLE, ME, Table},
13    },
14};
15
16// MARK: Handle
17/// Represents a single row in the `handle` table.
18#[derive(Debug)]
19pub struct Handle {
20    /// The unique identifier for the handle in the database
21    pub rowid: i32,
22    /// Identifier for a contact, i.e. a phone number or email address
23    pub id: String,
24    /// Field used to disambiguate divergent handles that represent the same contact
25    pub person_centric_id: Option<String>,
26}
27
28// MARK: Table
29impl Table for Handle {
30    fn from_row(row: &Row) -> Result<Handle> {
31        Ok(Handle {
32            rowid: row.get("rowid")?,
33            id: row.get("id")?,
34            person_centric_id: row.get("person_centric_id").unwrap_or(None),
35        })
36    }
37
38    fn get(db: &'_ Connection) -> Result<CachedStatement<'_>, TableError> {
39        Ok(db.prepare_cached(&format!("SELECT * from {HANDLE}"))?)
40    }
41}
42
43// MARK: Cache
44impl Cacheable for Handle {
45    type K = i32;
46    type V = String;
47    /// Generate a `HashMap` for looking up contacts by their IDs, collapsing
48    /// duplicate contacts to the same ID String regardless of service
49    ///
50    /// # Example:
51    ///
52    /// ```
53    /// use imessage_database::util::dirs::default_db_path;
54    /// use imessage_database::tables::table::{Cacheable, get_connection};
55    /// use imessage_database::tables::handle::Handle;
56    ///
57    /// let db_path = default_db_path();
58    /// let conn = get_connection(&db_path).unwrap();
59    /// let chatrooms = Handle::cache(&conn);
60    /// ```
61    fn cache(db: &Connection) -> Result<HashMap<Self::K, Self::V>, TableError> {
62        // Create cache for user IDs
63        let mut map = HashMap::new();
64        // Handle ID 0 is self in group chats
65        map.insert(0, ME.to_string());
66
67        // Create query
68        let mut statement = Handle::get(db)?;
69
70        // Execute query to build the Handles
71        let handles = statement.query_map([], |row| Ok(Handle::from_row(row)))?;
72
73        // Iterate over the handles and update the map
74        for handle in handles {
75            let contact = Handle::extract(handle)?;
76            map.insert(contact.rowid, contact.id);
77        }
78
79        // Condense contacts that share person_centric_id so their IDs map to the same strings
80        let dupe_contacts = Handle::get_person_id_map(db)?;
81        for contact in dupe_contacts {
82            let (id, new) = contact;
83            map.insert(id, new);
84        }
85
86        // Done!
87        Ok(map)
88    }
89}
90
91// MARK: Dedupe
92impl Handle {
93    /// Given the initial set of duplicated handles, deduplicate them
94    ///
95    /// This returns a new hashmap that maps the real handle ID to a new deduplicated unique handle ID
96    /// that represents a single handle for all of the deduplicate handles.
97    ///
98    /// Assuming no new handles have been written to the database, deduplicated data is deterministic across runs.
99    ///
100    /// # Example:
101    ///
102    /// ```
103    /// use imessage_database::util::dirs::default_db_path;
104    /// use imessage_database::tables::table::{Cacheable, get_connection};
105    /// use imessage_database::tables::handle::Handle;
106    ///
107    /// let db_path = default_db_path();
108    /// let conn = get_connection(&db_path).unwrap();
109    /// let handles = Handle::cache(&conn).unwrap();
110    /// let deduped_handles = Handle::dedupe(&handles);
111    /// ```
112    pub fn dedupe(duplicated_data: &HashMap<i32, String>) -> HashMap<i32, i32> {
113        let mut deduplicated_participants: HashMap<i32, i32> = HashMap::new();
114        let mut participant_to_unique_participant_id: HashMap<String, i32> = HashMap::new();
115
116        // Build cache of each unique set of participants to a new identifier:
117        let mut unique_participant_identifier = 0;
118
119        // Iterate over the values in a deterministic order
120        let mut sorted_dupes: Vec<(&i32, &String)> = duplicated_data.iter().collect();
121        sorted_dupes.sort_by(|(a, _), (b, _)| a.cmp(b));
122
123        for (participant_id, participant) in sorted_dupes {
124            if let Some(id) = participant_to_unique_participant_id.get(participant) {
125                deduplicated_participants.insert(*participant_id, *id);
126            } else {
127                participant_to_unique_participant_id
128                    .insert(participant.to_owned(), unique_participant_identifier);
129                deduplicated_participants
130                    .insert(*participant_id, unique_participant_identifier);
131                unique_participant_identifier += 1;
132            }
133        }
134        deduplicated_participants
135    }
136}
137
138// MARK: Diagnostic
139impl Handle {
140    /// Compute diagnostic data for the Handles table
141    ///
142    /// Counts the number of handles that are duplicated. The `person_centric_id`
143    /// is used to map handles that represent the same contact across ids (numbers,
144    /// emails, etc) and across services (iMessage, Jabber, iChat, SMS, etc).
145    ///
146    /// In some databases, `person_centric_id` may not be available.
147    ///
148    /// # Example:
149    ///
150    /// ```
151    /// use imessage_database::util::dirs::default_db_path;
152    /// use imessage_database::tables::table::get_connection;
153    /// use imessage_database::tables::handle::Handle;
154    ///
155    /// let db_path = default_db_path();
156    /// let conn = get_connection(&db_path).unwrap();
157    /// Handle::run_diagnostic(&conn);
158    /// ```
159    pub fn run_diagnostic(db: &Connection) -> Result<HandleDiagnostic, TableError> {
160        let query = concat!(
161            "SELECT COUNT(DISTINCT person_centric_id) ",
162            "FROM handle ",
163            "WHERE person_centric_id NOT NULL"
164        );
165
166        let handles_with_multiple_ids = if let Ok(mut rows) = db.prepare(query) {
167            rows.query_row([], |r| r.get::<_, i64>(0))
168                .ok()
169                .and_then(|count| usize::try_from(count).ok())
170                .unwrap_or(0)
171        } else {
172            0
173        };
174
175        // Cache all handles
176        let all_handles = Self::cache(db)?;
177
178        // Deduplicate handles
179        let unique_handles = Self::dedupe(&all_handles);
180
181        // Calculate total duplicated handles
182        let total_duplicated =
183            all_handles.len() - HashSet::<&i32>::from_iter(unique_handles.values()).len();
184
185        Ok(HandleDiagnostic {
186            total_handles: all_handles.len(),
187            handles_with_multiple_ids,
188            total_duplicated,
189        })
190    }
191}
192
193// MARK: Impl
194impl Handle {
195    /// The handles table does not have a lot of information and can have many duplicate values.
196    ///
197    /// This method generates a hashmap of each separate item in this table to a combined string
198    /// that represents all of the copies, so any handle ID will always map to the same string
199    /// for a given chat participant
200    fn get_person_id_map(db: &Connection) -> Result<HashMap<i32, String>, TableError> {
201        let mut person_to_id: HashMap<String, BTreeSet<String>> = HashMap::new();
202        let mut row_to_id: HashMap<i32, String> = HashMap::new();
203        let mut row_data: Vec<(String, i32, String)> = vec![];
204
205        // Build query
206        let query = concat!(
207            "SELECT DISTINCT A.person_centric_id, A.rowid, A.id ",
208            "FROM handle A ",
209            "INNER JOIN handle B ON B.id = A.id ",
210            "WHERE A.person_centric_id NOT NULL ",
211            "ORDER BY A.person_centric_id",
212        );
213        let statement = db.prepare(query);
214
215        if let Ok(mut statement) = statement {
216            // Cache the results of the query in memory
217            let contacts = statement.query_map([], |row| {
218                let person_centric_id: String = row.get(0)?;
219                let rowid: i32 = row.get(1)?;
220                let id: String = row.get(2)?;
221                Ok((person_centric_id, rowid, id))
222            })?;
223
224            for contact in contacts {
225                row_data.push(contact?);
226            }
227
228            // First pass: generate a map of each person_centric_id to its matching ids
229            for contact in &row_data {
230                let (person_centric_id, _, id) = contact;
231                if let Some(set) = person_to_id.get_mut(person_centric_id) {
232                    set.insert(id.to_owned());
233                } else {
234                    let mut set = BTreeSet::new();
235                    set.insert(id.to_owned());
236                    person_to_id.insert(person_centric_id.to_owned(), set);
237                }
238            }
239
240            // Second pass: point each ROWID to the matching ids
241            for contact in &row_data {
242                let (person_centric_id, rowid, _) = contact;
243                let data_to_insert = match person_to_id.get_mut(person_centric_id) {
244                    Some(person) => person.iter().cloned().collect::<Vec<String>>().join(" "),
245                    None => continue,
246                };
247                row_to_id.insert(rowid.to_owned(), data_to_insert);
248            }
249        }
250
251        Ok(row_to_id)
252    }
253}
254
255// MARK: Tests
256#[cfg(test)]
257mod tests {
258    use crate::tables::handle::Handle;
259    use std::collections::{HashMap, HashSet};
260
261    #[test]
262    fn test_can_dedupe() {
263        let mut input: HashMap<i32, String> = HashMap::new();
264        input.insert(1, String::from("A")); // 0
265        input.insert(2, String::from("A")); // 0
266        input.insert(3, String::from("A")); // 0
267        input.insert(4, String::from("B")); // 1
268        input.insert(5, String::from("B")); // 1
269        input.insert(6, String::from("C")); // 2
270
271        let output = Handle::dedupe(&input);
272        let expected_deduped_ids: HashSet<i32> = output.values().copied().collect();
273        assert_eq!(expected_deduped_ids.len(), 3);
274    }
275
276    #[test]
277    // Simulate 3 runs of the program and ensure that the order of the deduplicated contacts is stable
278    fn test_same_values() {
279        let mut input_1: HashMap<i32, String> = HashMap::new();
280        input_1.insert(1, String::from("A"));
281        input_1.insert(2, String::from("A"));
282        input_1.insert(3, String::from("A"));
283        input_1.insert(4, String::from("B"));
284        input_1.insert(5, String::from("B"));
285        input_1.insert(6, String::from("C"));
286
287        let mut input_2: HashMap<i32, String> = HashMap::new();
288        input_2.insert(1, String::from("A"));
289        input_2.insert(2, String::from("A"));
290        input_2.insert(3, String::from("A"));
291        input_2.insert(4, String::from("B"));
292        input_2.insert(5, String::from("B"));
293        input_2.insert(6, String::from("C"));
294
295        let mut input_3: HashMap<i32, String> = HashMap::new();
296        input_3.insert(1, String::from("A"));
297        input_3.insert(2, String::from("A"));
298        input_3.insert(3, String::from("A"));
299        input_3.insert(4, String::from("B"));
300        input_3.insert(5, String::from("B"));
301        input_3.insert(6, String::from("C"));
302
303        let mut output_1 = Handle::dedupe(&input_1)
304            .into_iter()
305            .collect::<Vec<(i32, i32)>>();
306        let mut output_2 = Handle::dedupe(&input_2)
307            .into_iter()
308            .collect::<Vec<(i32, i32)>>();
309        let mut output_3 = Handle::dedupe(&input_3)
310            .into_iter()
311            .collect::<Vec<(i32, i32)>>();
312
313        output_1.sort_unstable();
314        output_2.sort_unstable();
315        output_3.sort_unstable();
316
317        assert_eq!(output_1, output_2);
318        assert_eq!(output_1, output_3);
319        assert_eq!(output_2, output_3);
320    }
321}