imessage-database 4.2.0

Parsers and tools to interact with iMessage SQLite data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*!
 Date conversion and formatting helpers for Messages timestamps.

 Most dates are stored as nanosecond-precision unix timestamps with an epoch of `1/1/2001 00:00:00` in UTC.
*/
use std::fmt::Write;

use chrono::{DateTime, Datelike, Local, Months, TimeZone, Timelike, Utc};

use crate::error::message::MessageError;

const SEPARATOR: &str = ", ";
const SECONDS_PER_MINUTE: i64 = 60;
const SECONDS_PER_HOUR: i64 = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY: i64 = 24 * SECONDS_PER_HOUR;
const SECONDS_PER_YEAR: i64 = 365 * SECONDS_PER_DAY;

/// Factor used to convert nanosecond-precision timestamps to seconds.
///
/// Most Messages timestamps use nanoseconds, while older rows may store seconds.
pub const TIMESTAMP_FACTOR: i64 = 1_000_000_000;

/// Return the Unix timestamp offset for the Messages epoch.
///
/// Messages stores dates relative to `2001-01-01 00:00:00` UTC.
///
/// # Example
///
/// ```
/// use imessage_database::util::dates::get_offset;
///
/// let current_epoch = get_offset();
/// ```
#[must_use]
pub fn get_offset() -> i64 {
    Utc.with_ymd_and_hms(2001, 1, 1, 0, 0, 0)
        .unwrap()
        .timestamp()
}

/// Convert a raw Messages timestamp into local time.
///
/// `offset` is usually [`get_offset`].
///
/// # Example
///
/// ```
/// use imessage_database::util::dates::{get_local_time, get_offset};
///
/// let current_offset = get_offset();
/// let local = get_local_time(674526582885055488, current_offset).unwrap();
/// ```
pub fn get_local_time(date_stamp: i64, offset: i64) -> Result<DateTime<Local>, MessageError> {
    // Newer databases store timestamps as nanoseconds since 2001-01-01,
    // while older ones store plain seconds since 2001-01-01.
    let seconds_since_2001 = if date_stamp >= 1_000_000_000_000 {
        date_stamp / TIMESTAMP_FACTOR
    } else {
        date_stamp
    };

    let utc_stamp = DateTime::from_timestamp(seconds_since_2001 + offset, 0)
        .ok_or(MessageError::InvalidTimestamp(date_stamp))?
        .naive_utc();
    Ok(Local.from_utc_datetime(&utc_stamp))
}

/// Format a local timestamp for export output.
///
/// # Example:
///
/// ```
/// use chrono::offset::Local;
/// use imessage_database::util::dates::format;
///
/// let date = format(&Local::now());
/// println!("{date}");
/// ```
#[must_use]
pub fn format(date: &DateTime<Local>) -> String {
    // Equivalent to `date.format("%b %d, %Y %l:%M:%S %p").to_string()` but
    // written directly into one pre-sized buffer
    const MONTHS: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    let (hour12, meridiem) = match date.hour() {
        0 => (12, "AM"),
        12 => (12, "PM"),
        h if h < 12 => (h, "AM"),
        h => (h - 12, "PM"),
    };

    let mut out = String::with_capacity(24);
    let _ = write!(
        out,
        "{} {:02}, {} {hour12:2}:{:02}:{:02} {meridiem}",
        MONTHS[(date.month() - 1) as usize],
        date.day(),
        date.year(),
        date.minute(),
        date.second(),
    );
    out
}

