Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Util / Util.swift

Util.swift363 lines · 15.2 KiBRaw
1import Foundation
2import UIKit
3import UserNotifications
4import Contacts
5import ContactsUI
6import SwiftUI
7
8// MARK: - Strings (English only for v1)
9
10enum Strings {
11 static let appName = "FindFamily"
12 static let permissionGrantLocation = "Grant Location Permission"
13 static let permissionLocationGranted = "Location Permission Granted"
14 static let permissionGrantAlways = "Enable Always-On Location"
15 static let permissionAlwaysGranted = "Always-On Location Granted"
16 static let permissionAlwaysExplanation = "FindFamily needs Always-On Location so it can update your family while you're moving and the app is in the background."
17
18 static let sectionLocationSharingRequests = "Location Sharing Requests"
19 static let sectionTemporaryLinks = "Temporary Links"
20 static let sectionSavedPlaces = "Saved Places"
21 static let fabShareInvite = "Share Invite"
22 static let fabLocation = "Add Place"
23 static let fabLink = "Add Link"
24
25 static let nobodyHere = "Nobody is currently here"
26 static func userIsHere(_ name: String) -> String { "\(name) is currently here" }
27 static func usersAreHere(_ names: String) -> String { "\(names) are currently here" }
28
29 static let shareYourLocation = "Share your location"
30 static let changeConnectedContact = "Change connected contact"
31 static let lastUpdatedNever = "Never updated"
32 static let today = "today"
33 static let yesterday = "yesterday"
34
35 static let sinceJustNow = "Since just now"
36 static func sinceMinutesAgo(_ m: Int64) -> String { "Since \(m) minutes ago" }
37 static func sinceTimeDate(_ time: String, _ date: String) -> String { "Since \(time) \(date)" }
38 static func userCardStatus(_ updated: String, _ place: String, _ since: String) -> String {
39 "\(updated)\nAt \(place)\(since.isEmpty ? "" : "\n" + since)"
40 }
41 static func batteryPercentage(_ p: Int) -> String { "\(p)%" }
42
43 static let timeJustNow = "just now"
44 static func timeMinutesAgo(_ m: Int64) -> String { "\(m) minutes ago" }
45 static func timeHoursAgo(_ h: Int64) -> String { "\(h) hours ago" }
46 static func timeDaysAgo(_ d: Int64) -> String { "\(d) days ago" }
47 static let timeVerySoon = "very soon"
48 static func timeInMinutes(_ m: Int64) -> String { "in \(m) minutes" }
49 static func timeInHours(_ h: Int64) -> String { "in \(h) hours" }
50 static func timeInDays(_ d: Int64) -> String { "in \(d) days" }
51
52 static func expires(_ s: String) -> String { "Expires \(s)" }
53 static func requestFrom(_ id: String) -> String { "Request from \(id)" }
54
55 static let historyButton = "History"
56 static let hideButton = "Hide"
57 static let historyRewindSmall = "<"
58 static let historyForwardSmall = ">"
59 static let historyRewindMedium = "<<"
60 static let historyForwardMedium = ">>"
61 static let historyRewindLarge = "<<<"
62 static let historyForwardLarge = ">>>"
63
64 static let waypointNameBlankError = "Name is required"
65 static let waypointRangeError = "Range must be a number"
66 static let waypointRangeSuffix = "meters"
67
68 static let missingFeaturesTitle = "Missing features"
69 static let missingFeaturesExplanation = "Your device is missing the geocoder or network location provider. Some features may not work."
70
71 static let addLinkTitle = "Create Temporary Link"
72 static let addLinkLabelField = "Link Label (to differentiate links)"
73 static let addLinkExpiryField = "Expiry Time"
74 static let addLinkSubmit = "Create Link"
75
76 static let addPersonYourID = "Your FindFamily ID"
77 static let addPersonTheirID = "Contact's FindFamily ID"
78 static let addPersonName = "Contact's Name"
79 static let addPersonSubmit = "Request Location"
80 static let shareInviteLink = "Share invite link"
81 static let shareInviteTitle = "Share Invite"
82
83 static let backupExport = "Export Backup"
84 static let backupImport = "Import Backup"
85
86 static let notifSharingRequestTitle = "Location Requested"
87 static func notifSharingRequestBody(_ id: String) -> String { "ID \(id) wants to see your location." }
88 static let notifBatteryLowTitle = "Battery Low"
89 static func notifBatteryLowBody(_ name: String, _ pct: Int) -> String { "\(name)'s battery is at \(pct)%" }
90 static let notifWaypointEnterTitle = "Place Update"
91 static func notifWaypointEnterBody(_ name: String, _ place: String) -> String { "\(name) is at \(place)" }
92 static let notifWaypointExitTitle = "Place Update"
93 static func notifWaypointExitBody(_ name: String, _ place: String) -> String { "\(name) left \(place)" }
94
95 static let okButton = "OK"
96 static let cancelButton = "Cancel"
97 static let doneButton = "Done"
98
99 // Auto-toggle sharing ("Disable/Enable after" timer)
100 static let autoToggleNever = "Never"
101 static let disableAfter = "Disable after"
102 static let enableAfter = "Enable after"
103
104 // Duration options (shared with temporary-link expiry)
105 static let duration15Minutes = "15 minutes"
106 static let duration30Minutes = "30 minutes"
107 static let duration1Hour = "1 hour"
108 static let duration2Hours = "2 hours"
109 static let duration4Hours = "4 hours"
110 static let duration6Hours = "6 hours"
111 static let duration12Hours = "12 hours"
112 static let duration1Day = "1 day"
113 static let duration2Days = "2 days"
114 static let duration1Week = "1 week"
115
116 // Security code (safety number) verification
117 static let securityCodeTitle = "Security Code"
118 static func securityCodeCompare(_ name: String) -> String {
119 "Compare this code with the one shown on \(name)'s device. If they match, your connection is verified and no one is intercepting it."
120 }
121 static let securityCodeComputing = "Computing…"
122 static func securityCodeUnavailable(_ name: String) -> String {
123 "Couldn't compute the code yet — \(name)'s key isn't available. Try again once they've shared their location."
124 }
125
126 // Shown when connecting to a peer whose app is too old for post-quantum encryption.
127 static let outdatedPeerTitle = "Update needed"
128 static let outdatedPeerMessage = "This person is using an older version of FindFamily that doesn't support quantum-safe encryption. Ask them to update their app, then try connecting again."
129
130 // Shown when a peer's key doesn't match the fingerprint their invite link vouched for.
131 static let keyMismatchTitle = "Couldn't verify this person"
132 static let keyMismatchMessage = "The encryption key for this person doesn't match the one their invite link listed, so they weren't added. Check that you opened the whole link, and ask them to send a new one."
133}
134
135// MARK: - Time formatting
136
137enum TimeFormatting {
138 static let dayMonth: DateFormatter = {
139 let f = DateFormatter()
140 f.dateFormat = "MMM d"
141 return f
142 }()
143 static let amPmTimeSeconds: DateFormatter = {
144 let f = DateFormatter()
145 f.dateFormat = "h:mm:ss a"
146 return f
147 }()
148 static let amPmTime: DateFormatter = {
149 let f = DateFormatter()
150 f.dateFormat = "h:mm a"
151 return f
152 }()
153
154 static func timestring(_ timestamp: Date, future: Bool) -> String {
155 let secs = abs(Int64(Date().timeIntervalSince(timestamp)))
156 let mins = secs / 60
157 let hours = mins / 60
158 let days = hours / 24
159 if !future {
160 if secs < 60 { return Strings.timeJustNow }
161 if mins < 60 { return Strings.timeMinutesAgo(mins) }
162 if hours < 24 { return Strings.timeHoursAgo(hours) }
163 return Strings.timeDaysAgo(days)
164 } else {
165 if secs < 60 { return Strings.timeVerySoon }
166 if mins < 60 { return Strings.timeInMinutes(mins) }
167 if hours < 24 { return Strings.timeInHours(hours) }
168 return Strings.timeInDays(days)
169 }
170 }
171
172 /// Formatted speed in m/s -> mph or km/h (uses imperial when locale is US).
173 static func formatSpeed(_ speedMS: Float) -> String {
174 let usesImperial = Locale.current.measurementSystem == .us
175 if usesImperial {
176 let mph = Int((speedMS * 2.23694).rounded())
177 return "\(mph) mph"
178 } else {
179 let kmh = Int((speedMS * 3.6).rounded())
180 return "\(kmh) km/h"
181 }
182 }
183}
184
185// MARK: - Notifications
186
187enum NotificationsUtil {
188 static func send(title: String, body: String, category: String) {
189 let content = UNMutableNotificationContent()
190 content.title = title
191 content.body = body
192 content.categoryIdentifier = category
193 content.sound = .default
194 let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
195 UNUserNotificationCenter.current().add(req)
196 }
197}
198
199// MARK: - Deep links
200
201/// A tapped invite link: the sender's id, plus the bundle fingerprint it vouched for.
202struct AddInvite: Equatable {
203 let id: Int64
204 /// The `k=` value, or nil for links from builds before it existed.
205 let fingerprint: String?
206}
207
208/// Routes incoming `findfamily://add/<base26>[?k=<fingerprint>]` invites to the UI. The
209/// link carries the sender's public id and a hash of their public key — never a key and
210/// never a secret — so prefilling the Add Person dialog from it is safe; the user still
211/// explicitly accepts, and the fingerprint is checked against the relay's key on connect.
212final class DeepLinkRouter: ObservableObject {
213 static let shared = DeepLinkRouter()
214 private init() {}
215
216 /// Decoded invite awaiting presentation, or nil once consumed.
217 @Published var pendingAddInvite: AddInvite?
218
219 func handle(_ url: URL) {
220 guard url.scheme == "findfamily", url.host == "add" else { return }
221 let segment = (url.pathComponents.last { $0 != "/" } ?? "")
222 .trimmingCharacters(in: .whitespaces)
223 .uppercased()
224 guard !segment.isEmpty,
225 segment.allSatisfy({ $0.isASCII && $0.isLetter }),
226 let id = Base26.decode(segment) else { return }
227 pendingAddInvite = AddInvite(id: id, fingerprint: Self.fingerprint(from: url))
228 }
229
230 /// The `k` query value, accepted only if it looks like base64url. Anything else is
231 /// dropped, which leaves the invite unverified rather than failing the whole link.
232 private static func fingerprint(from url: URL) -> String? {
233 guard let value = URLComponents(url: url, resolvingAgainstBaseURL: false)?
234 .queryItems?.first(where: { $0.name == "k" })?.value?
235 .trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }
236 let isBase64url = value.allSatisfy {
237 $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_")
238 }
239 return isBase64url ? value : nil
240 }
241}
242
243// MARK: - Platform (clipboard, share, contact picker)
244
245enum Platform {
246 static func copy(_ text: String) {
247 UIPasteboard.general.string = text
248 }
249 static func share(_ text: String) {
250 guard let vc = topViewController() else { return }
251 let av = UIActivityViewController(activityItems: [text], applicationActivities: nil)
252 vc.present(av, animated: true)
253 }
254
255 /// Presents `CNContactPickerViewController` imperatively via UIKit on top of any
256 /// SwiftUI sheets. Using a SwiftUI `.sheet` here causes the *parent* sheet to be
257 /// dismissed when the picker closes; presenting via UIKit avoids that.
258 static func presentContactPicker(onPicked: @escaping (String, String?) -> Void) {
259 guard let vc = topViewController() else { return }
260 let handler = ContactPickerHandler(onPicked: onPicked)
261 let picker = CNContactPickerViewController()
262 picker.delegate = handler
263 // Retain the delegate for the picker's lifetime.
264 objc_setAssociatedObject(picker, &Self.handlerKey, handler, .OBJC_ASSOCIATION_RETAIN)
265 vc.present(picker, animated: true)
266 }
267
268 private static var handlerKey: UInt8 = 0
269
270 private static func topViewController() -> UIViewController? {
271 let scene = UIApplication.shared.connectedScenes
272 .compactMap { $0 as? UIWindowScene }
273 .first { $0.activationState == .foregroundActive } ?? UIApplication.shared.connectedScenes.first as? UIWindowScene
274 guard var vc = scene?.windows.first(where: { $0.isKeyWindow })?.rootViewController
275 ?? scene?.windows.first?.rootViewController
276 else { return nil }
277 while let presented = vc.presentedViewController { vc = presented }
278 return vc
279 }
280}
281
282private final class ContactPickerHandler: NSObject, CNContactPickerDelegate {
283 let onPicked: (String, String?) -> Void
284 init(onPicked: @escaping (String, String?) -> Void) { self.onPicked = onPicked }
285
286 func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
287 let name = [contact.givenName, contact.familyName].filter { !$0.isEmpty }.joined(separator: " ")
288 var photoB64: String?
289 if let data = contact.imageData {
290 photoB64 = "data:image/jpeg;base64," + data.base64EncodedString()
291 }
292 DispatchQueue.main.async {
293 self.onPicked(name.isEmpty ? "Unnamed" : name, photoB64)
294 }
295 }
296 func contactPickerDidCancel(_ picker: CNContactPickerViewController) {}
297}
298
299// MARK: - Contact picker (legacy SwiftUI sheet wrapper)
300//
301// Kept for backwards compatibility but not used — prefer `Platform.presentContactPicker`.
302struct ContactPicker: UIViewControllerRepresentable {
303 let onPicked: (String, String?) -> Void
304
305 func makeUIViewController(context: Context) -> CNContactPickerViewController {
306 let vc = CNContactPickerViewController()
307 vc.delegate = context.coordinator
308 return vc
309 }
310 func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: Context) {}
311 func makeCoordinator() -> Coordinator { Coordinator(onPicked: onPicked) }
312
313 final class Coordinator: NSObject, CNContactPickerDelegate {
314 let onPicked: (String, String?) -> Void
315 init(onPicked: @escaping (String, String?) -> Void) { self.onPicked = onPicked }
316
317 func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
318 let name = [contact.givenName, contact.familyName].filter { !$0.isEmpty }.joined(separator: " ")
319 var photoB64: String?
320 if let data = contact.imageData {
321 photoB64 = "data:image/jpeg;base64," + data.base64EncodedString()
322 }
323 onPicked(name.isEmpty ? "Unnamed" : name, photoB64)
324 }
325 func contactPickerDidCancel(_ picker: CNContactPickerViewController) {}
326 }
327}
328
329// MARK: - Permissions controller
330
331import CoreLocation
332
333final class PermissionsController: NSObject, ObservableObject, CLLocationManagerDelegate {
334 @Published var hasForeground = false
335 @Published var hasBackground = false
336
337 private let manager: CLLocationManager
338
339 override init() {
340 self.manager = CLLocationManager()
341 super.init()
342 self.manager.delegate = self
343 refresh()
344 }
345
346 func refresh() {
347 let s = manager.authorizationStatus
348 hasForeground = (s == .authorizedWhenInUse || s == .authorizedAlways)
349 hasBackground = (s == .authorizedAlways)
350 }
351
352 func requestForeground() {
353 manager.requestWhenInUseAuthorization()
354 }
355
356 func requestBackground() {
357 manager.requestAlwaysAuthorization()
358 }
359
360 func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
361 Task { @MainActor in self.refresh() }
362 }
363}