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
use request::notification::{NotificationBuilder, NotificationOptions};
use request::payload::{Payload, APS};
use std::collections::BTreeMap;

/// A builder to create an APNs silent notification payload which can be used to
/// send custom data to the user's phone if the user hasn't been running the app
/// for a while. The custom data needs to be implementing `Serialize` from Serde.
///
/// # Example
///
/// ```rust
/// # extern crate a2;
/// # use std::collections::HashMap;
/// # use a2::request::notification::{NotificationBuilder, SilentNotificationBuilder};
/// # fn main() {
/// let mut test_data = HashMap::new();
/// test_data.insert("a", "value");
///
/// let mut payload = SilentNotificationBuilder::new()
///    .build("device_id", Default::default());
///
/// payload.add_custom_data("custom", &test_data);
///
/// assert_eq!(
///     "{\"aps\":{\"content-available\":1},\"custom\":{\"a\":\"value\"}}",
///     &payload.to_json_string().unwrap()
/// );
/// # }
/// ```
pub struct SilentNotificationBuilder {
    content_available: u8,
}

impl SilentNotificationBuilder {
    /// Creates a new builder.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{SilentNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let payload = SilentNotificationBuilder::new()
    ///     .build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"content-available\":1}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn new() -> SilentNotificationBuilder {
        SilentNotificationBuilder {
            content_available: 1,
        }
    }
}

impl<'a> NotificationBuilder<'a> for SilentNotificationBuilder {
    fn build(self, device_token: &'a str, options: NotificationOptions<'a>) -> Payload<'a>
    {
        Payload {
            aps: APS {
                alert: None,
                badge: None,
                sound: None,
                content_available: Some(self.content_available),
                category: None,
                mutable_content: None,
            },
            device_token: device_token,
            options: options,
            data: BTreeMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    #[test]
    fn test_silent_notification_with_no_content() {
        let payload = SilentNotificationBuilder::new()
            .build("device-token", Default::default())
            .to_json_string()
            .unwrap();

        let expected_payload = json!({
            "aps": {
                "content-available": 1
            }
        }).to_string();

        assert_eq!(expected_payload, payload);
    }

    #[test]
    fn test_silent_notification_with_custom_data() {
        #[derive(Serialize, Debug)]
        struct SubData {
            nothing: &'static str,
        }

        #[derive(Serialize, Debug)]
        struct TestData {
            key_str: &'static str,
            key_num: u32,
            key_bool: bool,
            key_struct: SubData,
        }

        let test_data = TestData {
            key_str: "foo",
            key_num: 42,
            key_bool: false,
            key_struct: SubData { nothing: "here" },
        };

        let mut payload =
            SilentNotificationBuilder::new().build("device-token", Default::default());

        payload.add_custom_data("custom", &test_data).unwrap();

        let expected_payload = json!({
            "aps": {
                "content-available": 1
            },
            "custom": {
                "key_str": "foo",
                "key_num": 42,
                "key_bool": false,
                "key_struct": {
                    "nothing": "here"
                }
            }
        }).to_string();

        assert_eq!(expected_payload, payload.to_json_string().unwrap());
    }

    #[test]
    fn test_silent_notification_with_custom_hashmap() {
        let mut test_data = BTreeMap::new();
        test_data.insert("key_str", "foo");
        test_data.insert("key_str2", "bar");

        let mut payload =
            SilentNotificationBuilder::new().build("device-token", Default::default());

        payload.add_custom_data("custom", &test_data).unwrap();

        let expected_payload = json!({
            "aps": {
                "content-available": 1
            },
            "custom": {
                "key_str": "foo",
                "key_str2": "bar"
            }
        }).to_string();

        assert_eq!(expected_payload, payload.to_json_string().unwrap());
    }
}