-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase.go
189 lines (167 loc) · 5.08 KB
/
firebase.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
package notella
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/messaging"
ll "github.com/gwennlbh/label-logger-go"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
var firebaseClient *firebase.App
var firebaseCtx = context.Background()
const MaxTokensPerRequest = 490
func (msg Message) SendToFirebase(groupId string, subs []Subscription) error {
if firebaseClient == nil || !config.HasValidFirebaseServiceAccount() {
return nil
}
fcm, err := firebaseClient.Messaging(firebaseCtx)
if err != nil {
return fmt.Errorf("while initializing FCM client: %w", err)
}
if config.DryRunMode && len(config.DryRunExceptions) == 0 {
ll.Warn("dry run mode enabled, not sending FCM message to %d tokens", len(subs))
return nil
}
message := msg.FirebaseMessage(groupId)
tokens := make([]string, 0, len(subs))
for _, sub := range subs {
if config.DryRunMode {
exempt := false
for _, username := range config.DryRunExceptions {
if username == sub.Owner.Uid {
exempt = true
}
}
if !exempt {
continue
}
}
tokens = append(tokens, sub.FirebaseToken())
}
if config.DryRunMode {
ll.Warn("dry run mode enabled, only sending FCM message to %d tokens (owned by %+v)", len(tokens), config.DryRunExceptions)
}
for _, tokensChunk := range chunkBy(tokens, MaxTokensPerRequest) {
go func(tokens []string) {
if len(tokens) == 0 {
return
}
message.Tokens = tokens
resp, err := fcm.SendEachForMulticast(firebaseCtx, &message)
if err != nil {
ll.ErrorDisplay("while sending FCM message", err)
} else if resp.FailureCount > 0 {
fcmErrors := make([]string, 0, resp.FailureCount)
for i, result := range resp.Responses {
if !result.Success {
if result.Error.Error() == "Requested entity was not found." {
if sub, found := FindSubscriptionByNativeToken(tokens[i], subs); found {
ll.Log("Deleting", "yellow", "invalid native subscription %s", tokens[i])
sub.Destroy()
}
} else {
fcmErrors = append(fcmErrors, fmt.Sprintf("%s: %s", tokens[i], result.Error))
}
}
}
if len(fcmErrors) > 0 {
ll.ErrorDisplay(
"some FCM messages failed for %d tokens",
fmt.Errorf("- %s", strings.Join(fcmErrors, "\n- ")),
resp.FailureCount,
)
}
}
}(tokensChunk)
}
return nil
}
func (msg Message) FirebaseMessage(groupId string) messaging.MulticastMessage {
clickAction := ""
if len(msg.Actions) > 0 {
clickAction = msg.Actions[0].Label
}
return messaging.MulticastMessage{
Data: map[string]string{
"original": msg.JSONString(),
},
Android: &messaging.AndroidConfig{
RestrictedPackageName: config.AppPackageId,
Notification: &messaging.AndroidNotification{
VibrateTimingMillis: []int64{}, // TODO
EventTimestamp: nil, // TODO
ClickAction: clickAction,
},
},
Notification: &messaging.Notification{
Title: msg.Title,
Body: msg.Body,
ImageURL: msg.Image,
},
}
}
type firebaseServiceAccount struct {
Type string `json:"type"`
ProjectId string `json:"project_id"`
PrivateKeyId string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
ClientId string `json:"client_id"`
AuthUri string `json:"auth_uri"`
TokenUri string `json:"token_uri"`
AuthProviderX509CertUrl string `json:"auth_provider_x509_cert_url"`
ClientX509CertUrl string `json:"client_x509_cert_url"`
UniverseDomain string `json:"universe_domain"`
}
func setupFirebaseClient() (err error) {
httpClient := http.DefaultClient
if os.Getenv("DEBUG") == "1" {
httpClient = &http.Client{
Transport: debugTransport{t: http.DefaultTransport},
}
}
ctxWithClient := context.WithValue(firebaseCtx, oauth2.HTTPClient, httpClient)
creds, err := google.CredentialsFromJSON(ctxWithClient, []byte(config.FirebaseServiceAccount), "https://www.googleapis.com/auth/firebase.messaging")
if err != nil {
return fmt.Errorf("while setting credentials: %w", err)
}
client := &http.Client{
Transport: &oauth2.Transport{
Source: creds.TokenSource,
Base: httpClient.Transport,
},
Timeout: 10 * time.Second,
}
firebaseClient, err = firebase.NewApp(firebaseCtx, nil,
option.WithCredentialsJSON([]byte(config.FirebaseServiceAccount)),
option.WithHTTPClient(client),
)
return
}
func (config Configuration) HasValidFirebaseServiceAccount() bool {
var serviceAccount firebaseServiceAccount
err := json.Unmarshal([]byte(config.FirebaseServiceAccount), &serviceAccount)
if err != nil {
return false
}
if serviceAccount.Type != "service_account" {
return false
}
if err = setupFirebaseClient(); err != nil {
return false
}
return true
}
func (sub Subscription) FirebaseToken() string {
return strings.TrimPrefix(strings.TrimPrefix(sub.Webpush.Endpoint, "apns://"), "firebase://")
}
func (sub Subscription) IsNative() bool {
return !sub.IsWebpush()
}