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
/*!
 Contains date parsing functions for iMessage dates.

 Dates are stored as nanosecond-precision unix timestamps with an epoch of `1/1/2001 00:00:00` in the local time zone.
*/

use chrono::{DateTime, Duration, Local, TimeZone, Utc};

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

const SEPARATOR: &str = ", ";
pub const TIMESTAMP_FACTOR: i64 = 1000000000;

/// Get the date offset for the iMessage Database
///
/// This offset is used to adjust the unix timestamps stored in the iMessage database
/// with a non-standard epoch of `2001-01-01 00:00:00` in the local time zone.
pub fn get_offset() -> i64 {
    Utc.with_ymd_and_hms(2001, 1, 1, 0, 0, 0)
        .unwrap()
        .timestamp()
}

/// Format a date from the iMessage table for reading
///
/// # Example:
///
/// ```
/// use chrono::offset::Local;
/// use imessage_database::util::dates::format;
///
/// let date = format(&Ok(Local::now()));
/// println!("{date}");
/// ```
pub fn format(date: &Result<DateTime<Local>, MessageError>) -> String {
    match date {
        Ok(d) => DateTime::format(d, "%b %d, %Y %l:%M:%S %p").to_string(),
        Err(why) => why.to_string(),
    }
}

/// Generate a readable diff from two local timestamps.
///
/// # Example:
///
/// ```
/// use chrono::prelude::*;
/// use imessage_database::util::dates::readable_diff;
///
/// let start = Ok(Local.ymd(2020, 5, 20).and_hms_milli(9, 10, 11, 12));
/// let end = Ok(Local.ymd(2020, 5, 20).and_hms_milli(9, 15, 11, 12));
/// println!("{}", readable_diff(start, end).unwrap())
/// ```
pub fn readable_diff(
    start: Result<DateTime<Local>, MessageError>,
    end: Result<DateTime<Local>, MessageError>,
) -> Option<String> {
    // Calculate diff
    let diff: Duration = end.ok()? - start.ok()?;
    let seconds = diff.num_seconds();

    // Early escape for invalid date diff
    if seconds < 0 {
        return None;
    }

    // 42 is the length of a diff string that has all components with 2 digits each
    // This allocation improved performance over `::new()` by 20%
    // (21.99s to 27.79s over 250k messages)
    let mut out_s = String::with_capacity(42);

    let days = seconds / 86400;
    let hours = (seconds % 86400) / 3600;
    let minutes = (seconds % 86400 % 3600) / 60;
    let secs = seconds % 86400 % 3600 % 60;

    if days != 0 {
        let metric = match days {
            1 => "day",
            _ => "days",
        };
        out_s.push_str(&format!("{days} {metric}"));
    }
    if hours != 0 {
        let metric = match hours {
            1 => "hour",
            _ => "hours",
        };
        if !out_s.is_empty() {
            out_s.push_str(SEPARATOR);
        }
        out_s.push_str(&format!("{hours} {metric}"));
    }
    if minutes != 0 {
        let metric = match minutes {
            1 => "minute",
            _ => "minutes",
        };
        if !out_s.is_empty() {
            out_s.push_str(SEPARATOR);
        }
        out_s.push_str(&format!("{minutes} {metric}"));
    }
    if secs != 0 {
        let metric = match secs {
            1 => "second",
            _ => "seconds",
        };
        if !out_s.is_empty() {
            out_s.push_str(SEPARATOR);
        }
        out_s.push_str(&format!("{secs} {metric}"));
    }
    Some(out_s)
}

#[cfg(test)]
mod tests {
    use crate::{
        error::message::MessageError,
        util::dates::{format, 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)
            .single()
            .ok_or(MessageError::InvalidTimestamp(0));
        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)
            .single()
            .ok_or(MessageError::InvalidTimestamp(0));
        assert_eq!(format(&date), "May 20, 2020 10:10:11 AM")
    }

    #[test]
    fn cant_format_diff_backwards() {
        let end = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let start = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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_year() {
        let start = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(Local.with_ymd_and_hms(2022, 7, 20, 9, 10, 11).unwrap());
        assert_eq!(readable_diff(start, end), Some("791 days".to_owned()))
    }

    #[test]
    fn can_format_diff_all() {
        let start = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(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 = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        let end = Ok(Local.with_ymd_and_hms(2020, 5, 20, 9, 10, 11).unwrap());
        assert_eq!(readable_diff(start, end), Some("".to_owned()))
    }
}