Tusker/Packages/PushNotifications/Sources/PushNotifications/PushSubscription.swift

81 lines
2.7 KiB
Swift

//
// PushSubscription.swift
// PushNotifications
//
// Created by Shadowfacts on 4/7/24.
//
import Foundation
import CryptoKit
public struct PushSubscription {
public let accountID: String
public internal(set) var endpoint: URL
public let secretKey: P256.KeyAgreement.PrivateKey
public let authSecret: Data
public var alerts: Alerts
public var policy: Policy
var defaultsDict: [String: Any] {
[
"accountID": accountID,
"endpoint": endpoint.absoluteString,
"secretKey": secretKey.rawRepresentation,
"authSecret": authSecret,
"alerts": alerts.rawValue,
"policy": policy.rawValue
]
}
init?(defaultsDict: [String: Any]) {
guard let accountID = defaultsDict["accountID"] as? String,
let endpoint = (defaultsDict["endpoint"] as? String).flatMap(URL.init(string:)),
let secretKey = (defaultsDict["secretKey"] as? Data).flatMap({ try? P256.KeyAgreement.PrivateKey(rawRepresentation: $0) }),
let authSecret = defaultsDict["authSecret"] as? Data,
let alerts = defaultsDict["alerts"] as? Int,
let policy = (defaultsDict["policy"] as? String).flatMap(Policy.init(rawValue:)) else {
return nil
}
self.accountID = accountID
self.endpoint = endpoint
self.secretKey = secretKey
self.authSecret = authSecret
self.alerts = Alerts(rawValue: alerts)
self.policy = policy
}
init(accountID: String, endpoint: URL, secretKey: P256.KeyAgreement.PrivateKey, authSecret: Data, alerts: Alerts, policy: Policy) {
self.accountID = accountID
self.endpoint = endpoint
self.secretKey = secretKey
self.authSecret = authSecret
self.alerts = alerts
self.policy = policy
}
public enum Policy: String, CaseIterable, Identifiable {
case all, followed, followers
public var id: some Hashable {
self
}
}
public struct Alerts: OptionSet, Hashable {
public static let mention = Alerts(rawValue: 1 << 0)
public static let status = Alerts(rawValue: 1 << 1)
public static let reblog = Alerts(rawValue: 1 << 2)
public static let follow = Alerts(rawValue: 1 << 3)
public static let followRequest = Alerts(rawValue: 1 << 4)
public static let favorite = Alerts(rawValue: 1 << 5)
public static let poll = Alerts(rawValue: 1 << 6)
public static let update = Alerts(rawValue: 1 << 7)
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
}