-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
834 lines (740 loc) · 26.8 KB
/
types.go
File metadata and controls
834 lines (740 loc) · 26.8 KB
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
package fcm
import (
"encoding/json"
"fmt"
"maps"
"strconv"
"strings"
"time"
)
const rfc3339Zulu = "2006-01-02T15:04:05.000000000Z"
// Message to be sent via Firebase Cloud Messaging (FCM).
// A Message must specify exactly one of Token, Topic or Condition fields.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
type Message struct {
Data map[string]string `json:"data,omitempty"`
Notification *Notification `json:"notification,omitempty"`
Android *AndroidConfig `json:"android,omitempty"`
Webpush *WebpushConfig `json:"webpush,omitempty"`
APNS *APNSConfig `json:"apns,omitempty"`
FCMOptions *FCMOptions `json:"fcm_options,omitempty"`
Token string `json:"token,omitempty"`
Topic string `json:"-"`
Condition string `json:"condition,omitempty"`
}
func (m Message) IsValid() error {
return validateMessage(&m)
}
func (m *Message) MarshalJSON() ([]byte, error) {
type messageWrapper Message
tmp := &struct {
BareTopic string `json:"topic,omitempty"`
*messageWrapper
}{
BareTopic: strings.TrimPrefix(m.Topic, "/topics/"),
messageWrapper: (*messageWrapper)(m),
}
return json.Marshal(tmp)
}
func (m *Message) UnmarshalJSON(b []byte) error {
type messageWrapper Message
tmp := struct {
BareTopic string `json:"topic,omitempty"`
*messageWrapper
}{
messageWrapper: (*messageWrapper)(m),
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
m.Topic = tmp.BareTopic
return nil
}
// Notification is the basic notification template to use across all platforms.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification
type Notification struct {
Title string `json:"title,omitempty"`
Body string `json:"body,omitempty"`
ImageURL string `json:"image,omitempty"`
}
// AndroidConfig contains messaging options specific to the Android platform.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidconfig
type AndroidConfig struct {
CollapseKey string `json:"collapse_key,omitempty"`
Priority string `json:"priority,omitempty"` // one of "normal" or "high"
TTL *time.Duration `json:"-"`
RestrictedPackageName string `json:"restricted_package_name,omitempty"`
Data map[string]string `json:"data,omitempty"` // if set, overrides [Message.Data] field.
Notification *AndroidNotification `json:"notification,omitempty"`
FCMOptions *AndroidFCMOptions `json:"fcm_options,omitempty"`
DirectBootOK bool `json:"direct_boot_ok,omitempty"`
}
func (a *AndroidConfig) MarshalJSON() ([]byte, error) {
var ttl string
if a.TTL != nil {
ttl = durationToString(*a.TTL)
}
type androidWrapper AndroidConfig
tmp := &struct {
TTL string `json:"ttl,omitempty"`
*androidWrapper
}{
TTL: ttl,
androidWrapper: (*androidWrapper)(a),
}
return json.Marshal(tmp)
}
func (a *AndroidConfig) UnmarshalJSON(b []byte) error {
type androidWrapper AndroidConfig
tmp := struct {
TTL string `json:"ttl,omitempty"`
*androidWrapper
}{
androidWrapper: (*androidWrapper)(a),
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
if tmp.TTL != "" {
ttl, err := stringToDuration(tmp.TTL)
if err != nil {
return err
}
a.TTL = &ttl
}
return nil
}
// AndroidNotification is a notification to send to Android devices.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidnotification
type AndroidNotification struct {
Title string `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
Body string `json:"body,omitempty"` // if set, overrides [Notification.Body] field.
Icon string `json:"icon,omitempty"`
Color string `json:"color,omitempty"` // #RRGGBB format
Sound string `json:"sound,omitempty"`
Tag string `json:"tag,omitempty"`
ClickAction string `json:"click_action,omitempty"`
BodyLocKey string `json:"body_loc_key,omitempty"`
BodyLocArgs []string `json:"body_loc_args,omitempty"`
TitleLocKey string `json:"title_loc_key,omitempty"`
TitleLocArgs []string `json:"title_loc_args,omitempty"`
ChannelID string `json:"channel_id,omitempty"`
Ticker string `json:"ticker,omitempty"`
Sticky bool `json:"sticky,omitempty"`
EventTimestamp *time.Time `json:"-"`
LocalOnly bool `json:"local_only,omitempty"`
Priority AndroidNotificationPriority `json:"-"`
DefaultSound bool `json:"default_sound,omitempty"`
DefaultVibrateTimings bool `json:"default_vibrate_timings,omitempty"`
DefaultLightSettings bool `json:"default_light_settings,omitempty"`
VibrateTimingMillis []int64 `json:"-"`
Visibility AndroidNotificationVisibility `json:"-"`
NotificationCount *int `json:"notification_count,omitempty"`
LightSettings *LightSettings `json:"light_settings,omitempty"`
ImageURL string `json:"image,omitempty"`
Proxy AndroidNotificationProxy `json:"-"`
}
func (a *AndroidNotification) MarshalJSON() ([]byte, error) {
var priority string
if a.Priority != priorityUnknown {
priorities := map[AndroidNotificationPriority]string{
PriorityMin: "PRIORITY_MIN",
PriorityLow: "PRIORITY_LOW",
PriorityDefault: "PRIORITY_DEFAULT",
PriorityHigh: "PRIORITY_HIGH",
PriorityMax: "PRIORITY_MAX",
}
priority = priorities[a.Priority]
}
var visibility string
if a.Visibility != visibilityUnknown {
visibilities := map[AndroidNotificationVisibility]string{
VisibilityPrivate: "PRIVATE",
VisibilityPublic: "PUBLIC",
VisibilitySecret: "SECRET",
}
visibility = visibilities[a.Visibility]
}
var proxy string
if a.Proxy != proxyUnknown {
proxies := map[AndroidNotificationProxy]string{
ProxyAllow: "ALLOW",
ProxyDeny: "DENY",
ProxyIfPriorityLowered: "IF_PRIORITY_LOWERED",
}
proxy = proxies[a.Proxy]
}
var timestamp string
if a.EventTimestamp != nil {
timestamp = a.EventTimestamp.UTC().Format(rfc3339Zulu)
}
vibTimings := make([]string, 0, len(a.VibrateTimingMillis))
for _, t := range a.VibrateTimingMillis {
vibTimings = append(vibTimings, durationToString(time.Duration(t)*time.Millisecond))
}
type androidWrapper AndroidNotification
tmp := &struct {
EventTimestamp string `json:"event_time,omitempty"`
Priority string `json:"notification_priority,omitempty"`
Visibility string `json:"visibility,omitempty"`
Proxy string `json:"proxy,omitempty"`
VibrateTimings []string `json:"vibrate_timings,omitempty"`
*androidWrapper
}{
EventTimestamp: timestamp,
Priority: priority,
Visibility: visibility,
Proxy: proxy,
VibrateTimings: vibTimings,
androidWrapper: (*androidWrapper)(a),
}
return json.Marshal(tmp)
}
func (a *AndroidNotification) UnmarshalJSON(b []byte) error {
type androidWrapper AndroidNotification
tmp := struct {
EventTimestamp string `json:"event_time,omitempty"`
Priority string `json:"notification_priority,omitempty"`
Visibility string `json:"visibility,omitempty"`
Proxy string `json:"proxy,omitempty"`
VibrateTimings []string `json:"vibrate_timings,omitempty"`
*androidWrapper
}{
androidWrapper: (*androidWrapper)(a),
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
if tmp.Priority != "" {
priorities := map[string]AndroidNotificationPriority{
"PRIORITY_MIN": PriorityMin,
"PRIORITY_LOW": PriorityLow,
"PRIORITY_DEFAULT": PriorityDefault,
"PRIORITY_HIGH": PriorityHigh,
"PRIORITY_MAX": PriorityMax,
}
if prio, ok := priorities[tmp.Priority]; ok {
a.Priority = prio
} else {
return fmt.Errorf("unknown priority value: %q", tmp.Priority)
}
}
if tmp.Visibility != "" {
visibilities := map[string]AndroidNotificationVisibility{
"PRIVATE": VisibilityPrivate,
"PUBLIC": VisibilityPublic,
"SECRET": VisibilitySecret,
}
if vis, ok := visibilities[tmp.Visibility]; ok {
a.Visibility = vis
} else {
return fmt.Errorf("unknown visibility value: %q", tmp.Visibility)
}
}
if tmp.Proxy != "" {
proxies := map[string]AndroidNotificationProxy{
"ALLOW": ProxyAllow,
"DENY": ProxyDeny,
"IF_PRIORITY_LOWERED": ProxyIfPriorityLowered,
}
if prox, ok := proxies[tmp.Proxy]; ok {
a.Proxy = prox
} else {
return fmt.Errorf("unknown proxy value: %q", tmp.Proxy)
}
}
if tmp.EventTimestamp != "" {
ts, err := time.Parse(rfc3339Zulu, tmp.EventTimestamp)
if err != nil {
return err
}
a.EventTimestamp = &ts
}
vibTimings := make([]int64, 0, len(tmp.VibrateTimings))
for _, t := range tmp.VibrateTimings {
vibTime, err := stringToDuration(t)
if err != nil {
return err
}
millis := int64(vibTime / time.Millisecond)
vibTimings = append(vibTimings, millis)
}
a.VibrateTimingMillis = vibTimings
return nil
}
// AndroidNotificationPriority represents the priority levels of a notification.
type AndroidNotificationPriority int
const (
priorityUnknown AndroidNotificationPriority = 0
// PriorityMin is the lowest notification priority.
// Notifications with this priority might not be shown to the user except under special circumstances, such as detailed notification logs.
PriorityMin AndroidNotificationPriority = 1
// PriorityLow is a lower notification priority.
// The UI may choose to show the notifications smaller, or at a different position in the list, compared with notifications with PriorityDefault.
PriorityLow AndroidNotificationPriority = 2
// PriorityDefault is the default notification priority.
// If the application does not prioritize its own notifications, use this value for all notifications.
PriorityDefault AndroidNotificationPriority = 3
// PriorityHigh is a higher notification priority.
// Use this for more important notifications or alerts.
// The UI may choose to show these notifications larger, or at a different position in the notification lists, compared with notifications with PriorityDefault.
PriorityHigh AndroidNotificationPriority = 4
// PriorityMax is the highest notification priority.
// Use this for the application's most important items that require the user's prompt attention or input.
PriorityMax AndroidNotificationPriority = 5
)
// AndroidNotificationVisibility represents the different visibility levels of a notification.
type AndroidNotificationVisibility int
const (
visibilityUnknown AndroidNotificationVisibility = 0
// VisibilityPrivate shows this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens.
VisibilityPrivate AndroidNotificationVisibility = 1
// VisibilityPublic shows this notification in its entirety on all lockscreens.
VisibilityPublic AndroidNotificationVisibility = 2
// VisibilitySecret does not reveal any part of this notification on a secure lockscreen.
VisibilitySecret AndroidNotificationVisibility = 3
)
// AndroidNotificationProxy to control when a notification may be proxied.
type AndroidNotificationProxy int
const (
proxyUnknown AndroidNotificationProxy = 0
// ProxyAllow tries to proxy this notification.
ProxyAllow AndroidNotificationProxy = 1
// ProxyDeny does not proxy this notification.
ProxyDeny AndroidNotificationProxy = 2
// ProxyIfPriorityLowered only tries to proxy this notification if its AndroidConfig's Priority was lowered from high to normal on the device.
ProxyIfPriorityLowered AndroidNotificationProxy = 3
)
// LightSettings to control notification LED.
type LightSettings struct {
Color string
LightOnDurationMillis int64
LightOffDurationMillis int64
}
func (l *LightSettings) MarshalJSON() ([]byte, error) {
clr, err := newColor(l.Color)
if err != nil {
return nil, err
}
tmp := struct {
Color *color `json:"color"`
LightOnDuration string `json:"light_on_duration"`
LightOffDuration string `json:"light_off_duration"`
}{
Color: clr,
LightOnDuration: durationToString(time.Duration(l.LightOnDurationMillis) * time.Millisecond),
LightOffDuration: durationToString(time.Duration(l.LightOffDurationMillis) * time.Millisecond),
}
return json.Marshal(tmp)
}
func (l *LightSettings) UnmarshalJSON(b []byte) error {
tmp := struct {
Color *color `json:"color"`
LightOnDuration string `json:"light_on_duration"`
LightOffDuration string `json:"light_off_duration"`
}{}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
on, err := stringToDuration(tmp.LightOnDuration)
if err != nil {
return err
}
off, err := stringToDuration(tmp.LightOffDuration)
if err != nil {
return err
}
l.Color = tmp.Color.toString()
l.LightOnDurationMillis = int64(on / time.Millisecond)
l.LightOffDurationMillis = int64(off / time.Millisecond)
return nil
}
type color struct {
Red float64 `json:"red"`
Green float64 `json:"green"`
Blue float64 `json:"blue"`
Alpha float64 `json:"alpha"`
}
func newColor(clr string) (*color, error) {
red, err := strconv.ParseInt(clr[1:3], 16, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", clr, err)
}
green, err := strconv.ParseInt(clr[3:5], 16, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", clr, err)
}
blue, err := strconv.ParseInt(clr[5:7], 16, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", clr, err)
}
alpha := int64(255)
if len(clr) == 9 {
alpha, err = strconv.ParseInt(clr[7:9], 16, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", clr, err)
}
}
return &color{
Red: float64(red) / 255.0,
Green: float64(green) / 255.0,
Blue: float64(blue) / 255.0,
Alpha: float64(alpha) / 255.0,
}, nil
}
func (c *color) toString() string {
red := int(c.Red * 255.0)
green := int(c.Green * 255.0)
blue := int(c.Blue * 255.0)
alpha := int(c.Alpha * 255.0)
if alpha == 255 {
return fmt.Sprintf("#%X%X%X", red, green, blue)
}
return fmt.Sprintf("#%X%X%X%X", red, green, blue, alpha)
}
// AndroidFCMOptions contains additional options for features provided by the FCM Android SDK.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidfcmoptions
type AndroidFCMOptions struct {
AnalyticsLabel string `json:"analytics_label,omitempty"`
}
// WebpushConfig contains messaging options specific to the WebPush protocol.
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushconfig
//
// See https://tools.ietf.org/html/rfc8030#section-5
type WebpushConfig struct {
Headers map[string]string `json:"headers,omitempty"`
Data map[string]string `json:"data,omitempty"`
Notification *WebpushNotification `json:"notification,omitempty"`
FCMOptions *WebpushFCMOptions `json:"fcm_options,omitempty"`
}
// WebpushNotificationAction represents an action that can be performed upon receiving a WebPush notification.
type WebpushNotificationAction struct {
Action string `json:"action,omitempty"`
Title string `json:"title,omitempty"`
Icon string `json:"icon,omitempty"`
}
// WebpushNotification is a notification to send via WebPush protocol.
//
// See https://developer.mozilla.org/en-US/docs/Web/API/notification/Notification
type WebpushNotification struct {
Actions []*WebpushNotificationAction `json:"actions,omitempty"`
Title string `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
Body string `json:"body,omitempty"` // if set, overrides [Notification.Body] field.
Icon string `json:"icon,omitempty"`
Badge string `json:"badge,omitempty"`
Direction string `json:"dir,omitempty"` // one of 'ltr' or 'rtl'
Data any `json:"data,omitempty"`
Image string `json:"image,omitempty"`
Language string `json:"lang,omitempty"`
Renotify bool `json:"renotify,omitempty"`
RequireInteraction bool `json:"requireInteraction,omitempty"`
Silent bool `json:"silent,omitempty"`
Tag string `json:"tag,omitempty"`
TimestampMillis *int64 `json:"timestamp,omitempty"`
Vibrate []int `json:"vibrate,omitempty"`
CustomData map[string]any
}
// standardFields creates a map containing all the fields except the custom data.
func (n *WebpushNotification) standardFields() map[string]any {
m := make(map[string]any)
addNonEmpty := func(key, value string) {
if value != "" {
m[key] = value
}
}
addTrue := func(key string, value bool) {
if value {
m[key] = value
}
}
if len(n.Actions) > 0 {
m["actions"] = n.Actions
}
addNonEmpty("title", n.Title)
addNonEmpty("body", n.Body)
addNonEmpty("icon", n.Icon)
addNonEmpty("badge", n.Badge)
addNonEmpty("dir", n.Direction)
addNonEmpty("image", n.Image)
addNonEmpty("lang", n.Language)
addTrue("renotify", n.Renotify)
addTrue("requireInteraction", n.RequireInteraction)
addTrue("silent", n.Silent)
addNonEmpty("tag", n.Tag)
if n.Data != nil {
m["data"] = n.Data
}
if n.TimestampMillis != nil {
m["timestamp"] = *n.TimestampMillis
}
if len(n.Vibrate) > 0 {
m["vibrate"] = n.Vibrate
}
return m
}
func (n *WebpushNotification) MarshalJSON() ([]byte, error) {
m := n.standardFields()
for k, v := range n.CustomData {
m[k] = v
}
return json.Marshal(m)
}
func (n *WebpushNotification) UnmarshalJSON(b []byte) error {
type webpushNotificationWrapper WebpushNotification
tmp := (*webpushNotificationWrapper)(n)
if err := json.Unmarshal(b, tmp); err != nil {
return err
}
allFields := make(map[string]any)
if err := json.Unmarshal(b, &allFields); err != nil {
return err
}
for k := range n.standardFields() {
delete(allFields, k)
}
if len(allFields) > 0 {
n.CustomData = allFields
}
return nil
}
// WebpushFCMOptions contains additional options for features provided by the FCM web SDK.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions
type WebpushFCMOptions struct {
Link string `json:"link,omitempty"`
}
// APNSConfig contains messaging options specific to the Apple Push Notification Service (APNS).
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig
//
// See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html
type APNSConfig struct {
Headers map[string]string `json:"headers,omitempty"`
Payload *APNSPayload `json:"payload,omitempty"`
FCMOptions *APNSFCMOptions `json:"fcm_options,omitempty"`
LiveActivityToken string `json:"live_activity_token,omitempty"`
}
// APNSPayload is the payload that can be included in an APNS message.
//
// The payload mainly consists of the aps dictionary. Additionally it may contain arbitrary
// key-values pairs as custom data fields.
//
// See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
type APNSPayload struct {
Aps *Aps `json:"aps,omitempty"`
CustomData map[string]any `json:"-"`
}
// standardFields creates a map containing all the fields except the custom data.
func (p *APNSPayload) standardFields() map[string]any {
return map[string]any{"aps": p.Aps}
}
func (p *APNSPayload) MarshalJSON() ([]byte, error) {
m := p.standardFields()
maps.Copy(m, p.CustomData)
return json.Marshal(m)
}
func (p *APNSPayload) UnmarshalJSON(b []byte) error {
type apnsPayloadWrapper APNSPayload
tmp := (*apnsPayloadWrapper)(p)
if err := json.Unmarshal(b, tmp); err != nil {
return err
}
allFields := make(map[string]any)
if err := json.Unmarshal(b, &allFields); err != nil {
return err
}
for k := range p.standardFields() {
delete(allFields, k)
}
if len(allFields) > 0 {
p.CustomData = allFields
}
return nil
}
// Aps represents the aps dictionary that may be included in an APNSPayload.
//
// Alert may be specified as a string (via the AlertString field), or as a struct (via the Alert field).
type Aps struct {
AlertString string `json:"-"`
Alert *ApsAlert `json:"-"`
Badge *int `json:"badge,omitempty"`
Sound string `json:"-"`
CriticalSound *CriticalSound `json:"-"`
ContentAvailable bool `json:"-"`
MutableContent bool `json:"-"`
Category string `json:"category,omitempty"`
ThreadID string `json:"thread-id,omitempty"`
CustomData map[string]any `json:"-"`
}
// standardFields creates a map containing all the fields except the custom data.
func (a *Aps) standardFields() map[string]any {
m := make(map[string]any)
if a.Alert != nil {
m["alert"] = a.Alert
} else if a.AlertString != "" {
m["alert"] = a.AlertString
}
if a.ContentAvailable {
m["content-available"] = 1
}
if a.MutableContent {
m["mutable-content"] = 1
}
if a.Badge != nil {
m["badge"] = *a.Badge
}
if a.CriticalSound != nil {
m["sound"] = a.CriticalSound
} else if a.Sound != "" {
m["sound"] = a.Sound
}
if a.Category != "" {
m["category"] = a.Category
}
if a.ThreadID != "" {
m["thread-id"] = a.ThreadID
}
return m
}
func (a *Aps) MarshalJSON() ([]byte, error) {
m := a.standardFields()
maps.Copy(m, a.CustomData)
return json.Marshal(m)
}
func (a *Aps) UnmarshalJSON(b []byte) error {
type apsWrapper Aps
tmp := struct {
AlertObject *json.RawMessage `json:"alert,omitempty"`
SoundObject *json.RawMessage `json:"sound,omitempty"`
ContentAvailableInt int `json:"content-available,omitempty"`
MutableContentInt int `json:"mutable-content,omitempty"`
*apsWrapper
}{
apsWrapper: (*apsWrapper)(a),
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
a.ContentAvailable = (tmp.ContentAvailableInt == 1)
a.MutableContent = (tmp.MutableContentInt == 1)
if tmp.AlertObject != nil {
if err := json.Unmarshal(*tmp.AlertObject, &a.Alert); err != nil {
a.Alert = nil
if err := json.Unmarshal(*tmp.AlertObject, &a.AlertString); err != nil {
return fmt.Errorf("failed to unmarshal alert as a struct or a string: %w", err)
}
}
}
if tmp.SoundObject != nil {
if err := json.Unmarshal(*tmp.SoundObject, &a.CriticalSound); err != nil {
a.CriticalSound = nil
if err := json.Unmarshal(*tmp.SoundObject, &a.Sound); err != nil {
return fmt.Errorf("failed to unmarshal sound as a struct or a string")
}
}
}
allFields := make(map[string]any)
if err := json.Unmarshal(b, &allFields); err != nil {
return err
}
for k := range a.standardFields() {
delete(allFields, k)
}
if len(allFields) > 0 {
a.CustomData = allFields
}
return nil
}
// CriticalSound is the sound payload that can be included in an Aps.
type CriticalSound struct {
Critical bool `json:"-"`
Name string `json:"name,omitempty"`
Volume float64 `json:"volume,omitempty"`
}
func (cs *CriticalSound) MarshalJSON() ([]byte, error) {
type criticalSoundWrapper CriticalSound
tmp := struct {
CriticalInt int `json:"critical,omitempty"`
*criticalSoundWrapper
}{
criticalSoundWrapper: (*criticalSoundWrapper)(cs),
}
if cs.Critical {
tmp.CriticalInt = 1
}
return json.Marshal(tmp)
}
func (cs *CriticalSound) UnmarshalJSON(b []byte) error {
type criticalSoundWrapper CriticalSound
tmp := struct {
CriticalInt int `json:"critical,omitempty"`
*criticalSoundWrapper
}{
criticalSoundWrapper: (*criticalSoundWrapper)(cs),
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
cs.Critical = (tmp.CriticalInt == 1)
return nil
}
// ApsAlert is the alert payload that can be included in an Aps.
//
// See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
type ApsAlert struct {
Title string `json:"title,omitempty"` // if set, overrides [Notification.Title] field.
SubTitle string `json:"subtitle,omitempty"`
Body string `json:"body,omitempty"` // if set, overrides [Notification.Body] field.
LocKey string `json:"loc-key,omitempty"`
LocArgs []string `json:"loc-args,omitempty"`
TitleLocKey string `json:"title-loc-key,omitempty"`
TitleLocArgs []string `json:"title-loc-args,omitempty"`
SubTitleLocKey string `json:"subtitle-loc-key,omitempty"`
SubTitleLocArgs []string `json:"subtitle-loc-args,omitempty"`
ActionLocKey string `json:"action-loc-key,omitempty"`
LaunchImage string `json:"launch-image,omitempty"`
}
// APNSFCMOptions contains additional options for features provided by the FCM Aps SDK.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsfcmoptions
type APNSFCMOptions struct {
AnalyticsLabel string `json:"analytics_label,omitempty"`
ImageURL string `json:"image,omitempty"`
}
// FCMOptions contains additional options to use across all platforms.
//
// See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#fcmoptions
type FCMOptions struct {
AnalyticsLabel string `json:"analytics_label,omitempty"`
}
func durationToString(ms time.Duration) string {
seconds := int64(ms / time.Second)
nanos := int64((ms - time.Duration(seconds)*time.Second) / time.Nanosecond)
if nanos > 0 {
return fmt.Sprintf("%d.%09ds", seconds, nanos)
}
return fmt.Sprintf("%ds", seconds)
}
func stringToDuration(s string) (time.Duration, error) {
segments := strings.Split(strings.TrimSuffix(s, "s"), ".")
if len(segments) != 1 && len(segments) != 2 {
return 0, fmt.Errorf("incorrect number of segments in ttl: %q", s)
}
seconds, err := strconv.ParseInt(segments[0], 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse %s: %w", s, err)
}
ttl := time.Duration(seconds) * time.Second
if len(segments) == 2 {
nanos, err := strconv.ParseInt(strings.TrimLeft(segments[1], "0"), 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse %s: %w", s, err)
}
ttl += time.Duration(nanos) * time.Nanosecond
}
return ttl, nil
}