open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

DiveNotifier.swift (5356B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import UIKit
      4 @preconcurrency import UserNotifications
      5 #if canImport(ActivityKit)
      6 @preconcurrency import ActivityKit
      7 #endif
      8 import RemoraDeco
      9 import RemoraUI
     10 
     11 /// iPhone notifications:
     12 /// - when a dive is received (tapping it opens Sub Rascasse, which imports it);
     13 /// - at the end of the no-fly time;
     14 /// - "no-fly time" Live Activity (lock screen, Dynamic Island), started when the app is in the foreground
     15 ///   (iOS does not allow starting it in the background without a push notification server).
     16 @MainActor
     17 final class DiveNotifier: NSObject, UNUserNotificationCenterDelegate {
     18     static let subRascasseURL = URL(string: "subrascasse://open-remora")!
     19     private let center = UNUserNotificationCenter.current()
     20     /// Identifier of the pending notification: kept as is so that an update replaces the one already scheduled.
     21     private let noFlyEndID = "open-remora.avion"
     22 
     23     override init() {
     24         super.init()
     25         center.delegate = self
     26     }
     27 
     28     func requestAuthorization() async {
     29         _ = try? await center.requestAuthorization(options: [.alert, .sound])
     30     }
     31 
     32     /// Dive received from the watch (the app may be in the background).
     33     func diveReceived(_ dive: DiveLog, noFlyHours: Double) {
     34         let content = UNMutableNotificationContent()
     35         content.title = String(localized: "Dive no. \(dive.number) received")
     36         let depth = Format.depth(dive.maxDepth), duration = Format.minutes(dive.duration)
     37         content.body = noFlyHours > 0
     38             ? String(localized: "\(depth) m · \(duration) · flying in \(Format.hours(noFlyHours)). Tap to open it in Sub Rascasse.")
     39             : String(localized: "\(depth) m · \(duration). Tap to open it in Sub Rascasse.")
     40         content.sound = .default
     41         content.userInfo = ["open": "subrascasse"]
     42         center.add(UNNotificationRequest(identifier: "plongee-\(dive.id.uuidString)", content: content, trigger: nil))
     43         scheduleNoFlyEnd(after: noFlyHours)
     44     }
     45 
     46     /// Notification at the end of the no-fly time (replaces the previous one).
     47     func scheduleNoFlyEnd(after hours: Double) {
     48         center.removePendingNotificationRequests(withIdentifiers: [noFlyEndID])
     49         guard hours > 0 else { return }
     50         let content = UNMutableNotificationContent()
     51         content.title = String(localized: "No-fly time is over")
     52         content.body = String(localized: "According to Open Rémora and the DAN rule, you can fly. Also follow your primary computer.")
     53         content.sound = .default
     54         let trigger = UNTimeIntervalNotificationTrigger(timeInterval: hours * 3600, repeats: false)
     55         center.add(UNNotificationRequest(identifier: noFlyEndID, content: content, trigger: trigger))
     56     }
     57 
     58     /// Starts, updates or ends the Live Activity (app in the foreground).
     59     func updateLiveActivity(lastDive: DiveLog?, noFlyHours: Double, altitudeHours: Double) {
     60         #if canImport(ActivityKit)
     61         let now = Date()
     62         let attributes = lastDive.map { NoFlyAttributes(diveNumber: $0.number, maxDepth: $0.maxDepth, diveEnd: $0.end) }
     63         let state = NoFlyAttributes.ContentState(
     64             until: now.addingTimeInterval(noFlyHours * 3600),
     65             altitudeUntil: altitudeHours > 0 ? now.addingTimeInterval(altitudeHours * 3600) : nil)
     66         let enabled = ActivityAuthorizationInfo().areActivitiesEnabled
     67         Task.detached {
     68             await Self.apply(attributes: noFlyHours > 0 ? attributes : nil, state: state, enabled: enabled)
     69         }
     70         #endif
     71     }
     72 
     73     #if canImport(ActivityKit)
     74     /// All the work on activities happens here, off the main actor.
     75     nonisolated private static func apply(attributes: NoFlyAttributes?, state: NoFlyAttributes.ContentState,
     76                                           enabled: Bool) async {
     77         let content = ActivityContent(state: state, staleDate: state.until)
     78         var kept = false
     79         for activity in Activity<NoFlyAttributes>.activities {
     80             if let attributes, !kept, activity.attributes.diveNumber == attributes.diveNumber {
     81                 await activity.update(content)
     82                 kept = true
     83             } else {
     84                 await activity.end(nil, dismissalPolicy: .immediate)
     85             }
     86         }
     87         guard let attributes, !kept, enabled else { return }
     88         _ = try? Activity.request(attributes: attributes, content: content)
     89     }
     90     #endif
     91 
     92     // MARK: UNUserNotificationCenterDelegate
     93 
     94     /// Notification tapped: go straight to Sub Rascasse when it is installed.
     95     nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
     96                                             didReceive response: UNNotificationResponse) async {
     97         guard response.notification.request.content.userInfo["open"] as? String == "subrascasse" else { return }
     98         await MainActor.run {
     99             if UIApplication.shared.canOpenURL(Self.subRascasseURL) {
    100                 UIApplication.shared.open(Self.subRascasseURL)
    101             }
    102         }
    103     }
    104 
    105     /// App in the foreground: show the notification anyway.
    106     nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
    107                                             willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
    108         [.banner, .sound]
    109     }
    110 }