/// Format the elapsed time between two local timestamps.
///
/// # Example:
///
/// ```
/// use chrono::prelude::*;
/// use imessage_database::util::dates::readable_diff;
///
/// let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
/// let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 15, 13).unwrap();
/// println!("{}", readable_diff(&start, &end).unwrap()) // "5 minutes, 2 seconds"
/// ```
#[must_use]
pub fn readable_diff(start: &DateTime<Local>, end: &DateTime<Local>) -> Option<String> {
    let seconds = end.timestamp() - start.timestamp();

    if seconds < 0 {
        return None;
    }

    let (years, remaining_seconds) = years_and_remainder(start, end)
        .unwrap_or((seconds / SECONDS_PER_YEAR, seconds % SECONDS_PER_YEAR));

    // Enough room for each component when values are two digits.
    let mut out_s = String::with_capacity(51);

    let days = remaining_seconds / SECONDS_PER_DAY;
    let hours = (remaining_seconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR;
    let minutes = (remaining_seconds % SECONDS_PER_DAY % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
    let secs = remaining_seconds % SECONDS_PER_DAY % SECONDS_PER_HOUR % SECONDS_PER_MINUTE;

    append_component(&mut out_s, years, "year", "years");
    append_component(&mut out_s, days, "day", "days");
    append_component(&mut out_s, hours, "hour", "hours");
    append_component(&mut out_s, minutes, "minute", "minutes");
    append_component(&mut out_s, secs, "second", "seconds");

    Some(out_s)
}

/// Calculate whole years and the remaining seconds between two dates.
fn years_and_remainder(start: &DateTime<Local>, end: &DateTime<Local>) -> Option<(i64, i64)> {
    let mut years = end.year() - start.year();

    if years <= 0 {
        return Some((0, end.timestamp() - start.timestamp()));
    }

    let mut remainder_start =
        start.checked_add_months(Months::new(u32::try_from(years).ok()?.checked_mul(12)?))?;

    if remainder_start > *end {
        years -= 1;
        remainder_start =
            start.checked_add_months(Months::new(u32::try_from(years).ok()?.checked_mul(12)?))?;
    }

    Some((
        i64::from(years),
        end.timestamp() - remainder_start.timestamp(),
    ))
}

/// Append a time component to the output string if the value is greater than 0, with correct singular/plural formatting.
fn append_component(out_s: &mut String, value: i64, singular: &str, plural: &str) {
    if value == 0 {
        return;
    }

    if !out_s.is_empty() {
        out_s.push_str(SEPARATOR);
    }

    let metric = if value == 1 { singular } else { plural };
    let _ = write!(out_s, "{value} {metric}");
}

#[cfg(test)]
mod tests {
    use crate::util::dates::{TIMESTAMP_FACTOR, format, get_local_time, get_offset, readable_diff};
    use chrono::prelude::*;

    #[test]
    fn can_format_date_single_digit() {
        let date = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        assert_eq!(format(&date), "May 20, 2020  9:10:11 AM");
    }

    #[test]
    fn can_format_date_double_digit() {
        let date = Local.with_ymd_and_hms(2020, 5, 20, 10, 10, 11).unwrap();
        assert_eq!(format(&date), "May 20, 2020 10:10:11 AM");
    }

    #[test]
    fn can_format_date_midnight() {
        // Hour 0 renders as 12 AM (and single-digit minute/second are zero-padded).
        let date = Local.with_ymd_and_hms(2020, 5, 20, 0, 5, 9).unwrap();
        assert_eq!(format(&date), "May 20, 2020 12:05:09 AM");
    }

    #[test]
    fn can_format_date_noon() {
        // Hour 12 renders as 12 PM, not 0 PM.
        let date = Local.with_ymd_and_hms(2020, 5, 20, 12, 0, 0).unwrap();
        assert_eq!(format(&date), "May 20, 2020 12:00:00 PM");
    }

    #[test]
    fn can_format_date_afternoon() {
        // Hour 15 maps to a space-padded 12-hour `3` (note the double space) PM.
        let date = Local.with_ymd_and_hms(2020, 5, 20, 15, 4, 5).unwrap();
        assert_eq!(format(&date), "May 20, 2020  3:04:05 PM");
    }

    #[test]
    fn cant_format_diff_backwards() {
        let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 30).unwrap();
        assert_eq!(readable_diff(&start, &end), None);
    }

    #[test]
    fn can_format_diff_all_singular() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 21, 10, 11, 12).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("1 day, 1 hour, 1 minute, 1 second".to_owned())
        );
    }

    #[test]
    fn can_format_diff_mixed_singular() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 22, 10, 20, 12).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("2 days, 1 hour, 10 minutes, 1 second".to_owned())
        );
    }

    #[test]
    fn can_format_diff_seconds() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 30).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("19 seconds".to_owned()));
    }

    #[test]
    fn can_format_diff_minutes() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 15, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("5 minutes".to_owned()));
    }

    #[test]
    fn can_format_diff_hours() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 20, 12, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("3 hours".to_owned()));
    }

    #[test]
    fn can_format_diff_days() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 30, 9, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("10 days".to_owned()));
    }

    #[test]
    fn can_format_diff_minutes_seconds() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 15, 30).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("5 minutes, 19 seconds".to_owned())
        );
    }

    #[test]
    fn can_format_diff_days_minutes() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 22, 9, 30, 11).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("2 days, 20 minutes".to_owned())
        );
    }

    #[test]
    fn can_format_diff_month() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 7, 20, 9, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("61 days".to_owned()));
    }

    #[test]
    fn can_format_diff_single_year() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2021, 5, 20, 9, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("1 year".to_owned()));
    }

    #[test]
    fn can_format_diff_years_days() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2022, 7, 20, 9, 10, 11).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("2 years, 61 days".to_owned())
        );
    }

    #[test]
    fn can_format_diff_leap_day_anniversary_as_year() {
        let start = Local.with_ymd_and_hms(2020, 2, 29, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2021, 2, 28, 9, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some("1 year".to_owned()));
    }

    #[test]
    fn can_format_diff_all() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 22, 14, 32, 45).unwrap();
        assert_eq!(
            readable_diff(&start, &end),
            Some("2 days, 5 hours, 22 minutes, 34 seconds".to_owned())
        );
    }

    #[test]
    fn can_format_no_diff() {
        let start = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        let end = Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap();
        assert_eq!(readable_diff(&start, &end), Some(String::new()));
    }

    #[test]
    fn can_get_local_time_from_seconds_timestamp() {
        let offset = get_offset();
        let expected_utc = Utc
            .with_ymd_and_hms(2020, 5, 20, 9, 10, 11)
            .single()
            .unwrap();

        // Older databases store seconds since 2001-01-01 00:00:00
        let stamp_secs = expected_utc.timestamp() - offset;

        let local = get_local_time(stamp_secs, offset).unwrap();
        let expected_local = expected_utc.with_timezone(&Local);

        assert_eq!(local, expected_local);
    }

    #[test]
    fn can_get_local_time_from_nanoseconds_timestamp() {
        let offset = get_offset();
        let expected_utc = Utc
            .with_ymd_and_hms(2020, 5, 20, 9, 10, 11)
            .single()
            .unwrap();

        // Newer databases store nanoseconds since 2001-01-01 00:00:00
        let stamp_ns = (expected_utc.timestamp() - offset) * TIMESTAMP_FACTOR;

        let local = get_local_time(stamp_ns, offset).unwrap();
        let expected_local = expected_utc.with_timezone(&Local);

        assert_eq!(local, expected_local);
    }

    #[test]
    fn can_get_local_time_from_hardcoded_seconds_timestamp() {
        let offset = get_offset();

        // Legacy-style seconds timestamp
        let stamp_secs: i64 = 347_670_404;

        let expected_utc = Utc.timestamp_opt(stamp_secs + offset, 0).single().unwrap();

        let local = get_local_time(stamp_secs, offset).unwrap();
        let expected_local = expected_utc.with_timezone(&Local);

        assert_eq!(local, expected_local);
    }

    #[test]
    fn can_get_local_time_from_hardcoded_nanoseconds_timestamp() {
        let offset = get_offset();

        // Nanosecond-style timestamp
        let stamp_ns: i64 = 549_948_395_013_559_360;

        let seconds_since_2001 = stamp_ns / TIMESTAMP_FACTOR;

        let expected_utc = Utc
            .timestamp_opt(seconds_since_2001 + offset, 0)
            .single()
            .unwrap();

        let local = get_local_time(stamp_ns, offset).unwrap();
        let expected_local = expected_utc.with_timezone(&Local);

        assert_eq!(local, expected_local);
    }
}