mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 19:58:26 +00:00
* core, ui: chatItemUpdated event has the previous item Apps change counters by the difference between the previous and the new item, and insert an updated item only when the update created it. * core, ui: a recreated item is sent as newChatItems An update of a locally deleted message creates it again and sends it as a new item, so chatItemUpdated always has the previous item and the apps never insert on an update. * core, ui: previous item is optional and has no chat info Events from older remote hosts decode without it; the apps then insert the item if it is not loaded and change no counters. * core: catch-up subscriber gets an edited history post as a new item * ui: updates in another profile do not notify, as on iOS * core, ui: one type for the updated item and its previous version AChatItemUpdate has the chat info, the new item and the previous item with the same chat type and direction. Its JSON is the JSON of AChatItem with an optional prevChatItem; the event keeps the key chatItem. * core: tested event key, previous item reactions, cleared mentions One function renames the event field to chatItem for JSON and docs, and the test checks the wire key and compatibility with AChatItem. The previous item of a direct edit has its reactions. An edit that removes all mentions sends the item without them. * core: test that an edit removing mentions sends the item without them * core: event JSON field mapping inline in the TH options, for the Windows build * core: file chat item update checked in one store transaction * core: test that a file reset by unknown relays sends its previous item * core, ui: chatItemUpdated event key chatItemUpdate * core, ui: chatItemUpdated always has the previous item * ci: mcp scope tests the plugin with its published dependencies * core: mention of the user follows edits of a group message * core: previous item of a prohibited file is read before the prohibition * android, desktop: missed call check inline, counter test with core pairs * ios: spec link of the chatItemUpdated event * core: mention edits in support chats update members requiring attention * core: one rule for the mention of the user in received and edited items * core: record item events of updates for app tests * android, desktop: remove the missed call notification of updates, never shown * android, desktop: test item updates on events recorded by the core * ios: test item updates on events recorded by the core * docs: plan of app tests of item updates, recording tests in the CI guide * core: record the response to an update after its item status is final * ios: notification manager replaceable in tests * ios: test notifications of updates and the update response * android, desktop: test the recorded update response * docs: plan with iOS notifications and the update response * core: recorded response to an update of a sent message
295 lines
13 KiB
Swift
295 lines
13 KiB
Swift
//
|
|
// NtfManager.swift
|
|
// SimpleX
|
|
//
|
|
// Created by Evgeny Poberezkin on 08/02/2022.
|
|
// Copyright © 2022 SimpleX Chat. All rights reserved.
|
|
//
|
|
// Spec: spec/services/notifications.md
|
|
|
|
import Foundation
|
|
import UserNotifications
|
|
import UIKit
|
|
import SimpleXChat
|
|
|
|
let ntfActionAcceptContact = "NTF_ACT_ACCEPT_CONTACT"
|
|
let ntfActionAcceptCall = "NTF_ACT_ACCEPT_CALL"
|
|
let ntfActionRejectCall = "NTF_ACT_REJECT_CALL"
|
|
|
|
private let ntfTimeInterval: TimeInterval = 1
|
|
|
|
enum NtfCallAction {
|
|
case accept
|
|
case reject
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#NtfManager
|
|
class NtfManager: NSObject, UNUserNotificationCenterDelegate, ObservableObject {
|
|
static var shared = NtfManager()
|
|
|
|
public var navigatingToChat = false
|
|
private var granted = false
|
|
private var prevNtfTime: Dictionary<ChatId, Date> = [:]
|
|
|
|
override init() {
|
|
super.init()
|
|
UNUserNotificationCenter.current().delegate = self
|
|
}
|
|
|
|
// Handle notification when app is in background
|
|
func userNotificationCenter(_ center: UNUserNotificationCenter,
|
|
didReceive response: UNNotificationResponse,
|
|
withCompletionHandler handler: () -> Void) {
|
|
logger.debug("NtfManager.userNotificationCenter: didReceive")
|
|
if appStateGroupDefault.get() == .active {
|
|
processNotificationResponse(response)
|
|
} else {
|
|
logger.debug("NtfManager.userNotificationCenter: remember response in model")
|
|
ChatModel.shared.notificationResponse = response
|
|
}
|
|
handler()
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#processNotificationResponse
|
|
func processNotificationResponse(_ ntfResponse: UNNotificationResponse) {
|
|
let chatModel = ChatModel.shared
|
|
let content = ntfResponse.notification.request.content
|
|
let action = ntfResponse.actionIdentifier
|
|
logger.debug("NtfManager.processNotificationResponse: didReceive: action \(action), categoryIdentifier \(content.categoryIdentifier)")
|
|
if let userId = content.userInfo["userId"] as? Int64,
|
|
userId != chatModel.currentUser?.userId {
|
|
logger.debug("NtfManager.processNotificationResponse changeActiveUser")
|
|
changeActiveUser(userId, viewPwd: nil)
|
|
}
|
|
if content.categoryIdentifier == ntfCategoryContactRequest && action == ntfActionAcceptContact,
|
|
let chatId = content.userInfo["chatId"] as? String {
|
|
if case let .contactRequest(contactRequest) = chatModel.getChat(chatId)?.chatInfo {
|
|
Task { await acceptContactRequest(incognito: false, contactRequestId: contactRequest.apiId) }
|
|
} else {
|
|
chatModel.ntfContactRequest = NTFContactRequest(chatId: chatId)
|
|
}
|
|
} else if let (chatId, ntfAction) = ntfCallAction(content, action) {
|
|
if let invitation = chatModel.callInvitations.removeValue(forKey: chatId) {
|
|
CallController.shared.callAction(invitation: invitation, action: ntfAction)
|
|
} else {
|
|
chatModel.ntfCallInvitationAction = (chatId, ntfAction)
|
|
}
|
|
} else {
|
|
if let chatId = content.targetContentIdentifier {
|
|
self.navigatingToChat = true
|
|
ItemsModel.shared.loadOpenChat(chatId) {
|
|
self.navigatingToChat = false
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func ntfCallAction(_ content: UNNotificationContent, _ action: String) -> (ChatId, NtfCallAction)? {
|
|
if content.categoryIdentifier == ntfCategoryCallInvitation,
|
|
let chatId = content.userInfo["chatId"] as? String {
|
|
if action == ntfActionAcceptCall {
|
|
return (chatId, .accept)
|
|
} else if action == ntfActionRejectCall {
|
|
return (chatId, .reject)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Handle notification when the app is in foreground
|
|
func userNotificationCenter(_ center: UNUserNotificationCenter,
|
|
willPresent notification: UNNotification,
|
|
withCompletionHandler handler: (UNNotificationPresentationOptions) -> Void) {
|
|
logger.debug("NtfManager.userNotificationCenter: willPresent")
|
|
handler(presentationOptions(notification.request.content))
|
|
}
|
|
|
|
private func presentationOptions(_ content: UNNotificationContent) -> UNNotificationPresentationOptions {
|
|
let model = ChatModel.shared
|
|
if UIApplication.shared.applicationState == .active {
|
|
switch content.categoryIdentifier {
|
|
case ntfCategoryMessageReceived:
|
|
let recent = recentInTheSameChat(content)
|
|
let userId = content.userInfo["userId"] as? Int64
|
|
if let userId = userId, let user = model.getUser(userId), !user.showNotifications {
|
|
// ... inactive user with disabled notifications
|
|
return []
|
|
} else if model.chatId == nil {
|
|
// in the chat list...
|
|
if model.currentUser?.userId == userId {
|
|
// ... of the active user
|
|
return recent ? [] : [.sound, .list]
|
|
} else {
|
|
// ... of inactive user
|
|
return recent ? [.banner] : [.sound, .banner, .list]
|
|
}
|
|
} else if model.chatId == content.targetContentIdentifier {
|
|
// in the current chat
|
|
return recent ? [] : [.sound, .list]
|
|
} else {
|
|
// in another chat
|
|
return recent ? [.banner, .list] : [.sound, .banner, .list]
|
|
}
|
|
// this notification is deliverd from the notifications server
|
|
// when the app is in foreground it does not need to be shown
|
|
case ntfCategoryCheckMessage: return []
|
|
case ntfCategoryCallInvitation: return []
|
|
default: return [.sound, .banner, .list]
|
|
}
|
|
} else {
|
|
return content.categoryIdentifier == ntfCategoryCheckMessage ? [] : [.sound, .banner, .list]
|
|
}
|
|
}
|
|
|
|
private func recentInTheSameChat(_ content: UNNotificationContent) -> Bool {
|
|
let now = Date.now
|
|
if let chatId = content.targetContentIdentifier {
|
|
var res: Bool = false
|
|
if let t = prevNtfTime[chatId] { res = t.distance(to: now) < 30 }
|
|
prevNtfTime[chatId] = now
|
|
return res
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#registerCategories
|
|
func registerCategories() {
|
|
logger.debug("NtfManager.registerCategories")
|
|
UNUserNotificationCenter.current().setNotificationCategories([
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryContactRequest,
|
|
actions: [
|
|
UNNotificationAction(
|
|
identifier: ntfActionAcceptContact,
|
|
title: NSLocalizedString("Accept", comment: "accept contact request via notification"),
|
|
options: .foreground
|
|
)
|
|
],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("New contact request", comment: "notification")
|
|
),
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryContactConnected,
|
|
actions: [],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("Contact is connected", comment: "notification")
|
|
),
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryMessageReceived,
|
|
actions: [],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("New message", comment: "notification")
|
|
),
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryCallInvitation,
|
|
actions: [
|
|
UNNotificationAction(
|
|
identifier: ntfActionAcceptCall,
|
|
title: NSLocalizedString("Accept", comment: "accept incoming call via notification"),
|
|
options: .foreground
|
|
),
|
|
UNNotificationAction(
|
|
identifier: ntfActionRejectCall,
|
|
title: NSLocalizedString("Reject", comment: "reject incoming call via notification")
|
|
)
|
|
],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("Incoming call", comment: "notification")
|
|
),
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryConnectionEvent,
|
|
actions: [],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("SimpleX encrypted message or connection event", comment: "notification")
|
|
),
|
|
UNNotificationCategory(
|
|
identifier: ntfCategoryManyEvents,
|
|
actions: [],
|
|
intentIdentifiers: [],
|
|
hiddenPreviewsBodyPlaceholder: NSLocalizedString("New events", comment: "notification")
|
|
)
|
|
])
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#requestAuthorization
|
|
func requestAuthorization(onDeny denied: (()-> Void)? = nil, onAuthorized authorized: (()-> Void)? = nil, whenDone: (() -> Void)? = nil) {
|
|
logger.debug("NtfManager.requestAuthorization")
|
|
let center = UNUserNotificationCenter.current()
|
|
center.getNotificationSettings { settings in
|
|
switch settings.authorizationStatus {
|
|
case .denied:
|
|
denied?()
|
|
whenDone?()
|
|
case .authorized:
|
|
self.granted = true
|
|
authorized?()
|
|
whenDone?()
|
|
default:
|
|
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
|
|
if let error = error {
|
|
logger.error("NtfManager.requestAuthorization error \(error.localizedDescription)")
|
|
} else {
|
|
self.granted = granted
|
|
authorized?()
|
|
}
|
|
whenDone?()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#notifyContactRequest
|
|
func notifyContactRequest(_ user: any UserLike, _ contactRequest: UserContactRequest) {
|
|
logger.debug("NtfManager.notifyContactRequest")
|
|
addNotification(createContactRequestNtf(user, contactRequest, 0))
|
|
}
|
|
|
|
func notifyContactConnected(_ user: any UserLike, _ contact: Contact) {
|
|
logger.debug("NtfManager.notifyContactConnected")
|
|
addNotification(createContactConnectedNtf(user, contact, 0))
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#notifyMessageReceived
|
|
func notifyMessageReceived(_ user: any UserLike, _ cInfo: ChatInfo, _ cItem: ChatItem) {
|
|
logger.debug("NtfManager.notifyMessageReceived")
|
|
if cInfo.ntfsEnabled(chatItem: cItem) {
|
|
addNotification(createMessageReceivedNtf(user, cInfo, cItem, 0))
|
|
}
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#notifyCallInvitation
|
|
func notifyCallInvitation(_ invitation: RcvCallInvitation) {
|
|
logger.debug("NtfManager.notifyCallInvitation")
|
|
addNotification(createCallInvitationNtf(invitation, 0))
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#setNtfBadgeCount
|
|
func setNtfBadgeCount(_ count: Int) {
|
|
UIApplication.shared.applicationIconBadgeNumber = count
|
|
ntfBadgeCountGroupDefault.set(count)
|
|
}
|
|
|
|
// Spec: spec/services/notifications.md#changeNtfBadgeCount
|
|
func changeNtfBadgeCount(by count: Int = 1) {
|
|
setNtfBadgeCount(max(0, UIApplication.shared.applicationIconBadgeNumber + count))
|
|
}
|
|
|
|
func addNotification(_ content: UNMutableNotificationContent) {
|
|
if !granted { return }
|
|
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: ntfTimeInterval, repeats: false)
|
|
let request = UNNotificationRequest(identifier: appNotificationId, content: content, trigger: trigger)
|
|
UNUserNotificationCenter.current().add(request) { error in
|
|
if let error = error { logger.error("addNotification error: \(error.localizedDescription)") }
|
|
}
|
|
}
|
|
|
|
func removeAllNotifications() async {
|
|
let nc = UNUserNotificationCenter.current()
|
|
let settings = await nc.notificationSettings()
|
|
if settings.authorizationStatus == .authorized {
|
|
nc.removeAllPendingNotificationRequests()
|
|
nc.removeAllDeliveredNotifications()
|
|
}
|
|
}
|
|
}
|