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
/*!
 This module contains logic for handling query filter configurations
*/
use chrono::prelude::*;

use crate::{
    error::query_context::QueryContextError,
    util::dates::{get_offset, TIMESTAMP_FACTOR},
};

#[derive(Debug, Default)]
/// Represents filter configurations for a SQL query.
pub struct QueryContext {
    /// The start date filter. Only messages sent on or after this date will be included.
    pub start: Option<i64>,
    /// The end date filter. Only messages sent before this date will be included.
    pub end: Option<i64>,
}

impl QueryContext {
    /// Generate a QueryContext with a start date
    /// # Example:
    ///
    /// ```
    /// use imessage_database::util::query_context::QueryContext;
    ///
    /// let mut context = QueryContext::default();
    /// context.set_start("2023-01-01");
    /// ```
    pub fn set_start(&mut self, start: &str) -> Result<(), QueryContextError> {
        let timestamp = QueryContext::sanitize_date(start)
            .ok_or(QueryContextError::InvalidDate(start.to_string()))?;
        self.start = Some(timestamp);
        Ok(())
    }

    /// Generate a QueryContext with an end date
    /// # Example:
    ///
    /// ```
    /// use imessage_database::util::query_context::QueryContext;
    ///
    /// let mut context = QueryContext::default();
    /// context.set_end("2023-01-01");
    /// ```
    pub fn set_end(&mut self, end: &str) -> Result<(), QueryContextError> {
        let timestamp = QueryContext::sanitize_date(end)
            .ok_or(QueryContextError::InvalidDate(end.to_string()))?;
        self.end = Some(timestamp);
        Ok(())
    }

    /// Ensure a date string is valid
    fn sanitize_date(date: &str) -> Option<i64> {
        if date.len() < 9 {
            return None;
        }

        let year = date.get(0..4)?.parse::<i32>().ok()?;

        if !date.get(4..5)?.eq("-") {
            return None;
        }

        let month = date.get(5..7)?.parse::<u32>().ok()?;
        if month > 12 {
            return None;
        }

        if !date.get(7..8)?.eq("-") {
            return None;
        }

        let day = date.get(8..)?.parse::<u32>().ok()?;
        if day > 31 {
            return None;
        }

        let local = Local.with_ymd_and_hms(year, month, day, 0, 0, 0).single()?;
        let stamp = local.timestamp_nanos();

        Some(stamp - (get_offset() * TIMESTAMP_FACTOR))
    }

    /// Determine if the current QueryContext has any filters present
    ///
    /// # Example:
    ///
    /// ```
    /// use imessage_database::util::query_context::QueryContext;
    ///
    /// let mut context = QueryContext::default();
    /// assert!(!context.has_filters());
    /// context.set_start("2023-01-01");
    /// assert!(context.has_filters());
    pub fn has_filters(&self) -> bool {
        [self.start, self.end]
            .iter()
            .any(|maybe_date| maybe_date.is_some())
    }

    /// Generate the SQL `WHERE` clause described by this QueryContext
    /// # Example:
    ///
    /// ```
    /// use imessage_database::util::query_context::QueryContext;
    ///
    /// let mut context = QueryContext::default();
    /// context.set_start("2023-01-01");
    /// let filters = context.generate_filter_statement();
    pub fn generate_filter_statement(&self) -> String {
        let mut filters = String::new();
        if let Some(start) = self.start {
            filters.push_str(&format!("    m.date >= {start}"))
        }
        if let Some(end) = self.end {
            if !filters.is_empty() {
                filters.push_str(" AND ")
            }
            filters.push_str(&format!("    m.date <= {end}"));
        }

        if !filters.is_empty() {
            return format!(
                " WHERE
                 {filters}"
            );
        }
        filters
    }
}

#[cfg(test)]
mod use_tests {
    use chrono::prelude::*;

    use crate::util::{
        dates::{format, get_offset, TIMESTAMP_FACTOR},
        query_context::QueryContext,
    };

    #[test]
    fn can_create() {
        let context = QueryContext::default();
        assert!(context.start.is_none());
        assert!(context.end.is_none());
        assert!(!context.has_filters());
    }

