bark-apns 0.1.0

Direct APNs client for sending Bark notifications.
Documentation
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use crate::{
    crypto::Encryption,
    error::{Error, Result},
};
use serde::Serialize;

const DEFAULT_TITLE: &str = "Notification";
const CATEGORY: &str = "myNotificationCategory";
const ENCRYPTED_TITLE: &str = "Bark";
const ENCRYPTED_BODY: &str = "Encrypted Message";

/// Bark interruption level for a notification.
///
/// These values match Bark's documented `level` parameter. The level is also
/// serialized into APNs as `aps.interruption-level` for direct delivery.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum InterruptionLevel {
    /// Important alert. Bark uses this with critical notification sound handling.
    #[serde(rename = "critical")]
    Critical,
    /// Time-sensitive notification, available on iOS 15 and later.
    #[serde(rename = "timeSensitive")]
    TimeSensitive,
    /// Default active notification behavior.
    #[serde(rename = "active")]
    Active,
    /// Adds the notification to Notification Center without actively alerting.
    #[serde(rename = "passive")]
    Passive,
}

impl InterruptionLevel {
    /// Returns the `level` string recognized by Bark.
    pub const fn as_bark_str(self) -> &'static str {
        match self {
            Self::Critical => "critical",
            Self::TimeSensitive => "timeSensitive",
            Self::Active => "active",
            Self::Passive => "passive",
        }
    }
}

/// Builder for a Bark-compatible push message.
///
/// `Message` serializes to the JSON payload sent to APNs. For normal pushes it
/// writes both APNs `aps` fields and Bark custom fields. For encrypted pushes it
/// encrypts Bark request fields into `ciphertext` and keeps only the APNs
/// placeholder alert plus `ciphertext`/`iv` in clear text.
///
/// Start with [`Message::new`] and chain the fields that should be present:
///
/// ```
/// use bark_apns::{InterruptionLevel, Message};
///
/// let message = Message::new()
///     .title("Build")
///     .body("finished")
///     .group("ci")
///     .level(InterruptionLevel::TimeSensitive);
/// ```
#[derive(Clone, Debug)]
pub struct Message {
    /// Push title shown by iOS and stored by Bark.
    title: String,
    /// Optional push subtitle shown by iOS.
    subtitle: Option<String>,
    /// Plain-text fallback body.
    body: String,
    /// Optional Markdown body rendered by Bark before display.
    markdown: Option<String>,
    /// Optional image URL downloaded and attached by Bark.
    image: Option<String>,
    /// APNs and Bark interruption level.
    level: InterruptionLevel,
    /// Critical alert volume in Bark's 0-10 scale.
    volume: Option<u8>,
    /// App badge value.
    badge: Option<u64>,
    /// Bark automatic copy flag.
    auto_copy: Option<bool>,
    /// Explicit text copied by Bark when automatic copy runs.
    copy: Option<String>,
    /// Bark sound name, without requiring a `.caf` suffix from callers.
    sound: Option<String>,
    /// Bark call-style repeated ringing flag.
    call: bool,
    /// Optional custom notification icon URL.
    icon: Option<String>,
    /// Bark group name and APNs thread id for normal pushes.
    group: Option<String>,
    /// Bark archive preference override.
    archive: Option<bool>,
    /// Optional archive retention time in seconds.
    ttl: Option<u64>,
    /// URL opened when the notification is tapped.
    url: Option<String>,
    /// Bark action parameter, such as `alert`.
    action: Option<String>,
    /// Bark message id and APNs collapse id.
    id: Option<String>,
    /// Whether this message is a Bark delete request.
    delete: bool,
    /// Optional encryption settings for encrypted Bark pushes.
    encryption: Option<Encryption>,
}

impl Message {
    /// Creates an empty message builder.
    ///
    /// The default title is `"Notification"`, the default level is
    /// [`InterruptionLevel::Active`], and no sound is set. A normal notification
    /// must eventually contain either [`Message::body`] or [`Message::markdown`].
    /// Delete messages created with [`Message::delete`] do not require content.
    pub fn new() -> Self {
        Self {
            title: DEFAULT_TITLE.to_owned(),
            body: String::new(),
            subtitle: None,
            markdown: None,
            image: None,
            level: InterruptionLevel::Active,
            volume: None,
            badge: None,
            auto_copy: None,
            copy: None,
            sound: None,
            call: false,
            icon: None,
            group: None,
            archive: None,
            ttl: None,
            url: None,
            action: None,
            id: None,
            delete: false,
            encryption: None,
        }
    }

