-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
APNSClient.swift
198 lines (164 loc) · 7.23 KB
/
APNSClient.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the APNSwift open source project
//
// Copyright (c) 2022 the APNSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of APNSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import APNSCore
import AsyncHTTPClient
import struct Foundation.Date
import struct Foundation.UUID
import NIOConcurrencyHelpers
import NIOCore
import NIOHTTP1
import NIOSSL
import NIOTLS
import NIOPosix
/// A client to talk with the Apple Push Notification services.
public final class APNSClient<Decoder: APNSJSONDecoder, Encoder: APNSJSONEncoder>: APNSClientProtocol {
/// The configuration used by the ``APNSClient``.
private let configuration: APNSClientConfiguration
/// The ``HTTPClient`` used by the APNS.
private let httpClient: HTTPClient
/// The decoder for the responses from APNs.
private let responseDecoder: Decoder
/// The encoder for the requests to APNs.
@usableFromInline
/* private */ internal let requestEncoder: Encoder
/// The authentication token manager.
private let authenticationTokenManager: APNSAuthenticationTokenManager<ContinuousClock>?
/// The ByteBufferAllocator
@usableFromInline
/* private */ internal let byteBufferAllocator: ByteBufferAllocator
/// Default ``HTTPHeaders`` which will be adapted for each request. This saves some allocations.
private let defaultRequestHeaders: HTTPHeaders = {
var headers = HTTPHeaders()
headers.reserveCapacity(10)
headers.add(name: "content-type", value: "application/json")
headers.add(name: "user-agent", value: "APNS/swift-nio")
return headers
}()
/// Initializes a new APNS.
///
/// The client will create an internal `HTTPClient` which is used to make requests to APNs.
/// This `HTTPClient` is intentionally internal since both authentication mechanisms are bound to a
/// single connection and these connections cannot be shared.
///
///
/// - Parameters:
/// - configuration: The configuration used by the APNS.
/// - eventLoopGroupProvider: Specify how EventLoopGroup will be created.
/// - responseDecoder: The decoder for the responses from APNs.
/// - requestEncoder: The encoder for the requests to APNs.
/// - byteBufferAllocator: The `ByteBufferAllocator`.
public init(
configuration: APNSClientConfiguration,
eventLoopGroupProvider: NIOEventLoopGroupProvider,
responseDecoder: Decoder,
requestEncoder: Encoder,
byteBufferAllocator: ByteBufferAllocator = .init()
) {
self.configuration = configuration
self.byteBufferAllocator = byteBufferAllocator
self.responseDecoder = responseDecoder
self.requestEncoder = requestEncoder
var tlsConfiguration = TLSConfiguration.makeClientConfiguration()
switch configuration.authenticationMethod.method {
case .jwt(let privateKey, let teamIdentifier, let keyIdentifier):
self.authenticationTokenManager = APNSAuthenticationTokenManager(
privateKey: privateKey,
teamIdentifier: teamIdentifier,
keyIdentifier: keyIdentifier,
clock: ContinuousClock()
)
case .tls(let privateKey, let certificateChain):
self.authenticationTokenManager = nil
tlsConfiguration.privateKey = privateKey
tlsConfiguration.certificateChain = certificateChain
}
var httpClientConfiguration = HTTPClient.Configuration()
httpClientConfiguration.tlsConfiguration = tlsConfiguration
httpClientConfiguration.httpVersion = .automatic
httpClientConfiguration.proxy = configuration.proxy
switch eventLoopGroupProvider {
case .shared(let eventLoopGroup):
self.httpClient = HTTPClient(
eventLoopGroupProvider: .shared(eventLoopGroup),
configuration: httpClientConfiguration
)
case .createNew:
self.httpClient = HTTPClient(
configuration: httpClientConfiguration
)
}
}
/// Shuts down the client gracefully.
public func shutdown() async throws {
try await self.httpClient.shutdown()
}
}
extension APNSClient: Sendable where Decoder: Sendable, Encoder: Sendable {}
// MARK: - Raw sending
extension APNSClient {
public func send(_ request: APNSCore.APNSRequest<some APNSCore.APNSMessage>) async throws -> APNSCore.APNSResponse {
var headers = self.defaultRequestHeaders
// Push type
headers.add(name: "apns-push-type", value: request.pushType.description)
// APNS ID
if let apnsID = request.apnsID {
headers.add(name: "apns-id", value: apnsID.uuidString.lowercased())
}
// Expiration
if let expiration = request.expiration?.expiration {
headers.add(name: "apns-expiration", value: String(expiration))
}
// Priority
if let priority = request.priority?.rawValue {
headers.add(name: "apns-priority", value: String(priority))
}
// Topic
if let topic = request.topic {
headers.add(name: "apns-topic", value: topic)
}
// Collapse ID
if let collapseID = request.collapseID {
headers.add(name: "apns-collapse-id", value: collapseID)
}
// Authorization token
if let authenticationTokenManager = self.authenticationTokenManager {
let token = try await authenticationTokenManager.nextValidToken
headers.add(name: "authorization", value: token)
}
// Device token
let requestURL = "\(self.configuration.environment.absoluteURL)/\(request.deviceToken)"
var byteBuffer = self.byteBufferAllocator.buffer(capacity: 0)
try self.requestEncoder.encode(request.message, into: &byteBuffer)
var httpClientRequest = HTTPClientRequest(url: requestURL)
httpClientRequest.method = .POST
httpClientRequest.headers = headers
httpClientRequest.body = .bytes(byteBuffer)
let response = try await self.httpClient.execute(httpClientRequest, deadline: .distantFuture)
let apnsID = response.headers.first(name: "apns-id").flatMap { UUID(uuidString: $0) }
let apnsUniqueID = response.headers.first(name: "apns-unique-id").flatMap { UUID(uuidString: $0) }
if response.status == .ok {
return APNSResponse(apnsID: apnsID, apnsUniqueID: apnsUniqueID)
}
let body = try await response.body.collect(upTo: 1024)
let errorResponse = try responseDecoder.decode(APNSErrorResponse.self, from: body)
let error = APNSError(
responseStatus: Int(response.status.code),
apnsID: apnsID,
apnsUniqueID: apnsUniqueID,
apnsResponse: errorResponse,
timestamp: errorResponse.timestampInSeconds.flatMap { Date(timeIntervalSince1970: $0) }
)
throw error
}
}