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