forked from PerfectlySoft/Perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotificationPusher.swift
More file actions
473 lines (398 loc) · 14.9 KB
/
Copy pathNotificationPusher.swift
File metadata and controls
473 lines (398 loc) · 14.9 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//
// NotificationPusher.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-02-16.
// Copyright © 2016 PerfectlySoft. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
/**
Example code:
// BEGIN one-time initialization code
let configurationName = "My configuration name - can be whatever"
NotificationPusher.addConfigurationIOS(configurationName) {
(net:NetTCPSSL) in
// This code will be called whenever a new connection to the APNS service is required.
// Configure the SSL related settings.
net.keyFilePassword = "if you have password protected key file"
guard net.useCertificateChainFile("path/to/entrust_2048_ca.cer") &&
net.useCertificateFile("path/to/aps_development.pem") &&
net.usePrivateKeyFile("path/to/key.pem") &&
net.checkPrivateKey() else {
let code = Int32(net.errorCode())
print("Error validating private key file: \(net.errorStr(code))")
return
}
}
NotificationPusher.development = true // set to toggle to the APNS sandbox server
// END one-time initialization code
// BEGIN - individual notification push
let deviceId = "hex string device id"
let ary = [IOSNotificationItem.AlertBody("This is the message"), IOSNotificationItem.Sound("default")]
let n = NotificationPusher()
n.pushIOS(configurationName, deviceToken: deviceId, expiration: 0, priority: 10, notificationItems: ary) {
response in
print("NotificationResponse: \(response.code) \(response.body)")
}
// END - individual notification push
*/
/// Items to configure an individual notification push.
/// These correspond to what is described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html
public enum IOSNotificationItem {
case AlertBody(String)
case AlertTitle(String)
case AlertTitleLoc(String, [String]?)
case AlertActionLoc(String)
case AlertLoc(String, [String]?)
case AlertLaunchImage(String)
case Badge(Int)
case Sound(String)
case ContentAvailable
case Category(String)
case CustomPayload(String, Any)
}
enum IOSItemId: UInt8 {
case DeviceToken = 1
case Payload = 2
case NotificationIdentifier = 3
case ExpirationDate = 4
case Priority = 5
}
private let iosDeviceIdLength = 32
private let iosNotificationCommand = UInt8(2)
private let iosNotificationPort = UInt16(443)
private let iosNotificationDevelopmentHost = "api.development.push.apple.com"
private let iosNotificationProductionHost = "api.push.apple.com"
struct IOSNotificationError {
let code: UInt8
let identifier: UInt32
}
class NotificationConfiguration {
let configurator: NotificationPusher.netConfigurator
let lock = Threading.Lock()
var streams = [NotificationHTTP2Client]()
init(configurator: NotificationPusher.netConfigurator) {
self.configurator = configurator
}
}
class NotificationHTTP2Client: HTTP2Client {
let id: Int
init(id: Int) {
self.id = id
}
}
/// The response object given after a push attempt.
public struct NotificationResponse {
/// The response code for the request.
public let code: Int
/// The response body data bytes.
public let body: [UInt8]
/// The body data bytes interpreted as JSON and decoded into a Dictionary.
public var jsonObjectBody: [String:Any] {
do {
if let json = try self.stringBody.jsonDecode() as? [String:Any] {
return json
}
}
catch {}
return [String:Any]()
}
/// The body data bytes converted to String.
public var stringBody: String {
return UTF8Encoding.encode(self.body)
}
}
/// The interface for APNS notifications.
public class NotificationPusher {
/// On-demand configuration for SSL related functions.
public typealias netConfigurator = (NetTCPSSL) -> ()
/// Toggle development or production on a global basis.
public static var development = false
var responses = [NotificationResponse]()
static var idCounter = 0
static var notificationHostIOS: String {
if self.development {
return iosNotificationDevelopmentHost
}
return iosNotificationProductionHost
}
static let configurationsLock = Threading.Lock()
static var iosConfigurations = [String:NotificationConfiguration]()
static var activeStreams = [Int:NotificationHTTP2Client]()
/// Add a configuration given a name and a callback.
/// A particular configuration will generally correspond to an individual app.
/// The configuration callback will be called each time a new connection is initiated to the APNS.
/// Within the callback you will want to set:
/// 1. Path to chain file as provided by Apple: net.useCertificateChainFile("path/to/entrust_2048_ca.cer")
/// 2. Path to push notification certificate as obtained from Apple: net.useCertificateFile("path/to/aps.pem")
/// 3a. Password for the certificate's private key file, if it is password protected: net.keyFilePassword = "password"
/// 3b. Path to the certificate's private key file: net.usePrivateKeyFile("path/to/key.pem")
public static func addConfigurationIOS(name: String, configurator: netConfigurator) {
self.configurationsLock.doWithLock {
self.iosConfigurations[name] = NotificationConfiguration(configurator: configurator)
}
}
static func getStreamIOS(configurationName: String, callback: (HTTP2Client?) -> ()) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf {
var net: NotificationHTTP2Client?
var needsConnect = false
c.lock.doWithLock {
if c.streams.count > 0 {
net = c.streams.removeLast()
} else {
needsConnect = true
net = NotificationHTTP2Client(id: idCounter)
activeStreams[idCounter] = net
idCounter = idCounter &+ 1
}
}
if !needsConnect {
callback(net!)
} else {
// add a new connected stream
c.configurator(net!.net)
net!.connect(self.notificationHostIOS, port: iosNotificationPort, ssl: true, timeoutSeconds: 5.0) {
b in
if b {
callback(net!)
} else {
callback(nil)
}
}
}
} else {
callback(nil)
}
}
static func releaseStreamIOS(configurationName: String, net: HTTP2Client) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf, n = net as? NotificationHTTP2Client {
c.lock.doWithLock {
activeStreams.removeValueForKey(n.id)
if net.isConnected {
c.streams.append(n)
}
}
} else {
net.close()
}
}
public init() {
}
func resetResponses() {
self.responses.removeAll()
}
/// Push one message to one device.
/// Provide the previously set configuration name, device token.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the response.
public func pushIOS(configurationName: String, deviceToken: String, expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: (NotificationResponse) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: [deviceToken], expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses.first!)
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
}
/// Push multiple messages to one device.
/// Provide the previously set configuration name, and zero or more device tokens. The same message will be sent to each device.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the responses.
public func pushIOS(configurationName: String, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: deviceTokens, expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses)
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
}
func pushIOS(net: HTTP2Client, deviceToken: String, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: (NotificationResponse) -> ()) {
let request = net.createRequest()
request.setRequestMethod("POST")
request.postBodyBytes = notificationJson
request.headers["content-type"] = "application/json; charset=utf-8"
request.headers["apns-expiration"] = "\(expiration)"
request.headers["apns-priority"] = "\(priority)"
request.headers["apns-topic"] = "ca.treefrog.Smirkee"
request.setRequestURI("/3/device/\(deviceToken)")
net.sendRequest(request) {
response, msg in
if let r = response {
let code = r.getStatus().0
callback(NotificationResponse(code: code, body: r.bodyData))
} else {
callback(NotificationResponse(code: -1, body: UTF8Encoding.decode("No response")))
}
}
}
func pushIOS(client: HTTP2Client, deviceTokens: IndexingGenerator<[String]>, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: ([NotificationResponse]) -> ()) {
var g = deviceTokens
if let next = g.next() {
pushIOS(client, deviceToken: next, expiration: expiration, priority: priority, notificationJson: notificationJson) {
response in
self.responses.append(response)
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: notificationJson, callback: callback)
}
} else {
callback(self.responses)
}
}
func pushIOS(client: HTTP2Client, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
self.resetResponses()
let g = deviceTokens.generate()
let jsond = UTF8Encoding.decode(self.itemsToPayloadString(notificationItems))
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: jsond, callback: callback)
}
/// Push multiple messages to one device.
/// Provide the previously set configuration name, and zero or more device tokens. The same message will be sent to each device.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive any errors which may have occurred.
/// nil is passed to the callback if the push was successful.
/* public func pushIOS(configurationName: String, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: (errorMessage: String?) -> ()) {
do {
let jsond = try self.itemsToPayloadString(notificationItems)
NotificationPusher.getStreamIOS(configurationName) {
n in
if let net = n {
let request = net.createRequest()
request.setRequestMethod("POST")
request.postBodyBytes = UTF8Encoding.decode(jsond)
request.headers["content-type"] = "application/json; charset=utf-8"
request.headers["apns-expiration"] = "\(expiration)"
request.headers["apns-priority"] = "\(priority)"
request.headers["apns-topic"] = "ca.treefrog.Smirkee"
request.setRequestURI("/3/device/\(deviceToken)")
net.sendRequest(request) {
response, msg in
NotificationPusher.releaseStreamIOS(configurationName, net: net)
if let r = response {
let code = r.getStatus().0
if code != 200 {
callback(errorMessage: "Response code \(code)")
} else {
callback(errorMessage: nil)
}
} else {
callback(errorMessage: msg)
}
}
} else {
callback(errorMessage: "No stream")
}
}
} catch let e {
callback(errorMessage: "\(e)")
}
}
*/
func itemsToPayloadString(notificationItems: [IOSNotificationItem]) -> String {
var dict = [String:Any]()
var aps = [String:Any]()
var alert = [String:Any]()
var alertBody: String?
for item in notificationItems {
switch item {
case .AlertBody(let s):
alertBody = s
case .AlertTitle(let s):
alert["title"] = s
case .AlertTitleLoc(let s, let a):
alert["title-loc-key"] = s
if let titleLocArgs = a {
alert["title-loc-args"] = titleLocArgs
}
case .AlertActionLoc(let s):
alert["action-loc-key"] = s
case .AlertLoc(let s, let a):
alert["loc-key"] = s
if let locArgs = a {
alert["loc-args"] = locArgs
}
case .AlertLaunchImage(let s):
alert["launch-image"] = s
case .Badge(let i):
aps["badge"] = i
case .Sound(let s):
aps["sound"] = s
case .ContentAvailable:
aps["content-available"] = 1
case .Category(let s):
aps["category"] = s
case .CustomPayload(let s, let a):
dict[s] = a
}
}
if let ab = alertBody {
if alert.count == 0 { // just a string alert
aps["alert"] = ab
} else { // a dict alert
alert["body"] = ab
aps["alert"] = alert
}
}
dict["aps"] = aps
do {
return try dict.jsonEncodedString()
}
catch {}
return "{}"
}
}
private func jsonSerialize(o: Any) -> String? {
do {
return try jsonEncodedStringWorkAround(o)
} catch let e as JSONConversionError {
print("Could not convert to JSON: \(e)")
} catch {}
return nil
}