    /// Sets the push title.
    ///
    /// If omitted, Bark receives `"Notification"` as the title.
    pub fn title<T>(mut self, title: T) -> Self
    where
        T: Into<String>,
    {
        self.title = title.into();
        self
    }

    /// Sets the push subtitle.
    ///
    /// Bark maps this to the notification subtitle when the value is present.
    /// Empty or whitespace-only values are omitted.
    pub fn subtitle<S>(mut self, subtitle: S) -> Self
    where
        S: Into<String>,
    {
        self.subtitle = non_empty(subtitle.into());
        self
    }

    /// Sets the plain-text push body.
    ///
    /// Bark uses this as the notification body unless `markdown` is also
    /// provided. For encrypted pushes, this value is included inside the
    /// encrypted Bark JSON.
    pub fn body<B>(mut self, body: B) -> Self
    where
        B: Into<String>,
    {
        self.body = body.into();
        self
    }

    /// Sets the Markdown body.
    ///
    /// Bark's notification service extension renders this value and treats it as
    /// taking precedence over `body` for display. Empty or whitespace-only values
    /// are omitted.
    ///
    /// Bark parses Markdown with Apple's Swift Markdown package and its own
    /// `MarkdownParser`. The parser handles paragraphs, headings, block quotes,
    /// strong emphasis, emphasis, strikethrough, inline code, fenced or indented
    /// code blocks, links, images, ordered lists, unordered lists, nested list
    /// indentation, task-list checkboxes, soft breaks, and hard line breaks.
    ///
    /// For push notification display, Bark's notification service extension uses
    /// the parsed attributed string's plain `.string` value as the notification
    /// body and collapses repeated blank lines. That means visual styles such as
    /// bold, italic, strikethrough, link color, code font, and quote color are
    /// not preserved in the notification banner itself; the rendered text,
    /// headings, list markers, checkbox symbols, code text, link text, and image
    /// alt text remain.
    pub fn markdown<M>(mut self, markdown: M) -> Self
    where
        M: Into<String>,
    {
        self.markdown = non_empty(markdown.into());
        self
    }

    /// Sets a push image URL.
    ///
    /// Bark downloads this image in the notification service extension and
    /// attaches it to the notification when possible. Empty or whitespace-only
    /// values are omitted.
    pub fn image<I>(mut self, image: I) -> Self
    where
        I: Into<String>,
    {
        self.image = non_empty(image.into());
        self
    }

    /// Sets the notification interruption level.
    ///
    /// Defaults to [`InterruptionLevel::Active`]. Critical notifications may
    /// require the Bark app and APNs topic to have the appropriate entitlement.
    pub fn level(mut self, level: InterruptionLevel) -> Self {
        self.level = level;
        self
    }

    /// Sets the critical alert volume from `0` to `10`.
    ///
    /// Bark uses this value for `level=critical`. Values larger than `10` are
    /// clamped to `10`.
    pub fn volume(mut self, volume: u8) -> Self {
        self.volume = Some(volume.min(10));
        self
    }

    /// Sets the app badge number.
    ///
    /// The value is serialized into APNs `aps.badge` and Bark's `badge`
    /// parameter.
    pub fn badge(mut self, badge: u64) -> Self {
        self.badge = Some(badge);
        self
    }

    /// Sets Bark's automatic copy flag.
    ///
    /// Bark interprets `"1"` as enabled. On newer iOS versions the user may
    /// still need to long-press or expand the notification to copy.
    pub fn auto_copy(mut self, auto_copy: bool) -> Self {
        self.auto_copy = Some(auto_copy);
        self
    }

    /// Sets the text Bark should copy when automatic copy runs.
    ///
    /// If omitted, Bark copies the notification body. Empty or whitespace-only
    /// values are omitted.
    pub fn copy<C>(mut self, copy: C) -> Self
    where
        C: Into<String>,
    {
        self.copy = non_empty(copy.into());
        self
    }

    /// Sets the Bark sound name.
    ///
    /// This crate does not set a default sound, matching Bark's request
    /// semantics. For normal pushes, APNs receives `aps.sound`; if the value does
    /// not end in `.caf`, the APNs sound name is suffixed with `.caf`. For
    /// encrypted pushes, the sound is kept inside the encrypted Bark JSON and is
    /// not exposed in clear text.
    pub fn sound<S>(mut self, sound: S) -> Self
    where
        S: Into<String>,
    {
        self.sound = non_empty(sound.into());
        self
    }

