-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
client.go
81 lines (59 loc) · 1.76 KB
/
client.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
package push
import (
"context"
"encoding/json"
"io/ioutil"
"time"
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/messaging"
"github.com/twofas/2fas-server/internal/api/mobile/domain"
"github.com/twofas/2fas-server/internal/common/logging"
"google.golang.org/api/option"
)
type Pusher interface {
Send(ctx context.Context, message *messaging.Message) error
}
type FcmPushClient struct {
FcmMessaging *messaging.Client
}
func NewFcmPushClient(config *domain.FcmPushConfig) *FcmPushClient {
fileContent, err := ioutil.ReadAll(config.FcmApiServiceAccountFile)
if err != nil {
logging.Fatal(err)
}
opt := option.WithCredentialsJSON(fileContent)
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
logging.WithField("error", err.Error()).Fatal("Error initializing FCM App")
}
client, err := app.Messaging(context.Background())
return &FcmPushClient{
FcmMessaging: client,
}
}
func (p *FcmPushClient) Send(ctx context.Context, message *messaging.Message) error {
data, _ := json.Marshal(message)
logging.WithFields(logging.Fields{
"notification": string(data),
}).Debug("Sending push notifications")
contextWithTimeout, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
response, err := p.FcmMessaging.Send(contextWithTimeout, message)
if err != nil {
return err
}
logging.Infof("FCM notification has been sent: %s", response)
return nil
}
type FakePushClient struct {
}
func NewFakePushClient() *FakePushClient {
return &FakePushClient{}
}
func (p *FakePushClient) Send(ctx context.Context, message *messaging.Message) error {
data, _ := json.Marshal(message)
logging.WithFields(logging.Fields{
"notification": string(data),
}).Debug("Sending fake push notifications")
return nil
}