@fountispanel/connect-react-native 0.0.0-stage → 1.0.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 (57) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +24 -0
  3. package/README.md +90 -2
  4. package/android/build.gradle +36 -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 +161 -0
  11. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +616 -0
  12. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +321 -0
  13. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +143 -0
  14. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +167 -0
  15. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +128 -0
  16. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +109 -0
  17. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +74 -0
  18. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +45 -0
  19. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +72 -0
  20. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +12 -0
  21. package/android/connect-sdk/main/res/values/fountis_styles.xml +13 -0
  22. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +12 -0
  23. package/android/src/main/AndroidManifest.xml +18 -0
  24. package/android/src/main/java/org/fountis/connect/rn/FountisConnectModule.kt +113 -0
  25. package/app.plugin.js +41 -0
  26. package/build/index.d.ts +34 -0
  27. package/build/index.js +126 -0
  28. package/build/index.web.d.ts +22 -0
  29. package/build/index.web.js +57 -0
  30. package/build/types.d.ts +23 -0
  31. package/build/types.js +1 -0
  32. package/expo-module.config.json +10 -0
  33. package/ios/FountisConnectAppDelegateSubscriber.swift +16 -0
  34. package/ios/FountisConnectBundle.swift +15 -0
  35. package/ios/FountisConnectModule.swift +131 -0
  36. package/ios/FountisConnectReactNative.podspec +35 -0
  37. package/ios/FountisConnectSDK/ApiClient.swift +113 -0
  38. package/ios/FountisConnectSDK/Engine/engine.html +47 -0
  39. package/ios/FountisConnectSDK/Engine/i18n/ar.json +70 -0
  40. package/ios/FountisConnectSDK/Engine/i18n/en.json +70 -0
  41. package/ios/FountisConnectSDK/Engine/i18n/kmr.json +70 -0
  42. package/ios/FountisConnectSDK/Engine/i18n/ku.json +70 -0
  43. package/ios/FountisConnectSDK/FountisConnect.swift +436 -0
  44. package/ios/FountisConnectSDK/LocalState.swift +81 -0
  45. package/ios/FountisConnectSDK/Matcher.swift +102 -0
  46. package/ios/FountisConnectSDK/Models.swift +116 -0
  47. package/ios/FountisConnectSDK/Notifier.swift +63 -0
  48. package/ios/FountisConnectSDK/PrivacyInfo.xcprivacy +23 -0
  49. package/ios/FountisConnectSDK/RequestDeadline.swift +93 -0
  50. package/ios/FountisConnectSDK/SheetController.swift +259 -0
  51. package/ios/FountisConnectSDK/Strings.swift +34 -0
  52. package/ios/FountisConnectSDK/TokenProviderCall.swift +91 -0
  53. package/package.json +67 -4
  54. package/scripts/vendor-native.sh +16 -0
  55. package/src/index.ts +142 -0
  56. package/src/index.web.ts +64 -0
  57. package/src/types.ts +26 -0
