258 lines
9.5 KiB
Swift
258 lines
9.5 KiB
Swift
//
|
|
// PushManagerImpl.swift
|
|
// PushNotifications
|
|
//
|
|
// Created by Shadowfacts on 4/7/24.
|
|
//
|
|
|
|
import UIKit
|
|
import UserAccounts
|
|
#if canImport(Sentry)
|
|
import Sentry
|
|
#endif
|
|
|
|
class PushManagerImpl: _PushManager {
|
|
private let endpoint: URL
|
|
|
|
var enabled: Bool {
|
|
true
|
|
}
|
|
|
|
private var apnsEnvironment: String {
|
|
#if DEBUG
|
|
"development"
|
|
#else
|
|
"release"
|
|
#endif
|
|
}
|
|
|
|
private var remoteNotificationsRegistrationContinuation: CheckedContinuation<Data, any Error>?
|
|
|
|
private let defaults = UserDefaults(suiteName: "group.space.vaccor.Tusker")!
|
|
private(set) var pushProxyRegistration: PushProxyRegistration? {
|
|
get {
|
|
if let dict = defaults.dictionary(forKey: "PushProxyRegistration") as? [String: String],
|
|
let registration = PushProxyRegistration(defaultsDict: dict) {
|
|
return registration
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
set {
|
|
defaults.setValue(newValue?.defaultsDict, forKey: "PushProxyRegistration")
|
|
}
|
|
}
|
|
private(set) var pushSubscriptions: [PushSubscription] {
|
|
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")
|
|
}
|
|
}
|
|
|
|
init(endpoint: URL) {
|
|
self.endpoint = endpoint
|
|
}
|
|
|
|
func pushSubscription(account: UserAccountInfo) -> PushSubscription? {
|
|
pushSubscriptions.first { $0.accountID == account.id }
|
|
}
|
|
|
|
func register(transactionID: UInt64) async throws -> PushProxyRegistration {
|
|
guard remoteNotificationsRegistrationContinuation == nil else {
|
|
throw PushRegistrationError.alreadyRegistering
|
|
}
|
|
let deviceToken = try await getDeviceToken().hexEncodedString()
|
|
PushManager.logger.debug("Got device token: \(deviceToken)")
|
|
let registration: PushProxyRegistration
|
|
do {
|
|
registration = try await register(deviceToken: deviceToken)
|
|
PushManager.logger.debug("Got endpoint: \(registration.endpoint)")
|
|
} catch {
|
|
PushManager.logger.error("Proxy registration failed: \(String(describing: error))")
|
|
throw PushRegistrationError.registeringWithProxy(error)
|
|
}
|
|
pushProxyRegistration = registration
|
|
return registration
|
|
}
|
|
|
|
func unregister() async throws {
|
|
guard let pushProxyRegistration else {
|
|
return
|
|
}
|
|
var url = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
|
url.path = "/app/v1/registrations/\(pushProxyRegistration.id)"
|
|
var request = URLRequest(url: url.url!)
|
|
request.httpMethod = "DELETE"
|
|
let (data, resp) = try await URLSession.shared.data(for: request)
|
|
let status = (resp as! HTTPURLResponse).statusCode
|
|
if (200...299).contains(status) {
|
|
self.pushProxyRegistration = nil
|
|
PushManager.logger.debug("Unregistered from proxy")
|
|
} else {
|
|
PushManager.logger.error("Unregistering: unexpected status \(status)")
|
|
let error = (try? JSONDecoder().decode(ProxyRegistrationError.self, from: data)) ?? ProxyRegistrationError(error: "Unknown error", fields: nil)
|
|
throw PushRegistrationError.unregistering(error)
|
|
}
|
|
}
|
|
|
|
func updateIfNecessary() async {
|
|
guard let pushProxyRegistration else {
|
|
return
|
|
}
|
|
PushManager.logger.debug("Push proxy registration: \(pushProxyRegistration.id, privacy: .public)")
|
|
do {
|
|
let token = try await getDeviceToken().hexEncodedString()
|
|
guard token != pushProxyRegistration.deviceToken else {
|
|
// already up-to-date, nothing to do
|
|
return
|
|
}
|
|
let newRegistration = try await update(registration: pushProxyRegistration, deviceToken: token)
|
|
if pushProxyRegistration.endpoint != newRegistration.endpoint {
|
|
// TODO: update subscriptions if the endpoint's changed
|
|
}
|
|
} catch {
|
|
PushManager.logger.error("Failed to update push registration: \(String(describing: error), privacy: .public)")
|
|
#if canImport(Sentry)
|
|
SentrySDK.capture(error: error)
|
|
#endif
|
|
}
|
|
}
|
|
|
|
private func getDeviceToken() async throws -> Data {
|
|
defer {
|
|
remoteNotificationsRegistrationContinuation = nil
|
|
}
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
remoteNotificationsRegistrationContinuation = continuation
|
|
UIApplication.shared.registerForRemoteNotifications()
|
|
}
|
|
}
|
|
|
|
func didRegisterForRemoteNotifications(deviceToken: Data) {
|
|
remoteNotificationsRegistrationContinuation?.resume(returning: deviceToken)
|
|
}
|
|
|
|
func didFailToRegisterForRemoteNotifications(error: any Error) {
|
|
remoteNotificationsRegistrationContinuation?.resume(throwing: PushRegistrationError.registeringForRemoteNotifications(error))
|
|
}
|
|
|
|
private func register(deviceToken: String) async throws -> PushProxyRegistration {
|
|
var url = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
|
url.path = "/app/v1/registrations"
|
|
var request = URLRequest(url: url.url!)
|
|
request.httpMethod = "POST"
|
|
request.setValue("application/json", forHTTPHeaderField: "content-type")
|
|
request.httpBody = try! JSONEncoder().encode(PushRegistrationParams(transactionID: "TODO", environment: apnsEnvironment, deviceToken: deviceToken, pushVersion: 1))
|
|
let (data, resp) = try await URLSession.shared.data(for: request)
|
|
let status = (resp as! HTTPURLResponse).statusCode
|
|
guard (200...299).contains(status) else {
|
|
PushManager.logger.error("Registering: unexpected status \(status)")
|
|
let error = (try? JSONDecoder().decode(ProxyRegistrationError.self, from: data)) ?? ProxyRegistrationError(error: "Unknown error", fields: [])
|
|
throw error
|
|
}
|
|
return try JSONDecoder().decode(PushProxyRegistration.self, from: data)
|
|
}
|
|
|
|
private func update(registration: PushProxyRegistration, deviceToken: String) async throws -> PushProxyRegistration {
|
|
var url = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
|
|
url.path = "/app/v1/registrations/\(registration.id)"
|
|
var request = URLRequest(url: url.url!)
|
|
request.httpMethod = "PUT"
|
|
request.setValue("application/json", forHTTPHeaderField: "content-type")
|
|
request.httpBody = try! JSONEncoder().encode(PushUpdateParams(environment: apnsEnvironment, deviceToken: deviceToken, pushVersion: 1))
|
|
let (data, resp) = try await URLSession.shared.data(for: request)
|
|
let status = (resp as! HTTPURLResponse).statusCode
|
|
guard (200...299).contains(status) else {
|
|
PushManager.logger.error("Updating: unexpected status \(status)")
|
|
let error = (try? JSONDecoder().decode(ProxyRegistrationError.self, from: data)) ?? ProxyRegistrationError(error: "Unknown error", fields: [])
|
|
throw error
|
|
}
|
|
return try JSONDecoder().decode(PushProxyRegistration.self, from: data)
|
|
}
|
|
}
|
|
|
|
enum PushRegistrationError: LocalizedError {
|
|
case alreadyRegistering
|
|
case registeringForRemoteNotifications(any Error)
|
|
case registeringWithProxy(any Error)
|
|
case unregistering(any Error)
|
|
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .alreadyRegistering:
|
|
"Already registering"
|
|
case .registeringForRemoteNotifications(let error):
|
|
"Remote notifications: \(error.localizedDescription)"
|
|
case .registeringWithProxy(let error):
|
|
"Proxy: \(error.localizedDescription)"
|
|
case .unregistering(let error):
|
|
"Unregistering: \(error.localizedDescription)"
|
|
}
|
|
}
|
|
}
|
|
|
|
struct ProxyRegistrationError: LocalizedError, Decodable {
|
|
let error: String
|
|
let fields: [Field]?
|
|
|
|
var errorDescription: String? {
|
|
if let fields,
|
|
!fields.isEmpty {
|
|
error + ": " + fields.map { "\($0.key): \($0.reason)" }.joined(separator: ", ")
|
|
} else {
|
|
error
|
|
}
|
|
}
|
|
|
|
struct Field: Decodable {
|
|
let key: String
|
|
let reason: String
|
|
}
|
|
}
|
|
|
|
private struct PushRegistrationParams: Encodable {
|
|
let transactionID: String
|
|
let environment: String
|
|
let deviceToken: String
|
|
let pushVersion: Int
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case transactionID = "transaction_id"
|
|
case environment
|
|
case deviceToken = "device_token"
|
|
case pushVersion = "push_version"
|
|
}
|
|
}
|
|
|
|
private struct PushUpdateParams: Encodable {
|
|
let environment: String
|
|
let deviceToken: String
|
|
let pushVersion: Int
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case environment
|
|
case deviceToken = "device_token"
|
|
case pushVersion = "push_version"
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
}
|