forked from crow-misia/go-push-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fcm.go
193 lines (168 loc) · 4.67 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
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
/*
* Copyright (c) 2019 Zenichi Amano
*
* This file is part of go-push-receiver, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
package pushreceiver
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
pb "github.com/crow-misia/go-push-receiver/pb/mcs"
"github.com/pkg/errors"
"net/http"
"net/url"
"strings"
"time"
"log"
)
type fcmRegisterResponse struct {
Token string `json:"token"`
PushSet string `json:"pushSet"`
}
// FCMCredentials is Credentials for FCM
type FCMCredentials struct {
AppID string `json:"appId"`
AndroidID uint64 `json:"androidId"`
SecurityToken uint64 `json:"securityToken"`
Token string `json:"token"`
PrivateKey []byte `json:"privateKey"`
PublicKey []byte `json:"publicKey"`
AuthSecret []byte `json:"authSecret"`
}
// Subscribe subscribe to FCM.
func (c *Client) Subscribe(ctx context.Context) {
defer close(c.Events)
for ctx.Err() == nil {
var err error
if c.creds == nil {
err = c.register(ctx)
} else {
if c.gcmCheckin {
_, err = c.checkIn(ctx, &checkInOption{c.creds.AndroidID, c.creds.SecurityToken})
}
}
if err == nil {
// reset retry count when connection success
c.backoff.reset()
err = c.tryToConnect(ctx)
}
if err != nil {
if err == ErrGcmAuthorization {
c.Events <- &UnauthorizedError{err}
c.creds = nil
}
// retry
sleepDuration := c.backoff.duration()
c.Events <- &RetryEvent{err, sleepDuration}
tick := time.After(sleepDuration)
select {
case <-tick:
case <-ctx.Done():
return
}
}
}
}
func (c *Client) register(ctx context.Context) error {
response, err := c.registerGCM(ctx)
if err != nil {
return err
}
creds, err := c.subscribeFCM(ctx, response)
if err != nil {
return err
}
c.creds = creds
c.Events <- &UpdateCredentialsEvent{creds}
return nil
}
func (c *Client) tryToConnect(ctx context.Context) error {
conn, err := tls.DialWithDialer(c.dialer, "tcp", mtalkServer, c.tlsConfig)
if err != nil {
return errors.Wrap(err, "dial failed to FCM")
}
defer conn.Close()
mcs := newMCS(conn, c.log, c.creds, c.Events)
defer mcs.disconnect()
err = mcs.SendLoginPacket()
if err != nil {
return errors.Wrap(err, "send login packet failed")
}
// start heartbeat
go c.heartbeat.start(ctx, mcs)
return c.performRead(mcs)
}
func (c *Client) performRead(mcs *mcs) error {
// receive version
err := mcs.ReceiveVersion()
if err != nil {
return errors.Wrap(err, "receive version failed")
}
for {
// receive tag
data, err := mcs.PerformReadTag()
if err != nil {
return errors.Wrap(err, "receive tag failed")
}
if data == nil {
return ErrFcmNotEnoughData
}
err = c.onDataMessage(data)
if err != nil {
return errors.Wrap(err, "process data message failed")
}
}
}
func (c *Client) onDataMessage(tagData interface{}) error {
switch data := tagData.(type) {
case *pb.LoginResponse:
c.receivedPersistentID = nil
c.Events <- &ConnectedEvent{data.GetServerTimestamp()}
case *pb.DataMessageStanza:
// To avoid error loops, last streamID is notified even when an error occurs.
c.receivedPersistentID = append(c.receivedPersistentID, data.GetPersistentId())
event, err := decryptData(data, c.creds.PrivateKey, c.creds.AuthSecret)
if err != nil {
return err
}
c.Events <- event
}
return nil
}
func (c *Client) subscribeFCM(ctx context.Context, registerResponse *gcmRegisterResponse) (*FCMCredentials, error) {
credentials := &FCMCredentials{}
err := credentials.appendCryptoInfo()
if err != nil {
return nil, err
}
values := url.Values{}
values.Set("authorized_entity", c.senderID)
values.Set("endpoint", fcmEndpoint+registerResponse.token)
values.Set("encryption_key", base64.RawURLEncoding.EncodeToString(credentials.PublicKey))
values.Set("encryption_auth", base64.RawURLEncoding.EncodeToString(credentials.AuthSecret))
res, err := c.post(ctx, fcmSubscribe, strings.NewReader(values.Encode()), func(header *http.Header) {
header.Set("Content-Type", "application/x-www-form-urlencoded")
})
if err != nil {
return nil, errors.Wrap(err, "request FCM subscribe")
}
defer closeResponse(res)
if res.StatusCode < 200 || res.StatusCode > 299 {
return nil, errors.Errorf("server error: %s", res.Status)
}
var fcmRegisterResponse fcmRegisterResponse
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&fcmRegisterResponse)
if err != nil {
return nil, errors.Wrap(err, "unmarshal FCM subscribe response")
}
// set responses.
credentials.AppID = registerResponse.appID
credentials.AndroidID = registerResponse.androidID
credentials.SecurityToken = registerResponse.securityToken
credentials.Token = fcmRegisterResponse.Token
return credentials, nil
}