@fountispanel/connect-react-native 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +24 -0
  3. package/README.md +92 -2
  4. package/android/build.gradle +37 -0
  5. package/android/connect-sdk/main/assets/fountis-connect/engine.html +47 -0
  6. package/android/connect-sdk/main/assets/fountis-connect/i18n/ar.json +70 -0
  7. package/android/connect-sdk/main/assets/fountis-connect/i18n/en.json +70 -0
  8. package/android/connect-sdk/main/assets/fountis-connect/i18n/kmr.json +70 -0
  9. package/android/connect-sdk/main/assets/fountis-connect/i18n/ku.json +70 -0
  10. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +179 -0
  11. package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +234 -0
  12. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +641 -0
  13. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +321 -0
  14. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +143 -0
  15. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +167 -0
  16. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +144 -0
  17. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +109 -0
  18. package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +70 -0
  19. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +74 -0
  20. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +45 -0
  21. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +72 -0
  22. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +12 -0
  23. package/android/connect-sdk/main/res/values/fountis_styles.xml +13 -0
  24. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +12 -0
  25. package/android/src/main/AndroidManifest.xml +18 -0
  26. package/android/src/main/java/org/fountis/connect/rn/FountisConnectModule.kt +113 -0
  27. package/app.plugin.js +41 -0
  28. package/build/index.d.ts +34 -0
  29. package/build/index.js +126 -0
  30. package/build/index.web.d.ts +22 -0
  31. package/build/index.web.js +57 -0
  32. package/build/types.d.ts +23 -0
  33. package/build/types.js +1 -0
  34. package/expo-module.config.json +10 -0
  35. package/ios/FountisConnectAppDelegateSubscriber.swift +16 -0
  36. package/ios/FountisConnectBundle.swift +15 -0
  37. package/ios/FountisConnectModule.swift +131 -0
  38. package/ios/FountisConnectReactNative.podspec +35 -0
  39. package/ios/FountisConnectSDK/ApiClient.swift +137 -0
  40. package/ios/FountisConnectSDK/Attestation.swift +276 -0
  41. package/ios/FountisConnectSDK/Engine/engine.html +47 -0
  42. package/ios/FountisConnectSDK/Engine/i18n/ar.json +70 -0
  43. package/ios/FountisConnectSDK/Engine/i18n/en.json +70 -0
  44. package/ios/FountisConnectSDK/Engine/i18n/kmr.json +70 -0
  45. package/ios/FountisConnectSDK/Engine/i18n/ku.json +70 -0
  46. package/ios/FountisConnectSDK/FountisConnect.swift +441 -0
  47. package/ios/FountisConnectSDK/LocalState.swift +81 -0
  48. package/ios/FountisConnectSDK/Matcher.swift +102 -0
  49. package/ios/FountisConnectSDK/Models.swift +133 -0
  50. package/ios/FountisConnectSDK/Notifier.swift +63 -0
  51. package/ios/FountisConnectSDK/PrivacyInfo.xcprivacy +23 -0
  52. package/ios/FountisConnectSDK/RequestDeadline.swift +93 -0
  53. package/ios/FountisConnectSDK/SheetController.swift +259 -0
  54. package/ios/FountisConnectSDK/Strings.swift +34 -0
  55. package/ios/FountisConnectSDK/TokenProviderCall.swift +91 -0
  56. package/package.json +67 -4
  57. package/scripts/vendor-native.sh +16 -0
  58. package/src/index.ts +142 -0
  59. package/src/index.web.ts +64 -0
  60. package/src/types.ts +26 -0
