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), |
Kateryna Kostiuk | fb10d70 | 2022-11-30 14:32:28 -0500 | [diff] [blame] | 94 | let url = getRequestURL(data: requestData, path: proxyURL) else { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 95 | return |
| 96 | } |
| 97 | tasksGroup.enter() |
Kateryna Kostiuk | 0acc5f5 | 2022-08-15 10:21:26 -0400 | [diff] [blame] | 98 | let defaultSession = URLSession(configuration: .default) |
| 99 | let task = defaultSession.dataTask(with: url) {[weak self] (data, _, _) in |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 100 | guard let self = self, |
| 101 | let data = data else { |
Kateryna Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 102 | self?.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 103 | 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 Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 113 | self.verifyTasksStatus() |
| 114 | return |
| 115 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 116 | 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 Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 121 | /// jami will be started. Set accounts to not active state |
| 122 | if self.accountIsActive { |
| 123 | self.accountIsActive = false |
| 124 | self.adapterService.stop() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 125 | } |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 126 | var info = request.content.userInfo |
| 127 | info["peerId"] = peerId |
| 128 | info["hasVideo"] = hasVideo |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 129 | let name = self.bestName(accountId: self.accountId, contactId: peerId) |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 130 | if name.isEmpty { |
| 131 | info["displayName"] = peerId |
| 132 | self.pendingCalls[peerId] = info |
Kateryna Kostiuk | 1943765 | 2022-08-02 13:02:21 -0400 | [diff] [blame] | 133 | self.startAddressLookup(address: peerId, accountId: self.accountId) |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 134 | return |
| 135 | } |
| 136 | info["displayName"] = name |
| 137 | self.presentCall(info: info) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 138 | } |
Kateryna Kostiuk | 28e72e0 | 2023-02-01 16:31:39 -0500 | [diff] [blame] | 139 | switch result { |
| 140 | case .call(let peerId, let hasVideo): |
| 141 | handleCall(peerId, "\(hasVideo)") |
| 142 | return |
| 143 | case .gitMessage: |
Kateryna Kostiuk | 3dc364c | 2023-03-31 12:02:31 -0400 | [diff] [blame^] | 144 | self.handleGitMessage() |
Kateryna Kostiuk | 28e72e0 | 2023-02-01 16:31:39 -0500 | [diff] [blame] | 145 | case .unknown: |
| 146 | break |
| 147 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 148 | } 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 Kostiuk | 3dc364c | 2023-03-31 12:02:31 -0400 | [diff] [blame^] | 162 | private func handleGitMessage() { |
Kateryna Kostiuk | 28e72e0 | 2023-02-01 16:31:39 -0500 | [diff] [blame] | 163 | /// check if account already acive |
| 164 | guard !self.accountIsActive else { return } |
| 165 | self.accountIsActive = true |
| 166 | self.adapterService.startAccountsWithListener(accountId: self.accountId) { [weak self] event, eventData in |
| 167 | guard let self = self else { |
| 168 | return |
Alireza | 8154e1f | 2022-11-26 16:51:24 -0500 | [diff] [blame] | 169 | } |
Kateryna Kostiuk | 28e72e0 | 2023-02-01 16:31:39 -0500 | [diff] [blame] | 170 | 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 Kostiuk | 28e72e0 | 2023-02-01 16:31:39 -0500 | [diff] [blame] | 186 | 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 | } |
Alireza | 8154e1f | 2022-11-26 16:51:24 -0500 | [diff] [blame] | 195 | } |
| 196 | } |
| 197 | |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 198 | private func verifyTasksStatus() { |
| 199 | guard !self.tasksCompleted else { return } /// we already left taskGroup |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 200 | /// waiting for lookup |
| 201 | if !pendingCalls.isEmpty || !pendingLocalNotifications.isEmpty { |
| 202 | return |
| 203 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 204 | /// 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 Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 207 | if !self.accountIsActive || (self.syncCompleted && self.numberOfFiles == 0 && self.numberOfMessages == 0) { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 208 | 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 218 | /// 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 | } |
kkostiuk | abde7b9 | 2022-07-28 13:15:56 -0400 | [diff] [blame] | 227 | pendingLocalNotifications.removeAll() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 228 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 229 | 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 302 | |
| 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 Kostiuk | 1c0e756 | 2022-08-23 15:17:44 -0400 | [diff] [blame] | 321 | nameServer = ensureURLPrefix(urlString: nameServer) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 322 | let urlString = nameServer + "/addr/" + address |
Kateryna Kostiuk | 6fc1581 | 2022-08-12 10:17:34 -0400 | [diff] [blame] | 323 | guard let url = URL(string: urlString) else { |
| 324 | self.lookupCompleted(address: address, name: nil) |
| 325 | return |
| 326 | } |
Kateryna Kostiuk | 0acc5f5 | 2022-08-15 10:21:26 -0400 | [diff] [blame] | 327 | let defaultSession = URLSession(configuration: .default) |
| 328 | let task = defaultSession.dataTask(with: url) {[weak self](data, response, _) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 329 | 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 Kostiuk | 1c0e756 | 2022-08-23 15:17:44 -0400 | [diff] [blame] | 351 | 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 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 359 | 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) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 366 | 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 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 389 | } |
| 390 | // MARK: paths |
| 391 | extension 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 Kostiuk | fb10d70 | 2022-11-30 14:32:28 -0500 | [diff] [blame] | 400 | 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 | |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 415 | 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 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 438 | |
| 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 Kostiuk | 1efd001 | 2022-09-13 12:08:36 -0400 | [diff] [blame] | 447 | let vCard = vCards.first else { return nil } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 448 | return vCard.familyName.isEmpty ? vCard.givenName : vCard.familyName |
| 449 | } |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 450 | } |
| 451 | |
| 452 | // MARK: DarwinNotificationHandler |
| 453 | extension NotificationService: DarwinNotificationHandler { |
| 454 | func listenToMainAppResponse(completion: @escaping (Bool) -> Void) { |
| 455 | let observer = Unmanaged.passUnretained(self).toOpaque() |
| 456 | CFNotificationCenterAddObserver(notificationCenter, |
| 457 | observer, { (_, _, _, _, _) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 458 | NotificationCenter.default.post(name: NotificationService.localNotificationName, |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 459 | object: nil, |
| 460 | userInfo: nil) |
| 461 | }, |
| 462 | Constants.notificationAppIsActive, |
| 463 | nil, |
| 464 | .deliverImmediately) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 465 | NotificationCenter.default.addObserver(forName: NotificationService.localNotificationName, object: nil, queue: nil) { _ in |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 466 | completion(true) |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | func removeObserver() { |
| 471 | let observer = Unmanaged.passUnretained(self).toOpaque() |
| 472 | CFNotificationCenterRemoveEveryObserver(notificationCenter, observer) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 473 | NotificationCenter.default.removeObserver(self, name: NotificationService.localNotificationName, object: nil) |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 474 | } |
| 475 | |
| 476 | } |
| 477 | |
| 478 | // MARK: present notifications |
| 479 | extension 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 | |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 496 | private func configureFileNotification(from: String, url: URL, accountId: String, conversationId: String) { |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 497 | let content = UNMutableNotificationContent() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 498 | content.sound = UNNotificationSound.default |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 499 | let imageName = url.lastPathComponent |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 500 | content.body = imageName |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 501 | 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 |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 506 | if let image = UIImage(contentsOfFile: url.path), let attachement = createAttachment(identifier: imageName, image: image, options: nil) { |
| 507 | content.attachments = [ attachement ] |
| 508 | } |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 509 | 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 Kostiuk | 2648aab | 2022-08-30 14:24:03 -0400 | [diff] [blame] | 519 | private func configureMessageNotification(from: String, body: String, accountId: String, conversationId: String, groupTitle: String) { |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 520 | let content = UNMutableNotificationContent() |
| 521 | content.body = body |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 522 | content.sound = UNNotificationSound.default |
kkostiuk | 8e397cd | 2022-07-27 15:08:10 -0400 | [diff] [blame] | 523 | 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 Kostiuk | 2648aab | 2022-08-30 14:24:03 -0400 | [diff] [blame] | 528 | let title = !groupTitle.isEmpty ? groupTitle : self.bestName(accountId: accountId, contactId: from) |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 529 | 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 |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 540 | setNotificationCount(notification: content) |
| 541 | let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false) |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 542 | let notificationRequest = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger) |
| 543 | UNUserNotificationCenter.current().add(notificationRequest) { [weak self] (error) in |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 544 | if notification.type == .message { |
| 545 | self?.numberOfMessages -= 1 |
| 546 | } else { |
| 547 | self?.numberOfFiles -= 1 |
| 548 | } |
Kateryna Kostiuk | 3b58171 | 2022-07-21 08:42:14 -0400 | [diff] [blame] | 549 | self?.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 550 | if let error = error { |
| 551 | print("Unable to Add Notification Request (\(error), \(error.localizedDescription))") |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 556 | private func presentCall(info: [AnyHashable: Any]) { |
Kateryna Kostiuk | fd5e6f1 | 2022-08-02 11:24:05 -0400 | [diff] [blame] | 557 | CXProvider.reportNewIncomingVoIPPushPayload(info, completion: { error in |
| 558 | print("NotificationService", "Did report voip notification, error: \(String(describing: error))") |
| 559 | }) |
kkostiuk | abde7b9 | 2022-07-28 13:15:56 -0400 | [diff] [blame] | 560 | self.pendingCalls.removeAll() |
| 561 | self.pendingLocalNotifications.removeAll() |
kkostiuk | e10e657 | 2022-07-26 15:41:12 -0400 | [diff] [blame] | 562 | self.verifyTasksStatus() |
kkostiuk | 74d1ae4 | 2021-06-17 11:10:15 -0400 | [diff] [blame] | 563 | } |
| 564 | } |