blob: 5033f2156e3a43d10700c3b2294720d225c5f2cf [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 }
139 switch result {
140 case .call(let peerId, let hasVideo):
141 handleCall(peerId, "\(hasVideo)")
kkostiukabde7b92022-07-28 13:15:56 -0400142 return
kkostiuk74d1ae42021-06-17 11:10:15 -0400143 case .gitMessage:
144 /// check if account already acive
145 guard !self.accountIsActive else { break }
146 self.accountIsActive = true
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400147 self.adapterService.startAccountsWithListener(accountId: self.accountId) { [weak self] event, eventData in
kkostiuk74d1ae42021-06-17 11:10:15 -0400148 guard let self = self else {
149 return
150 }
151 switch event {
152 case .message:
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400153 self.numberOfMessages += 1
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400154 self.configureMessageNotification(from: eventData.jamiId, body: eventData.content, accountId: self.accountId, conversationId: eventData.conversationId, groupTitle: "")
kkostiuk74d1ae42021-06-17 11:10:15 -0400155 case .fileTransferDone:
156 if let url = URL(string: eventData.content) {
Kateryna Kostiuk19437652022-08-02 13:02:21 -0400157 self.configureFileNotification(from: eventData.jamiId, url: url, accountId: self.accountId, conversationId: eventData.conversationId)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400158 } else {
159 self.numberOfFiles -= 1
160 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400161 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400162 case .syncCompleted:
163 self.syncCompleted = true
164 self.verifyTasksStatus()
165 case .fileTransferInProgress:
166 self.numberOfFiles += 1
167 case .call:
168 handleCall(eventData.jamiId, eventData.content)
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400169 case .invitation:
170 self.syncCompleted = true
171 self.numberOfMessages += 1
Kateryna Kostiukfb10d702022-11-30 14:32:28 -0500172 self.configureMessageNotification(from: eventData.jamiId,
173 body: eventData.content,
174 accountId: self.accountId,
175 conversationId: eventData.conversationId,
176 groupTitle: eventData.groupTitle)
kkostiuk74d1ae42021-06-17 11:10:15 -0400177 }
178 }
179 case .unknown:
180 break
181 }
182 } catch {
183 print("serialization failed , \(error)")
184 }
185 }
186 self.verifyTasksStatus()
187 }
188 task.resume()
189 _ = tasksGroup.wait(timeout: .now() + notificationTimeout)
190 }
191
192 override func serviceExtensionTimeWillExpire() {
193 finish()
194 }
195
196 private func verifyTasksStatus() {
197 guard !self.tasksCompleted else { return } /// we already left taskGroup
kkostiuke10e6572022-07-26 15:41:12 -0400198 /// waiting for lookup
199 if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty {
200 return
201 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400202 /// We could finish in two cases:
203 /// 1. we did not start account we are not waiting for the signals from the daemon
204 /// 2. conversation synchronization completed and all files downloaded
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400205 if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400206 self.tasksCompleted = true
207 self.tasksGroup.leave()
208 }
209 }
210
211 private func finish() {
212 if self.accountIsActive {
213 self.accountIsActive = false
214 self.adapterService.stop()
215 }
kkostiuke10e6572022-07-26 15:41:12 -0400216 /// cleanup pending notifications
217 if !self.pendingCalls.isEmpty, let info = self.pendingCalls.first?.value {
218 self.presentCall(info: info)
219 } else {
220 for notifications in pendingLocalNotifications {
221 for notification in notifications.value {
222 self.presentLocalNotification(notification: notification)
223 }
224 }
kkostiukabde7b92022-07-28 13:15:56 -0400225 pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400226 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400227 if let contentHandler = contentHandler {
228 contentHandler(self.bestAttemptContent)
229 }
230 }
231
232 private func appIsActive() -> Bool {
233 let group = DispatchGroup()
234 defer {
235 self.removeObserver()
236 group.leave()
237 }
238 var appIsActive = false
239 group.enter()
240 /// post darwin notification and wait for the answer from the main app. If answer received app is active
241 self.listenToMainAppResponse { _ in
242 appIsActive = true
243 }
244 CFNotificationCenterPostNotification(notificationCenter, CFNotificationName(Constants.notificationReceived), nil, nil, true)
245 /// wait fro 100 milliseconds. If no answer from main app is received app is not active.
246 _ = group.wait(timeout: .now() + 0.3)
247
248 return appIsActive
249 }
250
251 private func saveData(data: [String: String]) {
252 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
253 return
254 }
255 var notificationData = [[String: String]]()
256 if let existingData = userDefaults.object(forKey: Constants.notificationData) as? [[String: String]] {
257 notificationData = existingData
258 }
259 notificationData.append(data)
260 userDefaults.set(notificationData, forKey: Constants.notificationData)
261 }
262
263 private func setNotificationCount(notification: UNMutableNotificationContent) {
264 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
265 return
266 }
267
268 if let count = userDefaults.object(forKey: Constants.notificationsCount) as? NSNumber {
269 let new: NSNumber = count.intValue + 1 as NSNumber
270 notification.badge = new
271 userDefaults.set(new, forKey: Constants.notificationsCount)
272 }
273 }
274
275 private func requestToDictionary(request: UNNotificationRequest) -> [String: String] {
276 var dictionary = [String: String]()
277 let userInfo = request.content.userInfo
278 for key in userInfo.keys {
279 /// "aps" is a field added for alert notification type, so it could be received in the extension. This field is not needed by dht
280 if String(describing: key) == NotificationField.aps.rawValue {
281 continue
282 }
283 if let value = userInfo[key] {
284 let keyString = String(describing: key)
285 let valueString = String(describing: value)
286 dictionary[keyString] = valueString
287 }
288 }
289 return dictionary
290 }
291
292 private func requestedData(request: UNNotificationRequest, map: [String: Any]) -> Bool {
293 guard let userInfo = request.content.userInfo as? [String: Any] else { return false }
294 guard let valueIds = userInfo["valueIds"] as? [String: String],
295 let id = map["id"] else {
296 return false
297 }
298 return valueIds.values.contains("\(id)")
299 }
kkostiuke10e6572022-07-26 15:41:12 -0400300
301 private func bestName(accountId: String, contactId: String) -> String {
302 if let name = self.names[contactId], !name.isEmpty {
303 return name
304 }
305 if let contactProfileName = self.contactProfileName(accountId: accountId, contactId: contactId),
306 !contactProfileName.isEmpty {
307 self.names[contactId] = contactProfileName
308 return contactProfileName
309 }
310 let registeredName = self.adapterService.getNameFor(address: contactId, accountId: accountId)
311 if !registeredName.isEmpty {
312 self.names[contactId] = registeredName
313 }
314 return registeredName
315 }
316
317 private func startAddressLookup(address: String, accountId: String) {
318 var nameServer = self.adapterService.getNameServerFor(accountId: accountId)
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400319 nameServer = ensureURLPrefix(urlString: nameServer)
kkostiuke10e6572022-07-26 15:41:12 -0400320 let urlString = nameServer + "/addr/" + address
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400321 guard let url = URL(string: urlString) else {
322 self.lookupCompleted(address: address, name: nil)
323 return
324 }
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -0400325 let defaultSession = URLSession(configuration: .default)
326 let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400327 guard let self = self else { return }
328 var name: String?
329 defer {
330 self.lookupCompleted(address: address, name: name)
331 }
332 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200,
333 let data = data else {
334 return
335 }
336 do {
337 guard let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String] else { return }
338 if map["name"] != nil {
339 name = map["name"]
340 self.names[address] = name
341 }
342 } catch {
343 print("serialization failed , \(error)")
344 }
345 }
346 task.resume()
347 }
348
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400349 private func ensureURLPrefix(urlString: String) -> String {
350 var urlWithPrefix = urlString
351 if !urlWithPrefix.hasPrefix("http://") && !urlWithPrefix.hasPrefix("https://") {
352 urlWithPrefix = "http://" + urlWithPrefix
353 }
354 return urlWithPrefix
355 }
356
kkostiuke10e6572022-07-26 15:41:12 -0400357 private func lookupCompleted(address: String, name: String?) {
358 for call in pendingCalls where call.key == address {
359 var info = call.value
360 if let name = name {
361 info["displayName"] = name
362 }
363 presentCall(info: info)
kkostiuke10e6572022-07-26 15:41:12 -0400364 return
365 }
366 for pending in pendingLocalNotifications where pending.key == address {
367 let notifications = pending.value
368 for notification in notifications {
369 if let name = name {
370 notification.content.title = name
371 }
372 presentLocalNotification(notification: notification)
373 }
374 pendingLocalNotifications.removeValue(forKey: address)
375 }
376 }
377
378 private func needUpdateNotification(notification: LocalNotification, peerId: String, accountId: String) {
379 if var pending = pendingLocalNotifications[peerId] {
380 pending.append(notification)
381 pendingLocalNotifications[peerId] = pending
382 } else {
383 pendingLocalNotifications[peerId] = [notification]
384 }
385 startAddressLookup(address: peerId, accountId: accountId)
386 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400387}
388// MARK: paths
389extension NotificationService {
390
391 private func getRequestURL(data: [String: String], proxyURL: URL) -> URL? {
392 guard let key = data[NotificationField.key.rawValue] else {
393 return nil
394 }
395 return proxyURL.appendingPathComponent(key)
396 }
397
Kateryna Kostiukfb10d702022-11-30 14:32:28 -0500398 private func getRequestURL(data: [String: String], path: URL) -> URL? {
399 guard let key = data[NotificationField.key.rawValue],
400 let jsonData = NSData(contentsOf: path) as? Data else {
401 return nil
402 }
403 guard let map = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: String],
404 var proxyAddress = map.first?.value else {
405 return nil
406 }
407
408 proxyAddress = ensureURLPrefix(urlString: proxyAddress)
409 guard let urlPrpxy = URL(string: proxyAddress) else { return nil }
410 return urlPrpxy.appendingPathComponent(key)
411 }
412
kkostiuk74d1ae42021-06-17 11:10:15 -0400413 private func getKeyPath(data: [String: String]) -> URL? {
414 guard let documentsPath = Constants.documentsPath,
415 let accountId = data[NotificationField.accountId.rawValue] else {
416 return nil
417 }
418 return documentsPath.appendingPathComponent(accountId).appendingPathComponent("ring_device.key")
419 }
420
421 private func getTreatedMessagesPath(data: [String: String]) -> URL? {
422 guard let cachesPath = Constants.cachesPath,
423 let accountId = data[NotificationField.accountId.rawValue] else {
424 return nil
425 }
426 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("treatedMessages")
427 }
428
429 private func getProxyCaches(data: [String: String]) -> URL? {
430 guard let cachesPath = Constants.cachesPath,
431 let accountId = data[NotificationField.accountId.rawValue] else {
432 return nil
433 }
434 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("dhtproxy")
435 }
kkostiuke10e6572022-07-26 15:41:12 -0400436
437 private func contactProfileName(accountId: String, contactId: String) -> String? {
438 guard let documents = Constants.documentsPath else { return nil }
439 let profileURI = "ring:" + contactId
440 let profilePath = documents.path + "/" + "\(accountId)" + "/profiles/" + "\(Data(profileURI.utf8).base64EncodedString()).vcf"
441 if !FileManager.default.fileExists(atPath: profilePath) { return nil }
442
443 guard let data = FileManager.default.contents(atPath: profilePath),
444 let vCards = try? CNContactVCardSerialization.contacts(with: data),
Kateryna Kostiuk1efd0012022-09-13 12:08:36 -0400445 let vCard = vCards.first else { return nil }
kkostiuke10e6572022-07-26 15:41:12 -0400446 return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName
447 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400448}
449
450// MARK: DarwinNotificationHandler
451extension NotificationService: DarwinNotificationHandler {
452 func listenToMainAppResponse(completion: @escaping (Bool) -> Void) {
453 let observer = Unmanaged.passUnretained(self).toOpaque()
454 CFNotificationCenterAddObserver(notificationCenter,
455 observer, { (_, _, _, _, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400456 NotificationCenter.default.post(name: NotificationService.localNotificationName,
kkostiuk74d1ae42021-06-17 11:10:15 -0400457 object: nil,
458 userInfo: nil)
459 },
460 Constants.notificationAppIsActive,
461 nil,
462 .deliverImmediately)
kkostiuke10e6572022-07-26 15:41:12 -0400463 NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in
kkostiuk74d1ae42021-06-17 11:10:15 -0400464 completion(true)
465 }
466 }
467
468 func removeObserver() {
469 let observer = Unmanaged.passUnretained(self).toOpaque()
470 CFNotificationCenterRemoveEveryObserver(notificationCenter, observer)
kkostiuke10e6572022-07-26 15:41:12 -0400471 NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil)
kkostiuk74d1ae42021-06-17 11:10:15 -0400472 }
473
474}
475
476// MARK: present notifications
477extension NotificationService {
478 private func createAttachment(identifier: String, image: UIImage, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? {
479 let fileManager = FileManager.default
480 let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
481 let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
482 do {
483 try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
484 let imageFileIdentifier = identifier
485 let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
486 let imageData = UIImage.pngData(image)
487 try imageData()?.write(to: fileURL)
488 let imageAttachment = try UNNotificationAttachment.init(identifier: identifier, url: fileURL, options: options)
489 return imageAttachment
490 } catch {}
491 return nil
492 }
493
kkostiuk8e397cd2022-07-27 15:08:10 -0400494 private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400495 let content = UNMutableNotificationContent()
kkostiuke10e6572022-07-26 15:41:12 -0400496 content.sound = UNNotificationSound.default
kkostiuk74d1ae42021-06-17 11:10:15 -0400497 let imageName = url.lastPathComponent
kkostiuk74d1ae42021-06-17 11:10:15 -0400498 content.body = imageName
kkostiuk8e397cd2022-07-27 15:08:10 -0400499 var data = [String: String]()
500 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
501 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
502 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
503 content.userInfo = data
kkostiuk74d1ae42021-06-17 11:10:15 -0400504 if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) {
505 content.attachments = [ attachement ]
506 }
kkostiuke10e6572022-07-26 15:41:12 -0400507 let title = self.bestName(accountId: accountId, contactId: from)
508 if title.isEmpty {
509 content.title = from
510 needUpdateNotification(notification: LocalNotification(content, .file), peerId: from, accountId: accountId)
511 } else {
512 content.title = title
513 presentLocalNotification(notification: LocalNotification(content, .file))
514 }
515 }
516
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400517 private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String, groupTitle: String) {
kkostiuke10e6572022-07-26 15:41:12 -0400518 let content = UNMutableNotificationContent()
519 content.body = body
kkostiuk74d1ae42021-06-17 11:10:15 -0400520 content.sound = UNNotificationSound.default
kkostiuk8e397cd2022-07-27 15:08:10 -0400521 var data = [String: String]()
522 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
523 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
524 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
525 content.userInfo = data
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400526 let title = !groupTitle.isEmpty ? groupTitle : self.bestName(accountId: accountId, contactId: from)
kkostiuke10e6572022-07-26 15:41:12 -0400527 if title.isEmpty {
528 content.title = from
529 needUpdateNotification(notification: LocalNotification(content, .message), peerId: from, accountId: accountId)
530 } else {
531 content.title = title
532 presentLocalNotification(notification: LocalNotification(content, .message))
533 }
534 }
535
536 private func presentLocalNotification(notification: LocalNotification) {
537 let content = notification.content
kkostiuk74d1ae42021-06-17 11:10:15 -0400538 setNotificationCount(notification: content)
539 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400540 let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)
541 UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in
kkostiuke10e6572022-07-26 15:41:12 -0400542 if notification.type == .message {
543 self?.numberOfMessages -= 1
544 } else {
545 self?.numberOfFiles -= 1
546 }
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400547 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400548 if let error = error {
549 print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
550 }
551 }
552 }
553
kkostiuke10e6572022-07-26 15:41:12 -0400554 private func presentCall(info: [AnyHashable: Any]) {
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400555 CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in
556 print("NotificationService", "Did report voip notification, error: \(String(describing: error))")
557 })
kkostiukabde7b92022-07-28 13:15:56 -0400558 self.pendingCalls.removeAll()
559 self.pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400560 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400561 }
562}