NotificationService.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import UserNotifications
  2. import CoreData
  3. import CryptoKit
  4. /// This app extension is responsible for persisting the incoming notification to the data store (Core Data). It will eventually be the entity that
  5. /// fetches notification content from selfhosted servers (when a "poll request" is received). This is not implemented yet.
  6. ///
  7. /// Note that the app extension does not run as part of the main app, so log messages are not printed in the main Xcode window. To debug,
  8. /// select Debug -> Attach to Process by PID or Name, and select the extension. Don't forget to set a breakpoint, or you're not gonna have a good time.
  9. class NotificationService: UNNotificationServiceExtension {
  10. private let tag = "NotificationService"
  11. private var store: Store?
  12. var contentHandler: ((UNNotificationContent) -> Void)?
  13. var bestAttemptContent: UNMutableNotificationContent?
  14. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
  15. self.store = Store.shared
  16. self.contentHandler = contentHandler
  17. self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
  18. Log.d(tag, "Notification received (in service)") // Logs from extensions are not printed in Xcode!
  19. if let bestAttemptContent = bestAttemptContent {
  20. let userInfo = bestAttemptContent.userInfo
  21. guard let message = Message.from(userInfo: userInfo) else {
  22. Log.w(tag, "Message cannot be parsed from userInfo", userInfo)
  23. contentHandler(request.content)
  24. return
  25. }
  26. switch message.event {
  27. case "poll_request":
  28. handlePollRequest(request, bestAttemptContent, message, contentHandler)
  29. case "message":
  30. let baseUrl = userInfo["base_url"] as? String ?? Config.appBaseUrl // messages only come for the main server
  31. handleMessage(request, bestAttemptContent, baseUrl, message, contentHandler)
  32. default:
  33. Log.w(tag, "Irrelevant message received", message)
  34. contentHandler(request.content)
  35. }
  36. }
  37. }
  38. override func serviceExtensionTimeWillExpire() {
  39. // Called just before the extension will be terminated by the system.
  40. // Use this as an opportunity to deliver your "best attempt" at modified content,
  41. // otherwise the original push payload will be used.
  42. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
  43. contentHandler(bestAttemptContent)
  44. }
  45. }
  46. private func handleMessage(_ request: UNNotificationRequest, _ content: UNMutableNotificationContent, _ baseUrl: String, _ message: Message, _ contentHandler: @escaping (UNNotificationContent) -> Void) {
  47. // Modify notification based on message
  48. content.modify(message: message, baseUrl: baseUrl)
  49. // Save notification to store, and display it
  50. guard let subscription = store?.getSubscription(baseUrl: baseUrl, topic: message.topic) else {
  51. Log.w(tag, "Subscription \(topicUrl(baseUrl: baseUrl, topic: message.topic)) unknown")
  52. contentHandler(request.content)
  53. return
  54. }
  55. Store.shared.save(notificationFromMessage: message, withSubscription: subscription)
  56. contentHandler(content)
  57. }
  58. private func handlePollRequest(_ request: UNNotificationRequest, _ content: UNMutableNotificationContent, _ pollRequest: Message, _ contentHandler: @escaping (UNNotificationContent) -> Void) {
  59. let subscription = store?.getSubscriptions()?.first { $0.urlHash() == pollRequest.topic }
  60. let baseUrl = subscription?.baseUrl
  61. guard
  62. let subscription = subscription,
  63. let pollId = pollRequest.pollId,
  64. let baseUrl = baseUrl
  65. else {
  66. Log.w(tag, "Cannot find subscription", pollRequest)
  67. contentHandler(request.content)
  68. return
  69. }
  70. // Poll original server
  71. let user = store?.getUser(baseUrl: baseUrl)?.toBasicUser()
  72. let semaphore = DispatchSemaphore(value: 0)
  73. ApiService.shared.poll(subscription: subscription, messageId: pollId, user: user) { message, error in
  74. guard let message = message else {
  75. Log.w(self.tag, "Error fetching message", error)
  76. contentHandler(request.content)
  77. return
  78. }
  79. self.handleMessage(request, content, baseUrl, message, contentHandler)
  80. semaphore.signal()
  81. }
  82. // Note: If notifications only show up as "New message", it may be because the "return" statement
  83. // happens before the contentHandler() is called. We add this semaphore here to synchronize the threads.
  84. // I don't know if this is necessary, but it feels like the right thing to do.
  85. _ = semaphore.wait(timeout: DispatchTime.now() + 25) // 30 seconds is the max for the entire extension
  86. }
  87. }