@@ -0,0 +1,441 @@
1
+ import Foundation
2
+ import UIKit
3
+ import UserNotifications
4
+
5
+ /// FOUNTIS Connect for iOS.
6
+ ///
7
+ /// Guests: when the token provider returns `nil` (nobody is signed in) and FOUNTIS has switched guests on
8
+ /// for your app, the SDK offers the free studies marked open to guests, after an 18+ confirmation. Nothing
9
+ /// to call; an app without accounts can pass `setUserToken { nil }`.
10
+ ///
11
+ /// ```swift
12
+ /// // At launch (App.init or application(_:didFinishLaunchingWithOptions:)), not in a view:
13
+ /// FountisConnect.start(key: "pk_live_...")
14
+ /// FountisConnect.setUserToken { try await myServer.fountisToken() } // nil when signed out
15
+ /// FountisConnect.enableNotifications() // optional
16
+ /// ```
17
+ ///
18
+ /// Background refresh needs `BGTaskSchedulerPermittedIdentifiers` = `org.fountis.connect.refresh` and
19
+ /// the `fetch` background mode in Info.plist, and `start` must run before the app finishes launching.
20
+ @MainActor
21
+ public enum FountisConnect {
22
+ /// Production base URL until `api.fountis.org` is live.
23
+ public static let defaultAPIBase = URL(string: "https://ucclsekjekdxzfwzyuji.supabase.co/functions/v1/connect-api/v1")!
24
+
25
+ /// Starts the SDK. Call once, at launch, before the app finishes launching (it registers the background refresh task).
26
+ public static func start(key: String, apiBase: URL? = nil) {
27
+ Core.shared.start(key: key, apiBase: apiBase ?? defaultAPIBase)
28
+ }
29
+
30
+ /// Gives the SDK a way to get the signed user token from your server. Return `nil` only when nobody is signed in.
31
+ /// Throw when you cannot get a token (offline, server error): the SDK shows nothing and treats it as `noFill`, never as a guest.
32
+ /// A provider that does not answer within 10 seconds counts as a failure the same way, and an empty string is not "signed out".
33
+ /// Called on demand, never cached by the SDK for longer than one check.
34
+ public static func setUserToken(_ provider: @escaping () async throws -> String?) {
35
+ Core.shared.setUserToken(provider)
36
+ }
37
+
38
+ /// Asks for notification permission and starts the background check. One local notification a day at most.
39
+ public static func enableNotifications() { Core.shared.enableNotifications() }
40
+
41
+ /// Looks for a matching study and shows it as a sheet. Returns `.noFill` fast when there is nothing to show.
42
+ @discardableResult
43
+ public static func show() async -> FountisResult { await Core.shared.run(mode: .manual) }
44
+
45
+ /// Call from your push handler with the payload. Returns `true` if it is a FOUNTIS push (it carries a `fountis` key).
46
+ @discardableResult
47
+ public static func handlePush(_ userInfo: [AnyHashable: Any]) -> Bool { Core.shared.handlePush(userInfo) }
48
+
49
+ /// For apps with their own `UNUserNotificationCenterDelegate`: call from `didReceive response`.
50
+ /// Returns `true` (and presents the study) if the notification was a FOUNTIS one.
51
+ @discardableResult
52
+ public static func handleNotificationResponse(_ response: UNNotificationResponse) -> Bool {
53
+ Core.shared.handleNotificationUserInfo(response.notification.request.content.userInfo)
54
+ }
55
+
56
+ /// Pass the person's consent to be offered studies (for example from your own consent screen). Default: `true`.
57
+ public static func setUserConsent(_ granted: Bool) { Core.shared.consent = granted }
58
+
59
+ /// Forget the signed-in person: removes this person's local state and pending notifications.
60
+ public static func signOut() { Core.shared.signOut() }
61
+
62
+ /// Anonymous lifecycle events (`shown`, `dismissed`, `completed`, `noFill`, `notified`).
63
+ public static func onEvent(_ listener: @escaping (FountisEvent) -> Void) { Core.shared.listeners.append(listener) }
64
+ }
65
+
66
+ // MARK: - Core
67
+
68
+ @MainActor
69
+ final class Core {
70
+ static let shared = Core()
71
+
72
+ enum Mode { case manual, auto, offer(String) }
73
+
74
+ var consent = true
75
+ var listeners: [(FountisEvent) -> Void] = []
76
+
77
+ private var api: ApiClient?
78
+ private var provider: (() async throws -> String?)?
79
+ private var started = false
80
+ private var presenting = false
81
+ private var autoShownThisSession = false
82
+ private var skippedWhileInactive = false
83
+ private var autoTask: Task<Void, Never>?
84
+ private var backgroundedAt: Date?
85
+ private var cache: (lang: String, at: Date, value: SurveysResponse)?
86
+ private var notificationsOn: Bool
87
+ private var forwardingDelegate: ForwardingNotificationDelegate?
88
+ private var lastSubHash: String?
89
+ private var guestSession: (token: String, expires: Date)?
90
+ /// Device attestation for guest sessions (only used when the app's `app.attest.mode` is `report` or `enforce`).
91
+ private let guestSessions = GuestSessionMaker(attestor: Attestor())
92
+ private let accentHex = "#5dc0a0"
93
+
94
+ private init() {
95
+ notificationsOn = UserDefaults(suiteName: "org.fountis.connect.state")?.bool(forKey: "notifications") ?? false
96
+ }
97
+
98
+ // MARK: setup
99
+
100
+ func start(key: String, apiBase: URL) {
101
+ guard !started else { return }
102
+ guard key.hasPrefix("pk_") else { fcLog.debug("start: key must be a publishable key (pk_...)"); return }
103
+ started = true
104
+ api = ApiClient(base: apiBase, key: key)
105
+ _ = BGRefresh.register { [weak self] in await self?.checkAndNotify() }
106
+ let nc = NotificationCenter.default
107
+ nc.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
108
+ Task { @MainActor in self?.didBecomeActive() }
109
+ }
110
+ nc.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
111
+ Task { @MainActor in self?.backgroundedAt = Date() }
112
+ }
113
+ if notificationsOn { BGRefresh.schedule(minutes: nil) }
114
+ if UIApplication.shared.applicationState == .active { scheduleAutoShow() }
115
+ }
116
+
117
+ func setUserToken(_ p: @escaping () async throws -> String?) {
118
+ provider = p
119
+ if started, UIApplication.shared.applicationState == .active { scheduleAutoShow() }
120
+ }
121
+
122
+ func enableNotifications() {
123
+ notificationsOn = true
124
+ UserDefaults(suiteName: "org.fountis.connect.state")?.set(true, forKey: "notifications")
125
+ let center = UNUserNotificationCenter.current()
126
+ if center.delegate == nil {
127
+ let d = ForwardingNotificationDelegate()
128
+ forwardingDelegate = d
129
+ center.delegate = d
130
+ }
131
+ center.requestAuthorization(options: [.alert, .sound]) { granted, _ in fcLog.debug("notification permission: \(granted)") }
132
+ BGRefresh.schedule(minutes: cache?.value.config?.checkIntervalMinutes)
133
+ }
134
+
135
+ func signOut() {
136
+ autoTask?.cancel()
137
+ if let h = lastSubHash { LocalState(subHash: h).clear() }
138
+ lastSubHash = nil
139
+ guestSession = nil
140
+ cache = nil
141
+ autoShownThisSession = false
142
+ UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
143
+ }
144
+
145
+ // MARK: foreground / push / notification tap
146
+
147
+ private func didBecomeActive() {
148
+ if let b = backgroundedAt, Date().timeIntervalSince(b) > 1800 { autoShownThisSession = false }
149
+ backgroundedAt = nil
150
+ scheduleAutoShow()
151
+ }
152
+
153
+ private func scheduleAutoShow() {
154
+ guard !autoShownThisSession, provider != nil else { return }
155
+ autoTask?.cancel()
156
+ autoTask = Task { [weak self] in
157
+ try? await Task.sleep(nanoseconds: 1_200_000_000) // let the host UI settle
158
+ guard let self, !Task.isCancelled, !self.autoShownThisSession else { return }
159
+ // A system alert (the notification permission prompt on first launch) makes the app inactive. Do not
160
+ // spend the session's one auto-show on that: didBecomeActive schedules it again once the alert is gone.
161
+ guard UIApplication.shared.applicationState == .active else { return }
162
+ self.autoShownThisSession = true
163
+ self.skippedWhileInactive = false
164
+ let result = await self.run(mode: .auto)
165
+ // The alert can also appear while the request is in flight; run() then refuses to present. Give the auto-show back.
166
+ if result == .noFill, self.skippedWhileInactive {
167
+ self.autoShownThisSession = false
168
+ if UIApplication.shared.applicationState == .active { self.scheduleAutoShow() }
169
+ }
170
+ }
171
+ }
172
+
173
+ func handlePush(_ userInfo: [AnyHashable: Any]) -> Bool {
174
+ guard userInfo["fountis"] != nil else { return false }
175
+ Task { [weak self] in
176
+ guard let self else { return }
177
+ if UIApplication.shared.applicationState == .active { _ = await self.run(mode: .auto) } else { await self.checkAndNotify() }
178
+ }
179
+ return true
180
+ }
181
+
182
+ func handleNotificationUserInfo(_ userInfo: [AnyHashable: Any]) -> Bool {
183
+ guard let offerId = userInfo["fountis"] as? String else { return false }
184
+ Task { [weak self] in
185
+ guard let self else { return }
186
+ // cold start: wait (briefly) for the app to be active with a window to present from
187
+ for _ in 0..<20 where UIApplication.shared.applicationState != .active || Presenter.topViewController() == nil {
188
+ try? await Task.sleep(nanoseconds: 250_000_000)
189
+ }
190
+ self.autoShownThisSession = true
191
+ _ = await self.run(mode: .offer(offerId))
192
+ }
193
+ return true
194
+ }
195
+
196
+ // MARK: data
197
+
198
+ private func fetchSurveys(api: ApiClient, lang: String) async throws -> SurveysResponse {
199
+ if let c = cache, c.lang == lang, Date().timeIntervalSince(c.at) < 60 { return c.value }
200
+ let r = try await api.surveys(lang: lang)
201
+ cache = (lang, Date(), r)
202
+ return r
203
+ }
204
+
205
+ private func emit(_ type: String, _ offerId: String? = nil) {
206
+ let e = FountisEvent(type: type, offerId: offerId)
207
+ listeners.forEach { $0(e) }
208
+ }
209
+
210
+ private struct Session {
211
+ let api: ApiClient
212
+ /// Signed user token; nil for a guest.
213
+ let token: String?
214
+ let info: TokenInfo?
215
+ let lang: String
216
+ let surveys: SurveysResponse
217
+ let state: LocalState
218
+
219
+ var isGuest: Bool { token == nil }
220
+
221
+ func matches(_ offer: Offer) -> Bool {
222
+ if let info { return Matcher.matches(offer, token: info) }
223
+ return Matcher.matchesGuest(offer)
224
+ }
225
+ }
226
+
227
+ /// A guest session token, kept in memory for most of its hour. `force` makes a new one.
228
+ /// A new one is attested when the app asks for it (`app.attest.mode`); with mode `off` or absent attestation is never touched.
229
+ private func guestToken(_ s: Session, force: Bool = false) async throws -> String {
230
+ if !force, let g = guestSession, g.expires > Date() { return g.token }
231
+ let t = try await guestSessions.make(api: s.api, mode: s.surveys.app?.attestMode ?? .off, installId: GuestInstall.id())
232
+ guestSession = (t, Date().addingTimeInterval(55 * 60))
233
+ return t
234
+ }
235
+
236
+ private func openSession() async -> Session? {
237
+ guard started, consent, let api, let provider else { return nil }
238
+ do {
239
+ // Only nil means signed out (the guest path). A throw or a provider that stays silent past the timeout is a failed check.
240
+ guard let token = try await callTokenProvider(provider) else { return await openGuestSession(api: api) }
241
+ // An empty string is an unusable token, not "signed out": noFill, never a guest.
242
+ guard !token.isEmpty, let info = TokenInfo.decode(token) else { return nil }
243
+ if let exp = info.exp, exp < Date().timeIntervalSince1970 { return nil }
244
+ lastSubHash = info.subHash
245
+ let lang = info.lang.map(Strings.normalize) ?? Strings.deviceLang
246
+ let surveys = try await fetchSurveys(api: api, lang: lang)
247
+ return Session(api: api, token: token, info: info, lang: lang, surveys: surveys, state: LocalState(subHash: info.subHash))
248
+ } catch is TokenProviderTimeout {
249
+ fcLog.debug("check failed: the token provider did not answer within \(Int(tokenProviderTimeout)) seconds")
250
+ return nil
251
+ } catch {
252
+ fcLog.debug("check failed: \(String(describing: error))")
253
+ return nil
254
+ }
255
+ }
256
+
257
+ /// Nobody is signed in: a guest session, only when the app allows guests.
258
+ private func openGuestSession(api: ApiClient) async -> Session? {
259
+ do {
260
+ let lang = Strings.deviceLang
261
+ let surveys = try await fetchSurveys(api: api, lang: lang)
262
+ guard surveys.app?.guests == true, surveys.surveys.contains(where: { $0.guest == true }) else { return nil }
263
+ lastSubHash = "guest"
264
+ return Session(api: api, token: nil, info: nil, lang: lang, surveys: surveys, state: LocalState(subHash: "guest"))
265
+ } catch {
266
+ fcLog.debug("guest check failed: \(String(describing: error))")
267
+ return nil
268
+ }
269
+ }
270
+
271
+ /// Starts the attempt for a person with a token or a guest session (a stale guest session is renewed once).
272
+ private func createAttempt(_ s: Session, offerId: String) async throws -> [String: Any] {
273
+ if let token = s.token { return try await s.api.createAttempt(offerId: offerId, token: token, lang: s.lang) }
274
+ let session = try await guestToken(s)
275
+ do {
276
+ return try await s.api.createGuestAttempt(offerId: offerId, guestSession: session, lang: s.lang)
277
+ } catch let e as APIError where e.code == "invalid_session" {
278
+ let fresh = try await guestToken(s, force: true)
279
+ return try await s.api.createGuestAttempt(offerId: offerId, guestSession: fresh, lang: s.lang)
280
+ }
281
+ }
282
+
283
+ // MARK: show
284
+
285
+ func run(mode: Mode) async -> FountisResult {
286
+ let result = await runInner(mode: mode)
287
+ if result == .noFill { emit("noFill") }
288
+ return result
289
+ }
290
+
291
+ private func runInner(mode: Mode) async -> FountisResult {
292
+ guard !presenting else { return .noFill }
293
+ presenting = true
294
+ defer { presenting = false }
295
+
296
+ guard let s = await openSession() else { return .noFill }
297
+ guard UIApplication.shared.applicationState == .active, Presenter.topViewController() != nil else {
298
+ skippedWhileInactive = true
299
+ return .noFill
300
+ }
301
+
302
+ var offers = s.surveys.surveys.filter { s.matches($0) }
303
+ switch mode {
304
+ case .manual: offers = offers.filter { !s.state.isTaken($0.offerId) }
305
+ case .auto: offers = offers.filter { !s.state.isSuppressedForAutoShow($0.offerId) }
306
+ case .offer(let id): offers = offers.filter { $0.offerId == id && !s.state.isTaken($0.offerId) }
307
+ }
308
+ // Rewarded first, then shortest.
309
+ offers.sort { (($0.reward?.isRewarded ?? false) && !($1.reward?.isRewarded ?? false)) }
310
+
311
+ for offer in offers.prefix(3) {
312
+ do {
313
+ let a = try await createAttempt(s, offerId: offer.offerId)
314
+ return await present(offer: offer, attempt: a, session: s)
315
+ } catch let e as APIError {
316
+ if e.code == "already_taken" { s.state.markTaken(offer.offerId) }
317
+ // The app enforces attestation and this device has none that passes: no guest offers this time, no retry.
318
+ if e.isAttestationRefusal { fcLog.debug("guest studies not offered: \(e.code)"); return .noFill }
319
+ if e.skipsToNextOffer { continue }
320
+ fcLog.debug("attempt failed: \(e.code)")
321
+ return .noFill
322
+ } catch {
323
+ fcLog.debug("attempt failed: \(String(describing: error))")
324
+ return .noFill
325
+ }
326
+ }
327
+ return .noFill
328
+ }
329
+
330
+ private func present(offer: Offer, attempt a: [String: Any], session s: Session) async -> FountisResult {
331
+ guard let attemptToken = a["attempt_token"] as? String, a["definition"] != nil,
332
+ let engineURL = Bundle.module.url(forResource: "engine", withExtension: "html", subdirectory: "Engine"),
333
+ let top = Presenter.topViewController() else { return .noFill }
334
+
335
+ var payload: [String: Any] = [
336
+ "mode": "native",
337
+ "definition": a["definition"] ?? NSNull(),
338
+ "answers": a["answers"] ?? [String: Any](),
339
+ "lang": s.lang,
340
+ "rtl": Strings.isRTL(s.lang),
341
+ "theme": ["accent": accentHex],
342
+ "consentNeeded": (a["consent_needed"] as? Bool) ?? false,
343
+ "attrs": s.info?.carriedAttrs ?? [],
344
+ ]
345
+ if s.isGuest || (a["guest"] as? Bool) == true { payload["guest"] = true }
346
+ if let name = s.surveys.app?.name { payload["partner"] = name }
347
+ if let rid = a["rid"] as? String { payload["rid"] = rid }
348
+ if let r = a["reward"] as? [String: Any], ((r["units"] as? NSNumber)?.intValue ?? 0) > 0 {
349
+ payload["reward"] = ["units": r["units"] ?? 0, "unit_name": r["unit_name"] ?? ""]
350
+ }
351
+
352
+ return await withCheckedContinuation { (cont: CheckedContinuation<FountisResult, Never>) in
353
+ let sheet = SheetController(engineURL: engineURL, initPayload: payload, api: s.api, attemptToken: attemptToken, onShown: { [weak self] in
354
+ self?.emit("shown", offer.offerId)
355
+ Task { await s.api.event(offerId: offer.offerId, type: "shown") }
356
+ }) { [weak self] fin in
357
+ // UIKit never showed it: nothing happened to the offer, so no taken/dismissed mark, no event.
358
+ if fin.unavailable { cont.resume(returning: .noFill); return }
359
+ let result: FountisResult
360
+ if fin.outcome == "complete" {
361
+ result = .completed
362
+ s.state.markTaken(offer.offerId)
363
+ self?.emit("completed", offer.offerId)
364
+ } else {
365
+ result = .dismissed
366
+ if fin.outcome == "screen_out" || fin.fatal == "already_taken" { s.state.markTaken(offer.offerId) } else { s.state.markDismissed(offer.offerId) }
367
+ self?.emit("dismissed", offer.offerId)
368
+ Task { await s.api.event(offerId: offer.offerId, type: "dismissed") }
369
+ }
370
+ cont.resume(returning: result)
371
+ }
372
+ guard !top.isBeingDismissed else { cont.resume(returning: .noFill); return }
373
+ Presenter.present(sheet, on: top)
374
+ }
375
+ }
376
+
377
+ // MARK: notifications
378
+
379
+ /// Background / push check: at most one local notification a day, never in quiet hours.
380
+ func checkAndNotify() async {
381
+ guard notificationsOn, let s = await openSession() else { return }
382
+ let cfg = s.surveys.config
383
+ BGRefresh.schedule(minutes: cfg?.checkIntervalMinutes)
384
+ guard UIApplication.shared.applicationState != .active else { return } // foreground uses auto-show
385
+ guard !Matcher.inQuietHours(cfg?.quietHours), s.state.notificationsToday < min(max(cfg?.maxNotificationsPerDay ?? 1, 0), 1) else { return }
386
+ let settings = await UNUserNotificationCenter.current().notificationSettings()
387
+ guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else { return }
388
+ guard let offer = s.surveys.surveys.first(where: { s.matches($0) && !s.state.isSuppressedForNotification($0.offerId) }) else { return }
389
+
390
+ let content = UNMutableNotificationContent()
391
+ content.title = Strings.get("connect.notify.title", lang: s.lang)
392
+ let minutes = String(max(offer.loiMinutes ?? 5, 1))
393
+ if let r = offer.reward, r.isRewarded {
394
+ content.body = Strings.get("connect.notify.bodyReward", lang: s.lang, ["minutes": minutes, "units": String(r.units ?? 0), "unit": r.unitLabel(lang: s.lang)])
395
+ } else {
396
+ content.body = Strings.get("connect.notify.body", lang: s.lang, ["minutes": minutes])
397
+ }
398
+ content.sound = .default
399
+ content.userInfo = ["fountis": offer.offerId]
400
+ let req = UNNotificationRequest(identifier: "org.fountis.connect.\(offer.offerId)", content: content,
401
+ trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false))
402
+ do {
403
+ try await UNUserNotificationCenter.current().add(req)
404
+ s.state.markNotified(offer.offerId)
405
+ emit("notified", offer.offerId)
406
+ } catch { fcLog.debug("notification failed: \(error.localizedDescription)") }
407
+ }
408
+ }
409
+
410
+ // MARK: - Presenter
411
+
412
+ /// How long UIKit may take to start showing the survey before `show()` gives up (`noFill`). Same 10 seconds as the Android SDK.
413
+ let sheetAppearTimeout: TimeInterval = 10
414
+
415
+ enum Presenter {
416
+ /// Presents `sheet` on `top`, and abandons it if UIKit has not started showing it within `timeout` seconds.
417
+ /// A presentation UIKit refuses (for example `top`'s view is not in a window) is only a console warning: no error,
418
+ /// no completion, never retried. Without the watchdog the sheet would never finish, `Core.presenting` would stay
419
+ /// set, and every later show would be `noFill`.
420
+ @MainActor
421
+ static func present(_ sheet: SheetController, on top: UIViewController, timeout: TimeInterval = sheetAppearTimeout) {
422
+ top.present(sheet, animated: true)
423
+ // The task holds the sheet: when UIKit refuses, nothing else does, and a sheet that deallocates drops its onFinish.
424
+ Task {
425
+ do { try await Task.sleep(nanoseconds: UInt64(max(timeout, 0) * 1_000_000_000)) } catch { return }
426
+ sheet.abandonIfNotShown()
427
+ }
428
+ }
429
+
430
+ /// The top-most view controller of the foreground window scene, or nil if there is nowhere to present.
431
+ @MainActor
432
+ static func topViewController() -> UIViewController? {
433
+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
434
+ let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first { $0.activationState == .foregroundInactive }
435
+ guard let window = scene?.windows.first(where: { $0.isKeyWindow }) ?? scene?.windows.first else { return nil }
436
+ var top = window.rootViewController
437
+ while let p = top?.presentedViewController, !p.isBeingDismissed { top = p }
438
+ if top is SheetController { return nil }
439
+ return top
440
+ }
441
+ }
@@ -0,0 +1,81 @@
1
+ import Foundation
2
+
3
+ /// Per-person local state (offers already notified / dismissed / taken, daily notification count).
4
+ /// Lives only in this app's UserDefaults suite, keyed by sha256(sub). Never sent anywhere.
5
+ struct LocalStateData: Codable {
6
+ var notified: [String] = []
7
+ var dismissed: [String] = []
8
+ var taken: [String] = []
9
+ var day: String = ""
10
+ var dayCount: Int = 0
11
+ }
12
+
13
+ /// The guest install id: 24 random bytes made on first use and kept in this app's UserDefaults suite.
14
+ /// It is not a device identifier and is never derived from one. FOUNTIS stores only a hash of it.
15
+ enum GuestInstall {
16
+ private static let key = "guest.install_id"
17
+
18
+ static func id() -> String {
19
+ let defaults = UserDefaults(suiteName: "org.fountis.connect.state") ?? .standard
20
+ if let v = defaults.string(forKey: key), v.count >= 22 { return v }
21
+ var bytes = [UInt8](repeating: 0, count: 24)
22
+ let ok = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess
23
+ if !ok { for i in bytes.indices { bytes[i] = UInt8.random(in: 0...255) } }
24
+ let v = Data(bytes).base64EncodedString()
25
+ .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")
26
+ .replacingOccurrences(of: "=", with: "")
27
+ defaults.set(v, forKey: key)
28
+ return v
29
+ }
30
+ }
31
+
32
+ final class LocalState {
33
+ private let defaults: UserDefaults
34
+ private let key: String
35
+
36
+ init(subHash: String) {
37
+ defaults = UserDefaults(suiteName: "org.fountis.connect.state") ?? .standard
38
+ key = "s." + subHash
39
+ }
40
+
41
+ private(set) var data: LocalStateData {
42
+ get {
43
+ guard let d = defaults.data(forKey: key), let v = try? JSONDecoder().decode(LocalStateData.self, from: d) else { return LocalStateData() }
44
+ return v
45
+ }
46
+ set { if let d = try? JSONEncoder().encode(newValue) { defaults.set(d, forKey: key) } }
47
+ }
48
+
49
+ private static func today() -> String {
50
+ let c = Calendar.current.dateComponents([.year, .month, .day], from: Date())
51
+ return "\(c.year ?? 0)-\(c.month ?? 0)-\(c.day ?? 0)"
52
+ }
53
+
54
+ private func add(_ id: String, to path: WritableKeyPath<LocalStateData, [String]>) {
55
+ var v = data
56
+ if !v[keyPath: path].contains(id) { v[keyPath: path].append(id) }
57
+ if v[keyPath: path].count > 200 { v[keyPath: path].removeFirst(v[keyPath: path].count - 200) }
58
+ data = v
59
+ }
60
+
61
+ func markNotified(_ id: String) {
62
+ add(id, to: \.notified)
63
+ var v = data
64
+ if v.day != Self.today() { v.day = Self.today(); v.dayCount = 0 }
65
+ v.dayCount += 1
66
+ data = v
67
+ }
68
+ func markDismissed(_ id: String) { add(id, to: \.dismissed) }
69
+ func markTaken(_ id: String) { add(id, to: \.taken) }
70
+
71
+ var notificationsToday: Int { data.day == Self.today() ? data.dayCount : 0 }
72
+
73
+ /// For the explicit `show()`: only studies already finished are excluded.
74
+ func isTaken(_ id: String) -> Bool { data.taken.contains(id) }
75
+ /// For auto-show and notifications: anything the person has already seen, closed or finished.
76
+ func isHandled(_ id: String) -> Bool { let d = data; return d.taken.contains(id) || d.dismissed.contains(id) || d.notified.contains(id) }
77
+ func isSuppressedForNotification(_ id: String) -> Bool { isHandled(id) }
78
+ func isSuppressedForAutoShow(_ id: String) -> Bool { let d = data; return d.taken.contains(id) || d.dismissed.contains(id) }
79
+
80
+ func clear() { defaults.removeObject(forKey: key) }
81
+ }
@@ -0,0 +1,102 @@
1
+ import Foundation
2
+ import CryptoKit
3
+
4
+ /// The decoded (never verified) token payload. The server verifies everything on POST /attempts.
5
+ struct TokenInfo {
6
+ let sub: String
7
+ let attrs: [String: Any]
8
+ let exp: Double?
9
+
10
+ var lang: String? { attrs["lang"] as? String }
11
+
12
+ /// Every attribute the token carries, in a fixed order, for the consent screen. FOUNTIS stores all of them when the
13
+ /// study opens, not only the ones the study's conditions use (`requiredAttrs`).
14
+ var carriedAttrs: [String] {
15
+ let order = ["gender", "birth_year", "governorate", "city", "lang"]
16
+ func rank(_ k: String) -> Int { order.firstIndex(of: k) ?? order.count }
17
+ return attrs.filter { !($0.value is NSNull) }.keys.sorted { (rank($0), $0) < (rank($1), $1) }
18
+ }
19
+
20
+ var subHash: String {
21
+ let d = SHA256.hash(data: Data(sub.utf8))
22
+ return d.prefix(8).map { String(format: "%02x", $0) }.joined()
23
+ }
24
+
25
+ static func decode(_ token: String) -> TokenInfo? {
26
+ let parts = token.split(separator: ".", omittingEmptySubsequences: false)
27
+ guard parts.count >= 2 else { return nil }
28
+ var b64 = String(parts[1]).replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
29
+ while b64.count % 4 != 0 { b64 += "=" }
30
+ guard let data = Data(base64Encoded: b64),
31
+ let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
32
+ let sub = o["sub"] as? String, !sub.isEmpty else { return nil }
33
+ return TokenInfo(sub: sub, attrs: (o["attrs"] as? [String: Any]) ?? [:], exp: (o["exp"] as? NSNumber)?.doubleValue)
34
+ }
35
+ }
36
+
37
+ enum Matcher {
38
+ /// Offer is offerable to this person: required attributes present, not expired, every condition holds.
39
+ static func matches(_ offer: Offer, token: TokenInfo, now: Date = Date()) -> Bool {
40
+ if let exp = offer.expiresAt, let d = parseDate(exp), d < now { return false }
41
+ for a in offer.requiredAttrs ?? [] where token.attrs[a] == nil { return false }
42
+ for c in offer.conditions?.all ?? [] where !holds(c, attrs: token.attrs, now: now) { return false }
43
+ return true
44
+ }
45
+
46
+ /// Offer is offerable to a guest: the server marked it guest-eligible and it has not expired.
47
+ static func matchesGuest(_ offer: Offer, now: Date = Date()) -> Bool {
48
+ guard offer.guest == true else { return false }
49
+ if let exp = offer.expiresAt, let d = parseDate(exp), d < now { return false }
50
+ return true
51
+ }
52
+
53
+ static func attrValue(_ name: String, _ attrs: [String: Any], now: Date) -> Any? {
54
+ if name == "age" {
55
+ guard let by = (attrs["birth_year"] as? NSNumber)?.intValue else { return nil }
56
+ return Calendar(identifier: .gregorian).component(.year, from: now) - by
57
+ }
58
+ return attrs[name]
59
+ }
60
+
61
+ static func holds(_ c: Condition, attrs: [String: Any], now: Date) -> Bool {
62
+ guard let v = attrValue(c.attr, attrs, now: now) else { return false }
63
+ let s = (v as? String) ?? (v as? NSNumber)?.stringValue ?? ""
64
+ let n: Double? = (v as? NSNumber)?.doubleValue ?? Double(s)
65
+ switch c.op {
66
+ case "in", "not_in":
67
+ guard case .array(let list) = c.value else { return false }
68
+ let hit = list.contains { $0.string == s || ($0.number != nil && $0.number == n) }
69
+ return c.op == "in" ? hit : !hit
70
+ case "eq":
71
+ return c.value.string == s || (c.value.number != nil && c.value.number == n)
72
+ case "gte":
73
+ guard let n = n, let t = c.value.number else { return false }
74
+ return n >= t
75
+ case "lte":
76
+ guard let n = n, let t = c.value.number else { return false }
77
+ return n <= t
78
+ case "between":
79
+ guard let n = n, case .array(let r) = c.value, r.count == 2, let lo = r[0].number, let hi = r[1].number else { return false }
80
+ return n >= lo && n <= hi
81
+ default:
82
+ return false
83
+ }
84
+ }
85
+
86
+ static func parseDate(_ s: String) -> Date? {
87
+ let f = ISO8601DateFormatter()
88
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
89
+ if let d = f.date(from: s) { return d }
90
+ f.formatOptions = [.withInternetDateTime]
91
+ return f.date(from: s)
92
+ }
93
+
94
+ /// `quiet = [start, end]` hours in local time, wrapping midnight (e.g. [22, 9]).
95
+ static func inQuietHours(_ quiet: [Int]?, now: Date = Date()) -> Bool {
96
+ guard let q = quiet, q.count == 2 else { return false }
97
+ let h = Calendar.current.component(.hour, from: now)
98
+ let (s, e) = (q[0], q[1])
99
+ if s == e { return false }
100
+ return s < e ? (h >= s && h < e) : (h >= s || h < e)
101
+ }
102
+ }