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
use crate::configuration::Configuration;
use crate::event::Event;
use crate::store::Store;
use crate::visit::Visit;

use chrono::{Utc, Duration};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct Insights {

    /// Matomo site ID.
    pub idsite: u32,

    /// Preferred user languages as an HTTP Accept header.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,

    /// User Agent string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ua: Option<String>,

    /// `Visit` data points.
    pub visits: Vec<Visit>,

    /// `Event` data points.
    pub events: Vec<Event>,
}

impl Insights {

    /// Create an `Insights` object according to configuration with all data from the store which is
    /// due for offloading to the server.
    ///
    /// # Arguments
    /// * conf: The current configuration.
    /// * store: The current measurement and consents store.
    /// * lang: User languages in order of preference.
    /// * ua: User Agent string.
    pub fn new(conf: &Configuration, store: &mut dyn Store, lang: &Vec<String>, ua: &Option<String>) -> Insights {

        Insights::purge(conf, store);

        let mut quality = 1.0;
        let mut lang_string = None;

        if !lang.is_empty() {
            let mut components = vec![];

            for l in lang {
                components.push(format!("{code};q={quality:.1}", code = l, quality = quality));

                quality -= 0.1;

                if quality < 0.5 {
                    break
                }
            }

            lang_string = Some(components.join(","));
        }

        let now = Utc::now();

        let visits = store.visits().iter().filter(|&v|
            conf.campaigns.contains_key(&v.campaign_id)
                // Only send, after aggregation period is over. `last` should contain that date!
                && now > v.last
        ).cloned().collect();

        let events = store.events().iter().filter(|&e|
            conf.campaigns.contains_key(&e.campaign_id)
                // Only send, after aggregation period is over. `last` should contain that date!
                && now > e.last
        ).cloned().collect();

        Insights { idsite: conf.site_id, lang: lang_string, ua: ua.clone(), visits, events }
    }

    pub fn is_empty(&self) -> bool {
        self.visits.is_empty() && self.events.is_empty()
    }

    /// Removes all visits and events from the given `Store`, which are also available in here.
    ///
    /// This should be called, when all `Insights` were offloaded at the server successfully.
    ///
    /// # Arguments
    /// * store: The store where the `Visit`s and `Event`s in here came from.
    pub fn clean(&self, store: &mut dyn Store) {
        store.visits_mut().retain(|v| !self.visits.contains(&v));

        store.events_mut().retain(|e| !self.events.contains(&e));
    }

    /// Removes `Visit`s and `Event`s, which are too old. These were never been sent, otherwise,
    /// they would have been removed, already.
    ///
    /// Remove them now, if they're over the threshold, to not accumulate too many `Visits` and
    /// `Events` and therefore reduce privacy.
    fn purge(conf: &Configuration, store: &mut dyn Store) {
        let threshold = Utc::now() - Duration::days(conf.max_age_of_old_data);

        store.visits_mut().retain(|v| v.last >= threshold);
        store.events_mut().retain(|e| e.last >= threshold);
    }
}

#[cfg(test)]
mod test {
    use crate::configuration::Configuration;
    use crate::consents::Consents;
    use crate::event::Event;
    use crate::insights::Insights;
    use crate::visit::Visit;
    use crate::store::Store;

    use std::error::Error;

    use chrono::{Utc, Duration};

    #[derive(Debug)]
    struct TestStore {

        visits: Vec<Visit>,

        events: Vec<Event>,
    }

    #[allow(unused_variables)]
    impl Store for TestStore {
        fn consents(&self) -> &Consents {
            todo!()
        }

        fn consents_mut(&mut self) -> &mut Consents {
            todo!()
        }

        fn visits(&self) -> &Vec<Visit> {
            &self.visits
        }

        fn visits_mut(&mut self) -> &mut Vec<Visit> {
            &mut self.visits
        }

        fn events(&self) -> &Vec<Event> {
            &self.events
        }

        fn events_mut(&mut self) -> &mut Vec<Event> {
            &mut self.events
        }

        fn persist(&self) -> Result<(), Box<dyn Error>> {
            todo!()
        }

        fn send(&self, data: String, server: &String, timeout: u64) -> Result<(), Box<dyn Error>> {
            todo!()
        }
    }

    #[test]
    fn purge() {
        let mut store = TestStore {
            visits: vec![],
            events: vec![]
        };

        let day_before_yesterday = Utc::now() - Duration::days(2);

        store.visits_mut().push(Visit {
            scene_path: vec!["foo".to_string()],
            campaign_id: "x".to_string(),
            times: 1,
            first: day_before_yesterday,
            last: day_before_yesterday
        });

        store.events_mut().push(Event {
            category: "foo".to_string(),
            action: "bar".to_string(),
            name: Some("baz".to_string()),
            value: Some(4567.0),
            campaign_id: "x".to_string(),
            times: 1,
            first: day_before_yesterday,
            last: day_before_yesterday
        });

        let conf = Configuration {
            server: "".to_string(),
            site_id: 0,
            timeout: 0,
            max_retry_delay: 0,
            max_age_of_old_data: 1,
            persist_every_n_times: 0,
            server_side_anonymous_usage: false,
            debug: false,
            campaigns: Default::default()
        };

        Insights::purge(&conf, &mut store);

        let v: Vec<Visit> = vec![];
        assert_eq!(store.visits(), &v);

        let e: Vec<Event> = vec![];
        assert_eq!(store.events(),&e);
    }
}