blob: 1b8d00d74f61b36a0b7982857b3673e2719ab503 [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),
kkostiuk53c55ff2022-07-18 15:02:17 -040094 var proxy = try? String(contentsOf: proxyURL, encoding: .utf8) else {
kkostiuk74d1ae42021-06-17 11:10:15 -040095 return
96 }
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -040097 proxy = ensureURLPrefix(urlString: proxy)
kkostiuk74d1ae42021-06-17 11:10:15 -040098 guard let urlPrpxy = URL(string: proxy),
99 let url = getRequestURL(data: requestData, proxyURL: urlPrpxy) else {
100 return
101 }
102 tasksGroup.enter()
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -0400103 let defaultSession = URLSession(configuration: .default)
104 let task = defaultSession.dataTask(with: url) {[weak self] (data, _, _) in
kkostiuk74d1ae42021-06-17 11:10:15 -0400105 guard let self = self,
106 let data = data else {
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400107 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400108 return
109 }
110 let str = String(decoding: data, as: UTF8.self)
111 let lines = str.split(whereSeparator: \.isNewline)
112 for line in lines {
113 do {
114 guard let jsonData = line.data(using: .utf8),
115 let map = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: Any],
116 let keyPath = self.getKeyPath(data: requestData),
117 let treatedMessages = self.getTreatedMessagesPath(data: requestData) else {
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400118 self.verifyTasksStatus()
119 return
120 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400121 let result = self.adapterService.decrypt(keyPath: keyPath.path, messagesPath: treatedMessages.path, value: map)
122 let handleCall: (String, String) -> Void = { [weak self] (peerId, hasVideo) in
123 guard let self = self else {
124 return
125 }
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400126 /// jami will be started. Set accounts to not active state
127 if self.accountIsActive {
128 self.accountIsActive = false
129 self.adapterService.stop()
kkostiuk74d1ae42021-06-17 11:10:15 -0400130 }
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400131 var info = request.content.userInfo
132 info["peerId"] = peerId
133 info["hasVideo"] = hasVideo
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400134 let name = self.bestName(accountId: self.accountId, contactId: peerId)
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400135 if name.isEmpty {
136 info["displayName"] = peerId
137 self.pendingCalls[peerId] = info
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400138 self.startAddressLookup(address: peerId, accountId: self.accountId)
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400139 return
140 }
141 info["displayName"] = name
142 self.presentCall(info: info)
kkostiuk74d1ae42021-06-17 11:10:15 -0400143 }
144 switch result {
145 case .call(let peerId, let hasVideo):
146 handleCall(peerId, "\(hasVideo)")
kkostiukabde7b92022-07-28 13:15:56 -0400147 return
kkostiuk74d1ae42021-06-17 11:10:15 -0400148 case .gitMessage:
149 /// check if account already acive
150 guard !self.accountIsActive else { break }
151 self.accountIsActive = true
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400152 self.adapterService.startAccountsWithListener(accountId: self.accountId) { [weak self] event, eventData in
kkostiuk74d1ae42021-06-17 11:10:15 -0400153 guard let self = self else {
154 return
155 }
156 switch event {
157 case .message:
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400158 self.numberOfMessages += 1
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400159 self.configureMessageNotification(from: eventData.jamiId, body: eventData.content, accountId: self.accountId, conversationId: eventData.conversationId)
kkostiuk74d1ae42021-06-17 11:10:15 -0400160 case .fileTransferDone:
161 if let url = URL(string: eventData.content) {
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400162 self.configureFileNotification(from: eventData.jamiId, url: url, accountId: self.accountId, conversationId: eventData.conversationId)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400163 } else {
164 self.numberOfFiles -= 1
165 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400166 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400167 case .syncCompleted:
168 self.syncCompleted = true
169 self.verifyTasksStatus()
170 case .fileTransferInProgress:
171 self.numberOfFiles += 1
172 case .call:
173 handleCall(eventData.jamiId, eventData.content)
174 }
175 }
176 case .unknown:
177 break
178 }
179 } catch {
180 print("serialization failed , \(error)")
181 }
182 }
183 self.verifyTasksStatus()
184 }
185 task.resume()
186 _ = tasksGroup.wait(timeout: .now() + notificationTimeout)
187 }
188
189 override func serviceExtensionTimeWillExpire() {
190 finish()
191 }
192
193 private func verifyTasksStatus() {
194 guard !self.tasksCompleted else { return } /// we already left taskGroup
kkostiuke10e6572022-07-26 15:41:12 -0400195 /// waiting for lookup
196 if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty {
197 return
198 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400199 /// We could finish in two cases:
200 /// 1. we did not start account we are not waiting for the signals from the daemon
201 /// 2. conversation synchronization completed and all files downloaded
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400202 if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400203 self.tasksCompleted = true
204 self.tasksGroup.leave()
205 }
206 }
207
208 private func finish() {
209 if self.accountIsActive {
210 self.accountIsActive = false
211 self.adapterService.stop()
212 }
kkostiuke10e6572022-07-26 15:41:12 -0400213 /// cleanup pending notifications
214 if !self.pendingCalls.isEmpty, let info = self.pendingCalls.first?.value {
215 self.presentCall(info: info)
216 } else {
217 for notifications in pendingLocalNotifications {
218 for notification in notifications.value {
219 self.presentLocalNotification(notification: notification)
220 }
221 }
kkostiukabde7b92022-07-28 13:15:56 -0400222 pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400223 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400224 if let contentHandler = contentHandler {
225 contentHandler(self.bestAttemptContent)
226 }
227 }
228
229 private func appIsActive() -> Bool {
230 let group = DispatchGroup()
231 defer {
232 self.removeObserver()
233 group.leave()
234 }
235 var appIsActive = false
236 group.enter()
237 /// post darwin notification and wait for the answer from the main app. If answer received app is active
238 self.listenToMainAppResponse { _ in
239 appIsActive = true
240 }
241 CFNotificationCenterPostNotification(notificationCenter, CFNotificationName(Constants.notificationReceived), nil, nil, true)
242 /// wait fro 100 milliseconds. If no answer from main app is received app is not active.
243 _ = group.wait(timeout: .now() + 0.3)
244
245 return appIsActive
246 }
247
248 private func saveData(data: [String: String]) {
249 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
250 return
251 }
252 var notificationData = [[String: String]]()
253 if let existingData = userDefaults.object(forKey: Constants.notificationData) as? [[String: String]] {
254 notificationData = existingData
255 }
256 notificationData.append(data)
257 userDefaults.set(notificationData, forKey: Constants.notificationData)
258 }
259
260 private func setNotificationCount(notification: UNMutableNotificationContent) {
261 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
262 return
263 }
264
265 if let count = userDefaults.object(forKey: Constants.notificationsCount) as? NSNumber {
266 let new: NSNumber = count.intValue + 1 as NSNumber
267 notification.badge = new
268 userDefaults.set(new, forKey: Constants.notificationsCount)
269 }
270 }
271
272 private func requestToDictionary(request: UNNotificationRequest) -> [String: String] {
273 var dictionary = [String: String]()
274 let userInfo = request.content.userInfo
275 for key in userInfo.keys {
276 /// "aps" is a field added for alert notification type, so it could be received in the extension. This field is not needed by dht
277 if String(describing: key) == NotificationField.aps.rawValue {
278 continue
279 }
280 if let value = userInfo[key] {
281 let keyString = String(describing: key)
282 let valueString = String(describing: value)
283 dictionary[keyString] = valueString
284 }
285 }
286 return dictionary
287 }
288
289 private func requestedData(request: UNNotificationRequest, map: [String: Any]) -> Bool {
290 guard let userInfo = request.content.userInfo as? [String: Any] else { return false }
291 guard let valueIds = userInfo["valueIds"] as? [String: String],
292 let id = map["id"] else {
293 return false
294 }
295 return valueIds.values.contains("\(id)")
296 }
kkostiuke10e6572022-07-26 15:41:12 -0400297
298 private func bestName(accountId: String, contactId: String) -> String {
299 if let name = self.names[contactId], !name.isEmpty {
300 return name
301 }
302 if let contactProfileName = self.contactProfileName(accountId: accountId, contactId: contactId),
303 !contactProfileName.isEmpty {
304 self.names[contactId] = contactProfileName
305 return contactProfileName
306 }
307 let registeredName = self.adapterService.getNameFor(address: contactId, accountId: accountId)
308 if !registeredName.isEmpty {
309 self.names[contactId] = registeredName
310 }
311 return registeredName
312 }
313
314 private func startAddressLookup(address: String, accountId: String) {
315 var nameServer = self.adapterService.getNameServerFor(accountId: accountId)
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400316 nameServer = ensureURLPrefix(urlString: nameServer)
kkostiuke10e6572022-07-26 15:41:12 -0400317 let urlString = nameServer + "/addr/" + address
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400318 guard let url = URL(string: urlString) else {
319 self.lookupCompleted(address: address, name: nil)
320 return
321 }
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -0400322 let defaultSession = URLSession(configuration: .default)
323 let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400324 guard let self = self else { return }
325 var name: String?
326 defer {
327 self.lookupCompleted(address: address, name: name)
328 }
329 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200,
330 let data = data else {
331 return
332 }
333 do {
334 guard let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String] else { return }
335 if map["name"] != nil {
336 name = map["name"]
337 self.names[address] = name
338 }
339 } catch {
340 print("serialization failed , \(error)")
341 }
342 }
343 task.resume()
344 }
345
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400346 private func ensureURLPrefix(urlString: String) -> String {
347 var urlWithPrefix = urlString
348 if !urlWithPrefix.hasPrefix("http://") && !urlWithPrefix.hasPrefix("https://") {
349 urlWithPrefix = "http://" + urlWithPrefix
350 }
351 return urlWithPrefix
352 }
353
kkostiuke10e6572022-07-26 15:41:12 -0400354 private func lookupCompleted(address: String, name: String?) {
355 for call in pendingCalls where call.key == address {
356 var info = call.value
357 if let name = name {
358 info["displayName"] = name
359 }
360 presentCall(info: info)
kkostiuke10e6572022-07-26 15:41:12 -0400361 return
362 }
363 for pending in pendingLocalNotifications where pending.key == address {
364 let notifications = pending.value
365 for notification in notifications {
366 if let name = name {
367 notification.content.title = name
368 }
369 presentLocalNotification(notification: notification)
370 }
371 pendingLocalNotifications.removeValue(forKey: address)
372 }
373 }
374
375 private func needUpdateNotification(notification: LocalNotification, peerId: String, accountId: String) {
376 if var pending = pendingLocalNotifications[peerId] {
377 pending.append(notification)
378 pendingLocalNotifications[peerId] = pending
379 } else {
380 pendingLocalNotifications[peerId] = [notification]
381 }
382 startAddressLookup(address: peerId, accountId: accountId)
383 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400384}
385// MARK: paths
386extension NotificationService {
387
388 private func getRequestURL(data: [String: String], proxyURL: URL) -> URL? {
389 guard let key = data[NotificationField.key.rawValue] else {
390 return nil
391 }
392 return proxyURL.appendingPathComponent(key)
393 }
394
395 private func getKeyPath(data: [String: String]) -> URL? {
396 guard let documentsPath = Constants.documentsPath,
397 let accountId = data[NotificationField.accountId.rawValue] else {
398 return nil
399 }
400 return documentsPath.appendingPathComponent(accountId).appendingPathComponent("ring_device.key")
401 }
402
403 private func getTreatedMessagesPath(data: [String: String]) -> URL? {
404 guard let cachesPath = Constants.cachesPath,
405 let accountId = data[NotificationField.accountId.rawValue] else {
406 return nil
407 }
408 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("treatedMessages")
409 }
410
411 private func getProxyCaches(data: [String: String]) -> URL? {
412 guard let cachesPath = Constants.cachesPath,
413 let accountId = data[NotificationField.accountId.rawValue] else {
414 return nil
415 }
416 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("dhtproxy")
417 }
kkostiuke10e6572022-07-26 15:41:12 -0400418
419 private func contactProfileName(accountId: String, contactId: String) -> String? {
420 guard let documents = Constants.documentsPath else { return nil }
421 let profileURI = "ring:" + contactId
422 let profilePath = documents.path + "/" + "\(accountId)" + "/profiles/" + "\(Data(profileURI.utf8).base64EncodedString()).vcf"
423 if !FileManager.default.fileExists(atPath: profilePath) { return nil }
424
425 guard let data = FileManager.default.contents(atPath: profilePath),
426 let vCards = try? CNContactVCardSerialization.contacts(with: data),
Kateryna Kostiuk1efd0012022-09-13 12:08:36 -0400427 let vCard = vCards.first else { return nil }
kkostiuke10e6572022-07-26 15:41:12 -0400428 return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName
429 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400430}
431
432// MARK: DarwinNotificationHandler
433extension NotificationService: DarwinNotificationHandler {
434 func listenToMainAppResponse(completion: @escaping (Bool) -> Void) {
435 let observer = Unmanaged.passUnretained(self).toOpaque()
436 CFNotificationCenterAddObserver(notificationCenter,
437 observer, { (_, _, _, _, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400438 NotificationCenter.default.post(name: NotificationService.localNotificationName,
kkostiuk74d1ae42021-06-17 11:10:15 -0400439 object: nil,
440 userInfo: nil)
441 },
442 Constants.notificationAppIsActive,
443 nil,
444 .deliverImmediately)
kkostiuke10e6572022-07-26 15:41:12 -0400445 NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in
kkostiuk74d1ae42021-06-17 11:10:15 -0400446 completion(true)
447 }
448 }
449
450 func removeObserver() {
451 let observer = Unmanaged.passUnretained(self).toOpaque()
452 CFNotificationCenterRemoveEveryObserver(notificationCenter, observer)
kkostiuke10e6572022-07-26 15:41:12 -0400453 NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil)
kkostiuk74d1ae42021-06-17 11:10:15 -0400454 }
455
456}
457
458// MARK: present notifications
459extension NotificationService {
460 private func createAttachment(identifier: String, image: UIImage, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? {
461 let fileManager = FileManager.default
462 let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
463 let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
464 do {
465 try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
466 let imageFileIdentifier = identifier
467 let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
468 let imageData = UIImage.pngData(image)
469 try imageData()?.write(to: fileURL)
470 let imageAttachment = try UNNotificationAttachment.init(identifier: identifier, url: fileURL, options: options)
471 return imageAttachment
472 } catch {}
473 return nil
474 }
475
kkostiuk8e397cd2022-07-27 15:08:10 -0400476 private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400477 let content = UNMutableNotificationContent()
kkostiuke10e6572022-07-26 15:41:12 -0400478 content.sound = UNNotificationSound.default
kkostiuk74d1ae42021-06-17 11:10:15 -0400479 let imageName = url.lastPathComponent
kkostiuk74d1ae42021-06-17 11:10:15 -0400480 content.body = imageName
kkostiuk8e397cd2022-07-27 15:08:10 -0400481 var data = [String: String]()
482 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
483 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
484 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
485 content.userInfo = data
kkostiuk74d1ae42021-06-17 11:10:15 -0400486 if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) {
487 content.attachments = [ attachement ]
488 }
kkostiuke10e6572022-07-26 15:41:12 -0400489 let title = self.bestName(accountId: accountId, contactId: from)
490 if title.isEmpty {
491 content.title = from
492 needUpdateNotification(notification: LocalNotification(content, .file), peerId: from, accountId: accountId)
493 } else {
494 content.title = title
495 presentLocalNotification(notification: LocalNotification(content, .file))
496 }
497 }
498
kkostiuk8e397cd2022-07-27 15:08:10 -0400499 private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String) {
kkostiuke10e6572022-07-26 15:41:12 -0400500 let content = UNMutableNotificationContent()
501 content.body = body
kkostiuk74d1ae42021-06-17 11:10:15 -0400502 content.sound = UNNotificationSound.default
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
kkostiuke10e6572022-07-26 15:41:12 -0400508 let title = self.bestName(accountId: accountId, contactId: from)
509 if title.isEmpty {
510 content.title = from
511 needUpdateNotification(notification: LocalNotification(content, .message), peerId: from, accountId: accountId)
512 } else {
513 content.title = title
514 presentLocalNotification(notification: LocalNotification(content, .message))
515 }
516 }
517
518 private func presentLocalNotification(notification: LocalNotification) {
519 let content = notification.content
kkostiuk74d1ae42021-06-17 11:10:15 -0400520 setNotificationCount(notification: content)
521 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400522 let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)
523 UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in
kkostiuke10e6572022-07-26 15:41:12 -0400524 if notification.type == .message {
525 self?.numberOfMessages -= 1
526 } else {
527 self?.numberOfFiles -= 1
528 }
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400529 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400530 if let error = error {
531 print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
532 }
533 }
534 }
535
kkostiuke10e6572022-07-26 15:41:12 -0400536 private func presentCall(info: [AnyHashable: Any]) {
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400537 CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in
538 print("NotificationService", "Did report voip notification, error: \(String(describing: error))")
539 })
kkostiukabde7b92022-07-28 13:15:56 -0400540 self.pendingCalls.removeAll()
541 self.pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400542 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400543 }
544}