-
Notifications
You must be signed in to change notification settings - Fork 9
/
fcm.go
195 lines (169 loc) · 5.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
194
195
package fcm
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net"
"net/http"
"strconv"
"time"
)
const (
// FCM server address
serverURL = "https://fcm.googleapis.com/fcm/send"
// Network timeout for connecting to the server. Not setting it may create a large
// pool of waiting connectins in case of network problems.
connectionTimeout = 5 * time.Second
PriorityHigh = "high"
PriorityNormal = "normal"
)
// Error messages
const (
ErrorMissingRegistration = "MissingRegistration"
ErrorInvalidRegistration = "InvalidRegistration"
ErrorNotRegistered = "NotRegistered"
ErrorInvalidPackageName = "InvalidPackageName"
ErrorMismatchSenderId = "MismatchSenderId"
ErrorMessageTooBig = "MessageTooBig"
ErrorInvalidDataKey = "InvalidDataKey"
ErrorInvalidTtl = "InvalidTtl"
ErrorUnavailable = "Unavailable"
ErrorInternalServerError = "InternalServerError"
ErrorDeviceMessageRateExceeded = "DeviceMessageRateExceeded"
ErrorTopicsMessageRateExceeded = "TopicsMessageRateExceeded"
)
// HttpMessage is an FCM HTTP request message
type HttpMessage struct {
To string `json:"to,omitempty"`
RegistrationIds []string `json:"registration_ids,omitempty"`
Condition string `json:"condition,omitempty"`
CollapseKey string `json:"collapse_key,omitempty"`
Priority string `json:"priority,omitempty"`
ContentAvailable bool `json:"content_available,omitempty"`
TimeToLive *uint `json:"time_to_live,omitempty"`
RestrictedPackageName string `json:"restricted_package_name,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
Data interface{} `json:"data,omitempty"`
Notification *Notification `json:"notification,omitempty"`
}
// HttpResponse is an FCM response message
type HttpResponse struct {
MulticastId int `json:"multicast_id"`
Success int `json:"success"`
Fail int `json:"failure"`
CanonicalIds int `json:"canonical_ids"`
Results []Result `json:"results,omitempty"`
}
type Result struct {
MessageId string `json:"message_id"`
RegistrationId string `json:"registration_id"`
Error string `json:"error"`
}
// Notification notification message structure
type Notification struct {
Title string `json:"title,omitempty"`
Body string `json:"body,omitempty"`
Sound string `json:"sound,omitempty"`
ClickAction string `json:"click_action,omitempty"`
BodyLocKey string `json:"body_loc_key,omitempty"`
BodyLocArgs string `json:"body_loc_args,omitempty"`
TitleLocKey string `json:"title_loc_key,omitempty"`
TitleLocArgs string `json:"title_loc_args,omitempty"`
// Android only
Icon string `json:"icon,omitempty"`
Tag string `json:"tag,omitempty"`
Color string `json:"color,omitempty"`
// iOS only
Badge string `json:"badge,omitempty"`
}
type Client struct {
apiKey string
connection *http.Transport
retryAfter string
}
// NewClient returns an FCM client. The client is expected to be
// long-lived. It maintains an internal pool of HTTP connections.
// Multiple sumultaneous Send requests can be issued on the same client.
func NewClient(apikey string) *Client {
return &Client{
apiKey: "key=" + apikey,
connection: &http.Transport{
Dial: (&net.Dialer{
Timeout: connectionTimeout,
}).Dial,
TLSHandshakeTimeout: connectionTimeout,
},
}
}
// SendHttp is a blocking call to send an HTTP message to FCM server.
// Multiple Send requests can be issued simultaneously on the same
// Client.
func (c *Client) SendHttp(msg *HttpMessage) (*HttpResponse, error) {
// Encode message to JSON
var rw bytes.Buffer
encoder := json.NewEncoder(&rw)
err := encoder.Encode(msg)
if err != nil {
return nil, err
}
// Format request
req, err := http.NewRequest(http.MethodPost, serverURL, &rw)
if err != nil {
return nil, err
}
req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json")
req.Header.Add(http.CanonicalHeaderKey("Authorization"), c.apiKey)
//debug, err := httputil.DumpRequest(req, true)
//log.Printf("request: '%s'", string(debug))
// Call the server, issue HTTP POST, wait for response
httpResp, err := c.connection.RoundTrip(req)
if httpResp != nil {
defer httpResp.Body.Close()
}
if err != nil {
return nil, err
}
// debug, err := httputil.DumpResponse(httpResp, true)
// log.Printf("response: '%s'", string(debug))
// Read response completely and close the body to make
// the underlying connection reusable.
body, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return nil, err
}
if httpResp.StatusCode != http.StatusOK {
// Assuming non-JSON response
return nil, errors.New(httpResp.Status + ": " + string(body))
}
// Decode JSON response
var response HttpResponse
err = json.Unmarshal(body, &response)
// Get value of retry-after if present
if err == nil {
c.retryAfter = httpResp.Header.Get(http.CanonicalHeaderKey("Retry-After"))
}
return &response, err
}
// GetRetryAfter returns the number fo seconds to wait before retrying Send in case the previous
// Send has failed.
func (c *Client) GetRetryAfter() uint {
if c.retryAfter == "" {
return 0
}
if ra, err := strconv.Atoi(c.retryAfter); err == nil {
return uint(ra)
}
if ts, err := http.ParseTime(c.retryAfter); err == nil {
sec := ts.Sub(time.Now()).Seconds()
if sec < 0 {
return 0
}
return uint(sec)
}
return 0
}
// PostHttp is a non-blocking version of Send. Not implemented yet.
func (c *Client) PostHttp(msg *HttpMessage) (<-chan *HttpResponse, error) {
return nil, errors.New("Not implmented")
}