kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 1 | /* |
| 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 | |
| 21 | import UserNotifications |
| 22 | import UIKit |
| 23 | import CallKit |
| 24 | import Foundation |
| 25 | import CoreFoundation |
| 26 | import os |
| 27 | import Darwin |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 28 | import Contacts |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 29 | |
| 30 | protocol DarwinNotificationHandler { |
| 31 | func listenToMainAppResponse(completion: @escaping (Bool) -> Void) |
| 32 | func removeObserver() |
| 33 | } |
| 34 | |
| 35 | enum NotificationField: String { |
| 36 | case key |
| 37 | case accountId = "to" |
| 38 | case aps |
| 39 | } |
| 40 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 41 | enum LocalNotificationType: String { |
| 42 | case message |
| 43 | case file |
| 44 | } |
| 45 | |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 46 | class NotificationService: UNNotificationServiceExtension { |
| 47 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 48 | private static let localNotificationName = Notification.Name("com.savoirfairelinux.jami.appActive.internal") |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 49 | |
Kateryna Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 50 | private let notificationTimeout = DispatchTimeInterval.seconds(25) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 51 | |
| 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 Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 62 | var numberOfMessages = 0 /// number of scheduled messages |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 63 | var syncCompleted = false |
| 64 | private let tasksGroup = DispatchGroup() |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 65 | var accountId = "" |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 66 | |
| 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 |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 72 | // 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 Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 89 | guard let account = requestData[NotificationField.accountId.rawValue] else { return } |
| 90 | accountId = account |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 91 | |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 92 | /// app is not active. Querry value from dht |
| 93 | guard let proxyURL = getProxyCaches(data: requestData), |
kkostiuk | 53c55ff | 2022-07-18 15:02:17 -0400 | [diff] [blame] | 94 | var proxy = try? String(contentsOf: proxyURL, encoding: .utf8) else { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 95 | return |
| 96 | } |
Kateryna Kostiuk | 1c0e756 | 2022-08-23 15:17:44 -0400 | [diff] [blame] | 97 | proxy = ensureURLPrefix(urlString: proxy) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 98 | guard let urlPrpxy = URL(string: proxy), |
| 99 | let url = getRequestURL(data: requestData, proxyURL: urlPrpxy) else { |
| 100 | return |
| 101 | } |
| 102 | tasksGroup.enter() |
Kateryna Kostiuk | 0acc5f5 | 2022-08-15 10:21:26 -0400 | [diff] [blame] | 103 | let defaultSession = URLSession(configuration: .default) |
| 104 | let task = defaultSession.dataTask(with: url) {[weak self] (data, _, _) in |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 105 | guard let self = self, |
| 106 | let data = data else { |
Kateryna Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 107 | self?.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 108 | 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 Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 118 | self.verifyTasksStatus() |
| 119 | return |
| 120 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 121 | 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 Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 126 | /// jami will be started. Set accounts to not active state |
| 127 | if self.accountIsActive { |
| 128 | self.accountIsActive = false |
| 129 | self.adapterService.stop() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 130 | } |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 131 | var info = request.content.userInfo |
| 132 | info["peerId"] = peerId |
| 133 | info["hasVideo"] = hasVideo |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 134 | let name = self.bestName(accountId: self.accountId, contactId: peerId) |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 135 | if name.isEmpty { |
| 136 | info["displayName"] = peerId |
| 137 | self.pendingCalls[peerId] = info |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 138 | self.startAddressLookup(address: peerId, accountId: self.accountId) |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 139 | return |
| 140 | } |
| 141 | info["displayName"] = name |
| 142 | self.presentCall(info: info) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 143 | } |
| 144 | switch result { |
| 145 | case .call(let peerId, let hasVideo): |
| 146 | handleCall(peerId, "\(hasVideo)") |
kkostiuk | abde7b9 | 2022-07-28 13:15:56 -0400 | [diff] [blame] | 147 | return |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 148 | case .gitMessage: |
| 149 | /// check if account already acive |
| 150 | guard !self.accountIsActive else { break } |
| 151 | self.accountIsActive = true |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 152 | self.adapterService.startAccountsWithListener(accountId: self.accountId) { [weak self] event, eventData in |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 153 | guard let self = self else { |
| 154 | return |
| 155 | } |
| 156 | switch event { |
| 157 | case .message: |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 158 | self.numberOfMessages += 1 |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 159 | self.configureMessageNotification(from: eventData.jamiId, body: eventData.content, accountId: self.accountId, conversationId: eventData.conversationId) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 160 | case .fileTransferDone: |
| 161 | if let url = URL(string: eventData.content) { |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 162 | self.configureFileNotification(from: eventData.jamiId, url: url, accountId: self.accountId, conversationId: eventData.conversationId) |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 163 | } else { |
| 164 | self.numberOfFiles -= 1 |
| 165 | self.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 166 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 167 | 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 |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 195 | /// waiting for lookup |
| 196 | if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty { |
| 197 | return |
| 198 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 199 | /// 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 Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 202 | if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 203 | 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 213 | /// 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 | } |
kkostiuk | abde7b9 | 2022-07-28 13:15:56 -0400 | [diff] [blame] | 222 | pendingLocalNotifications.removeAll() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 223 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 224 | 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 297 | |
| 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 Kostiuk | 1c0e756 | 2022-08-23 15:17:44 -0400 | [diff] [blame] | 316 | nameServer = ensureURLPrefix(urlString: nameServer) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 317 | let urlString = nameServer + "/addr/" + address |
Kateryna Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 318 | guard let url = URL(string: urlString) else { |
| 319 | self.lookupCompleted(address: address, name: nil) |
| 320 | return |
| 321 | } |
Kateryna Kostiuk | 0acc5f5 | 2022-08-15 10:21:26 -0400 | [diff] [blame] | 322 | let defaultSession = URLSession(configuration: .default) |
| 323 | let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 324 | 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 Kostiuk | 1c0e756 | 2022-08-23 15:17:44 -0400 | [diff] [blame] | 346 | 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 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 354 | 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) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 361 | 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 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 384 | } |
| 385 | // MARK: paths |
| 386 | extension 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 418 | |
| 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 Kostiuk | 1efd001 | 2022-09-13 12:08:36 -0400 | [diff] [blame] | 427 | let vCard = vCards.first else { return nil } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 428 | return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName |
| 429 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 430 | } |
| 431 | |
| 432 | // MARK: DarwinNotificationHandler |
| 433 | extension NotificationService: DarwinNotificationHandler { |
| 434 | func listenToMainAppResponse(completion: @escaping (Bool) -> Void) { |
| 435 | let observer = Unmanaged.passUnretained(self).toOpaque() |
| 436 | CFNotificationCenterAddObserver(notificationCenter, |
| 437 | observer, { (_, _, _, _, _) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 438 | NotificationCenter.default.post(name: NotificationService.localNotificationName, |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 439 | object: nil, |
| 440 | userInfo: nil) |
| 441 | }, |
| 442 | Constants.notificationAppIsActive, |
| 443 | nil, |
| 444 | .deliverImmediately) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 445 | NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 446 | completion(true) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | func removeObserver() { |
| 451 | let observer = Unmanaged.passUnretained(self).toOpaque() |
| 452 | CFNotificationCenterRemoveEveryObserver(notificationCenter, observer) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 453 | NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 454 | } |
| 455 | |
| 456 | } |
| 457 | |
| 458 | // MARK: present notifications |
| 459 | extension 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 | |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 476 | private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 477 | let content = UNMutableNotificationContent() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 478 | content.sound = UNNotificationSound.default |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 479 | let imageName = url.lastPathComponent |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 480 | content.body = imageName |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 481 | 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 |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 486 | if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) { |
| 487 | content.attachments = [ attachement ] |
| 488 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 489 | 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 | |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 499 | private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String) { |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 500 | let content = UNMutableNotificationContent() |
| 501 | content.body = body |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 502 | content.sound = UNNotificationSound.default |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 503 | 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 |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 508 | 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 |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 520 | setNotificationCount(notification: content) |
| 521 | let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false) |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 522 | let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger) |
| 523 | UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 524 | if notification.type == .message { |
| 525 | self?.numberOfMessages -= 1 |
| 526 | } else { |
| 527 | self?.numberOfFiles -= 1 |
| 528 | } |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 529 | self?.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 530 | if let error = error { |
| 531 | print("Unable to Add Notification Request (\(error), \(error.localizedDescription))") |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 536 | private func presentCall(info: [AnyHashable: Any]) { |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 537 | CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in |
| 538 | print("NotificationService", "Did report voip notification, error: \(String(describing: error))") |
| 539 | }) |
kkostiuk | abde7b9 | 2022-07-28 13:15:56 -0400 | [diff] [blame] | 540 | self.pendingCalls.removeAll() |
| 541 | self.pendingLocalNotifications.removeAll() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 542 | self.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 543 | } |
| 544 | } |