blob: 3d1e57bbff8b0e9660c375b1ebf380e6faac7379 [file] [log] [blame]
kkostiuk74d1ae42021-06-17 11:10:15 -04001/*
2 * Copyright (C) 2021-2022 Savoir-faire Linux Inc.
3 *
4 * Author: Kateryna Kostiuk <kateryna.kostiuk@savoirfairelinux.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21import UserNotifications
22import UIKit
23import CallKit
24import Foundation
25import CoreFoundation
26import os
27import Darwin
kkostiuke10e6572022-07-26 15:41:12 -040028import Contacts
kkostiuk74d1ae42021-06-17 11:10:15 -040029
30protocol DarwinNotificationHandler {
31 func listenToMainAppResponse(completion: @escaping (Bool) -> Void)
32 func removeObserver()
33}
34
35enum NotificationField: String {
36 case key
37 case accountId = "to"
38 case aps
39}
40
kkostiuke10e6572022-07-26 15:41:12 -040041enum LocalNotificationType: String {
42 case message
43 case file
44}
45
kkostiuk74d1ae42021-06-17 11:10:15 -040046class NotificationService: UNNotificationServiceExtension {
47
kkostiuke10e6572022-07-26 15:41:12 -040048 private static let localNotificationName = Notification.Name("com.savoirfairelinux.jami.appActive.internal")
kkostiuk74d1ae42021-06-17 11:10:15 -040049
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -040050 private let notificationTimeout = DispatchTimeInterval.seconds(25)
kkostiuk74d1ae42021-06-17 11:10:15 -040051
52 private let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
53
54 private var contentHandler: ((UNNotificationContent) -> Void)?
55 private var bestAttemptContent = UNMutableNotificationContent()
56
57 private var adapterService: AdapterService = AdapterService(withAdapter: Adapter())
58
59 private var accountIsActive = false
60 var tasksCompleted = false /// all values from dht parsed, conversation synchronized if needed and files downloaded
61 var numberOfFiles = 0 /// number of files need to be downloaded
Kateryna Kostiuk3b581712022-07-21 08:42:14 -040062 var numberOfMessages = 0 /// number of scheduled messages
kkostiuk74d1ae42021-06-17 11:10:15 -040063 var syncCompleted = false
64 private let tasksGroup = DispatchGroup()
Kateryna Kostiuk19437652022-08-02 13:02:21 -040065 var accountId = ""
kkostiuke10e6572022-07-26 15:41:12 -040066
67 typealias LocalNotification = (content: UNMutableNotificationContent, type: LocalNotificationType)
68
69 private var pendingLocalNotifications = [String: [LocalNotification]]() /// local notification waiting for name lookup
70 private var pendingCalls = [String: [AnyHashable: Any]]() /// calls waiting for name lookup
71 private var names = [String: String]() /// map of peerId and best name
kkostiuk74d1ae42021-06-17 11:10:15 -040072 // swiftlint:disable cyclomatic_complexity
73 override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
74 self.contentHandler = contentHandler
75 defer {
76 finish()
77 }
78 let requestData = requestToDictionary(request: request)
79 if requestData.isEmpty {
80 return
81 }
82
83 /// if main app is active extension should save notification data and let app handle notification
84 saveData(data: requestData)
85 if appIsActive() {
86 return
87 }
88
Kateryna Kostiuk19437652022-08-02 13:02:21 -040089 guard let account = requestData[NotificationField.accountId.rawValue] else { return }
90 accountId = account
kkostiuke10e6572022-07-26 15:41:12 -040091
kkostiuk74d1ae42021-06-17 11:10:15 -040092 /// app is not active. Querry value from dht
93 guard let proxyURL = getProxyCaches(data: requestData),
Kateryna Kostiukfb10d702022-11-30 14:32:28 -050094 let url = getRequestURL(data: requestData, path: proxyURL) else {
kkostiuk74d1ae42021-06-17 11:10:15 -040095 return
96 }
97 tasksGroup.enter()
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -040098 let defaultSession = URLSession(configuration: .default)
99 let task = defaultSession.dataTask(with: url) {[weak self] (data, _, _) in
kkostiuk74d1ae42021-06-17 11:10:15 -0400100 guard let self = self,
101 let data = data else {
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400102 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400103 return
104 }
105 let str = String(decoding: data, as: UTF8.self)
106 let lines = str.split(whereSeparator: \.isNewline)
107 for line in lines {
108 do {
109 guard let jsonData = line.data(using: .utf8),
110 let map = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: Any],
111 let keyPath = self.getKeyPath(data: requestData),
112 let treatedMessages = self.getTreatedMessagesPath(data: requestData) else {
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400113 self.verifyTasksStatus()
114 return
115 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400116 let result = self.adapterService.decrypt(keyPath: keyPath.path, messagesPath: treatedMessages.path, value: map)
117 let handleCall: (String, String) -> Void = { [weak self] (peerId, hasVideo) in
118 guard let self = self else {
119 return
120 }
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400121 /// jami will be started. Set accounts to not active state
122 if self.accountIsActive {
123 self.accountIsActive = false
124 self.adapterService.stop()
kkostiuk74d1ae42021-06-17 11:10:15 -0400125 }
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400126 var info = request.content.userInfo
127 info["peerId"] = peerId
128 info["hasVideo"] = hasVideo
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400129 let name = self.bestName(accountId: self.accountId, contactId: peerId)
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400130 if name.isEmpty {
131 info["displayName"] = peerId
132 self.pendingCalls[peerId] = info
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400133 self.startAddressLookup(address: peerId, accountId: self.accountId)
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400134 return
135 }
136 info["displayName"] = name
137 self.presentCall(info: info)
kkostiuk74d1ae42021-06-17 11:10:15 -0400138 }
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500139 switch result {
140 case .call(let peerId, let hasVideo):
141 handleCall(peerId, "\(hasVideo)")
142 return
143 case .gitMessage:
144 self.handleGitMessage(handleCall: handleCall)
145 case .unknown:
146 break
147 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400148 } catch {
149 print("serialization failed , \(error)")
150 }
151 }
152 self.verifyTasksStatus()
153 }
154 task.resume()
155 _ = tasksGroup.wait(timeout: .now() + notificationTimeout)
156 }
157
158 override func serviceExtensionTimeWillExpire() {
159 finish()
160 }
161
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500162 private func handleGitMessage(handleCall: @escaping (String, String) -> Void) {
163 /// check if account already acive
164 guard !self.accountIsActive else { return }
165 self.accountIsActive = true
166 self.adapterService.startAccountsWithListener(accountId: self.accountId) { [weak self] event, eventData in
167 guard let self = self else {
168 return
Alireza8154e1f2022-11-26 16:51:24 -0500169 }
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500170 switch event {
171 case .message:
172 self.numberOfMessages += 1
173 self.configureMessageNotification(from: eventData.jamiId, body: eventData.content, accountId: self.accountId, conversationId: eventData.conversationId, groupTitle: "")
174 case .fileTransferDone:
175 if let url = URL(string: eventData.content) {
176 self.configureFileNotification(from: eventData.jamiId, url: url, accountId: self.accountId, conversationId: eventData.conversationId)
177 } else {
178 self.numberOfFiles -= 1
179 self.verifyTasksStatus()
180 }
181 case .syncCompleted:
182 self.syncCompleted = true
183 self.verifyTasksStatus()
184 case .fileTransferInProgress:
185 self.numberOfFiles += 1
186 case .call:
187 handleCall(eventData.jamiId, eventData.content)
188 case .invitation:
189 self.syncCompleted = true
190 self.numberOfMessages += 1
191 self.configureMessageNotification(from: eventData.jamiId,
192 body: eventData.content,
193 accountId: self.accountId,
194 conversationId: eventData.conversationId,
195 groupTitle: eventData.groupTitle)
196 }
Alireza8154e1f2022-11-26 16:51:24 -0500197 }
198 }
199
kkostiuk74d1ae42021-06-17 11:10:15 -0400200 private func verifyTasksStatus() {
201 guard !self.tasksCompleted else { return } /// we already left taskGroup
kkostiuke10e6572022-07-26 15:41:12 -0400202 /// waiting for lookup
203 if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty {
204 return
205 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400206 /// We could finish in two cases:
207 /// 1. we did not start account we are not waiting for the signals from the daemon
208 /// 2. conversation synchronization completed and all files downloaded
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400209 if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400210 self.tasksCompleted = true
211 self.tasksGroup.leave()
212 }
213 }
214
215 private func finish() {
216 if self.accountIsActive {
217 self.accountIsActive = false
218 self.adapterService.stop()
219 }
kkostiuke10e6572022-07-26 15:41:12 -0400220 /// cleanup pending notifications
221 if !self.pendingCalls.isEmpty, let info = self.pendingCalls.first?.value {
222 self.presentCall(info: info)
223 } else {
224 for notifications in pendingLocalNotifications {
225 for notification in notifications.value {
226 self.presentLocalNotification(notification: notification)
227 }
228 }
kkostiukabde7b92022-07-28 13:15:56 -0400229 pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400230 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400231 if let contentHandler = contentHandler {
232 contentHandler(self.bestAttemptContent)
233 }
234 }
235
236 private func appIsActive() -> Bool {
237 let group = DispatchGroup()
238 defer {
239 self.removeObserver()
240 group.leave()
241 }
242 var appIsActive = false
243 group.enter()
244 /// post darwin notification and wait for the answer from the main app. If answer received app is active
245 self.listenToMainAppResponse { _ in
246 appIsActive = true
247 }
248 CFNotificationCenterPostNotification(notificationCenter, CFNotificationName(Constants.notificationReceived), nil, nil, true)
249 /// wait fro 100 milliseconds. If no answer from main app is received app is not active.
250 _ = group.wait(timeout: .now() + 0.3)
251
252 return appIsActive
253 }
254
255 private func saveData(data: [String: String]) {
256 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
257 return
258 }
259 var notificationData = [[String: String]]()
260 if let existingData = userDefaults.object(forKey: Constants.notificationData) as? [[String: String]] {
261 notificationData = existingData
262 }
263 notificationData.append(data)
264 userDefaults.set(notificationData, forKey: Constants.notificationData)
265 }
266
267 private func setNotificationCount(notification: UNMutableNotificationContent) {
268 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
269 return
270 }
271
272 if let count = userDefaults.object(forKey: Constants.notificationsCount) as? NSNumber {
273 let new: NSNumber = count.intValue + 1 as NSNumber
274 notification.badge = new
275 userDefaults.set(new, forKey: Constants.notificationsCount)
276 }
277 }
278
279 private func requestToDictionary(request: UNNotificationRequest) -> [String: String] {
280 var dictionary = [String: String]()
281 let userInfo = request.content.userInfo
282 for key in userInfo.keys {
283 /// "aps" is a field added for alert notification type, so it could be received in the extension. This field is not needed by dht
284 if String(describing: key) == NotificationField.aps.rawValue {
285 continue
286 }
287 if let value = userInfo[key] {
288 let keyString = String(describing: key)
289 let valueString = String(describing: value)
290 dictionary[keyString] = valueString
291 }
292 }
293 return dictionary
294 }
295
296 private func requestedData(request: UNNotificationRequest, map: [String: Any]) -> Bool {
297 guard let userInfo = request.content.userInfo as? [String: Any] else { return false }
298 guard let valueIds = userInfo["valueIds"] as? [String: String],
299 let id = map["id"] else {
300 return false
301 }
302 return valueIds.values.contains("\(id)")
303 }
kkostiuke10e6572022-07-26 15:41:12 -0400304
305 private func bestName(accountId: String, contactId: String) -> String {
306 if let name = self.names[contactId], !name.isEmpty {
307 return name
308 }
309 if let contactProfileName = self.contactProfileName(accountId: accountId, contactId: contactId),
310 !contactProfileName.isEmpty {
311 self.names[contactId] = contactProfileName
312 return contactProfileName
313 }
314 let registeredName = self.adapterService.getNameFor(address: contactId, accountId: accountId)
315 if !registeredName.isEmpty {
316 self.names[contactId] = registeredName
317 }
318 return registeredName
319 }
320
321 private func startAddressLookup(address: String, accountId: String) {
322 var nameServer = self.adapterService.getNameServerFor(accountId: accountId)
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400323 nameServer = ensureURLPrefix(urlString: nameServer)
kkostiuke10e6572022-07-26 15:41:12 -0400324 let urlString = nameServer + "/addr/" + address
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400325 guard let url = URL(string: urlString) else {
326 self.lookupCompleted(address: address, name: nil)
327 return
328 }
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -0400329 let defaultSession = URLSession(configuration: .default)
330 let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400331 guard let self = self else { return }
332 var name: String?
333 defer {
334 self.lookupCompleted(address: address, name: name)
335 }
336 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200,
337 let data = data else {
338 return
339 }
340 do {
341 guard let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String] else { return }
342 if map["name"] != nil {
343 name = map["name"]
344 self.names[address] = name
345 }
346 } catch {
347 print("serialization failed , \(error)")
348 }
349 }
350 task.resume()
351 }
352
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400353 private func ensureURLPrefix(urlString: String) -> String {
354 var urlWithPrefix = urlString
355 if !urlWithPrefix.hasPrefix("http://") && !urlWithPrefix.hasPrefix("https://") {
356 urlWithPrefix = "http://" + urlWithPrefix
357 }
358 return urlWithPrefix
359 }
360
kkostiuke10e6572022-07-26 15:41:12 -0400361 private func lookupCompleted(address: String, name: String?) {
362 for call in pendingCalls where call.key == address {
363 var info = call.value
364 if let name = name {
365 info["displayName"] = name
366 }
367 presentCall(info: info)
kkostiuke10e6572022-07-26 15:41:12 -0400368 return
369 }
370 for pending in pendingLocalNotifications where pending.key == address {
371 let notifications = pending.value
372 for notification in notifications {
373 if let name = name {
374 notification.content.title = name
375 }
376 presentLocalNotification(notification: notification)
377 }
378 pendingLocalNotifications.removeValue(forKey: address)
379 }
380 }
381
382 private func needUpdateNotification(notification: LocalNotification, peerId: String, accountId: String) {
383 if var pending = pendingLocalNotifications[peerId] {
384 pending.append(notification)
385 pendingLocalNotifications[peerId] = pending
386 } else {
387 pendingLocalNotifications[peerId] = [notification]
388 }
389 startAddressLookup(address: peerId, accountId: accountId)
390 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400391}
392// MARK: paths
393extension NotificationService {
394
395 private func getRequestURL(data: [String: String], proxyURL: URL) -> URL? {
396 guard let key = data[NotificationField.key.rawValue] else {
397 return nil
398 }
399 return proxyURL.appendingPathComponent(key)
400 }
401
Kateryna Kostiukfb10d702022-11-30 14:32:28 -0500402 private func getRequestURL(data: [String: String], path: URL) -> URL? {
403 guard let key = data[NotificationField.key.rawValue],
404 let jsonData = NSData(contentsOf: path) as? Data else {
405 return nil
406 }
407 guard let map = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: String],
408 var proxyAddress = map.first?.value else {
409 return nil
410 }
411
412 proxyAddress = ensureURLPrefix(urlString: proxyAddress)
413 guard let urlPrpxy = URL(string: proxyAddress) else { return nil }
414 return urlPrpxy.appendingPathComponent(key)
415 }
416
kkostiuk74d1ae42021-06-17 11:10:15 -0400417 private func getKeyPath(data: [String: String]) -> URL? {
418 guard let documentsPath = Constants.documentsPath,
419 let accountId = data[NotificationField.accountId.rawValue] else {
420 return nil
421 }
422 return documentsPath.appendingPathComponent(accountId).appendingPathComponent("ring_device.key")
423 }
424
425 private func getTreatedMessagesPath(data: [String: String]) -> URL? {
426 guard let cachesPath = Constants.cachesPath,
427 let accountId = data[NotificationField.accountId.rawValue] else {
428 return nil
429 }
430 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("treatedMessages")
431 }
432
433 private func getProxyCaches(data: [String: String]) -> URL? {
434 guard let cachesPath = Constants.cachesPath,
435 let accountId = data[NotificationField.accountId.rawValue] else {
436 return nil
437 }
438 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("dhtproxy")
439 }
kkostiuke10e6572022-07-26 15:41:12 -0400440
441 private func contactProfileName(accountId: String, contactId: String) -> String? {
442 guard let documents = Constants.documentsPath else { return nil }
443 let profileURI = "ring:" + contactId
444 let profilePath = documents.path + "/" + "\(accountId)" + "/profiles/" + "\(Data(profileURI.utf8).base64EncodedString()).vcf"
445 if !FileManager.default.fileExists(atPath: profilePath) { return nil }
446
447 guard let data = FileManager.default.contents(atPath: profilePath),
448 let vCards = try? CNContactVCardSerialization.contacts(with: data),
Kateryna Kostiuk1efd0012022-09-13 12:08:36 -0400449 let vCard = vCards.first else { return nil }
kkostiuke10e6572022-07-26 15:41:12 -0400450 return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName
451 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400452}
453
454// MARK: DarwinNotificationHandler
455extension NotificationService: DarwinNotificationHandler {
456 func listenToMainAppResponse(completion: @escaping (Bool) -> Void) {
457 let observer = Unmanaged.passUnretained(self).toOpaque()
458 CFNotificationCenterAddObserver(notificationCenter,
459 observer, { (_, _, _, _, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400460 NotificationCenter.default.post(name: NotificationService.localNotificationName,
kkostiuk74d1ae42021-06-17 11:10:15 -0400461 object: nil,
462 userInfo: nil)
463 },
464 Constants.notificationAppIsActive,
465 nil,
466 .deliverImmediately)
kkostiuke10e6572022-07-26 15:41:12 -0400467 NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in
kkostiuk74d1ae42021-06-17 11:10:15 -0400468 completion(true)
469 }
470 }
471
472 func removeObserver() {
473 let observer = Unmanaged.passUnretained(self).toOpaque()
474 CFNotificationCenterRemoveEveryObserver(notificationCenter, observer)
kkostiuke10e6572022-07-26 15:41:12 -0400475 NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil)
kkostiuk74d1ae42021-06-17 11:10:15 -0400476 }
477
478}
479
480// MARK: present notifications
481extension NotificationService {
482 private func createAttachment(identifier: String, image: UIImage, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? {
483 let fileManager = FileManager.default
484 let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
485 let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
486 do {
487 try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
488 let imageFileIdentifier = identifier
489 let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
490 let imageData = UIImage.pngData(image)
491 try imageData()?.write(to: fileURL)
492 let imageAttachment = try UNNotificationAttachment.init(identifier: identifier, url: fileURL, options: options)
493 return imageAttachment
494 } catch {}
495 return nil
496 }
497
kkostiuk8e397cd2022-07-27 15:08:10 -0400498 private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400499 let content = UNMutableNotificationContent()
kkostiuke10e6572022-07-26 15:41:12 -0400500 content.sound = UNNotificationSound.default
kkostiuk74d1ae42021-06-17 11:10:15 -0400501 let imageName = url.lastPathComponent
kkostiuk74d1ae42021-06-17 11:10:15 -0400502 content.body = imageName
kkostiuk8e397cd2022-07-27 15:08:10 -0400503 var data = [String: String]()
504 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
505 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
506 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
507 content.userInfo = data
kkostiuk74d1ae42021-06-17 11:10:15 -0400508 if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) {
509 content.attachments = [ attachement ]
510 }
kkostiuke10e6572022-07-26 15:41:12 -0400511 let title = self.bestName(accountId: accountId, contactId: from)
512 if title.isEmpty {
513 content.title = from
514 needUpdateNotification(notification: LocalNotification(content, .file), peerId: from, accountId: accountId)
515 } else {
516 content.title = title
517 presentLocalNotification(notification: LocalNotification(content, .file))
518 }
519 }
520
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400521 private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String, groupTitle: String) {
kkostiuke10e6572022-07-26 15:41:12 -0400522 let content = UNMutableNotificationContent()
523 content.body = body
kkostiuk74d1ae42021-06-17 11:10:15 -0400524 content.sound = UNNotificationSound.default
kkostiuk8e397cd2022-07-27 15:08:10 -0400525 var data = [String: String]()
526 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
527 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
528 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
529 content.userInfo = data
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400530 let title = !groupTitle.isEmpty ? groupTitle : self.bestName(accountId: accountId, contactId: from)
kkostiuke10e6572022-07-26 15:41:12 -0400531 if title.isEmpty {
532 content.title = from
533 needUpdateNotification(notification: LocalNotification(content, .message), peerId: from, accountId: accountId)
534 } else {
535 content.title = title
536 presentLocalNotification(notification: LocalNotification(content, .message))
537 }
538 }
539
540 private func presentLocalNotification(notification: LocalNotification) {
541 let content = notification.content
kkostiuk74d1ae42021-06-17 11:10:15 -0400542 setNotificationCount(notification: content)
543 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400544 let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)
545 UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in
kkostiuke10e6572022-07-26 15:41:12 -0400546 if notification.type == .message {
547 self?.numberOfMessages -= 1
548 } else {
549 self?.numberOfFiles -= 1
550 }
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400551 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400552 if let error = error {
553 print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
554 }
555 }
556 }
557
kkostiuke10e6572022-07-26 15:41:12 -0400558 private func presentCall(info: [AnyHashable: Any]) {
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400559 CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in
560 print("NotificationService", "Did report voip notification, error: \(String(describing: error))")
561 })
kkostiukabde7b92022-07-28 13:15:56 -0400562 self.pendingCalls.removeAll()
563 self.pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400564 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400565 }
566}