forked from mercari/gaurun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notification.go
318 lines (277 loc) · 8.28 KB
/
notification.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package gaurun
import (
"encoding/json"
"errors"
"fmt"
"github.com/alexjlockwood/gcm"
"github.com/cubicdaiya/apns"
"io/ioutil"
"net/http"
"sync/atomic"
"time"
)
type RequestGaurun struct {
Notifications []RequestGaurunNotification `json:"notifications"`
}
type RequestGaurunNotification struct {
// Common
Tokens []string `json:"token"`
Platform int `json:"platform"`
Message string `json:"message"`
// Android
CollapseKey string `json:"collapse_key,omitempty"`
DelayWhileIdle bool `json:"delay_while_idle,omitempty"`
TimeToLive int `json:"time_to_live,omitempty"`
// iOS
Badge int `json:"badge,omitempty"`
Sound string `json:"sound,omitempty"`
Expiry int `json:"expiry,omitempty"`
Retry int `json:"retry,omitempty"`
// meta
IDs []uint64 `json:"seq_id,omitempty"`
}
type ResponseGaurun struct {
Message string `json:"message"`
}
type CertificatePem struct {
Cert []byte
Key []byte
}
func StartPushWorkers(workerNum, queueNum int) {
QueueNotification = make(chan RequestGaurunNotification, queueNum)
for i := 0; i < workerNum; i++ {
go pushNotificationWorker()
}
}
func enqueueNotifications(notifications []RequestGaurunNotification) {
for _, notification := range notifications {
err := validateNotification(¬ification)
if err != nil {
LogError.Error(err.Error())
continue
}
var enabledPush bool
switch notification.Platform {
case PlatFormIos:
enabledPush = ConfGaurun.Ios.Enabled
case PlatFormAndroid:
enabledPush = ConfGaurun.Android.Enabled
}
if enabledPush {
notification.IDs = make([]uint64, len(notification.Tokens))
for i := 0; i < len(notification.IDs); i++ {
notification.IDs[i] = numberingPush()
LogPush(notification.IDs[i], StatusAcceptedPush, notification.Tokens[i], 0, notification)
}
QueueNotification <- notification
}
}
}
func classifyByDevice(reqGaurun *RequestGaurun) ([]RequestGaurunNotification, []RequestGaurunNotification) {
var (
reqGaurunNotificationIos []RequestGaurunNotification
reqGaurunNotificationAndroid []RequestGaurunNotification
)
for _, notification := range reqGaurun.Notifications {
switch notification.Platform {
case PlatFormIos:
reqGaurunNotificationIos = append(reqGaurunNotificationIos, notification)
case PlatFormAndroid:
reqGaurunNotificationAndroid = append(reqGaurunNotificationAndroid, notification)
}
}
return reqGaurunNotificationIos, reqGaurunNotificationAndroid
}
func pushNotificationIos(req RequestGaurunNotification) bool {
LogError.Debug("START push notification for iOS")
var ep string
if ConfGaurun.Ios.Sandbox {
ep = EpApnsSandbox
} else {
ep = EpApnsProd
}
client, err := apns.NewClient(
ep,
ConfGaurun.Ios.PemCertPath,
ConfGaurun.Ios.PemKeyPath,
time.Duration(ConfGaurun.Ios.Timeout)*time.Second,
)
if err != nil {
atomic.AddInt64(&StatGaurun.Ios.PushError, int64(len(req.Tokens)))
for i, token := range req.Tokens {
LogPush(req.IDs[i], StatusFailedPush, token, 0, req)
}
return false
}
client.TimeoutWaitError = time.Duration(ConfGaurun.Ios.TimeoutError) * time.Millisecond
for i, token := range req.Tokens {
id := req.IDs[i]
payload := apns.NewPayload()
payload.Alert = req.Message
payload.Badge = req.Badge
payload.Sound = req.Sound
pn := apns.NewPushNotification()
pn.DeviceToken = token
pn.Expiry = uint32(req.Expiry)
pn.AddPayload(payload)
stime := time.Now()
resp := client.Send(pn)
etime := time.Now()
ptime := etime.Sub(stime).Seconds()
if resp.Error != nil {
atomic.AddInt64(&StatGaurun.Ios.PushError, 1)
LogPush(req.IDs[i], StatusFailedPush, token, ptime, req)
// reconnect
client.Conn.Close()
client.ConnTls.Close()
client, err = apns.NewClient(
ep,
ConfGaurun.Ios.PemCertPath,
ConfGaurun.Ios.PemKeyPath,
time.Duration(ConfGaurun.Ios.Timeout)*time.Second,
)
if err != nil {
atomic.AddInt64(&StatGaurun.Ios.PushError, int64(len(req.Tokens)-i))
LogPush(req.IDs[i], StatusFailedPush, token, 0, req)
return false
}
client.TimeoutWaitError = time.Duration(ConfGaurun.Ios.TimeoutError) * time.Millisecond
} else {
LogPush(id, StatusSucceededPush, token, ptime, req)
atomic.AddInt64(&StatGaurun.Ios.PushSuccess, 1)
}
}
client.Conn.Close()
client.ConnTls.Close()
LogError.Debug("END push notification for iOS")
return true
}
func pushNotificationAndroid(req RequestGaurunNotification) bool {
LogError.Debug("START push notification for Android")
data := map[string]interface{}{"message": req.Message}
msg := gcm.NewMessage(data, req.Tokens...)
msg.CollapseKey = req.CollapseKey
msg.DelayWhileIdle = req.DelayWhileIdle
msg.TimeToLive = req.TimeToLive
sender := &gcm.Sender{ApiKey: ConfGaurun.Android.ApiKey}
sender.Http = new(http.Client)
sender.Http.Timeout = time.Duration(ConfGaurun.Android.Timeout) * time.Second
stime := time.Now()
resp, err := sender.SendNoRetry(msg)
etime := time.Now()
ptime := etime.Sub(stime).Seconds()
if err != nil {
atomic.AddInt64(&StatGaurun.Android.PushError, 1)
for i, token := range req.Tokens {
LogPush(req.IDs[i], StatusFailedPush, token, ptime, req)
}
return false
}
if resp.Failure > 0 {
atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(resp.Success))
atomic.AddInt64(&StatGaurun.Android.PushError, int64(resp.Failure))
if len(resp.Results) == len(req.Tokens) {
for i, token := range req.Tokens {
if resp.Results[i].Error != "" {
LogPush(req.IDs[i], StatusFailedPush, token, ptime, req)
}
}
}
return true
}
for i, token := range req.Tokens {
LogPush(req.IDs[i], StatusSucceededPush, token, ptime, req)
}
StatGaurun.Android.PushSuccess += int64(len(req.Tokens))
LogError.Debug("END push notification for Android")
return true
}
func pushNotificationWorker() {
var (
success bool
retryMax int
)
for {
notification := <-QueueNotification
switch notification.Platform {
case PlatFormIos:
success = pushNotificationIos(notification)
retryMax = ConfGaurun.Ios.RetryMax
case PlatFormAndroid:
success = pushNotificationAndroid(notification)
retryMax = ConfGaurun.Android.RetryMax
}
if !success && notification.Retry < retryMax {
if len(QueueNotification) < cap(QueueNotification) {
notification.Retry++
QueueNotification <- notification
}
}
}
}
func validateNotification(notification *RequestGaurunNotification) error {
for _, token := range notification.Tokens {
if len(token) == 0 {
return errors.New("empty token")
}
}
if notification.Platform < 1 || notification.Platform > 2 {
return errors.New("invalid platform")
}
if len(notification.Message) == 0 {
return errors.New("empty message")
}
return nil
}
func sendResponse(w http.ResponseWriter, msg string, code int) {
var (
respBody []byte
respGaurun ResponseGaurun
)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Server", fmt.Sprintf("Gaurun %s", Version))
respGaurun.Message = msg
respBody, err := json.Marshal(respGaurun)
if err != nil {
msg := "Response-body could not be created"
http.Error(w, msg, http.StatusInternalServerError)
LogError.Error(msg)
return
}
switch code {
case http.StatusOK:
fmt.Fprintf(w, string(respBody))
default:
http.Error(w, string(respBody), code)
LogError.Error(msg)
}
}
func PushNotificationHandler(w http.ResponseWriter, r *http.Request) {
LogAcceptedRequest("/push", r.Method, r.Proto, r.ContentLength)
LogError.Debug("push-request is Accepted")
LogError.Debug("method check")
if r.Method != "POST" {
sendResponse(w, "method must be POST", http.StatusBadRequest)
return
}
LogError.Debug("parse request body")
var reqGaurun RequestGaurun
reqBody, _ := ioutil.ReadAll(r.Body)
err := json.Unmarshal(reqBody, &reqGaurun)
if err != nil {
sendResponse(w, "Request-body is malformed", http.StatusBadRequest)
return
}
if len(reqGaurun.Notifications) == 0 {
sendResponse(w, "empty notification", http.StatusBadRequest)
return
} else if len(reqGaurun.Notifications) > ConfGaurun.Core.NotificationMax {
msg := fmt.Sprintf("number of notifications(%d) over limit(%d)", len(reqGaurun.Notifications), ConfGaurun.Core.NotificationMax)
sendResponse(w, msg, http.StatusBadRequest)
return
}
LogError.Debug("enqueue notification")
go enqueueNotifications(reqGaurun.Notifications)
LogError.Debug("response to client")
sendResponse(w, "ok", http.StatusOK)
}