-
Notifications
You must be signed in to change notification settings - Fork 388
/
services_push_fcm.go
88 lines (70 loc) · 1.94 KB
/
services_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
package bertypushrelay
import (
"encoding/base64"
"strings"
"github.com/appleboy/go-fcm"
"go.uber.org/zap"
"berty.tech/berty/v2/go/pkg/errcode"
"berty.tech/berty/v2/go/pkg/protocoltypes"
"berty.tech/berty/v2/go/pkg/pushtypes"
)
type pushDispatcherFCM struct {
client *fcm.Client
appID string
logger *zap.Logger
}
func (d *pushDispatcherFCM) TokenType() pushtypes.PushServiceTokenType {
return pushtypes.PushServiceTokenType_PushTokenFirebaseCloudMessaging
}
func PushDispatcherLoadFirebaseAPIKey(logger *zap.Logger, input *string) ([]PushDispatcher, error) {
if input == nil || *input == "" {
return nil, nil
}
apiKeys := strings.Split(*input, ",")
dispatchers := make([]PushDispatcher, len(apiKeys))
for i, apiKeyDetails := range apiKeys {
var err error
dispatchers[i], err = pushDispatcherLoadFCMAPIKey(logger, apiKeyDetails)
if err != nil {
return nil, err
}
}
return dispatchers, nil
}
func pushDispatcherLoadFCMAPIKey(logger *zap.Logger, apiKeyDetails string) (PushDispatcher, error) {
splitResult := strings.SplitN(apiKeyDetails, ":", 2)
if len(splitResult) != 2 {
return nil, errcode.ErrPushInvalidServerConfig
}
appID := splitResult[0]
apiKey := splitResult[1]
client, err := fcm.NewClient(apiKey)
if err != nil {
return nil, errcode.ErrPushInvalidServerConfig.Wrap(err)
}
dispatcher := &pushDispatcherFCM{
client: client,
appID: appID,
logger: logger,
}
return dispatcher, nil
}
func (d *pushDispatcherFCM) Dispatch(payload []byte, receiver *protocoltypes.PushServiceReceiver) error {
msg := &fcm.Message{
To: string(receiver.Token),
Data: map[string]interface{}{
pushtypes.ServicePushPayloadKey: base64.RawURLEncoding.EncodeToString(payload),
},
}
res, err := d.client.Send(msg)
if err != nil {
return errcode.ErrPushProvider.Wrap(err)
}
if res.Error != nil {
return errcode.ErrPushProvider.Wrap(res.Error)
}
return nil
}
func (d *pushDispatcherFCM) BundleID() string {
return d.appID
}