    #[test]
    fn can_create_start() {
        let mut context = QueryContext::default();
        context.set_start("2020-01-01").unwrap();

        let from_timestamp = NaiveDateTime::from_timestamp_opt(
            (context.start.unwrap() / TIMESTAMP_FACTOR) + get_offset(),
            0,
        )
        .unwrap();
        let local = Local.from_utc_datetime(&from_timestamp);

        assert_eq!(format(&Ok(local)), "Jan 01, 2020 12:00:00 AM");
        assert_eq!(
            context.generate_filter_statement(),
            " WHERE\n                     m.date >= 599558400000000000"
        );
        assert!(context.start.is_some());
        assert!(context.end.is_none());
        assert!(context.has_filters());
    }

    #[test]
    fn can_create_end() {
        let mut context = QueryContext::default();
        context.set_end("2020-01-01").unwrap();

        let from_timestamp = NaiveDateTime::from_timestamp_opt(
            (context.end.unwrap() / TIMESTAMP_FACTOR) + get_offset(),
            0,
        )
        .unwrap();
        let local = Local.from_utc_datetime(&from_timestamp);

        assert_eq!(format(&Ok(local)), "Jan 01, 2020 12:00:00 AM");
        assert_eq!(
            context.generate_filter_statement(),
            " WHERE\n                     m.date <= 599558400000000000"
        );
        assert!(context.start.is_none());
        assert!(context.end.is_some());
        assert!(context.has_filters());
    }

    #[test]
    fn can_create_both() {
        let mut context = QueryContext::default();
        context.set_start("2020-01-01").unwrap();
        context.set_end("2020-02-02").unwrap();

        let from_timestamp = NaiveDateTime::from_timestamp_opt(
            (context.start.unwrap() / TIMESTAMP_FACTOR) + get_offset(),
            0,
        )
        .unwrap();
        let local_start = Local.from_utc_datetime(&from_timestamp);

        let from_timestamp = NaiveDateTime::from_timestamp_opt(
            (context.end.unwrap() / TIMESTAMP_FACTOR) + get_offset(),
            0,
        )
        .unwrap();
        let local_end = Local.from_utc_datetime(&from_timestamp);

        assert_eq!(format(&Ok(local_start)), "Jan 01, 2020 12:00:00 AM");
        assert_eq!(format(&Ok(local_end)), "Feb 02, 2020 12:00:00 AM");
        assert_eq!(
            context.generate_filter_statement(),
            " WHERE\n                     m.date >= 599558400000000000 AND     m.date <= 602323200000000000"
        );
        assert!(context.start.is_some());
        assert!(context.end.is_some());
        assert!(context.has_filters());
    }

    #[test]
    fn can_create_invalid_start() {
        let mut context = QueryContext::default();
        assert!(context.set_start("2020-13-32").is_err());
        assert!(!context.has_filters());
        assert_eq!(context.generate_filter_statement(), "");
    }

    #[test]
    fn can_create_invalid_end() {
        let mut context = QueryContext::default();
        assert!(context.set_end("fake").is_err());
        assert!(!context.has_filters());
        assert_eq!(context.generate_filter_statement(), "");
    }
}

#[cfg(test)]
mod sanitize_tests {
    use crate::util::query_context::QueryContext;

    #[test]
    fn can_sanitize_good() {
        let res = QueryContext::sanitize_date("2020-01-01");
        assert!(res.is_some())
    }

    #[test]
    fn can_reject_bad_short() {
        let res = QueryContext::sanitize_date("1-1-20");
        assert!(res.is_none())
    }

    #[test]
    fn can_reject_bad_order() {
        let res = QueryContext::sanitize_date("01-01-2020");
        assert!(res.is_none())
    }

    #[test]
    fn can_reject_bad_month() {
        let res = QueryContext::sanitize_date("2020-31-01");
        assert!(res.is_none())
    }

    #[test]
    fn can_reject_bad_day() {
        let res = QueryContext::sanitize_date("2020-01-32");
        assert!(res.is_none())
    }

    #[test]
    fn can_reject_bad_data() {
        let res = QueryContext::sanitize_date("2020-AB-CD");
        assert!(res.is_none())
    }

    #[test]
    fn can_reject_wrong_hyphen() {
        let res = QueryContext::sanitize_date("2020–01–01");
        assert!(res.is_none())
    }
}