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

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

Util.swift367 lines · 15.5 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 fabPerson = "Add Person"
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 addPersonAccept = "Accept Location Request"
81 static let shareInviteLink = "Share invite link"
82 static let addPersonAwaitingRequest = "This person has requested your location"
83 static let addPersonSelf = "Cannot share your location with yourself"
84 static let addPersonAlreadyMutual = "Already sharing location with this person"
85 static let addPersonAlreadyRequested = "Already requested to share with this person"
86
87 static let backupExport = "Export Backup"
88 static let backupImport = "Import Backup"
89
90 static let notifSharingRequestTitle = "Location Requested"
91 static func notifSharingRequestBody(_ id: String) -> String { "ID \(id) wants to see your location." }
92 static let notifBatteryLowTitle = "Battery Low"
93 static func notifBatteryLowBody(_ name: String, _ pct: Int) -> String { "\(name)'s battery is at \(pct)%" }
94 static let notifWaypointEnterTitle = "Place Update"
95 static func notifWaypointEnterBody(_ name: String, _ place: String) -> String { "\(name) is at \(place)" }
96 static let notifWaypointExitTitle = "Place Update"
97 static func notifWaypointExitBody(_ name: String, _ place: String) -> String { "\(name) left \(place)" }
98
99 static let okButton = "OK"
100 static let cancelButton = "Cancel"
101 static let doneButton = "Done"
102
103 // Auto-toggle sharing ("Disable/Enable after" timer)
104 static let autoToggleNever = "Never"
105 static let disableAfter = "Disable after"
106 static let enableAfter = "Enable after"
107
108 // Duration options (shared with temporary-link expiry)
109 static let duration15Minutes = "15 minutes"
110 static let duration30Minutes = "30 minutes"
111 static let duration1Hour = "1 hour"
112 static let duration2Hours = "2 hours"
113 static let duration4Hours = "4 hours"
114 static let duration6Hours = "6 hours"
115 static let duration12Hours = "12 hours"
116 static let duration1Day = "1 day"
117 static let duration2Days = "2 days"
118 static let duration1Week = "1 week"
119
120 // Security code (safety number) verification
121 static let securityCodeTitle = "Security Code"
122 static func securityCodeCompare(_ name: String) -> String {
123 "Compare this code with the one shown on \(name)'s device. If they match, your connection is verified and no one is intercepting it."
124 }
125 static let securityCodeComputing = "Computing…"
126 static func securityCodeUnavailable(_ name: String) -> String {
127 "Couldn't compute the code yet — \(name)'s key isn't available. Try again once they've shared their location."
128 }
129
130 // Shown when connecting to a peer whose app is too old for post-quantum encryption.
131 static let outdatedPeerTitle = "Update needed"
132 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."
133
134 // Shown when a peer's key doesn't match the fingerprint their invite link vouched for.
135 static let keyMismatchTitle = "Couldn't verify this person"
136 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."
137}
138
139// MARK: - Time formatting
140
141enum TimeFormatting {
142 static let dayMonth: DateFormatter = {
143 let f = DateFormatter()
144 f.dateFormat = "MMM d"
145 return f
146 }()
147 static let amPmTimeSeconds: DateFormatter = {
148 let f = DateFormatter()
149 f.dateFormat = "h:mm:ss a"
150 return f
151 }()
152 static let amPmTime: DateFormatter = {
153 let f = DateFormatter()
154 f.dateFormat = "h:mm a"
155 return f
156 }()
157
158 static func timestring(_ timestamp: Date, future: Bool) -> String {
159 let secs = abs(Int64(Date().timeIntervalSince(timestamp)))
160 let mins = secs / 60
161 let hours = mins / 60
162 let days = hours / 24
163 if !future {
164 if secs < 60 { return Strings.timeJustNow }
165 if mins < 60 { return Strings.timeMinutesAgo(mins) }
166 if hours < 24 { return Strings.timeHoursAgo(hours) }
167 return Strings.timeDaysAgo(days)
168 } else {
169 if secs < 60 { return Strings.timeVerySoon }
170 if mins < 60 { return Strings.timeInMinutes(mins) }
171 if hours < 24 { return Strings.timeInHours(hours) }
172 return Strings.timeInDays(days)
173 }
174 }
175
176 /// Formatted speed in m/s -> mph or km/h (uses imperial when locale is US).
177 static func formatSpeed(_ speedMS: Float) -> String {
178 let usesImperial = Locale.current.measurementSystem == .us
179 if usesImperial {
180 let mph = Int((speedMS * 2.23694).rounded())
181 return "\(mph) mph"
182 } else {
183 let kmh = Int((speedMS * 3.6).rounded())
184 return "\(kmh) km/h"
185 }
186 }
187}
188
189// MARK: - Notifications
190
191enum NotificationsUtil {
192 static func send(title: String, body: String, category: String) {
193 let content = UNMutableNotificationContent()
194 content.title = title
195 content.body = body
196 content.categoryIdentifier = category
197 content.sound = .default
198 let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
199 UNUserNotificationCenter.current().add(req)
200 }
201}
202
203// MARK: - Deep links
204
205/// A tapped invite link: the sender's id, plus the bundle fingerprint it vouched for.
206struct AddInvite: Equatable {
207 let id: Int64
208 /// The `k=` value, or nil for links from builds before it existed.
209 let fingerprint: String?
210}
211
212/// Routes incoming `findfamily://add/<base26>[?k=<fingerprint>]` invites to the UI. The
213/// link carries the sender's public id and a hash of their public key — never a key and
214/// never a secret — so prefilling the Add Person dialog from it is safe; the user still
215/// explicitly accepts, and the fingerprint is checked against the relay's key on connect.
216final class DeepLinkRouter: ObservableObject {
217 static let shared = DeepLinkRouter()
218 private init() {}
219
220 /// Decoded invite awaiting presentation, or nil once consumed.
221 @Published var pendingAddInvite: AddInvite?
222
223 func handle(_ url: URL) {
224 guard url.scheme == "findfamily", url.host == "add" else { return }
225 let segment = (url.pathComponents.last { $0 != "/" } ?? "")
226 .trimmingCharacters(in: .whitespaces)
227 .uppercased()
228 guard !segment.isEmpty,
229 segment.allSatisfy({ $0.isASCII && $0.isLetter }),
230 let id = Base26.decode(segment) else { return }
231 pendingAddInvite = AddInvite(id: id, fingerprint: Self.fingerprint(from: url))
232 }
233
234 /// The `k` query value, accepted only if it looks like base64url. Anything else is
235 /// dropped, which leaves the invite unverified rather than failing the whole link.
236 private static func fingerprint(from url: URL) -> String? {
237 guard let value = URLComponents(url: url, resolvingAgainstBaseURL: false)?
238 .queryItems?.first(where: { $0.name == "k" })?.value?
239 .trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }
240 let isBase64url = value.allSatisfy {
241 $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_")
242 }
243 return isBase64url ? value : nil
244 }
245}
246
247// MARK: - Platform (clipboard, share, contact picker)
248
249enum Platform {
250 static func copy(_ text: String) {
251 UIPasteboard.general.string = text
252 }
253 static func share(_ text: String) {
254 guard let vc = topViewController() else { return }
255 let av = UIActivityViewController(activityItems: [text], applicationActivities: nil)
256 vc.present(av, animated: true)
257 }
258
259 /// Presents `CNContactPickerViewController` imperatively via UIKit on top of any
260 /// SwiftUI sheets. Using a SwiftUI `.sheet` here causes the *parent* sheet to be
261 /// dismissed when the picker closes; presenting via UIKit avoids that.
262 static func presentContactPicker(onPicked: @escaping (String, String?) -> Void) {
263 guard let vc = topViewController() else { return }
264 let handler = ContactPickerHandler(onPicked: onPicked)
265 let picker = CNContactPickerViewController()
266 picker.delegate = handler
267 // Retain the delegate for the picker's lifetime.
268 objc_setAssociatedObject(picker, &Self.handlerKey, handler, .OBJC_ASSOCIATION_RETAIN)
269 vc.present(picker, animated: true)
270 }
271
272 private static var handlerKey: UInt8 = 0
273
274 private static func topViewController() -> UIViewController? {
275 let scene = UIApplication.shared.connectedScenes
276 .compactMap { $0 as? UIWindowScene }
277 .first { $0.activationState == .foregroundActive } ?? UIApplication.shared.connectedScenes.first as? UIWindowScene
278 guard var vc = scene?.windows.first(where: { $0.isKeyWindow })?.rootViewController
279 ?? scene?.windows.first?.rootViewController
280 else { return nil }
281 while let presented = vc.presentedViewController { vc = presented }
282 return vc
283 }
284}
285
286private final class ContactPickerHandler: NSObject, CNContactPickerDelegate {
287 let onPicked: (String, String?) -> Void
288 init(onPicked: @escaping (String, String?) -> Void) { self.onPicked = onPicked }
289
290 func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
291 let name = [contact.givenName, contact.familyName].filter { !$0.isEmpty }.joined(separator: " ")
292 var photoB64: String?
293 if let data = contact.imageData {
294 photoB64 = "data:image/jpeg;base64," + data.base64EncodedString()
295 }
296 DispatchQueue.main.async {
297 self.onPicked(name.isEmpty ? "Unnamed" : name, photoB64)
298 }
299 }
300 func contactPickerDidCancel(_ picker: CNContactPickerViewController) {}
301}
302
303// MARK: - Contact picker (legacy SwiftUI sheet wrapper)
304//
305// Kept for backwards compatibility but not used — prefer `Platform.presentContactPicker`.
306struct ContactPicker: UIViewControllerRepresentable {
307 let onPicked: (String, String?) -> Void
308
309 func makeUIViewController(context: Context) -> CNContactPickerViewController {
310 let vc = CNContactPickerViewController()
311 vc.delegate = context.coordinator
312 return vc
313 }
314 func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: Context) {}
315 func makeCoordinator() -> Coordinator { Coordinator(onPicked: onPicked) }
316
317 final class Coordinator: NSObject, CNContactPickerDelegate {
318 let onPicked: (String, String?) -> Void
319 init(onPicked: @escaping (String, String?) -> Void) { self.onPicked = onPicked }
320
321 func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
322 let name = [contact.givenName, contact.familyName].filter { !$0.isEmpty }.joined(separator: " ")
323 var photoB64: String?
324 if let data = contact.imageData {
325 photoB64 = "data:image/jpeg;base64," + data.base64EncodedString()
326 }
327 onPicked(name.isEmpty ? "Unnamed" : name, photoB64)
328 }
329 func contactPickerDidCancel(_ picker: CNContactPickerViewController) {}
330 }
331}
332
333// MARK: - Permissions controller
334
335import CoreLocation
336
337final class PermissionsController: NSObject, ObservableObject, CLLocationManagerDelegate {
338 @Published var hasForeground = false
339 @Published var hasBackground = false
340
341 private let manager: CLLocationManager
342
343 override init() {
344 self.manager = CLLocationManager()
345 super.init()
346 self.manager.delegate = self
347 refresh()
348 }
349
350 func refresh() {
351 let s = manager.authorizationStatus
352 hasForeground = (s == .authorizedWhenInUse || s == .authorizedAlways)
353 hasBackground = (s == .authorizedAlways)
354 }
355
356 func requestForeground() {
357 manager.requestWhenInUseAuthorization()
358 }
359
360 func requestBackground() {
361 manager.requestAlwaysAuthorization()
362 }
363
364 func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
365 Task { @MainActor in self.refresh() }
366 }
367}