-
Notifications
You must be signed in to change notification settings - Fork 0
/
push_fcm.go
399 lines (354 loc) · 9.9 KB
/
push_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
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
// Package fcm implements push notification plugin for Google FCM backend.
// Push notifications for Android, iOS and web clients are sent through Google's Firebase Cloud Messaging service.
package fcm
import (
"context"
"encoding/json"
"errors"
"log"
"strconv"
"time"
fbase "firebase.google.com/go"
fcm "firebase.google.com/go/messaging"
"github.com/tinode/chat/server/drafty"
"github.com/tinode/chat/server/push"
"github.com/tinode/chat/server/store"
t "github.com/tinode/chat/server/store/types"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
var handler Handler
// Size of the input channel buffer.
const defaultBuffer = 32
// Maximum length of a text message in runes
const maxMessageLength = 80
// Handler represents the push handler; implements push.PushHandler interface.
type Handler struct {
input chan *push.Receipt
stop chan bool
client *fcm.Client
}
// Configuration of AndroidNotification payload.
type androidConfig struct {
Enabled bool `json:"enabled,omitempty"`
// Common defauls for all push types.
androidPayload
// Configs for specific push types.
Msg androidPayload `json:"msg,omitempty"`
Sub androidPayload `json:"msg,omitempty"`
}
func (ac *androidConfig) getTitleLocKey(what string) string {
var title string
if what == push.ActMsg {
title = ac.Msg.TitleLocKey
} else if what == push.ActSub {
title = ac.Sub.TitleLocKey
}
if title == "" {
title = ac.androidPayload.TitleLocKey
}
return title
}
func (ac *androidConfig) getTitle(what string) string {
var title string
if what == push.ActMsg {
title = ac.Msg.Title
} else if what == push.ActSub {
title = ac.Sub.Title
}
if title == "" {
title = ac.androidPayload.Title
}
return title
}
func (ac *androidConfig) getBodyLocKey(what string) string {
var body string
if what == push.ActMsg {
body = ac.Msg.BodyLocKey
} else if what == push.ActSub {
body = ac.Sub.BodyLocKey
}
if body == "" {
body = ac.androidPayload.BodyLocKey
}
return body
}
func (ac *androidConfig) getBody(what string) string {
var body string
if what == push.ActMsg {
body = ac.Msg.Body
} else if what == push.ActSub {
body = ac.Sub.Body
}
if body == "" {
body = ac.androidPayload.Body
}
return body
}
func (ac *androidConfig) getIcon(what string) string {
var icon string
if what == push.ActMsg {
icon = ac.Msg.Icon
} else if what == push.ActSub {
icon = ac.Sub.Icon
}
if icon == "" {
icon = ac.androidPayload.Icon
}
return icon
}
func (ac *androidConfig) getIconColor(what string) string {
var color string
if what == push.ActMsg {
color = ac.Msg.IconColor
} else if what == push.ActSub {
color = ac.Sub.IconColor
}
if color == "" {
color = ac.androidPayload.IconColor
}
return color
}
// Payload to be sent for a specific notification type.
type androidPayload struct {
TitleLocKey string `json:"title_loc_key,omitempty"`
Title string `json:"title,omitempty"`
BodyLocKey string `json:"body_loc_key,omitempty"`
Body string `json:"body,omitempty"`
Icon string `json:"icon,omitempty"`
IconColor string `json:"icon_color,omitempty"`
ClickAction string `json:"click_action,omitempty"`
}
type configType struct {
Enabled bool `json:"enabled"`
Buffer int `json:"buffer"`
Credentials json.RawMessage `json:"credentials"`
CredentialsFile string `json:"credentials_file"`
TimeToLive uint `json:"time_to_live,omitempty"`
Android androidConfig `json:"android,omitempty"`
}
// Init initializes the push handler
func (Handler) Init(jsonconf string) error {
var config configType
err := json.Unmarshal([]byte(jsonconf), &config)
if err != nil {
return errors.New("failed to parse config: " + err.Error())
}
if !config.Enabled {
return nil
}
ctx := context.Background()
var opt option.ClientOption
if config.Credentials != nil {
credentials, err := google.CredentialsFromJSON(ctx, config.Credentials,
"https://www.googleapis.com/auth/firebase.messaging")
if err != nil {
return err
}
opt = option.WithCredentials(credentials)
} else if config.CredentialsFile != "" {
opt = option.WithCredentialsFile(config.CredentialsFile)
} else {
return errors.New("missing credentials")
}
app, err := fbase.NewApp(ctx, &fbase.Config{}, opt)
if err != nil {
return err
}
handler.client, err = app.Messaging(ctx)
if err != nil {
return err
}
if config.Buffer <= 0 {
config.Buffer = defaultBuffer
}
handler.input = make(chan *push.Receipt, config.Buffer)
handler.stop = make(chan bool, 1)
go func() {
for {
select {
case rcpt := <-handler.input:
go sendNotifications(rcpt, &config)
case <-handler.stop:
return
}
}
}()
return nil
}
func sendNotifications(rcpt *push.Receipt, config *configType) {
ctx := context.Background()
data, _ := payloadToData(&rcpt.Payload)
if data == nil {
log.Println("fcm push: could not parse payload")
return
}
// List of UIDs for querying the database
uids := make([]t.Uid, len(rcpt.To))
skipDevices := make(map[string]bool)
i := 0
for uid, to := range rcpt.To {
uids[i] = uid
i++
// Some devices were online and received the message. Skip them.
for _, deviceID := range to.Devices {
skipDevices[deviceID] = true
}
}
devices, count, err := store.Devices.GetAll(uids...)
if err != nil {
log.Println("fcm push: db error", err)
return
}
if count == 0 {
return
}
var titlelc, title, bodylc, body, icon, color string
if config.Android.Enabled {
titlelc = config.Android.getTitleLocKey(rcpt.Payload.What)
title = config.Android.getTitle(rcpt.Payload.What)
bodylc = config.Android.getBodyLocKey(rcpt.Payload.What)
body = config.Android.getBody(rcpt.Payload.What)
if body == "$content" {
body = data["content"]
}
icon = config.Android.getIcon(rcpt.Payload.What)
color = config.Android.getIconColor(rcpt.Payload.What)
}
for uid, devList := range devices {
for i := range devList {
d := &devList[i]
if _, ok := skipDevices[d.DeviceId]; !ok && d.DeviceId != "" {
msg := fcm.Message{
Token: d.DeviceId,
Data: data,
}
if d.Platform == "android" {
msg.Android = &fcm.AndroidConfig{
Priority: "high",
}
if config.Android.Enabled {
// When this notification type is included and the app is not in the foreground
// Android won't wake up the app and won't call FirebaseMessagingService:onMessageReceived.
// See dicussion: https://github.com/firebase/quickstart-js/issues/71
msg.Android.Notification = &fcm.AndroidNotification{
// Android uses Tag value to group notifications together:
// show just one notification per topic.
Tag: rcpt.Payload.Topic,
TitleLocKey: titlelc,
Title: title,
BodyLocKey: bodylc,
Body: body,
Icon: icon,
Color: color,
}
}
} else if d.Platform == "ios" {
// iOS uses Badge to show the total unread message count.
badge := rcpt.To[uid].Unread
// Need to duplicate these in APNS.Payload.Aps.Alert so
// iOS may call NotificationServiceExtension (if present).
title := "New message"
body := data["content"]
msg.APNS = &fcm.APNSConfig{
Payload: &fcm.APNSPayload{
Aps: &fcm.Aps{
Badge: &badge,
ContentAvailable: true,
MutableContent: true,
Sound: "default",
Alert: &fcm.ApsAlert{
Title: title,
Body: body,
},
},
},
}
msg.Notification = &fcm.Notification{
Title: title,
Body: body,
}
}
_, err := handler.client.Send(ctx, &msg)
if err != nil {
if fcm.IsMessageRateExceeded(err) ||
fcm.IsServerUnavailable(err) ||
fcm.IsInternal(err) ||
fcm.IsUnknown(err) {
// Transient errors. Stop sending this batch.
log.Println("fcm transient failure", err)
return
}
if fcm.IsMismatchedCredential(err) || fcm.IsInvalidArgument(err) {
// Config errors
log.Println("fcm push: failed", err)
return
}
if fcm.IsRegistrationTokenNotRegistered(err) {
// Token is no longer valid.
log.Println("fcm push: invalid token", err)
err = store.Devices.Delete(uid, d.DeviceId)
if err != nil {
log.Println("fcm push: failed to delete invalid token", err)
}
} else {
log.Println("fcm push:", err)
}
}
}
}
}
}
func payloadToData(pl *push.Payload) (map[string]string, error) {
if pl == nil {
return nil, nil
}
data := make(map[string]string)
var err error
data["what"] = pl.What
if pl.Silent {
data["silent"] = "true"
}
data["topic"] = pl.Topic
data["ts"] = pl.Timestamp.Format(time.RFC3339Nano)
// Must use "xfrom" because "from" is a reserved word. Google did not bother to document it anywhere.
data["xfrom"] = pl.From
if pl.What == push.ActMsg {
data["seq"] = strconv.Itoa(pl.SeqId)
data["mime"] = pl.ContentType
data["content"], err = drafty.ToPlainText(pl.Content)
if err != nil {
return nil, err
}
// Trim long strings to 80 runes.
// Check byte length first and don't waste time converting short strings.
if len(data["content"]) > maxMessageLength {
runes := []rune(data["content"])
if len(runes) > maxMessageLength {
data["content"] = string(runes[:maxMessageLength]) + "…"
}
}
} else if pl.What == push.ActSub {
data["modeWant"] = pl.ModeWant.String()
data["modeGiven"] = pl.ModeGiven.String()
} else {
return nil, errors.New("unknown push type")
}
return data, nil
}
// IsReady checks if the push handler has been initialized.
func (Handler) IsReady() bool {
return handler.input != nil
}
// Push returns a channel that the server will use to send messages to.
// If the adapter blocks, the message will be dropped.
func (Handler) Push() chan<- *push.Receipt {
return handler.input
}
// Stop shuts down the handler
func (Handler) Stop() {
handler.stop <- true
}
func init() {
push.Register("fcm", &handler)
}