forked from mercari/gaurun
/
notification.go
256 lines (209 loc) · 6.63 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
package gaurun
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"sync/atomic"
"time"
"github.com/mercari/gaurun/gcm"
"go.uber.org/zap"
)
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
Title string `json:"title,omitempty"`
Subtitle string `json:"subtitle,omitempty"`
Badge int `json:"badge,omitempty"`
Category string `json:"category,omitempty"`
Sound string `json:"sound,omitempty"`
ContentAvailable bool `json:"content_available,omitempty"`
MutableContent bool `json:"mutable_content,omitempty"`
Expiry int `json:"expiry,omitempty"`
Retry int `json:"retry,omitempty"`
Extend []ExtendJSON `json:"extend,omitempty"`
// meta
ID uint64 `json:"seq_id,omitempty"`
}
type ExtendJSON struct {
Key string `json:"key"`
Value string `json:"val"`
}
type ResponseGaurun struct {
Message string `json:"message"`
}
type CertificatePem struct {
Cert []byte
Key []byte
}
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
}
// Enqueue notification per token
for _, token := range notification.Tokens {
notification2 := notification
notification2.Tokens = []string{token}
notification2.ID = numberingPush()
if enabledPush {
LogPush(notification2.ID, StatusAcceptedPush, token, 0, notification2, nil)
QueueNotification <- notification2
} else {
LogPush(notification2.ID, StatusDisabledPush, token, 0, notification2, nil)
}
}
}
}
func pushNotificationIos(req RequestGaurunNotification) error {
LogError.Debug("START push notification for iOS")
service := NewApnsServiceHttp2(APNSClient)
token := req.Tokens[0]
headers := NewApnsHeadersHttp2(&req)
payload := NewApnsPayloadHttp2(&req)
stime := time.Now()
err := ApnsPushHttp2(token, service, headers, payload)
etime := time.Now()
ptime := etime.Sub(stime).Seconds()
if err != nil {
atomic.AddInt64(&StatGaurun.Ios.PushError, 1)
LogPush(req.ID, StatusFailedPush, token, ptime, req, err)
return err
}
atomic.AddInt64(&StatGaurun.Ios.PushSuccess, 1)
LogPush(req.ID, StatusSucceededPush, token, ptime, req, nil)
LogError.Debug("END push notification for iOS")
return nil
}
func pushNotificationAndroid(req RequestGaurunNotification) error {
LogError.Debug("START push notification for Android")
data := map[string]interface{}{"message": req.Message}
if len(req.Extend) > 0 {
for _, extend := range req.Extend {
data[extend.Key] = extend.Value
}
}
token := req.Tokens[0]
msg := gcm.NewMessage(data, token)
msg.CollapseKey = req.CollapseKey
msg.DelayWhileIdle = req.DelayWhileIdle
msg.TimeToLive = req.TimeToLive
stime := time.Now()
resp, err := GCMClient.SendNoRetry(msg)
etime := time.Now()
ptime := etime.Sub(stime).Seconds()
if err != nil {
atomic.AddInt64(&StatGaurun.Android.PushError, 1)
LogPush(req.ID, StatusFailedPush, token, ptime, req, err)
return err
}
if resp.Failure > 0 {
atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(resp.Success))
atomic.AddInt64(&StatGaurun.Android.PushError, int64(resp.Failure))
LogPush(req.ID, StatusFailedPush, token, ptime, req, errors.New(resp.Results[0].Error))
return errors.New(resp.Results[0].Error)
}
LogPush(req.ID, StatusSucceededPush, token, ptime, req, nil)
atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(len(req.Tokens)))
LogError.Debug("END push notification for Android")
return nil
}
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) {
respGaurun := ResponseGaurun{
Message: msg,
}
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(respGaurun); err != nil {
buf = bytes.NewBufferString("{\"message\":\"Response-body could not be created\"}")
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Server", serverHeader())
w.WriteHeader(code)
w.Write(buf.Bytes())
}
func PushNotificationHandler(w http.ResponseWriter, r *http.Request) {
LogAcceptedRequest(r)
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("content-length check")
if r.ContentLength == 0 {
sendResponse(w, "request body is empty", http.StatusBadRequest)
return
}
var (
reqGaurun RequestGaurun
err error
)
if ConfGaurun.Log.Level == "debug" {
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
sendResponse(w, "failed to read request-body", http.StatusInternalServerError)
return
}
if m := LogError.Check(zap.DebugLevel, "parse request body"); m != nil {
m.Write(zap.String("body", string(reqBody)))
}
err = json.Unmarshal(reqBody, &reqGaurun)
} else {
LogError.Debug("parse request body")
err = json.NewDecoder(r.Body).Decode(&reqGaurun)
}
if err != nil {
LogError.Error(err.Error())
sendResponse(w, "Request-body is malformed", http.StatusBadRequest)
return
}
if len(reqGaurun.Notifications) == 0 {
LogError.Error("empty notification")
sendResponse(w, "empty notification", http.StatusBadRequest)
return
} else if int64(len(reqGaurun.Notifications)) > ConfGaurun.Core.NotificationMax {
msg := fmt.Sprintf("number of notifications(%d) over limit(%d)", len(reqGaurun.Notifications), ConfGaurun.Core.NotificationMax)
LogError.Error(msg)
sendResponse(w, msg, http.StatusBadRequest)
return
}
LogError.Debug("enqueue notification")
go enqueueNotifications(reqGaurun.Notifications)
LogError.Debug("response to client")
sendResponse(w, "ok", http.StatusOK)
}