2024-04-07 18:04:42 +00:00
|
|
|
//
|
2024-04-08 13:48:40 +00:00
|
|
|
// PushManagerImpl.swift
|
|
|
|
// PushNotifications
|
2024-04-07 18:04:42 +00:00
|
|
|
//
|
2024-04-08 13:48:40 +00:00
|
|
|
// Created by Shadowfacts on 4/7/24.
|
2024-04-07 18:04:42 +00:00
|
|
|
//
|
|
|
|
|
2024-04-08 13:48:40 +00:00
|
|
|
import UIKit
|
|
|
|
import UserAccounts
|
2024-04-08 16:25:39 +00:00
|
|
|
import CryptoKit
|
2024-04-07 18:04:42 +00:00
|
|
|
|
2024-04-08 13:48:40 +00:00
|
|
|
class PushManagerImpl: _PushManager {
|
2024-04-07 18:04:42 +00:00
|
|
|
private let endpoint: URL
|
|
|
|
|
|
|
|
var enabled: Bool {
|
|
|
|
true
|
|
|
|
}
|
|
|
|
|
|
|
|
private var apnsEnvironment: String {
|
|
|
|
#if DEBUG
|
|
|
|
"development"
|
|
|
|
#else
|
2024-04-12 20:15:52 +00:00
|
|
|
"production"
|
2024-04-07 18:04:42 +00:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
private var remoteNotificationsRegistrationContinuation: CheckedContinuation<Data, any Error>?
|
|
|
|
|
|
|
|
private let defaults = UserDefaults(suiteName: "group.space.vaccor.Tusker")!
|
2024-04-11 16:58:43 +00:00
|
|
|
public private(set) var subscriptions: [PushSubscription] {
|
2024-04-07 19:49:12 +00:00
|
|
|
get {
|
|
|
|
if let array = defaults.array(forKey: "PushSubscriptions") as? [[String: Any]] {
|
|
|
|
return array.compactMap(PushSubscription.init(defaultsDict:))
|
|
|
|
} else {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
}
|
|
|
|
set {
|
|
|
|
defaults.setValue(newValue.map(\.defaultsDict), forKey: "PushSubscriptions")
|
|
|
|
}
|
|
|
|
}
|
2024-04-07 18:04:42 +00:00
|
|
|
|
|
|
|
init(endpoint: URL) {
|
|
|
|
self.endpoint = endpoint
|
|
|
|
}
|
2024-04-08 03:14:12 +00:00
|
|
|
|
2024-04-12 20:15:52 +00:00
|
|
|
func createSubscription(account: UserAccountInfo) async throws -> PushSubscription {
|
2024-04-08 16:25:39 +00:00
|
|
|
if let existing = pushSubscription(account: account) {
|
|
|
|
return existing
|
|
|
|
}
|
|
|
|
let key = P256.KeyAgreement.PrivateKey()
|
|
|
|
var authSecret = Data(count: 16)
|
|
|
|
let res = authSecret.withUnsafeMutableBytes { ptr in
|
|
|
|
SecRandomCopyBytes(kSecRandomDefault, 16, ptr.baseAddress!)
|
|
|
|
}
|
|
|
|
guard res == errSecSuccess else {
|
|
|
|
throw CreateSubscriptionError.generatingAuthSecret(res)
|
|
|
|
}
|
2024-04-12 20:15:52 +00:00
|
|
|
let token = try await getDeviceToken()
|
2024-04-08 16:25:39 +00:00
|
|
|
let subscription = PushSubscription(
|
|
|
|
accountID: account.id,
|
2024-04-12 20:15:52 +00:00
|
|
|
endpoint: endpointURL(deviceToken: token, accountID: account.id),
|
2024-04-08 16:25:39 +00:00
|
|
|
secretKey: key,
|
|
|
|
authSecret: authSecret,
|
|
|
|
alerts: [],
|
|
|
|
policy: .all
|
|
|
|
)
|
2024-04-09 16:35:51 +00:00
|
|
|
subscriptions.append(subscription)
|
2024-04-08 16:25:39 +00:00
|
|
|
return subscription
|
|
|
|
}
|
|
|
|
|
2024-04-12 20:15:52 +00:00
|
|
|
private func endpointURL(deviceToken: Data, accountID: String) -> URL {
|
|
|
|
var endpoint = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
2024-04-16 02:19:24 +00:00
|
|
|
let accountID = accountID.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
|
2024-04-12 20:15:52 +00:00
|
|
|
endpoint.path = "/push/v1/\(apnsEnvironment)/\(deviceToken.hexEncodedString())/\(accountID)"
|
2024-04-09 16:35:00 +00:00
|
|
|
return endpoint.url!
|
|
|
|
}
|
|
|
|
|
2024-04-08 16:25:39 +00:00
|
|
|
func removeSubscription(account: UserAccountInfo) {
|
2024-04-09 16:35:51 +00:00
|
|
|
subscriptions.removeAll { $0.accountID == account.id }
|
2024-04-08 16:25:39 +00:00
|
|
|
}
|
|
|
|
|
2024-04-10 01:07:14 +00:00
|
|
|
func updateSubscription(account: UserAccountInfo, alerts: PushSubscription.Alerts, policy: PushSubscription.Policy) {
|
|
|
|
guard let index = subscriptions.firstIndex(where: { $0.accountID == account.id }) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var copy = subscriptions[index]
|
|
|
|
copy.alerts = alerts
|
|
|
|
copy.policy = policy
|
|
|
|
subscriptions[index] = copy
|
|
|
|
}
|
|
|
|
|
2024-04-08 03:14:12 +00:00
|
|
|
func pushSubscription(account: UserAccountInfo) -> PushSubscription? {
|
2024-04-09 16:35:51 +00:00
|
|
|
subscriptions.first { $0.accountID == account.id }
|
2024-04-08 03:14:12 +00:00
|
|
|
}
|
2024-04-07 18:04:42 +00:00
|
|
|
|
2024-04-09 16:35:00 +00:00
|
|
|
func updateIfNecessary(updateSubscription: @escaping (PushSubscription) async -> Bool) async {
|
2024-04-12 20:15:52 +00:00
|
|
|
let subscriptions = self.subscriptions
|
|
|
|
guard !subscriptions.isEmpty else {
|
2024-04-07 18:04:42 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
do {
|
2024-04-12 20:15:52 +00:00
|
|
|
let token = try await getDeviceToken()
|
|
|
|
self.subscriptions = await AsyncSequenceAdaptor(wrapping: subscriptions).map {
|
|
|
|
let newEndpoint = await self.endpointURL(deviceToken: token, accountID: $0.accountID)
|
|
|
|
guard newEndpoint != $0.endpoint else {
|
2024-05-27 20:33:00 +00:00
|
|
|
PushManager.logger.debug("Skipping update of push subscription with endpoint \($0.endpoint, privacy: .public)")
|
2024-04-12 20:15:52 +00:00
|
|
|
return $0
|
|
|
|
}
|
|
|
|
var copy = $0
|
|
|
|
copy.endpoint = newEndpoint
|
|
|
|
if await updateSubscription(copy) {
|
|
|
|
return copy
|
|
|
|
} else {
|
|
|
|
return $0
|
|
|
|
}
|
|
|
|
}.reduce(into: [], { partialResult, el in
|
|
|
|
partialResult.append(el)
|
|
|
|
})
|
2024-04-07 18:04:42 +00:00
|
|
|
} catch {
|
2024-04-08 13:48:40 +00:00
|
|
|
PushManager.logger.error("Failed to update push registration: \(String(describing: error), privacy: .public)")
|
2024-04-09 15:56:22 +00:00
|
|
|
PushManager.captureError?(error)
|
2024-04-07 18:04:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func getDeviceToken() async throws -> Data {
|
|
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
|
|
remoteNotificationsRegistrationContinuation = continuation
|
|
|
|
UIApplication.shared.registerForRemoteNotifications()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func didRegisterForRemoteNotifications(deviceToken: Data) {
|
|
|
|
remoteNotificationsRegistrationContinuation?.resume(returning: deviceToken)
|
2024-04-12 02:30:43 +00:00
|
|
|
remoteNotificationsRegistrationContinuation = nil
|
2024-04-07 18:04:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func didFailToRegisterForRemoteNotifications(error: any Error) {
|
|
|
|
remoteNotificationsRegistrationContinuation?.resume(throwing: PushRegistrationError.registeringForRemoteNotifications(error))
|
2024-04-12 02:30:43 +00:00
|
|
|
remoteNotificationsRegistrationContinuation = nil
|
2024-04-07 18:04:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
enum PushRegistrationError: LocalizedError {
|
|
|
|
case alreadyRegistering
|
|
|
|
case registeringForRemoteNotifications(any Error)
|
|
|
|
|
|
|
|
var errorDescription: String? {
|
|
|
|
switch self {
|
|
|
|
case .alreadyRegistering:
|
|
|
|
"Already registering"
|
|
|
|
case .registeringForRemoteNotifications(let error):
|
|
|
|
"Remote notifications: \(error.localizedDescription)"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-08 16:25:39 +00:00
|
|
|
enum CreateSubscriptionError: LocalizedError {
|
|
|
|
case generatingAuthSecret(OSStatus)
|
|
|
|
|
|
|
|
var errorDescription: String? {
|
|
|
|
switch self {
|
|
|
|
case .generatingAuthSecret(let code):
|
|
|
|
"Generating auth secret: \(code)"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-07 18:04:42 +00:00
|
|
|
private extension Data {
|
|
|
|
func hexEncodedString() -> String {
|
|
|
|
String(unsafeUninitializedCapacity: count * 2) { buffer in
|
|
|
|
let chars = Array("0123456789ABCDEF".utf8)
|
|
|
|
for (i, x) in enumerated() {
|
|
|
|
let (upper, lower) = x.quotientAndRemainder(dividingBy: 16)
|
|
|
|
buffer[i * 2] = chars[Int(upper)]
|
|
|
|
buffer[i * 2 + 1] = chars[Int(lower)]
|
|
|
|
}
|
|
|
|
return count * 2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-04-09 16:35:00 +00:00
|
|
|
|
|
|
|
private struct AsyncSequenceAdaptor<S: Sequence>: AsyncSequence {
|
|
|
|
typealias Element = S.Element
|
|
|
|
|
|
|
|
let base: S
|
|
|
|
|
|
|
|
init(wrapping base: S) {
|
|
|
|
self.base = base
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeAsyncIterator() -> AsyncIterator {
|
|
|
|
AsyncIterator(base: base.makeIterator())
|
|
|
|
}
|
|
|
|
|
|
|
|
struct AsyncIterator: AsyncIteratorProtocol {
|
|
|
|
var base: S.Iterator
|
|
|
|
|
|
|
|
mutating func next() async -> Element? {
|
|
|
|
base.next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|