forked from SkygearIO/skygear-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apns.go
247 lines (210 loc) · 6.31 KB
/
apns.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
// Copyright 2015-present Oursky Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package push
import (
"encoding/json"
"errors"
"fmt"
"time"
log "github.com/Sirupsen/logrus"
"github.com/skygeario/skygear-server/skydb"
"github.com/timehop/apns"
)
// GatewayType determine which kind of gateway should be used for APNS
type GatewayType string
// Available gateways
const (
Sandbox GatewayType = "sandbox"
Production = "production"
)
// private interface s.t. we can mock apns.Client in test
type apnsSender interface {
Send(n apns.Notification) error
FailedNotifs() chan apns.NotificationResult
}
// private interface to mock apns.Feedback in test
type feedbackReceiver interface {
Receive() <-chan apns.FeedbackTuple
}
// APNSPusher pushes notification via apns
type APNSPusher struct {
// Function to obtain a skydb connection
connOpener func() (skydb.Conn, error)
// we are directly coupling on apns as it seems redundant to duplicate
// all the payload and client logic and interfaces.
client apnsSender
feedback feedbackReceiver
}
// NewAPNSPusher returns a new APNSPusher from content of certificate
// and private key as string
func NewAPNSPusher(connOpener func() (skydb.Conn, error), gwType GatewayType, cert string, key string) (*APNSPusher, error) {
var gateway, fbGateway string
switch gwType {
case Sandbox:
gateway = apns.SandboxGateway
fbGateway = apns.SandboxFeedbackGateway
case Production:
gateway = apns.ProductionGateway
fbGateway = apns.ProductionFeedbackGateway
default:
return nil, fmt.Errorf("unrecgonized GatewayType = %#v", gwType)
}
client, err := apns.NewClient(gateway, cert, key)
if err != nil {
return nil, err
}
fb, err := apns.NewFeedback(fbGateway, cert, key)
if err != nil {
return nil, err
}
return &APNSPusher{
connOpener: connOpener,
client: &wrappedClient{&client},
feedback: fb,
}, nil
}
// Run listens to the notification error channel
func (pusher *APNSPusher) Run() {
for result := range pusher.client.FailedNotifs() {
log.Errorf("Failed to send notification = %s: %v", result.Notif.ID, result.Err)
}
}
// RunFeedback kicks start receiving from the Feedback Service.
//
// The checking behaviour is to:
// 1. Receive once on startup
// 2. Receive once at 00:00:00 everyday
func (pusher *APNSPusher) RunFeedback() {
pusher.recvFeedback()
for {
now := time.Now()
year, month, day := now.Date()
nextDay := time.Date(year, month, day+1, 0, 0, 0, 0, time.UTC)
d := nextDay.Sub(now)
log.Infof("apns/fb: next feedback scheduled after %v, at %v", d, nextDay)
<-time.After(d)
log.Infoln("apns/fb: going to query feedback service")
pusher.recvFeedback()
}
}
func (pusher *APNSPusher) recvFeedback() {
conn, err := pusher.connOpener()
if err != nil {
log.Errorf("apns/fb: failed to open skydb.Conn, abort feedback retrival: %v\n", err)
return
}
received := false
for fb := range pusher.feedback.Receive() {
log.Infof("apns/fb: got a feedback = %v", fb)
received = true
// NOTE(limouren): it might be more elegant in the future to extend
// push.Sender as NotificationService and bridge over the differences
// between gcm and apns on handling unregistered devices (probably
// as an async channel)
if err := conn.DeleteDeviceByToken(fb.DeviceToken, fb.Timestamp); err != nil {
log.Errorf("apns/fb: failed to delete device token = %s: %v", fb.DeviceToken, err)
}
}
if !received {
log.Infoln("apns/fb: no feedback received")
}
}
func setPayloadAPS(apsMap map[string]interface{}, aps *apns.APS) {
for key, value := range apsMap {
switch key {
case "content-available":
switch value := value.(type) {
case int:
aps.ContentAvailable = value
case float64:
aps.ContentAvailable = int(value)
}
case "sound":
if sound, ok := value.(string); ok {
aps.Sound = sound
}
case "badge":
switch value := value.(type) {
case int:
aps.Badge.Set(uint(value))
case float64:
aps.Badge.Set(uint(value))
}
case "alert":
if body, ok := value.(string); ok {
aps.Alert.Body = body
} else if alertMap, ok := value.(map[string]interface{}); ok {
jsonbytes, err := json.Marshal(&alertMap)
if err != nil {
panic("Unable to convert alert to json.")
}
err = json.Unmarshal(jsonbytes, &aps.Alert)
if err != nil {
panic("Unable to convert json back to Alert struct.")
}
}
}
}
}
func setPayload(m map[string]interface{}, p *apns.Payload) {
if apsValue, ok := m["aps"]; ok {
if apsMap, ok := apsValue.(map[string]interface{}); ok {
setPayloadAPS(apsMap, &p.APS)
} else {
log.Errorf("Want aps.(type) be map[string]interface{}, got %T", apsValue)
}
}
// set custom values
for key, value := range m {
// the "aps" key is not a custom key
if key == "aps" {
continue
}
if err := p.SetCustomValue(key, value); err != nil {
log.Errorf("Failed to set data[%v] = %v", key, value)
}
}
}
// Send sends a notification to the device identified by the
// specified device
func (pusher *APNSPusher) Send(m Mapper, device skydb.Device) error {
if m == nil {
return nil
}
apnsMap, ok := m.Map()["apns"].(map[string]interface{})
if !ok {
return errors.New("push/apns: payload has no apns dictionary")
}
payload := apns.NewPayload()
setPayload(apnsMap, payload)
notification := apns.NewNotification()
notification.Payload = payload
notification.DeviceToken = device.Token
notification.Priority = apns.PriorityImmediate
if err := pusher.client.Send(notification); err != nil {
log.Errorf("Failed to send APNS Notification: %v", err)
return err
}
return nil
}
// wrapper of apns.Client which implement apnsSender
type wrappedClient struct {
ci *apns.Client
}
func (c *wrappedClient) Send(n apns.Notification) error {
return c.ci.Send(n)
}
func (c *wrappedClient) FailedNotifs() chan apns.NotificationResult {
return c.ci.FailedNotifs
}