    /// Enables or disables Bark's repeated call-style ringing.
    ///
    /// Bark expects `"1"` to enable this behavior. Passing `false` omits the
    /// field.
    pub fn call(mut self, call: bool) -> Self {
        self.call = call;
        self
    }

    /// Sets a custom icon URL.
    ///
    /// Bark's notification service extension downloads and caches the icon, then
    /// uses it to replace the default Bark icon when iOS supports the feature.
    /// Empty or whitespace-only values are omitted.
    pub fn icon<I>(mut self, icon: I) -> Self
    where
        I: Into<String>,
    {
        self.icon = non_empty(icon.into());
        self
    }

    /// Sets the Bark group name.
    ///
    /// The group is used for Notification Center grouping and for Bark's history
    /// grouping. Normal pushes also set APNs `aps.thread-id`.
    pub fn group<G>(mut self, group: G) -> Self
    where
        G: Into<String>,
    {
        self.group = non_empty(group.into());
        self
    }

    /// Sets Bark's archive flag.
    ///
    /// `true` serializes `"1"` and asks Bark to save the push to history.
    /// `false` serializes `"0"` and asks Bark not to archive it. If omitted,
    /// Bark uses the app's own archive setting.
    pub fn archive(mut self, archive: bool) -> Self {
        self.archive = Some(archive);
        self
    }

    /// Sets the archive time-to-live in seconds.
    ///
    /// Bark applies this only to messages saved to history.
    pub fn ttl(mut self, ttl: u64) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Sets the URL opened when the notification is tapped.
    ///
    /// Bark supports URL schemes and universal links. Empty or whitespace-only
    /// values are omitted.
    pub fn url<U>(mut self, url: U) -> Self
    where
        U: Into<String>,
    {
        self.url = non_empty(url.into());
        self
    }

    /// Sets Bark's `action` parameter.
    ///
    /// Bark documents `action=alert` as showing an action popup when the user
    /// opens the app from the notification.
    pub fn action<A>(mut self, action: A) -> Self
    where
        A: Into<String>,
    {
        self.action = non_empty(action.into());
        self
    }

    /// Sets the Bark message id.
    ///
    /// The same id can update a delivered notification. It is also required for
    /// delete messages. APNs collapse ids must be at most 64 bytes, so this crate
    /// validates the id before sending.
    pub fn id<I>(mut self, id: I) -> Self
    where
        I: Into<String>,
    {
        self.id = non_empty(id.into());
        self
    }

    /// Marks this message as a Bark delete request.
    ///
    /// Delete requests serialize as a background APNs payload with `delete=1`
    /// and require [`Message::id`]. They do not require body or markdown
    /// content.
    pub fn delete(mut self) -> Self {
        self.delete = true;
        self
    }

    /// Encrypts Bark request fields before sending.
    ///
    /// The APNs payload will contain the placeholder alert plus top-level
    /// `ciphertext` and, for CBC/GCM, `iv`. Fields such as `title`, `body`,
    /// `markdown`, `sound`, `group`, and `badge` are placed in the encrypted JSON
    /// rather than clear-text APNs custom fields.
    pub fn encryption(mut self, encryption: Encryption) -> Self {
        self.encryption = Some(encryption);
        self
    }

    pub(crate) fn is_delete(&self) -> bool {
        self.delete
    }

    pub(crate) fn id_value(&self) -> Option<&str> {
        self.id.as_deref()
    }

    pub(crate) fn payload_bytes(&self) -> Result<Vec<u8>> {
        Ok(serde_json::to_vec(&self.payload_value()?)?)
    }

    pub(crate) fn validate_headers(&self) -> Result<()> {
        if let Some(id) = &self.id {
            let actual = id.len();
            if actual > 64 {
                return Err(Error::InvalidCollapseId { actual });
            }
        }

        if self.delete && self.id.is_none() {
            return Err(Error::MissingMessageIdForDelete);
        }

        Ok(())
    }

