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

commit 7ef9a9cc9083f40cecad3aae75b05888ce163309
parent cfeb0b31b6d904f843993262ec6d2496c320d098
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 23:41:40 -0500

iPhone: notification when a dive arrives (opens Sub Rascasse), "time to fly" Live Activity, notification at the end of the delay; watch: transfer status to the iPhone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYGcjJYQu2t1EUEKgbs

Diffstat:
M.gitignore | 1+
AOpenRemora/DiveNotifier.swift | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MOpenRemora/HomeView.swift | 1+
MOpenRemora/OpenRemoraApp.swift | 5++++-
MOpenRemora/PhoneStore.swift | 18++++++++++++++++++
MOpenRemoraWatch/DiveDetailView.swift | 13+++++++++++++
MOpenRemoraWatch/PhoneLink.swift | 13++++++++++++-
AOpenRemoraWidgets/NoFlyLiveActivity.swift | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AShared/NoFlyActivity.swift | 21+++++++++++++++++++++
Mfastlane/Fastfile | 4++--
Mproject.yml | 25+++++++++++++++++++++++++
11 files changed, 294 insertions(+), 4 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -5,3 +5,4 @@ build/ OpenRemoraWatch/Info.plist OpenRemora/Info.plist OpenRemora/OpenRemora.entitlements +OpenRemoraWidgets/Info.plist diff --git a/OpenRemora/DiveNotifier.swift b/OpenRemora/DiveNotifier.swift @@ -0,0 +1,112 @@ +import Foundation +import UIKit +@preconcurrency import UserNotifications +#if canImport(ActivityKit) +@preconcurrency import ActivityKit +#endif +import RemoraDeco + +/// Notifications de l'iPhone : +/// - à la réception d'une plongée (la toucher ouvre Sub Rascasse, qui l'importe) ; +/// - à la fin du délai avant l'avion ; +/// - activité en direct « délai avant l'avion » (écran verrouillé, Dynamic Island), démarrée quand l'app +/// est au premier plan (iOS ne permet pas de la lancer en arrière-plan sans serveur de notifications). +@MainActor +final class DiveNotifier: NSObject, UNUserNotificationCenterDelegate { + static let subRascasseURL = URL(string: "subrascasse://open-remora")! + private let center = UNUserNotificationCenter.current() + private let noFlyEndID = "open-remora.avion" + + override init() { + super.init() + center.delegate = self + } + + func requestAuthorization() async { + _ = try? await center.requestAuthorization(options: [.alert, .sound]) + } + + /// Plongée reçue de la montre (l'app peut être en arrière-plan). + func diveReceived(_ dive: DiveLog, noFlyHours: Double) { + let content = UNMutableNotificationContent() + content.title = "Plongée nº \(dive.number) reçue" + var body = "\(Format.depth(dive.maxDepth)) m · \(Format.minutes(dive.duration))" + if noFlyHours > 0 { body += " · avion dans \(Self.hours(noFlyHours))" } + body += ". Touchez pour l'ouvrir dans Sub Rascasse." + content.body = body + content.sound = .default + content.userInfo = ["open": "subrascasse"] + center.add(UNNotificationRequest(identifier: "plongee-\(dive.id.uuidString)", content: content, trigger: nil)) + scheduleNoFlyEnd(after: noFlyHours) + } + + /// Notification à la fin du délai avant l'avion (remplace la précédente). + func scheduleNoFlyEnd(after hours: Double) { + center.removePendingNotificationRequests(withIdentifiers: [noFlyEndID]) + guard hours > 0 else { return } + let content = UNMutableNotificationContent() + content.title = "Délai avant l'avion terminé" + content.body = "D'après Open Rémora et la règle de DAN, vous pouvez prendre l'avion. Suivez aussi votre ordinateur principal." + content.sound = .default + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: hours * 3600, repeats: false) + center.add(UNNotificationRequest(identifier: noFlyEndID, content: content, trigger: trigger)) + } + + /// Démarre, met à jour ou termine l'activité en direct (app au premier plan). + func updateLiveActivity(lastDive: DiveLog?, noFlyHours: Double, altitudeHours: Double) { + #if canImport(ActivityKit) + let now = Date() + let attributes = lastDive.map { NoFlyAttributes(diveNumber: $0.number, maxDepth: $0.maxDepth, diveEnd: $0.end) } + let state = NoFlyAttributes.ContentState( + until: now.addingTimeInterval(noFlyHours * 3600), + altitudeUntil: altitudeHours > 0 ? now.addingTimeInterval(altitudeHours * 3600) : nil) + let enabled = ActivityAuthorizationInfo().areActivitiesEnabled + Task.detached { + await Self.apply(attributes: noFlyHours > 0 ? attributes : nil, state: state, enabled: enabled) + } + #endif + } + + #if canImport(ActivityKit) + /// Tout le travail sur les activités se fait ici, hors de l'acteur principal. + nonisolated private static func apply(attributes: NoFlyAttributes?, state: NoFlyAttributes.ContentState, + enabled: Bool) async { + let content = ActivityContent(state: state, staleDate: state.until) + var kept = false + for activity in Activity<NoFlyAttributes>.activities { + if let attributes, !kept, activity.attributes.diveNumber == attributes.diveNumber { + await activity.update(content) + kept = true + } else { + await activity.end(nil, dismissalPolicy: .immediate) + } + } + guard let attributes, !kept, enabled else { return } + _ = try? Activity.request(attributes: attributes, content: content) + } + #endif + + // MARK: UNUserNotificationCenterDelegate + + /// Notification touchée : on passe directement dans Sub Rascasse s'il est installé. + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse) async { + guard response.notification.request.content.userInfo["open"] as? String == "subrascasse" else { return } + await MainActor.run { + if UIApplication.shared.canOpenURL(Self.subRascasseURL) { + UIApplication.shared.open(Self.subRascasseURL) + } + } + } + + /// App au premier plan : afficher quand même la notification. + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, + willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { + [.banner, .sound] + } + + static func hours(_ h: Double) -> String { + let total = Int((h * 60).rounded(.up)) + return total >= 60 ? "\(total / 60) h \(String(format: "%02d", total % 60))" : "\(total) min" + } +} diff --git a/OpenRemora/HomeView.swift b/OpenRemora/HomeView.swift @@ -35,6 +35,7 @@ struct HomeView: View { private func refresh() { store.refreshOutbox() + store.refreshLiveActivity() subRascasseInstalled = UIApplication.shared.canOpenURL(Self.subRascasseURL) exportURL = store.dives.isEmpty ? nil : store.exportUDDF() } diff --git a/OpenRemora/OpenRemoraApp.swift b/OpenRemora/OpenRemoraApp.swift @@ -12,7 +12,10 @@ struct OpenRemoraApp: App { .requiresTerms() .environment(store) .task { - if CommandLine.arguments.contains("-demo") { store.seedDemo() } else { store.activate() } + if CommandLine.arguments.contains("-demo") { store.seedDemo() } else { + store.activate() + await store.notifier.requestAuthorization() + } } } } diff --git a/OpenRemora/PhoneStore.swift b/OpenRemora/PhoneStore.swift @@ -18,6 +18,7 @@ final class PhoneStore: NSObject, WCSessionDelegate { private let folder: URL private var demo = false + let notifier = DiveNotifier() private var logbookURL: URL { folder.appendingPathComponent("plongees.json") } private var settingsURL: URL { folder.appendingPathComponent("reglages-montre.json") } @@ -49,6 +50,7 @@ final class PhoneStore: NSObject, WCSessionDelegate { logbook.add(second) pendingForSubRascasse = 1 sharedFolderAvailable = true + refreshLiveActivity() // seulement avec -liveActivity (voir refreshLiveActivity) } func activate() { @@ -101,6 +103,22 @@ final class PhoneStore: NSObject, WCSessionDelegate { } } refreshOutbox() + notifier.diveReceived(dive, noFlyHours: noFlyHours) + } + + /// Heures avant l'avion d'après les plongées reçues (0 = plus de restriction). + var noFlyHours: Double { + SurfaceAdvice.noFlyHours(logbook: logbook, at: Date(), surfacePressure: standardSurfacePressure) + } + + var altitudeHours: Double { + SurfaceAdvice.hoursBeforeAltitude(2000, logbook: logbook, at: Date(), surfacePressure: standardSurfacePressure) + } + + /// Activité en direct « délai avant l'avion » (à appeler app au premier plan). + func refreshLiveActivity() { + guard !demo || CommandLine.arguments.contains("-liveActivity") else { return } + notifier.updateLiveActivity(lastDive: dives.first, noFlyHours: noFlyHours, altitudeHours: altitudeHours) } private func receive(context: [String: Any]) { diff --git a/OpenRemoraWatch/DiveDetailView.swift b/OpenRemoraWatch/DiveDetailView.swift @@ -5,6 +5,7 @@ import RemoraDeco /// Résumé d'une plongée : le profil en premier, on le touche pour le parcourir à la couronne. struct DiveDetailView: View { let dive: DiveLog + @AppStorage(PhoneLink.deliveredKey) private var delivered = "" var body: some View { List { @@ -17,6 +18,18 @@ struct DiveDetailView: View { } } + if dive.source == .remora { + Section { + if delivered.contains(dive.id.uuidString) { + Label("Sur l'iPhone", systemImage: "checkmark.circle.fill").foregroundStyle(.green) + } else { + Label("En attente de l'iPhone", systemImage: "iphone.slash").foregroundStyle(.orange) + } + } footer: { + Text("De là, elle passe dans Sub Rascasse.") + } + } + Section { row("Profondeur max", "\(Format.depth(dive.maxDepth)) m") row("Durée", Format.clock(dive.duration)) diff --git a/OpenRemoraWatch/PhoneLink.swift b/OpenRemoraWatch/PhoneLink.swift @@ -55,9 +55,20 @@ final class PhoneLink: NSObject, WCSessionDelegate { } } + /// Plongées bien arrivées sur l'iPhone (identifiants séparés par des virgules, lus par le résumé de plongée). + static let deliveredKey = "phoneDeliveredDiveIDs" + nonisolated func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: (any Error)?) { try? FileManager.default.removeItem(at: fileTransfer.file.fileURL) - guard error != nil else { return } + guard error != nil else { + let id = fileTransfer.file.fileURL.deletingPathExtension().lastPathComponent + Task { @MainActor in + var delivered = Set((UserDefaults.standard.string(forKey: Self.deliveredKey) ?? "").split(separator: ",").map(String.init)) + delivered.insert(id) + UserDefaults.standard.set(delivered.sorted().joined(separator: ","), forKey: Self.deliveredKey) + } + return + } // Échec : la plongée repartira au prochain lancement. let id = fileTransfer.file.fileURL.deletingPathExtension().lastPathComponent Task { @MainActor in diff --git a/OpenRemoraWidgets/NoFlyLiveActivity.swift b/OpenRemoraWidgets/NoFlyLiveActivity.swift @@ -0,0 +1,85 @@ +import ActivityKit +import SwiftUI +import WidgetKit + +@main +struct OpenRemoraWidgets: WidgetBundle { + var body: some Widget { + NoFlyLiveActivity() + } +} + +/// Écran verrouillé et Dynamic Island : compte à rebours jusqu'à l'heure où l'avion redevient possible. +struct NoFlyLiveActivity: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: NoFlyAttributes.self) { context in + LockScreenView(context: context) + .padding() + .activityBackgroundTint(Color(red: 0.02, green: 0.12, blue: 0.28)) + .activitySystemActionForegroundColor(.white) + } dynamicIsland: { context in + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + Label("Avion", systemImage: "airplane").font(.headline) + } + DynamicIslandExpandedRegion(.trailing) { + Countdown(until: context.state.until).font(.title3.monospacedDigit()) + } + DynamicIslandExpandedRegion(.bottom) { + Text("Plongée nº \(context.attributes.diveNumber) · \(depth(context.attributes.maxDepth)) m") + .font(.caption).foregroundStyle(.secondary) + } + } compactLeading: { + Image(systemName: "airplane").foregroundStyle(.orange) + } compactTrailing: { + Countdown(until: context.state.until).monospacedDigit().frame(maxWidth: 52) + } minimal: { + Image(systemName: "airplane").foregroundStyle(.orange) + } + } + } +} + +private struct LockScreenView: View { + let context: ActivityViewContext<NoFlyAttributes> + + var body: some View { + HStack(alignment: .center, spacing: 12) { + Image(systemName: "airplane") + .font(.title2) + .foregroundStyle(.orange) + VStack(alignment: .leading, spacing: 2) { + Text("Pas d'avion avant \(context.state.until.formatted(date: .omitted, time: .shortened))") + .font(.headline) + if let altitude = context.state.altitudeUntil, altitude > .now { + Text("Pas au-dessus de 2000 m avant \(altitude.formatted(date: .omitted, time: .shortened))") + .font(.caption) + } + Text("Open Rémora · plongée nº \(context.attributes.diveNumber), \(depth(context.attributes.maxDepth)) m") + .font(.caption2).foregroundStyle(.secondary) + } + Spacer(minLength: 0) + Countdown(until: context.state.until) + .font(.title2.monospacedDigit().bold()) + .multilineTextAlignment(.trailing) + } + .foregroundStyle(.white) + } +} + +/// Compte à rebours tenu à jour par le système, sans réveiller l'app. +private struct Countdown: View { + let until: Date + + var body: some View { + if until > .now { + Text(timerInterval: Date.now...until, countsDown: true) + } else { + Text("OK") + } + } +} + +private func depth(_ metres: Double) -> String { + String(format: "%.0f", metres) +} diff --git a/Shared/NoFlyActivity.swift b/Shared/NoFlyActivity.swift @@ -0,0 +1,21 @@ +import Foundation +#if canImport(ActivityKit) && os(iOS) +import ActivityKit + +/// Activité en direct « délai avant l'avion » : sur l'écran verrouillé et dans la Dynamic Island de l'iPhone, +/// avec un compte à rebours jusqu'à l'heure où l'avion redevient possible. +/// Limite d'iOS : une activité en direct reste active 8 h, puis jusqu'à 4 h sur l'écran verrouillé ; +/// une notification annonce la fin du délai dans tous les cas. +struct NoFlyAttributes: ActivityAttributes { + struct ContentState: Codable, Hashable { + /// Heure à partir de laquelle l'avion redevient possible. + var until: Date + /// Heure à partir de laquelle on peut monter à 2000 m (nil : déjà possible). + var altitudeUntil: Date? + } + + var diveNumber: Int + var maxDepth: Double + var diveEnd: Date +} +#endif diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -68,9 +68,9 @@ platform :ios do end texts = { "fr-CA" => ["Ordinateur de plongée secondaire, libre et gratuit, pour Apple Watch Ultra. Non certifié : à porter avec un ordinateur principal.", - "0.1 (5) : dossier partagé avec Sub Rascasse (groupe d'apps). Depuis la 4 : avertissement à accepter au premier lancement (montre et iPhone) ; « Prêt à plonger » sur la montre (séance d'entraînement, l'app reste ouverte) ; plongées enregistrées dans Santé ; app iPhone : réglages de la montre, dernière plongée, délai avant l'avion. À essayer à sec : accepter, autoriser Santé, « Prêt à plonger » puis Annuler, plongée de démonstration, ouvrir l'app iPhone."], + "0.1 (6) : notification à l'arrivée d'une plongée sur l'iPhone (la toucher ouvre Sub Rascasse) ; activité en direct « délai avant l'avion » sur l'écran verrouillé ; notification à la fin du délai ; sur la montre, « Sur l'iPhone » ou « En attente de l'iPhone » dans le résumé d'une plongée. Depuis la 4 : avertissement à accepter au premier lancement (montre et iPhone) ; « Prêt à plonger » sur la montre (séance d'entraînement, l'app reste ouverte) ; plongées enregistrées dans Santé ; app iPhone : réglages de la montre, dernière plongée, délai avant l'avion. À essayer à sec : accepter, autoriser Santé, « Prêt à plonger » puis Annuler, plongée de démonstration, ouvrir l'app iPhone."], "en-CA" => ["Free, open-source backup dive computer for Apple Watch Ultra. Not certified: wear it with a primary dive computer.", - "0.1 (5): folder shared with Sub Rascasse (app group). Since build 4: warning to accept on first launch (watch and iPhone); \"Prêt à plonger\" on the watch (workout session keeps the app open); dives saved to Health; iPhone app: watch settings, last dive, no-fly time. Try it dry: accept, allow Health, \"Prêt à plonger\" then Cancel, demo dive, open the iPhone app."], + "0.1 (6): notification when a dive reaches the iPhone (tap opens Sub Rascasse); no-fly Live Activity on the Lock Screen; notification when the no-fly time ends; on the watch, delivery status in the dive summary. Since build 4: warning to accept on first launch (watch and iPhone); \"Prêt à plonger\" on the watch (workout session keeps the app open); dives saved to Health; iPhone app: watch settings, last dive, no-fly time. Try it dry: accept, allow Health, \"Prêt à plonger\" then Cancel, demo dive, open the iPhone app."], } _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations") texts.each do |locale, (description, _)| diff --git a/project.yml b/project.yml @@ -25,6 +25,8 @@ targets: - path: Shared dependencies: - target: OpenRemoraWatch + - target: OpenRemoraWidgets + embed: true - package: RemoraDeco settings: base: @@ -45,12 +47,35 @@ targets: UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait] # Ouvrir Sub Rascasse (le carnet) s'il est installé. LSApplicationQueriesSchemes: [subrascasse] + # Activité en direct « délai avant l'avion ». + NSSupportsLiveActivities: true entitlements: path: OpenRemora/OpenRemora.entitlements properties: # Dossier partagé avec Sub Rascasse (même équipe) : voir docs/PARTAGE.md. # Groupe créé et rattaché à la main sur le portail développeur (la clé API ne peut pas le faire). com.apple.security.application-groups: [group.org.schurger.dive] + # Activité en direct « délai avant l'avion » (écran verrouillé, Dynamic Island). + OpenRemoraWidgets: + type: app-extension + platform: iOS + sources: + - path: OpenRemoraWidgets + - path: Shared/NoFlyActivity.swift + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openremora.widgets + PRODUCT_NAME: OpenRemoraWidgets + TARGETED_DEVICE_FAMILY: "1" + SKIP_INSTALL: YES + info: + path: OpenRemoraWidgets/Info.plist + properties: + CFBundleDisplayName: Open Rémora + CFBundleShortVersionString: $(MARKETING_VERSION) + CFBundleVersion: $(CURRENT_PROJECT_VERSION) + NSExtension: + NSExtensionPointIdentifier: com.apple.widgetkit-extension OpenRemoraWatch: type: application platform: watchOS