forked from nikoksr/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfcm.go
106 lines (88 loc) · 2.51 KB
/
fcm.go
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
package fcm
import (
"context"
"github.com/appleboy/go-fcm"
"github.com/pkg/errors"
)
// Compile-time check that fcm.Client satisfies fcmClient interface.
var _ fcmClient = &fcm.Client{}
var (
// DataKey is used as a context.Context key to optionally add data to the message payload.
DataKey = msgDataKey{}
// RetriesKey is used as a context.Context key to optionally set a total of retry attempts per each message.
RetriesKey = msgRetriesKey{}
)
type (
msgDataKey struct{}
msgRetriesKey struct{}
)
// fcmClient abstracts go-fcm for writing unit tests
//
//go:generate mockery --name=fcmClient --output=. --case=underscore --inpackage
type fcmClient interface {
SendWithRetry(*fcm.Message, int) (*fcm.Response, error)
}
// Service encapsulates the FCM client along with internal state for storing device tokens.
type Service struct {
client fcmClient
deviceTokens []string
}
// New returns a new instance of a FCM notification service.
func New(serverAPIKey string) (*Service, error) {
client, err := fcm.NewClient(serverAPIKey)
if err != nil {
return nil, err
}
s := &Service{
client: client,
deviceTokens: []string{},
}
return s, nil
}
// AddReceivers takes FCM device tokens and appends them to the internal device tokens slice.
// The Send method will send a given message to all those devices.
func (s *Service) AddReceivers(deviceTokens ...string) {
s.deviceTokens = append(s.deviceTokens, deviceTokens...)
}
// Send takes a message subject and a message body and sends them to all previously set devices.
func (s *Service) Send(ctx context.Context, subject, message string) error {
msg := &fcm.Message{
Notification: &fcm.Notification{
Title: subject,
Body: message,
},
}
if data, ok := getMessageData(ctx); ok {
msg.Data = data
}
retryAttempts := getMessageRetryAttempts(ctx)
for _, deviceToken := range s.deviceTokens {
select {
case <-ctx.Done():
return ctx.Err()
default:
msg.To = deviceToken
_, err := s.client.SendWithRetry(msg, retryAttempts)
if err != nil {
return errors.Wrapf(err, "failed to send message to FCM device with token '%s'", deviceToken)
}
}
}
return nil
}
func getMessageData(ctx context.Context) (data map[string]interface{}, ok bool) {
value := ctx.Value(DataKey)
if value != nil {
data, ok = value.(map[string]interface{})
}
return
}
func getMessageRetryAttempts(ctx context.Context) int {
value := ctx.Value(RetriesKey)
if value != nil {
if retryAttempts, ok := value.(int); ok {
return retryAttempts
}
}
return 0
}