    fn payload_value(&self) -> Result<serde_json::Value> {
        self.validate_headers()?;

        if self.delete {
            return Ok(serde_json::to_value(DeletePayload {
                aps: DeleteAps {
                    content_available: 1,
                },
                delete: "1",
                id: self.id.as_deref().expect("validated delete id"),
            })?);
        }

        self.validate_content()?;

        if let Some(encryption) = &self.encryption {
            let fields = BarkPlaintextFields::from_message(self);
            let plaintext = serde_json::to_vec(&fields)?;
            let ciphertext = encryption.encrypt_bark_json(&plaintext)?;
            return Ok(serde_json::to_value(EncryptedNotificationPayload {
                aps: ApsPayload::encrypted(),
                ciphertext,
                iv: encryption.apns_iv(),
            })?);
        }

        Ok(serde_json::to_value(NotificationPayload {
            aps: ApsPayload::plain(self),
            fields: BarkFields::from_message(self),
        })?)
    }

    fn validate_content(&self) -> Result<()> {
        if self.body.trim().is_empty() && self.markdown.is_none() {
            return Err(Error::EmptyMessage);
        }

        Ok(())
    }
}

impl Default for Message {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Serialize)]
struct NotificationPayload {
    aps: ApsPayload,
    #[serde(flatten)]
    fields: BarkFields,
}

#[derive(Debug, Serialize)]
struct EncryptedNotificationPayload<'a> {
    aps: ApsPayload,
    ciphertext: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    iv: Option<&'a str>,
}

#[derive(Debug, Serialize)]
struct DeletePayload<'a> {
    aps: DeleteAps,
    delete: &'static str,
    id: &'a str,
}

#[derive(Debug, Serialize)]
struct DeleteAps {
    #[serde(rename = "content-available")]
    content_available: u8,
}

#[derive(Debug, Serialize)]
struct ApsPayload {
    #[serde(rename = "mutable-content")]
    mutable_content: u8,
    category: &'static str,
    #[serde(rename = "interruption-level")]
    interruption_level: InterruptionLevel,
    #[serde(skip_serializing_if = "Option::is_none")]
    badge: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sound: Option<String>,
    #[serde(rename = "thread-id", skip_serializing_if = "Option::is_none")]
    thread_id: Option<String>,
    alert: AlertPayload,
}

impl ApsPayload {
    fn plain(message: &Message) -> Self {
        Self {
            mutable_content: 1,
            category: CATEGORY,
            interruption_level: message.level,
            badge: message.badge,
            sound: message.sound.as_deref().map(apns_sound_name),
            thread_id: message.group.clone(),
            alert: AlertPayload {
                title: message.title.clone(),
                subtitle: message.subtitle.clone(),
                body: message.body.clone(),
            },
        }
    }

    fn encrypted() -> Self {
        Self {
            mutable_content: 1,
            category: CATEGORY,
            interruption_level: InterruptionLevel::Active,
            badge: None,
            sound: None,
            thread_id: None,
            alert: AlertPayload {
                title: ENCRYPTED_TITLE.to_owned(),
                subtitle: None,
                body: ENCRYPTED_BODY.to_owned(),
            },
        }
    }
}

#[derive(Debug, Serialize)]
struct AlertPayload {
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,
    body: String,
}

#[derive(Debug, Default, Serialize)]
struct BarkFields {
    #[serde(skip_serializing_if = "Option::is_none")]
    level: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    volume: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    badge: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    call: Option<&'static str>,
    #[serde(rename = "autocopy", skip_serializing_if = "Option::is_none")]
    auto_copy: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    copy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sound: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    image: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    group: Option<String>,
    #[serde(rename = "isarchive", skip_serializing_if = "Option::is_none")]
    archive: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ttl: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    action: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    markdown: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,
}

impl BarkFields {
    fn from_message(message: &Message) -> Self {
        Self {
            level: Some(message.level.as_bark_str()),
            volume: message.volume.map(|volume| volume.to_string()),
            badge: message.badge.map(|badge| badge.to_string()),
            call: message.call.then_some("1"),
            auto_copy: message
                .auto_copy
                .map(|auto_copy| if auto_copy { "1" } else { "0" }),
            copy: message.copy.clone(),
            sound: message.sound.clone(),
            icon: message.icon.clone(),
            image: message.image.clone(),
            group: message.group.clone(),
            archive: message
                .archive
                .map(|archive| if archive { "1" } else { "0" }),
            ttl: message.ttl.map(|ttl| ttl.to_string()),
            url: message.url.clone(),
            action: message.action.clone(),
            markdown: message.markdown.clone(),
            id: message.id.clone(),
        }
    }
}

