bark_dev/
msg.rs

1// MIT License
2//
3// Copyright (c) 2025 66f94eae
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in all
13// copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23
24use openssl::symm::{Cipher, Crypter, Mode};
25
26///
27/// Push Notification Message
28/// 
29/// # Example
30/// ```rust
31/// use bark::msg::Msg;
32/// 
33/// // new a simple message with title and body
34/// let msg = Msg::new("title", "body");
35/// 
36/// // new a message with title = Notification and body
37/// let mut msg = Msg::with_body("body");
38/// 
39/// // set some fields
40/// msg.set_level("active");
41/// msg.set_badge(1);
42/// // and so on
43/// ```
44pub struct Msg {
45    /// Push Title
46    title: String,
47    
48    /// Push Content
49    body: String,
50    
51    /// Push Interruption Level
52    /// active: Default value, the system will immediately display the notification on the screen.
53    /// timeSensitive: Time-sensitive notification, can be displayed while in focus mode.
54    /// passive: Only adds the notification to the notification list, will not display on the screen.
55    level: Option<String>,
56    
57    /// Push Badge, can be any number
58    badge: Option<u64>,
59    
60    /// Pass 0 to disable; Automatically copy push content below iOS 14.5; above iOS 14.5, you need to manually long-press the push or pull down the push
61    auto_copy: Option<u8>,
62    
63    /// When copying the push, specify the content to copy; if this parameter is not provided, the entire push content will be copied
64    copy: Option<String>,
65    
66    /// You can set different ringtones for the push
67    sound: Option<String>,
68    
69    /// Set a custom icon for the push; the set icon will replace the default Bark icon
70    icon: Option<String>,
71    
72    /// Group messages; pushes will be displayed in groups in the notification center
73    group: Option<String>,
74    
75    /// Pass 1 to save the push; passing anything else will not save the push; if not passed, it will be decided according to the app's internal settings
76    is_archive: Option<u8>,
77    
78    /// The URL to jump to when clicking the push, supports URL Scheme and Universal Link
79    url: Option<String>,
80
81    /// iv
82    iv: Option<String>,
83    /// encrypt type
84    enc_type: Option<String>,
85    /// encrypt mode
86    mode: Option<String>,
87    /// encrypt key
88    key: Option<String>,
89    /// cipher
90    cipher: Option<Cipher>,
91}
92
93impl Msg {
94    pub fn new(title: &str, body: &str) -> Self {
95        Msg {
96            ..Self::default(Some(title.to_string()), body.to_string())
97        }
98    }
99
100    pub fn with_body(body: &str) -> Self {
101        Msg {
102            ..Self::default(None, body.to_string())
103        }
104    }
105
106    fn default(title: Option<String>, body: String) -> Self {
107        Msg {
108            title: title.unwrap_or("Notification".to_string()),
109            body,
110            level: None,
111            badge: None,
112            auto_copy: None,
113            copy: None,
114            sound: Some("chime.caf".to_string()),
115            icon: Some("https://github.com/66f94eae/bark-dev/raw/main/bot.jpg".to_string()),
116            group: None,
117            is_archive: None,
118            url: None,
119            iv: None,
120            enc_type: None,
121            mode: None,
122            key: None,
123            cipher: None,
124        }
125    }
126
127    pub fn set_level(&mut self, level: &str) -> &mut Self {
128        match level.to_lowercase().as_str() {
129            "active" => self.level = Some("active".to_string()),
130            "timesensitive" => self.level = Some("timeSensitive".to_string()),
131            "passive" => self.level = Some("passive".to_string()),
132            _ => self.level = None,
133        }
134        self
135    }
136
137    pub fn set_badge(&mut self, badge: u64) -> &mut  Self {
138        if badge > 0 {
139            self.badge = Some(badge);
140        } else {
141            self.badge = None;
142        }
143        self
144    }
145
146    pub fn set_auto_copy(&mut self, auto_copy: u8) -> &mut Self {
147        match auto_copy {
148            0 => self.auto_copy = Some(0),
149            _ => self.auto_copy = None,
150        }
151        self
152    }
153
154    pub fn set_copy(&mut self, copy: &str) -> &mut Self {
155        if copy.trim().is_empty() {
156            self.copy = None;
157        } else {
158            self.copy = Some(copy.to_string());
159        }
160        self
161    }
162
163    pub fn set_sound(&mut self, sound: &str) -> &mut Self {
164        self.sound = Some(sound.to_string());
165        self
166    }
167
168    pub fn set_icon(&mut self, icon: &str) -> &mut Self {
169        if icon.trim().is_empty() {
170            self.icon = None;
171        } else {
172            self.icon = Some(icon.to_string());
173        }
174        self
175    }
176
177    pub fn set_group(&mut self, group: &str) -> &mut Self {
178        self.group = Some(group.to_string());
179        self
180    }
181
182    pub fn set_is_archive(&mut self, is_archive: u8) -> &mut Self {
183        match is_archive {
184            1 => self.is_archive = Some(1),
185            _ => self.is_archive = None,
186        }
187        self
188    }
189
190    pub fn set_url(&mut self, url: &str) -> &mut Self {
191        if url.trim().is_empty() {
192            self.url = None;
193        } else {
194            self.url = Some(url.to_string());
195        }
196        self
197    }
198
199    pub fn set_iv(&mut self, iv: &str) -> &mut Self {
200        if iv.trim().is_empty() {
201            self.iv = None;
202        } else {
203            self.iv = Some(iv.to_string());
204        }
205        self
206    }
207
208    fn set_cipher(&mut self) -> &mut Self {
209        if self.enc_type.is_none() || self.mode.is_none() {
210            return self;
211        }
212        let enc_type = self.enc_type.as_ref().unwrap().clone();
213        let mode = self.mode.as_ref().unwrap().clone();
214
215        let cipher: Cipher = match enc_type.to_lowercase().as_str() {
216            "aes128" => {
217                match mode.to_lowercase().as_str() {
218                    "cbc" => {
219                        Cipher::aes_128_cbc()
220                    },
221                    "ecb" => {
222                        Cipher::aes_128_ecb()
223                    },
224                    "gcm" => {
225                        Cipher::aes_128_gcm()
226                    },
227                    _ => panic!("Invalid mode"),
228                }
229            },
230            "aes192" => {
231                match mode.to_lowercase().as_str() {
232                    "cbc" => {
233                        Cipher::aes_192_cbc()
234                    },
235                    "ecb" => {
236                        Cipher::aes_192_ecb()
237                    },
238                    "gcm" => {
239                        Cipher::aes_192_gcm()
240                    },
241                    _ => panic!("Invalid mode"),
242                }
243            }, 
244            "aes256" => {
245                match mode.to_lowercase().as_str() {
246                    "cbc" => {
247                        Cipher::aes_256_cbc()
248                    },
249                    "ecb" => {
250                        Cipher::aes_256_ecb()
251                    },
252                    "gcm" => {
253                        Cipher::aes_256_gcm()
254                    },
255                    _ => panic!("Invalid mode"),
256                }
257            },
258            _ => panic!("Invalid type"),
259        };
260        self.cipher = Some(cipher);
261        self
262    }
263
264    pub fn set_enc_type(&mut self, enc_type: &str) -> &mut Self {
265       if self.enc_type.is_some() {
266            panic!("Encrypt type can only be set once");
267        }
268        match enc_type.to_lowercase().as_str() {
269            "aes128" => self.enc_type = Some("aes128".to_string()),
270            "aes192" => self.enc_type = Some("aes192".to_string()),
271            "aes256" => self.enc_type = Some("aes256".to_string()),
272            _ => panic!("Invalid encrypt type"),
273        }
274        self.set_cipher();
275        self
276    }
277
278    pub fn set_mode(&mut self, mode: &str) -> &mut Self {
279        if self.mode.is_some() {
280            panic!("Encrypt mode can only be set once");
281        }
282        match mode.to_lowercase().as_str() {
283            "cbc" => self.mode = Some("cbc".to_string()),
284            "ecb" => self.mode = Some("ecb".to_string()),
285            "gcm" => self.mode = Some("gcm".to_string()),
286            _ => panic!("Invalid encrypt mode"),
287        }
288        self.set_cipher();
289        self
290    }
291
292    pub fn set_key(&mut self, key: &str) -> &mut Self {
293        self.key = Some(key.to_string());
294        self
295    }
296    
297    fn json(&self, encry_body: Option<String>) -> String {
298        let mut body: String = format!("{{\"aps\":{{\"mutable-content\":1,\"category\":\"myNotificationCategory\",\"interruption-level\":\"{level}\",", level = self.level.as_ref().unwrap_or(&"active".to_string()));
299
300        if let Some(badge) = self.badge {
301            body += &format!("\"badge\":{badge},", badge = badge);
302        }
303
304        if let Some(sound) = &self.sound {
305            body += &format!("\"sound\":\"{sound}\",", sound = sound);
306        }
307
308        if let Some(group) = &self.group {
309            body += &format!("\"thread-id\":\"{group}\",", group = group);
310        }
311
312        let alert: String = format!("\"alert\":{{\"title\":\"{title}\",\"body\":\"{body}\"}}}}",
313            title = self.title, body = if encry_body.is_some() {"NoContent"} else {self.body.as_str()}
314        );
315
316        body = body + &alert;
317
318        if let Some(icon) = &self.icon {
319            body += &format!(",\"icon\":\"{icon}\"", icon = icon);
320        }
321
322        if let Some(auto_copy) = self.auto_copy {
323            body += &format!(",\"autoCopy\":{auto_copy}", auto_copy = auto_copy);
324        }
325
326        if let Some(is_archive) = self.is_archive {
327            body += &format!(",\"isArchive\":{is_archive}", is_archive = is_archive);
328        }
329
330        if let Some(copy) = &self.copy {
331            body += &format!(",\"copy\":\"{copy}\"", copy = copy);
332        }
333
334        if let Some(url) = &self.url {
335            body += &format!(",\"url\":\"{url}\"", url = url);
336        }
337
338        if let Some(iv) = &self.iv {
339            body += &format!(",\"iv\":\"{iv}\"", iv = iv);
340        }
341        
342        if let Some(encry_body) = encry_body {
343            body += &format!(",\"ciphertext\":\"{encry_body}\"", encry_body = encry_body);
344        }
345
346        body + "}"
347    }
348
349    pub fn to_json(&self) -> String {
350        // let body: String = format!("{{\"aps\":{{\"interruption-level\":\"critical\",\"mutable-content\":1,\"alert\":{{\"title\":\"{title}\",\"body\":\"{body}\"}},\"category\":\"myNotificationCategory\",\"sound\":\"chime.caf\"}},\"icon\":\"{icon}\"}}",
351        // title = self.title, body = self.body, icon= self.icon
352        //     );
353        self.json(None)
354    }
355
356
357    pub fn encrypt(&self) -> Result<String, Box<dyn std::error::Error>> {
358        if self.enc_type.is_none() || self.mode.is_none() || self.key.is_none() {
359            panic!("Encrypt type, mode, and key must be set");
360        }
361
362        let key: String = self.key.as_ref().unwrap().clone();
363
364        let original: String = format!("{{\"body\":\"{}\"}}", self.body);
365        let original: &[u8] = original.as_bytes();
366
367        let cipher: Cipher = self.cipher.unwrap();
368        
369        let mut crypter: Crypter = Crypter::new(cipher, Mode::Encrypt, key.as_bytes(), Some(self.iv.as_ref().unwrap().as_bytes())).unwrap();
370        crypter.pad(true); // Enable PKCS7 padding
371        let mut buffer: Vec<u8> = vec![0; original.len() + cipher.block_size()];
372        let count: usize = crypter.update(&original, &mut buffer).unwrap();
373        let rest: usize = crypter.finalize(&mut buffer[count..]).unwrap();
374        buffer.truncate(count + rest);
375        Ok(self.json(Some(openssl::base64::encode_block(&buffer))))
376    }
377
378    pub fn serialize(&self) -> String {
379        if self.cipher.is_some() {
380            match self.encrypt() {
381                Ok(encrypted) => {
382                    encrypted
383                },
384                Err(e) => panic!("Error encrypting message: {}", e),
385             }
386        } else {
387            self.to_json()
388        }
389    }
390    
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn test_to_json_all_field() {
399        let mut msg = Msg::new("Test Title", "Test Body");
400        msg.set_level("timeSensitive");
401        msg.set_badge(1);
402        msg.set_auto_copy(1);
403        msg.set_copy("Test Copy");
404        msg.set_sound("chime.caf");
405        msg.set_icon("icon.png");
406        msg.set_group("Test Group");
407        msg.set_is_archive(1);
408        msg.set_url("https://example.com");
409        let json = msg.to_json();
410        println!("{}", json);
411        assert_eq!(json, "{\"aps\":{\"mutable-content\":1,\"category\":\"myNotificationCategory\",\"interruption-level\":\"timeSensitive\",\"badge\":1,\"sound\":\"chime.caf\",\"thread-id\":\"Test Group\",\"alert\":{\"title\":\"Test Title\",\"body\":\"Test Body\"},\"icon\":\"icon.png\"},\"isArchive\":1,\"copy\":\"Test Copy\",\"url\":\"https://example.com\"}");
412    }
413
414    #[test]
415    fn test_to_json_part_field() {
416        let mut msg = Msg::new("Test Title", "Test Body");
417        msg.set_level("passive");
418        msg.set_badge(1);
419        msg.set_auto_copy(1);
420        msg.set_copy("");
421        msg.set_sound("chime.caf");
422        msg.set_icon("icon.png");
423        let json = msg.to_json();
424        println!("{}", json);
425        assert_eq!(json, "{\"aps\":{\"mutable-content\":1,\"category\":\"myNotificationCategory\",\"interruption-level\":\"passive\",\"badge\":1,\"sound\":\"chime.caf\",\"alert\":{\"title\":\"Test Title\",\"body\":\"Test Body\"},\"icon\":\"icon.png\"}}");
426    }
427
428    #[test]
429    fn test_to_json_default() {
430        let msg = Msg::new("Test Title", "Test Body");
431        let json = msg.to_json();
432        println!("{}", json);
433        assert_eq!(json, "{\"aps\":{\"mutable-content\":1,\"category\":\"myNotificationCategory\",\"interruption-level\":\"active\",\"alert\":{\"title\":\"Test Title\",\"body\":\"Test Body\"}}}");
434    }
435}