blob: 98f9ccb6b8ba880c643e1e3c0c196c9cf67595dd [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:
Kateryna Kostiuk3dc364c2023-03-31 12:02:31 -0400144 self.handleGitMessage()
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500145 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 Kostiuk3dc364c2023-03-31 12:02:31 -0400162 private func handleGitMessage() {
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500163 /// 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
Kateryna Kostiuk28e72e02023-02-01 16:31:39 -0500186 case .invitation:
187 self.syncCompleted = true
188 self.numberOfMessages += 1
189 self.configureMessageNotification(from: eventData.jamiId,
190 body: eventData.content,
191 accountId: self.accountId,
192 conversationId: eventData.conversationId,
193 groupTitle: eventData.groupTitle)
194 }
Alireza8154e1f2022-11-26 16:51:24 -0500195 }
196 }
197
kkostiuk74d1ae42021-06-17 11:10:15 -0400198 private func verifyTasksStatus() {
199 guard !self.tasksCompleted else { return } /// we already left taskGroup
kkostiuke10e6572022-07-26 15:41:12 -0400200 /// waiting for lookup
201 if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty {
202 return
203 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400204 /// We could finish in two cases:
205 /// 1. we did not start account we are not waiting for the signals from the daemon
206 /// 2. conversation synchronization completed and all files downloaded
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400207 if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400208 self.tasksCompleted = true
209 self.tasksGroup.leave()
210 }
211 }
212
213 private func finish() {
214 if self.accountIsActive {
215 self.accountIsActive = false
216 self.adapterService.stop()
217 }
kkostiuke10e6572022-07-26 15:41:12 -0400218 /// cleanup pending notifications
219 if !self.pendingCalls.isEmpty, let info = self.pendingCalls.first?.value {
220 self.presentCall(info: info)
221 } else {
222 for notifications in pendingLocalNotifications {
223 for notification in notifications.value {
224 self.presentLocalNotification(notification: notification)
225 }
226 }
kkostiukabde7b92022-07-28 13:15:56 -0400227 pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400228 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400229 if let contentHandler = contentHandler {
230 contentHandler(self.bestAttemptContent)
231 }
232 }
233
234 private func appIsActive() -> Bool {
235 let group = DispatchGroup()
236 defer {
237 self.removeObserver()
238 group.leave()
239 }
240 var appIsActive = false
241 group.enter()
242 /// post darwin notification and wait for the answer from the main app. If answer received app is active
243 self.listenToMainAppResponse { _ in
244 appIsActive = true
245 }
246 CFNotificationCenterPostNotification(notificationCenter, CFNotificationName(Constants.notificationReceived), nil, nil, true)
247 /// wait fro 100 milliseconds. If no answer from main app is received app is not active.
248 _ = group.wait(timeout: .now() + 0.3)
249
250 return appIsActive
251 }
252
253 private func saveData(data: [String: String]) {
254 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
255 return
256 }
257 var notificationData = [[String: String]]()
258 if let existingData = userDefaults.object(forKey: Constants.notificationData) as? [[String: String]] {
259 notificationData = existingData
260 }
261 notificationData.append(data)
262 userDefaults.set(notificationData, forKey: Constants.notificationData)
263 }
264
265 private func setNotificationCount(notification: UNMutableNotificationContent) {
266 guard let userDefaults = UserDefaults(suiteName: Constants.appGroupIdentifier) else {
267 return
268 }
269
270 if let count = userDefaults.object(forKey: Constants.notificationsCount) as? NSNumber {
271 let new: NSNumber = count.intValue + 1 as NSNumber
272 notification.badge = new
273 userDefaults.set(new, forKey: Constants.notificationsCount)
274 }
275 }
276
277 private func requestToDictionary(request: UNNotificationRequest) -> [String: String] {
278 var dictionary = [String: String]()
279 let userInfo = request.content.userInfo
280 for key in userInfo.keys {
281 /// "aps" is a field added for alert notification type, so it could be received in the extension. This field is not needed by dht
282 if String(describing: key) == NotificationField.aps.rawValue {
283 continue
284 }
285 if let value = userInfo[key] {
286 let keyString = String(describing: key)
287 let valueString = String(describing: value)
288 dictionary[keyString] = valueString
289 }
290 }
291 return dictionary
292 }
293
294 private func requestedData(request: UNNotificationRequest, map: [String: Any]) -> Bool {
295 guard let userInfo = request.content.userInfo as? [String: Any] else { return false }
296 guard let valueIds = userInfo["valueIds"] as? [String: String],
297 let id = map["id"] else {
298 return false
299 }
300 return valueIds.values.contains("\(id)")
301 }
kkostiuke10e6572022-07-26 15:41:12 -0400302
303 private func bestName(accountId: String, contactId: String) -> String {
304 if let name = self.names[contactId], !name.isEmpty {
305 return name
306 }
307 if let contactProfileName = self.contactProfileName(accountId: accountId, contactId: contactId),
308 !contactProfileName.isEmpty {
309 self.names[contactId] = contactProfileName
310 return contactProfileName
311 }
312 let registeredName = self.adapterService.getNameFor(address: contactId, accountId: accountId)
313 if !registeredName.isEmpty {
314 self.names[contactId] = registeredName
315 }
316 return registeredName
317 }
318
319 private func startAddressLookup(address: String, accountId: String) {
320 var nameServer = self.adapterService.getNameServerFor(accountId: accountId)
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400321 nameServer = ensureURLPrefix(urlString: nameServer)
kkostiuke10e6572022-07-26 15:41:12 -0400322 let urlString = nameServer + "/addr/" + address
Kateryna Kostiuk6fc15812022-08-12 10:17:34 -0400323 guard let url = URL(string: urlString) else {
324 self.lookupCompleted(address: address, name: nil)
325 return
326 }
Kateryna Kostiuk0acc5f52022-08-15 10:21:26 -0400327 let defaultSession = URLSession(configuration: .default)
328 let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400329 guard let self = self else { return }
330 var name: String?
331 defer {
332 self.lookupCompleted(address: address, name: name)
333 }
334 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200,
335 let data = data else {
336 return
337 }
338 do {
339 guard let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String] else { return }
340 if map["name"] != nil {
341 name = map["name"]
342 self.names[address] = name
343 }
344 } catch {
345 print("serialization failed , \(error)")
346 }
347 }
348 task.resume()
349 }
350
Kateryna Kostiuk1c0e7562022-08-23 15:17:44 -0400351 private func ensureURLPrefix(urlString: String) -> String {
352 var urlWithPrefix = urlString
353 if !urlWithPrefix.hasPrefix("http://") && !urlWithPrefix.hasPrefix("https://") {
354 urlWithPrefix = "http://" + urlWithPrefix
355 }
356 return urlWithPrefix
357 }
358
kkostiuke10e6572022-07-26 15:41:12 -0400359 private func lookupCompleted(address: String, name: String?) {
360 for call in pendingCalls where call.key == address {
361 var info = call.value
362 if let name = name {
363 info["displayName"] = name
364 }
365 presentCall(info: info)
kkostiuke10e6572022-07-26 15:41:12 -0400366 return
367 }
368 for pending in pendingLocalNotifications where pending.key == address {
369 let notifications = pending.value
370 for notification in notifications {
371 if let name = name {
372 notification.content.title = name
373 }
374 presentLocalNotification(notification: notification)
375 }
376 pendingLocalNotifications.removeValue(forKey: address)
377 }
378 }
379
380 private func needUpdateNotification(notification: LocalNotification, peerId: String, accountId: String) {
381 if var pending = pendingLocalNotifications[peerId] {
382 pending.append(notification)
383 pendingLocalNotifications[peerId] = pending
384 } else {
385 pendingLocalNotifications[peerId] = [notification]
386 }
387 startAddressLookup(address: peerId, accountId: accountId)
388 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400389}
390// MARK: paths
391extension NotificationService {
392
393 private func getRequestURL(data: [String: String], proxyURL: URL) -> URL? {
394 guard let key = data[NotificationField.key.rawValue] else {
395 return nil
396 }
397 return proxyURL.appendingPathComponent(key)
398 }
399
Kateryna Kostiukfb10d702022-11-30 14:32:28 -0500400 private func getRequestURL(data: [String: String], path: URL) -> URL? {
401 guard let key = data[NotificationField.key.rawValue],
402 let jsonData = NSData(contentsOf: path) as? Data else {
403 return nil
404 }
405 guard let map = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: String],
406 var proxyAddress = map.first?.value else {
407 return nil
408 }
409
410 proxyAddress = ensureURLPrefix(urlString: proxyAddress)
411 guard let urlPrpxy = URL(string: proxyAddress) else { return nil }
412 return urlPrpxy.appendingPathComponent(key)
413 }
414
kkostiuk74d1ae42021-06-17 11:10:15 -0400415 private func getKeyPath(data: [String: String]) -> URL? {
416 guard let documentsPath = Constants.documentsPath,
417 let accountId = data[NotificationField.accountId.rawValue] else {
418 return nil
419 }
420 return documentsPath.appendingPathComponent(accountId).appendingPathComponent("ring_device.key")
421 }
422
423 private func getTreatedMessagesPath(data: [String: String]) -> URL? {
424 guard let cachesPath = Constants.cachesPath,
425 let accountId = data[NotificationField.accountId.rawValue] else {
426 return nil
427 }
428 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("treatedMessages")
429 }
430
431 private func getProxyCaches(data: [String: String]) -> URL? {
432 guard let cachesPath = Constants.cachesPath,
433 let accountId = data[NotificationField.accountId.rawValue] else {
434 return nil
435 }
436 return cachesPath.appendingPathComponent(accountId).appendingPathComponent("dhtproxy")
437 }
kkostiuke10e6572022-07-26 15:41:12 -0400438
439 private func contactProfileName(accountId: String, contactId: String) -> String? {
440 guard let documents = Constants.documentsPath else { return nil }
441 let profileURI = "ring:" + contactId
442 let profilePath = documents.path + "/" + "\(accountId)" + "/profiles/" + "\(Data(profileURI.utf8).base64EncodedString()).vcf"
443 if !FileManager.default.fileExists(atPath: profilePath) { return nil }
444
445 guard let data = FileManager.default.contents(atPath: profilePath),
446 let vCards = try? CNContactVCardSerialization.contacts(with: data),
Kateryna Kostiuk1efd0012022-09-13 12:08:36 -0400447 let vCard = vCards.first else { return nil }
kkostiuke10e6572022-07-26 15:41:12 -0400448 return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName
449 }
kkostiuk74d1ae42021-06-17 11:10:15 -0400450}
451
452// MARK: DarwinNotificationHandler
453extension NotificationService: DarwinNotificationHandler {
454 func listenToMainAppResponse(completion: @escaping (Bool) -> Void) {
455 let observer = Unmanaged.passUnretained(self).toOpaque()
456 CFNotificationCenterAddObserver(notificationCenter,
457 observer, { (_, _, _, _, _) in
kkostiuke10e6572022-07-26 15:41:12 -0400458 NotificationCenter.default.post(name: NotificationService.localNotificationName,
kkostiuk74d1ae42021-06-17 11:10:15 -0400459 object: nil,
460 userInfo: nil)
461 },
462 Constants.notificationAppIsActive,
463 nil,
464 .deliverImmediately)
kkostiuke10e6572022-07-26 15:41:12 -0400465 NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in
kkostiuk74d1ae42021-06-17 11:10:15 -0400466 completion(true)
467 }
468 }
469
470 func removeObserver() {
471 let observer = Unmanaged.passUnretained(self).toOpaque()
472 CFNotificationCenterRemoveEveryObserver(notificationCenter, observer)
kkostiuke10e6572022-07-26 15:41:12 -0400473 NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil)
kkostiuk74d1ae42021-06-17 11:10:15 -0400474 }
475
476}
477
478// MARK: present notifications
479extension NotificationService {
480 private func createAttachment(identifier: String, image: UIImage, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? {
481 let fileManager = FileManager.default
482 let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
483 let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
484 do {
485 try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
486 let imageFileIdentifier = identifier
487 let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
488 let imageData = UIImage.pngData(image)
489 try imageData()?.write(to: fileURL)
490 let imageAttachment = try UNNotificationAttachment.init(identifier: identifier, url: fileURL, options: options)
491 return imageAttachment
492 } catch {}
493 return nil
494 }
495
kkostiuk8e397cd2022-07-27 15:08:10 -0400496 private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) {
kkostiuk74d1ae42021-06-17 11:10:15 -0400497 let content = UNMutableNotificationContent()
kkostiuke10e6572022-07-26 15:41:12 -0400498 content.sound = UNNotificationSound.default
kkostiuk74d1ae42021-06-17 11:10:15 -0400499 let imageName = url.lastPathComponent
kkostiuk74d1ae42021-06-17 11:10:15 -0400500 content.body = imageName
kkostiuk8e397cd2022-07-27 15:08:10 -0400501 var data = [String: String]()
502 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
503 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
504 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
505 content.userInfo = data
kkostiuk74d1ae42021-06-17 11:10:15 -0400506 if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) {
507 content.attachments = [ attachement ]
508 }
kkostiuke10e6572022-07-26 15:41:12 -0400509 let title = self.bestName(accountId: accountId, contactId: from)
510 if title.isEmpty {
511 content.title = from
512 needUpdateNotification(notification: LocalNotification(content, .file), peerId: from, accountId: accountId)
513 } else {
514 content.title = title
515 presentLocalNotification(notification: LocalNotification(content, .file))
516 }
517 }
518
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400519 private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String, groupTitle: String) {
kkostiuke10e6572022-07-26 15:41:12 -0400520 let content = UNMutableNotificationContent()
521 content.body = body
kkostiuk74d1ae42021-06-17 11:10:15 -0400522 content.sound = UNNotificationSound.default
kkostiuk8e397cd2022-07-27 15:08:10 -0400523 var data = [String: String]()
524 data[Constants.NotificationUserInfoKeys.participantID.rawValue] = from
525 data[Constants.NotificationUserInfoKeys.accountID.rawValue] = accountId
526 data[Constants.NotificationUserInfoKeys.conversationID.rawValue] = conversationId
527 content.userInfo = data
Kateryna Kostiuk2648aab2022-08-30 14:24:03 -0400528 let title = !groupTitle.isEmpty ? groupTitle : self.bestName(accountId: accountId, contactId: from)
kkostiuke10e6572022-07-26 15:41:12 -0400529 if title.isEmpty {
530 content.title = from
531 needUpdateNotification(notification: LocalNotification(content, .message), peerId: from, accountId: accountId)
532 } else {
533 content.title = title
534 presentLocalNotification(notification: LocalNotification(content, .message))
535 }
536 }
537
538 private func presentLocalNotification(notification: LocalNotification) {
539 let content = notification.content
kkostiuk74d1ae42021-06-17 11:10:15 -0400540 setNotificationCount(notification: content)
541 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400542 let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)
543 UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in
kkostiuke10e6572022-07-26 15:41:12 -0400544 if notification.type == .message {
545 self?.numberOfMessages -= 1
546 } else {
547 self?.numberOfFiles -= 1
548 }
Kateryna Kostiuk3b581712022-07-21 08:42:14 -0400549 self?.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400550 if let error = error {
551 print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
552 }
553 }
554 }
555
kkostiuke10e6572022-07-26 15:41:12 -0400556 private func presentCall(info: [AnyHashable: Any]) {
Kateryna Kostiukfd5e6f12022-08-02 11:24:05 -0400557 CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in
558 print("NotificationService", "Did report voip notification, error: \(String(describing: error))")
559 })
kkostiukabde7b92022-07-28 13:15:56 -0400560 self.pendingCalls.removeAll()
561 self.pendingLocalNotifications.removeAll()
kkostiuke10e6572022-07-26 15:41:12 -0400562 self.verifyTasksStatus()
kkostiuk74d1ae42021-06-17 11:10:15 -0400563 }
564}