#[derive(Debug, Default, Serialize)]
struct BarkPlaintextFields {
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,
    body: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    markdown: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    level: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    volume: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    badge: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    call: Option<&'static str>,
    #[serde(rename = "autocopy", skip_serializing_if = "Option::is_none")]
    auto_copy: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    copy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sound: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    image: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    group: Option<String>,
    #[serde(rename = "isarchive", skip_serializing_if = "Option::is_none")]
    archive: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ttl: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    action: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,
}

impl BarkPlaintextFields {
    fn from_message(message: &Message) -> Self {
        let fields = BarkFields::from_message(message);
        Self {
            title: message.title.clone(),
            subtitle: message.subtitle.clone(),
            body: message.body.clone(),
            markdown: fields.markdown,
            level: fields.level,
            volume: fields.volume,
            badge: fields.badge,
            call: fields.call,
            auto_copy: fields.auto_copy,
            copy: fields.copy,
            sound: fields.sound,
            icon: fields.icon,
            image: fields.image,
            group: fields.group,
            archive: fields.archive,
            ttl: fields.ttl,
            url: fields.url,
            action: fields.action,
            id: fields.id,
        }
    }
}

fn non_empty(value: String) -> Option<String> {
    if value.trim().is_empty() {
        None
    } else {
        Some(value)
    }
}

fn apns_sound_name(sound: &str) -> String {
    if sound.ends_with(".caf") {
        sound.to_owned()
    } else {
        format!("{sound}.caf")
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::crypto::{EncryptionAlgorithm, EncryptionMode};

    fn payload(message: Message) -> serde_json::Value {
        message.payload_value().unwrap()
    }

    #[test]
    fn serializes_markdown_without_manual_escaping() {
        let payload = payload(
            Message::new()
                .title("build")
                .body("fallback")
                .markdown("## ok\nquoted: \"yes\"")
                .group(String::from("ci")),
        );

        assert_eq!(payload["markdown"], "## ok\nquoted: \"yes\"");
        assert_eq!(payload["group"], "ci");
        assert_eq!(payload["aps"]["alert"]["body"], "fallback");
    }

    #[test]
    fn sound_is_only_serialized_when_explicitly_set() {
        let default_payload = payload(Message::new().body("quiet"));
        let sound_payload = payload(Message::new().body("loud").sound("birdsong"));

        assert!(default_payload["aps"].get("sound").is_none());
        assert_eq!(sound_payload["aps"]["sound"], "birdsong.caf");
        assert_eq!(sound_payload["sound"], "birdsong");
    }

    #[test]
    fn serializes_delete_as_background_payload() {
        let payload = payload(Message::new().id("deploy-42").delete());

        assert_eq!(
            payload,
            json!({
                "aps": { "content-available": 1 },
                "delete": "1",
                "id": "deploy-42"
            })
        );
    }

    #[test]
    fn encrypted_payload_keeps_bark_fields_out_of_apns_user_info() {
        let encryption = Encryption::with_iv(
            EncryptionAlgorithm::AES128,
            EncryptionMode::CBC,
            "1234567890123456",
            "1111111111111111",
        )
        .unwrap();

        let payload = payload(
            Message::new()
                .title("secret title")
                .body("secret body")
                .markdown("**secret**")
                .badge(7)
                .group("ops")
                .sound("birdsong")
                .encryption(encryption),
        );

        assert_eq!(payload["aps"]["alert"]["title"], ENCRYPTED_TITLE);
        assert_eq!(payload["aps"]["alert"]["body"], ENCRYPTED_BODY);
        assert!(payload["aps"].get("sound").is_none());
        assert_eq!(payload["iv"], "1111111111111111");
        assert!(payload.get("ciphertext").is_some());
        assert!(payload.get("group").is_none());
        assert!(payload.get("markdown").is_none());
        assert!(payload.get("badge").is_none());
    }

    #[test]
    fn delete_requires_id() {
        let err = Message::new().delete().payload_bytes().unwrap_err();

        assert!(matches!(err, Error::MissingMessageIdForDelete));
    }

    #[test]
    fn normal_message_requires_body_or_markdown() {
        let err = Message::new().title("empty").payload_bytes().unwrap_err();

        assert!(matches!(err, Error::EmptyMessage));
    }
}