IceCubesApp/IceCubesNotifications/NotificationService.swift

228 lines
8.1 KiB
Swift
Raw Normal View History

import AppAccount
2023-01-08 09:22:52 +00:00
import CryptoKit
2023-01-17 10:36:01 +00:00
import Env
import Intents
2023-01-17 10:36:01 +00:00
import KeychainSwift
2023-01-08 09:22:52 +00:00
import Models
2023-02-14 07:54:23 +00:00
import Network
2023-02-14 11:17:27 +00:00
import Notifications
2023-02-18 06:26:48 +00:00
import UIKit
import UserNotifications
2023-01-08 09:22:52 +00:00
2024-10-28 09:57:48 +00:00
extension UNMutableNotificationContent: @unchecked @retroactive Sendable {}
2023-01-17 10:36:01 +00:00
class NotificationService: UNNotificationServiceExtension {
2024-10-28 09:57:48 +00:00
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
let bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent
let provider = NotificationServiceContentProvider(bestAttemptContent: bestAttemptContent)
2024-10-28 09:57:48 +00:00
let casted = unsafeBitCast(
contentHandler,
to: (@Sendable (UNNotificationContent) -> Void).self)
Task {
if let content = await provider.buildContent() {
casted(content)
}
}
}
}
2023-01-17 10:36:01 +00:00
actor NotificationServiceContentProvider {
var bestAttemptContent: UNMutableNotificationContent?
2024-10-28 09:57:48 +00:00
private let pushKeys = PushKeys()
private let keychainAccounts = AppAccount.retrieveAll()
2024-10-28 09:57:48 +00:00
init(bestAttemptContent: UNMutableNotificationContent? = nil) {
self.bestAttemptContent = bestAttemptContent
}
2024-10-28 09:57:48 +00:00
func buildContent() async -> UNMutableNotificationContent? {
2023-02-14 07:54:23 +00:00
if var bestAttemptContent {
let privateKey = pushKeys.notificationsPrivateKeyAsKey
let auth = pushKeys.notificationsAuthKeyAsKey
2024-10-28 09:57:48 +00:00
2023-01-08 09:22:52 +00:00
guard let encodedPayload = bestAttemptContent.userInfo["m"] as? String,
2024-10-28 09:57:48 +00:00
let payload = Data(base64Encoded: encodedPayload.URLSafeBase64ToBase64())
2023-01-17 10:36:01 +00:00
else {
return bestAttemptContent
2023-01-08 09:22:52 +00:00
}
2024-10-28 09:57:48 +00:00
2023-01-08 09:22:52 +00:00
guard let encodedPublicKey = bestAttemptContent.userInfo["k"] as? String,
2024-10-28 09:57:48 +00:00
let publicKeyData = Data(base64Encoded: encodedPublicKey.URLSafeBase64ToBase64()),
let publicKey = try? P256.KeyAgreement.PublicKey(x963Representation: publicKeyData)
2023-01-17 10:36:01 +00:00
else {
return bestAttemptContent
2023-01-08 09:22:52 +00:00
}
2024-10-28 09:57:48 +00:00
2023-01-08 09:22:52 +00:00
guard let encodedSalt = bestAttemptContent.userInfo["s"] as? String,
2024-10-28 09:57:48 +00:00
let salt = Data(base64Encoded: encodedSalt.URLSafeBase64ToBase64())
2023-01-17 10:36:01 +00:00
else {
return bestAttemptContent
2023-01-08 09:22:52 +00:00
}
2024-10-28 09:57:48 +00:00
guard
let plaintextData = NotificationService.decrypt(
payload: payload,
salt: salt,
auth: auth,
privateKey: privateKey,
publicKey: publicKey),
let notification = try? JSONDecoder().decode(
MastodonPushNotification.self, from: plaintextData)
2023-01-17 10:36:01 +00:00
else {
return bestAttemptContent
2023-01-08 09:22:52 +00:00
}
2024-10-28 09:57:48 +00:00
2023-01-08 09:22:52 +00:00
bestAttemptContent.title = notification.title
if keychainAccounts.count > 1 {
bestAttemptContent.subtitle = bestAttemptContent.userInfo["i"] as? String ?? ""
}
2023-01-08 09:22:52 +00:00
bestAttemptContent.body = notification.body.escape()
bestAttemptContent.userInfo["plaintext"] = plaintextData
2024-10-28 09:57:48 +00:00
bestAttemptContent.sound = UNNotificationSound(
named: UNNotificationSoundName(rawValue: "glass.caf"))
let badgeCount = await updateBadgeCoung(notification: notification)
bestAttemptContent.badge = .init(integerLiteral: badgeCount)
2024-10-28 09:57:48 +00:00
2023-01-08 10:13:17 +00:00
if let urlString = notification.icon,
2024-10-28 09:57:48 +00:00
let url = URL(string: urlString)
{
let temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("notification-attachments")
try? FileManager.default.createDirectory(
at: temporaryDirectoryURL, withIntermediateDirectories: true, attributes: nil)
2023-01-08 10:13:17 +00:00
let filename = url.lastPathComponent
let fileURL = temporaryDirectoryURL.appendingPathComponent(filename)
2024-10-28 09:57:48 +00:00
// Warning: Non-sendable type '(any URLSessionTaskDelegate)?' exiting main actor-isolated
// context in call to non-isolated instance method 'data(for:delegate:)' cannot cross actor
// boundary.
// This is on the defaulted-to-nil second parameter of `.data(from:delegate:)`.
// There is a Radar tracking this & others like it.
if let (data, _) = try? await URLSession.shared.data(for: .init(url: url)) {
if let image = UIImage(data: data) {
try? image.pngData()?.write(to: fileURL)
2024-10-28 09:57:48 +00:00
if let remoteNotification = await toRemoteNotification(localNotification: notification),
2024-10-28 09:57:48 +00:00
let type = remoteNotification.supportedType
{
2024-10-28 09:57:48 +00:00
let intent = buildMessageIntent(
remoteNotification: remoteNotification,
currentUser: bestAttemptContent.userInfo["i"] as? String ?? "",
avatarURL: fileURL)
do {
2024-10-28 09:57:48 +00:00
bestAttemptContent =
try bestAttemptContent.updating(from: intent) as! UNMutableNotificationContent
2023-02-14 17:55:26 +00:00
bestAttemptContent.threadIdentifier = remoteNotification.type
2023-02-14 11:17:27 +00:00
if type == .mention {
bestAttemptContent.body = notification.body.escape()
} else {
2024-10-28 09:57:48 +00:00
let newBody =
"\(NSLocalizedString(type.notificationKey(), bundle: .main, comment: ""))\(notification.body.escape())"
bestAttemptContent.body = newBody
}
return bestAttemptContent
} catch {
return bestAttemptContent
}
} else {
2024-10-28 09:57:48 +00:00
if let attachment = try? UNNotificationAttachment(
identifier: filename,
url: fileURL,
options: nil)
{
bestAttemptContent.attachments = [attachment]
2023-01-08 10:13:17 +00:00
}
}
}
} else {
return bestAttemptContent
2023-01-08 10:13:17 +00:00
}
} else {
return bestAttemptContent
2023-01-08 10:13:17 +00:00
}
2023-01-08 09:22:52 +00:00
}
return nil
2023-01-08 09:22:52 +00:00
}
2024-10-28 09:57:48 +00:00
private func toRemoteNotification(localNotification: MastodonPushNotification) async -> Models
.Notification?
{
2023-02-14 07:54:23 +00:00
do {
2024-10-28 09:57:48 +00:00
if let account = keychainAccounts.first(where: {
$0.oauthToken?.accessToken == localNotification.accessToken
}) {
2023-02-14 07:54:23 +00:00
let client = Client(server: account.server, oauthToken: account.oauthToken)
2024-10-28 09:57:48 +00:00
let remoteNotification: Models.Notification = try await client.get(
endpoint: Notifications.notification(id: String(localNotification.notificationID)))
2023-02-14 07:54:23 +00:00
return remoteNotification
}
} catch {
return nil
}
return nil
}
2024-10-28 09:57:48 +00:00
private func buildMessageIntent(
remoteNotification: Models.Notification,
currentUser: String,
avatarURL: URL
) -> INSendMessageIntent {
2023-02-14 07:54:23 +00:00
let handle = INPersonHandle(value: remoteNotification.account.id, type: .unknown)
let avatar = INImage(url: avatarURL)
2024-10-28 09:57:48 +00:00
let sender = INPerson(
personHandle: handle,
nameComponents: nil,
displayName: remoteNotification.account.safeDisplayName,
image: avatar,
contactIdentifier: nil,
customIdentifier: nil)
2023-02-14 11:17:27 +00:00
var recipents: [INPerson]?
var groupName: INSpeakableString?
if keychainAccounts.count > 1 {
2024-10-28 09:57:48 +00:00
let me = INPerson(
personHandle: .init(value: currentUser, type: .unknown),
nameComponents: nil,
displayName: currentUser,
image: nil,
contactIdentifier: nil,
customIdentifier: nil)
2023-02-14 11:17:27 +00:00
recipents = [me, sender]
groupName = .init(spokenPhrase: currentUser)
}
2024-10-28 09:57:48 +00:00
let intent = INSendMessageIntent(
recipients: recipents,
outgoingMessageType: .outgoingMessageText,
content: nil,
speakableGroupName: groupName,
conversationIdentifier: remoteNotification.account.id,
serviceName: nil,
sender: sender,
attachments: nil)
2023-02-14 11:17:27 +00:00
if groupName != nil {
intent.setImage(avatar, forParameterNamed: \.speakableGroupName)
}
2023-02-14 07:54:23 +00:00
return intent
}
2024-10-28 09:57:48 +00:00
@MainActor
private func updateBadgeCoung(notification: MastodonPushNotification) -> Int {
let preferences = UserPreferences.shared
let tokens = AppAccountsManager.shared.pushAccounts.map(\.token)
preferences.reloadNotificationsCount(tokens: tokens)
2024-10-28 09:57:48 +00:00
if let token = keychainAccounts.first(where: {
$0.oauthToken?.accessToken == notification.accessToken
})?.oauthToken {
var currentCount = preferences.notificationsCount[token] ?? 0
currentCount += 1
preferences.notificationsCount[token] = currentCount
}
return preferences.totalNotificationsCount
}
2023-01-08 09:22:52 +00:00
}