@@ -0,0 +1,616 @@
1
+ package org.fountis.connect
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.content.pm.PackageManager
8
+ import android.os.Build
9
+ import android.os.Bundle
10
+ import android.os.Handler
11
+ import android.os.Looper
12
+ import androidx.core.app.ActivityCompat
13
+ import androidx.lifecycle.DefaultLifecycleObserver
14
+ import androidx.lifecycle.LifecycleOwner
15
+ import androidx.lifecycle.ProcessLifecycleOwner
16
+ import java.lang.ref.WeakReference
17
+ import java.util.concurrent.CopyOnWriteArrayList
18
+ import kotlinx.coroutines.CancellationException
19
+ import kotlinx.coroutines.CompletableDeferred
20
+ import kotlinx.coroutines.CoroutineScope
21
+ import kotlinx.coroutines.Dispatchers
22
+ import kotlinx.coroutines.Job
23
+ import kotlinx.coroutines.SupervisorJob
24
+ import kotlinx.coroutines.delay
25
+ import kotlinx.coroutines.launch
26
+ import kotlinx.coroutines.withContext
27
+ import org.json.JSONArray
28
+ import org.json.JSONObject
29
+
30
+ /**
31
+ * FOUNTIS Connect for Android.
32
+ *
33
+ * ```kotlin
34
+ * // In Application.onCreate (not in an Activity):
35
+ * FountisConnect.start(this, "pk_live_...")
36
+ * FountisConnect.setUserToken { myServer.fountisToken() } // null when signed out
37
+ * // Later, from an Activity (optional):
38
+ * FountisConnect.enableNotifications(this)
39
+ * ```
40
+ *
41
+ * Guests: when the token provider returns `null` (nobody is signed in) and FOUNTIS has switched guests on for your
42
+ * app, the SDK offers the free studies marked open to guests, after an 18+ confirmation. Nothing to call; an app
43
+ * without accounts can pass `setUserToken { null }`.
44
+ *
45
+ * Every failure is silent and becomes [FountisResult.NoFill] plus a `Log.d` line with the tag `FountisConnect`.
46
+ * The SDK never throws into the host app.
47
+ */
48
+ public object FountisConnect {
49
+ /** Production base URL until `api.fountis.org` is live. */
50
+ public const val DEFAULT_API_BASE: String = "https://ucclsekjekdxzfwzyuji.supabase.co/functions/v1/connect-api/v1"
51
+
52
+ /**
53
+ * Starts the SDK. Call once, from `Application.onCreate`, so the background check also works when the
54
+ * process is started by the system. [apiBase] defaults to [DEFAULT_API_BASE].
55
+ */
56
+ @JvmStatic
57
+ @JvmOverloads
58
+ public fun start(context: Context, key: String, apiBase: String? = null) {
59
+ guarded { Core.start(context, key, apiBase ?: DEFAULT_API_BASE) }
60
+ }
61
+
62
+ /**
63
+ * Gives the SDK a way to get the signed user token from your server. Return `null` only when nobody is signed
64
+ * in; that is the one case the SDK treats as a guest. Throw when you cannot get a token (offline, server error):
65
+ * the SDK shows nothing and tries again later. No answer within 10 seconds counts as a failure too (nothing is
66
+ * shown, and the person is never treated as a guest). An empty string is not "signed out": it is an unusable
67
+ * token and shows nothing.
68
+ * Called on demand, never cached by the SDK for longer than one check.
69
+ */
70
+ @JvmStatic
71
+ public fun setUserToken(provider: suspend () -> String?) {
72
+ guarded { Core.setUserToken(provider) }
73
+ }
74
+
75
+ /**
76
+ * Java variant of [setUserToken]: [provider] runs on a background thread, so a blocking call is fine. Return
77
+ * `null` only when nobody is signed in; throw when you cannot get a token. A call that has not returned after
78
+ * 10 seconds counts as a failure (nothing is shown, never a guest).
79
+ */
80
+ @JvmStatic
81
+ public fun setUserTokenProvider(provider: FountisTokenProvider) {
82
+ guarded { Core.setUserToken { withContext(Dispatchers.IO) { provider.getToken() } } }
83
+ }
84
+
85
+ /**
86
+ * Turns on the background check (WorkManager, about every 4 hours) and asks for the notification permission on
87
+ * Android 13+ if it is not already granted. One local notification a day at most.
88
+ */
89
+ @JvmStatic
90
+ public fun enableNotifications(activity: Activity) {
91
+ guarded { Core.enableNotifications(activity) }
92
+ }
93
+
94
+ /** Looks for a matching study and shows it full screen. Returns [FountisResult.NoFill] fast when there is nothing to show. */
95
+ @JvmStatic
96
+ public suspend fun show(activity: Activity): FountisResult = try {
97
+ withContext(Dispatchers.Main.immediate) { Core.run(Mode.Manual, activity) }
98
+ } catch (e: CancellationException) {
99
+ throw e
100
+ } catch (t: Throwable) {
101
+ logd("show failed: $t")
102
+ FountisResult.NoFill
103
+ }
104
+
105
+ /** Callback variant of [show] for Java; [callback] runs on the main thread. */
106
+ @JvmStatic
107
+ public fun show(activity: Activity, callback: FountisResultCallback) {
108
+ guarded {
109
+ Core.scope.launch {
110
+ val r = show(activity)
111
+ try {
112
+ callback.onResult(r)
113
+ } catch (t: Throwable) {
114
+ logd("callback failed: $t")
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ /** Call from your push handler with the message data. Returns `true` if it is a FOUNTIS push (it carries a `fountis` key). */
121
+ @JvmStatic
122
+ public fun handlePush(data: Map<String, String>): Boolean = guarded(false) { Core.handlePush(data) }
123
+
124
+ /**
125
+ * The notification tap opens your app's launcher activity with an extra. The SDK picks it up by itself when an
126
+ * activity resumes; call this from `onNewIntent` if your launcher activity is `singleTop`/`singleTask`.
127
+ * Returns `true` (and presents the study) if the intent came from a FOUNTIS notification.
128
+ */
129
+ @JvmStatic
130
+ public fun handleIntent(intent: Intent?): Boolean = guarded(false) { Core.handleIntent(intent) }
131
+
132
+ /** Pass the person's consent to be offered studies (for example from your own consent screen). Default: `true`. */
133
+ @JvmStatic
134
+ public fun setUserConsent(granted: Boolean) {
135
+ Core.consent = granted
136
+ }
137
+
138
+ /** Forget the signed-in person: removes this person's local state and any posted notification. */
139
+ @JvmStatic
140
+ public fun signOut() {
141
+ guarded { Core.signOut() }
142
+ }
143
+
144
+ /** Anonymous lifecycle events (`shown`, `dismissed`, `completed`, `noFill`, `notified`), delivered on the main thread. */
145
+ @JvmStatic
146
+ public fun onEvent(listener: FountisEventListener) {
147
+ Core.listeners.add(listener)
148
+ }
149
+
150
+ private inline fun guarded(block: () -> Unit) {
151
+ try {
152
+ block()
153
+ } catch (t: Throwable) {
154
+ logd("failed: $t")
155
+ }
156
+ }
157
+
158
+ private inline fun <T> guarded(fallback: T, block: () -> T): T = try {
159
+ block()
160
+ } catch (t: Throwable) {
161
+ logd("failed: $t")
162
+ fallback
163
+ }
164
+ }
165
+
166
+ internal sealed class Mode {
167
+ object Manual : Mode()
168
+ object Auto : Mode()
169
+ class Offer(val id: String) : Mode()
170
+ }
171
+
172
+ internal object Core {
173
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
174
+ private val mainHandler = Handler(Looper.getMainLooper())
175
+
176
+ @Volatile var consent = true
177
+ val listeners = CopyOnWriteArrayList<FountisEventListener>()
178
+
179
+ private var app: Application? = null
180
+ private var api: ApiClient? = null
181
+ private var store: StateStore? = null
182
+
183
+ @Volatile private var provider: (suspend () -> String?)? = null
184
+ @Volatile private var started = false
185
+ @Volatile private var foreground = false
186
+ private var presenting = false
187
+ private var autoShownThisSession = false
188
+ // Set when run() refused to present because no activity was in front (the notification permission dialog pauses
189
+ // the host activity) or the app was not in the foreground. An auto-show that hits this is given back, not spent.
190
+ @Volatile private var skippedWhileInactive = false
191
+ private var autoJob: Job? = null
192
+ private var backgroundedAt = 0L
193
+ private var notificationsOn = false
194
+ private var lastSubHash: String? = null
195
+ private var guestSession: Pair<String, Long>? = null
196
+ private var resumed: WeakReference<Activity>? = null
197
+ private var webViewOk: Boolean? = null
198
+ private var cache: Cached? = null
199
+
200
+ private class Cached(val lang: String, val at: Long, val value: SurveysResponse)
201
+
202
+ private class Session(
203
+ val api: ApiClient,
204
+ /** The signed user token; null for a guest. */
205
+ val token: String?,
206
+ val info: TokenInfo?,
207
+ val lang: String,
208
+ val surveys: SurveysResponse,
209
+ val state: LocalState,
210
+ ) {
211
+ val isGuest: Boolean get() = token == null
212
+
213
+ fun matches(offer: Offer): Boolean = if (info != null) Matcher.matches(offer, info) else Matcher.matchesGuest(offer)
214
+ }
215
+
216
+ private const val ACCENT = "#5dc0a0"
217
+ private const val PERMISSION_REQUEST_CODE = 4670
218
+
219
+ // ---- setup ----
220
+
221
+ fun start(context: Context, key: String, apiBase: String) {
222
+ val a = context.applicationContext as? Application ?: return
223
+ synchronized(this) {
224
+ if (started) return
225
+ if (!key.startsWith("pk_")) {
226
+ logd("start: key must be a publishable key (pk_...)")
227
+ return
228
+ }
229
+ val st = StateStore(a)
230
+ app = a
231
+ api = ApiClient(apiBase, key)
232
+ store = st
233
+ notificationsOn = st.getBoolean("notifications")
234
+ a.registerActivityLifecycleCallbacks(callbacks)
235
+ started = true
236
+ }
237
+ mainHandler.post {
238
+ try {
239
+ ProcessLifecycleOwner.get().lifecycle.addObserver(processObserver)
240
+ } catch (t: Throwable) {
241
+ logd("lifecycle observer failed: $t")
242
+ }
243
+ }
244
+ if (notificationsOn) {
245
+ Notifier.ensureChannel(a)
246
+ Notifier.schedule(a, null)
247
+ }
248
+ }
249
+
250
+ fun setUserToken(p: suspend () -> String?) {
251
+ provider = p
252
+ mainHandler.post { if (started && foreground) scheduleAutoShow() }
253
+ }
254
+
255
+ fun enableNotifications(activity: Activity) {
256
+ val a = app
257
+ val st = store
258
+ if (!started || a == null || st == null) {
259
+ logd("enableNotifications: call start() first")
260
+ return
261
+ }
262
+ notificationsOn = true
263
+ st.setBoolean("notifications", true)
264
+ Notifier.ensureChannel(a)
265
+ activity.runOnUiThread {
266
+ try {
267
+ if (Build.VERSION.SDK_INT >= 33 &&
268
+ activity.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
269
+ ) {
270
+ ActivityCompat.requestPermissions(activity, arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), PERMISSION_REQUEST_CODE)
271
+ }
272
+ } catch (t: Throwable) {
273
+ logd("permission request failed: $t")
274
+ }
275
+ }
276
+ Notifier.schedule(a, cache?.value?.config?.checkIntervalMinutes)
277
+ }
278
+
279
+ fun signOut() {
280
+ mainHandler.post {
281
+ autoJob?.cancel()
282
+ val st = store
283
+ lastSubHash?.let { h -> st?.let { LocalState(it, h).clear() } }
284
+ lastSubHash = null
285
+ guestSession = null
286
+ cache = null
287
+ autoShownThisSession = false
288
+ app?.let { Notifier.cancel(it) }
289
+ }
290
+ }
291
+
292
+ // ---- foreground / activities / push / tap ----
293
+
294
+ private val processObserver = object : DefaultLifecycleObserver {
295
+ override fun onStart(owner: LifecycleOwner) {
296
+ foreground = true
297
+ if (backgroundedAt != 0L && System.currentTimeMillis() - backgroundedAt > 1_800_000L) autoShownThisSession = false
298
+ backgroundedAt = 0L
299
+ scheduleAutoShow()
300
+ }
301
+
302
+ override fun onStop(owner: LifecycleOwner) {
303
+ foreground = false
304
+ backgroundedAt = System.currentTimeMillis()
305
+ }
306
+ }
307
+
308
+ private val callbacks = object : Application.ActivityLifecycleCallbacks {
309
+ override fun onActivityResumed(activity: Activity) {
310
+ if (activity is FountisSurveyActivity) return
311
+ resumed = WeakReference(activity)
312
+ // The notification permission dialog pauses the host activity. An auto-show that found no resumed
313
+ // activity gave up without being consumed, so try again as soon as one is back in front.
314
+ if (started) scheduleAutoShow()
315
+ try {
316
+ val id = activity.intent?.getStringExtra(Notifier.EXTRA_OFFER)
317
+ if (id != null) {
318
+ activity.intent.removeExtra(Notifier.EXTRA_OFFER)
319
+ handleTap(id)
320
+ }
321
+ } catch (t: Throwable) {
322
+ logd("intent check failed: $t")
323
+ }
324
+ }
325
+
326
+ override fun onActivityPaused(activity: Activity) {
327
+ if (resumed?.get() === activity) resumed = null
328
+ }
329
+
330
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
331
+ override fun onActivityStarted(activity: Activity) {}
332
+ override fun onActivityStopped(activity: Activity) {}
333
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
334
+ override fun onActivityDestroyed(activity: Activity) {}
335
+ }
336
+
337
+ private fun topActivity(): Activity? = resumed?.get()?.takeIf { !it.isFinishing && !it.isDestroyed }
338
+
339
+ private fun scheduleAutoShow() {
340
+ if (autoShownThisSession || provider == null || !started) return
341
+ autoJob?.cancel()
342
+ autoJob = scope.launch {
343
+ delay(1200) // let the host UI settle
344
+ if (autoShownThisSession || !foreground) return@launch
345
+ val act = topActivity() ?: return@launch
346
+ autoShownThisSession = true
347
+ skippedWhileInactive = false
348
+ val result = run(Mode.Auto, act)
349
+ // The dialog can also appear while the request is in flight; run() then refuses to present. Give the
350
+ // auto-show back and try again once an activity is resumed again.
351
+ if (result == FountisResult.NoFill && skippedWhileInactive) {
352
+ autoShownThisSession = false
353
+ if (foreground && topActivity() != null) scheduleAutoShow()
354
+ }
355
+ }
356
+ }
357
+
358
+ fun handlePush(data: Map<String, String>): Boolean {
359
+ if (!data.containsKey("fountis")) return false
360
+ scope.launch {
361
+ try {
362
+ if (foreground) run(Mode.Auto, topActivity()) else checkAndNotify()
363
+ } catch (e: CancellationException) {
364
+ throw e
365
+ } catch (t: Throwable) {
366
+ logd("push check failed: $t")
367
+ }
368
+ }
369
+ return true
370
+ }
371
+
372
+ fun handleIntent(intent: Intent?): Boolean {
373
+ val id = intent?.getStringExtra(Notifier.EXTRA_OFFER) ?: return false
374
+ intent.removeExtra(Notifier.EXTRA_OFFER)
375
+ handleTap(id)
376
+ return true
377
+ }
378
+
379
+ private fun handleTap(offerId: String) {
380
+ scope.launch {
381
+ // cold start: wait (briefly) for the app to be in front with an activity to present from
382
+ for (i in 0 until 20) {
383
+ if (foreground && topActivity() != null) break
384
+ delay(250)
385
+ }
386
+ autoShownThisSession = true
387
+ run(Mode.Offer(offerId), topActivity())
388
+ }
389
+ }
390
+
391
+ // ---- data ----
392
+
393
+ private suspend fun fetchSurveys(api: ApiClient, lang: String): SurveysResponse {
394
+ cache?.let { if (it.lang == lang && System.currentTimeMillis() - it.at < 60_000) return it.value }
395
+ val r = api.surveys(lang)
396
+ cache = Cached(lang, System.currentTimeMillis(), r)
397
+ return r
398
+ }
399
+
400
+ private fun emit(type: String, offerId: String? = null) {
401
+ val e = FountisEvent(type, offerId)
402
+ for (l in listeners) {
403
+ try {
404
+ l.onEvent(e)
405
+ } catch (t: Throwable) {
406
+ logd("listener failed: $t")
407
+ }
408
+ }
409
+ }
410
+
411
+ private suspend fun openSession(): Session? {
412
+ val api = api
413
+ val provider = provider
414
+ val st = store
415
+ if (!started || !consent || api == null || provider == null || st == null) return null
416
+ return try {
417
+ // Only null means nobody is signed in. A throw or no answer in 10 s is a failure (noFill), never a guest.
418
+ val token = callTokenProvider(scope) { provider() } ?: return openGuestSession(api, st)
419
+ // An empty string is not "signed out": it is an unusable token. (decode returns null for it anyway.)
420
+ if (token.isEmpty()) return null
421
+ val info = TokenInfo.decode(token) ?: return null
422
+ if (info.expSeconds != null && info.expSeconds < System.currentTimeMillis() / 1000.0) return null
423
+ lastSubHash = info.subHash
424
+ val lang = info.lang?.let { Strings.normalize(it) } ?: Strings.deviceLang()
425
+ Session(api, token, info, lang, fetchSurveys(api, lang), LocalState(st, info.subHash))
426
+ } catch (e: CancellationException) {
427
+ throw e
428
+ } catch (e: TokenProviderTimeoutException) {
429
+ logd("token provider gave no answer within ${TOKEN_PROVIDER_TIMEOUT_MS / 1000} s")
430
+ null
431
+ } catch (t: Throwable) {
432
+ logd("check failed: $t")
433
+ null
434
+ }
435
+ }
436
+
437
+ /** Nobody is signed in: a guest session, only when the app allows guests and a guest study exists. */
438
+ private suspend fun openGuestSession(api: ApiClient, st: StateStore): Session? {
439
+ val lang = Strings.deviceLang()
440
+ val surveys = fetchSurveys(api, lang)
441
+ if (!surveys.guests || surveys.surveys.none { it.guest }) return null
442
+ lastSubHash = "guest"
443
+ return Session(api, null, null, lang, surveys, LocalState(st, "guest"))
444
+ }
445
+
446
+ /** A guest session token, kept in memory for most of its hour. `force` makes a new one. */
447
+ private suspend fun guestToken(s: Session, force: Boolean = false): String {
448
+ val st = store ?: throw ApiError(0, "not_started", "not started")
449
+ guestSession?.let { if (!force && it.second > System.currentTimeMillis()) return it.first }
450
+ val t = s.api.guestSession(st.installId())
451
+ guestSession = t to (System.currentTimeMillis() + 55 * 60_000L)
452
+ return t
453
+ }
454
+
455
+ /** Starts the attempt for a person with a token or a guest session (a stale guest session is renewed once). */
456
+ private suspend fun createAttempt(s: Session, offerId: String): JSONObject {
457
+ if (s.token != null) return s.api.createAttempt(offerId, s.token, s.lang)
458
+ return try {
459
+ s.api.createGuestAttempt(offerId, guestToken(s), s.lang)
460
+ } catch (e: ApiError) {
461
+ if (e.code != "invalid_session") throw e
462
+ s.api.createGuestAttempt(offerId, guestToken(s, force = true), s.lang)
463
+ }
464
+ }
465
+
466
+ // ---- show ----
467
+
468
+ suspend fun run(mode: Mode, activity: Activity?): FountisResult {
469
+ val result = try {
470
+ runInner(mode, activity)
471
+ } catch (e: CancellationException) {
472
+ throw e
473
+ } catch (t: Throwable) {
474
+ logd("run failed: $t")
475
+ FountisResult.NoFill
476
+ }
477
+ if (result == FountisResult.NoFill) emit("noFill")
478
+ return result
479
+ }
480
+
481
+ private suspend fun runInner(mode: Mode, activity: Activity?): FountisResult {
482
+ if (presenting) return FountisResult.NoFill
483
+ presenting = true
484
+ try {
485
+ val s = openSession() ?: return FountisResult.NoFill
486
+ val act = (activity ?: topActivity())?.takeIf { !it.isFinishing && !it.isDestroyed }
487
+ if (act == null) { skippedWhileInactive = true; return FountisResult.NoFill }
488
+ if (mode !is Mode.Manual && !foreground) { skippedWhileInactive = true; return FountisResult.NoFill }
489
+ val ok = webViewOk ?: WebViewSupport.isSupported(act).also { webViewOk = it }
490
+ if (!ok) {
491
+ logd("WebView missing or older than Chromium 88")
492
+ return FountisResult.NoFill
493
+ }
494
+
495
+ var offers = s.surveys.surveys.filter { s.matches(it) }
496
+ offers = when (mode) {
497
+ is Mode.Manual -> offers.filter { !s.state.isTaken(it.offerId) }
498
+ is Mode.Auto -> offers.filter { !s.state.isSuppressedForAutoShow(it.offerId) }
499
+ is Mode.Offer -> offers.filter { it.offerId == mode.id && !s.state.isTaken(it.offerId) }
500
+ }
501
+ // Rewarded first (the sort is stable).
502
+ offers = offers.sortedByDescending { it.reward?.isRewarded == true }
503
+
504
+ for (offer in offers.take(3)) {
505
+ try {
506
+ val a = createAttempt(s, offer.offerId)
507
+ return present(offer, a, s, act)
508
+ } catch (e: ApiError) {
509
+ if (e.code == "already_taken") s.state.markTaken(offer.offerId)
510
+ if (e.code in setOf("already_taken", "not_eligible", "closed", "quota_full", "guests_not_allowed")) continue
511
+ logd("attempt failed: ${e.code}")
512
+ return FountisResult.NoFill
513
+ } catch (e: CancellationException) {
514
+ throw e
515
+ } catch (t: Throwable) {
516
+ logd("attempt failed: $t")
517
+ return FountisResult.NoFill
518
+ }
519
+ }
520
+ return FountisResult.NoFill
521
+ } finally {
522
+ presenting = false
523
+ }
524
+ }
525
+
526
+ private suspend fun present(offer: Offer, a: JSONObject, s: Session, activity: Activity): FountisResult {
527
+ val attemptToken = a.optString("attempt_token", "")
528
+ if (attemptToken.isEmpty() || !a.has("definition")) return FountisResult.NoFill
529
+
530
+ val payload = JSONObject()
531
+ .put("mode", "native")
532
+ .put("definition", a.opt("definition") ?: JSONObject.NULL)
533
+ .put("answers", a.optJSONObject("answers") ?: JSONObject())
534
+ .put("lang", s.lang)
535
+ .put("rtl", Strings.isRtl(s.lang))
536
+ .put("theme", JSONObject().put("accent", ACCENT))
537
+ .put("consentNeeded", a.optBoolean("consent_needed", false))
538
+ .put("attrs", JSONArray(s.info?.carriedAttrs ?: emptyList<String>()))
539
+ if (s.isGuest || a.optBoolean("guest", false)) payload.put("guest", true)
540
+ s.surveys.appName?.let { payload.put("partner", it) }
541
+ a.optString("rid", "").takeIf { it.isNotEmpty() }?.let { payload.put("rid", it) }
542
+ a.optJSONObject("reward")?.let { r ->
543
+ if (r.optInt("units", 0) > 0) {
544
+ payload.put("reward", JSONObject().put("units", r.optInt("units", 0)).put("unit_name", r.opt("unit_name") ?: ""))
545
+ }
546
+ }
547
+
548
+ val done = CompletableDeferred<Finish>()
549
+ val pending = SurveyPending(payload.toString(), s.api, attemptToken) { done.complete(it) }
550
+ pending.onShown = {
551
+ emit("shown", offer.offerId)
552
+ scope.launch { s.api.event(offer.offerId, "shown") }
553
+ }
554
+ SurveyHost.pending = pending
555
+ try {
556
+ activity.startActivity(Intent(activity, FountisSurveyActivity::class.java))
557
+ } catch (t: Throwable) {
558
+ logd("could not open the study: $t")
559
+ SurveyHost.pending = null
560
+ return FountisResult.NoFill
561
+ }
562
+ scope.launch {
563
+ delay(10_000)
564
+ if (!pending.attached) {
565
+ if (SurveyHost.pending === pending) SurveyHost.pending = null
566
+ done.complete(Finish(null, null, unavailable = true))
567
+ }
568
+ }
569
+
570
+ val fin = done.await()
571
+ if (fin.unavailable) return FountisResult.NoFill
572
+ return if (fin.outcome == "complete") {
573
+ s.state.markTaken(offer.offerId)
574
+ emit("completed", offer.offerId)
575
+ FountisResult.Completed
576
+ } else {
577
+ if (fin.outcome == "screen_out" || fin.fatal == "already_taken") s.state.markTaken(offer.offerId) else s.state.markDismissed(offer.offerId)
578
+ emit("dismissed", offer.offerId)
579
+ scope.launch { s.api.event(offer.offerId, "dismissed") }
580
+ FountisResult.Dismissed
581
+ }
582
+ }
583
+
584
+ // ---- notifications ----
585
+
586
+ /** Background / push check: at most one local notification a day, never in quiet hours, never while the app is in front. */
587
+ suspend fun checkAndNotify() {
588
+ withContext(Dispatchers.Main.immediate) { checkAndNotifyInner() }
589
+ }
590
+
591
+ private suspend fun checkAndNotifyInner() {
592
+ val a = app ?: return
593
+ if (!notificationsOn) return
594
+ val s = openSession() ?: return
595
+ val cfg = s.surveys.config
596
+ if (foreground) return // foreground uses auto-show
597
+ if (Matcher.inQuietHours(cfg?.quietHours)) return
598
+ if (s.state.notificationsToday >= minOf(maxOf(cfg?.maxNotificationsPerDay ?: 1, 0), 1)) return
599
+ if (!Notifier.permissionGranted(a)) return
600
+ val offer = s.surveys.surveys.firstOrNull { s.matches(it) && !s.state.isSuppressedForNotification(it.offerId) } ?: return
601
+
602
+ Notifier.ensureChannel(a)
603
+ val title = Strings.get(a, "connect.notify.title", s.lang)
604
+ val minutes = maxOf(offer.loiMinutes ?: 5, 1).toString()
605
+ val r = offer.reward
606
+ val body = if (r != null && r.isRewarded) {
607
+ Strings.get(a, "connect.notify.bodyReward", s.lang, mapOf("minutes" to minutes, "units" to (r.units ?: 0).toString(), "unit" to r.unitLabel(s.lang)))
608
+ } else {
609
+ Strings.get(a, "connect.notify.body", s.lang, mapOf("minutes" to minutes))
610
+ }
611
+ if (Notifier.post(a, title, body, offer.offerId)) {
612
+ s.state.markNotified(offer.offerId)
613
+ emit("notified", offer.offerId)
614
+ }
615
+ }
616
+ }