@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,144 @@
1
+ package org.fountis.connect
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+
6
+ /** What `show()` returns. Every failure is [NoFill]. */
7
+ public enum class FountisResult {
8
+ /** Nothing to show (no matching study, no consent, no token, network trouble, nowhere to present). */
9
+ NoFill,
10
+
11
+ /** The person closed the study before finishing it, or was screened out / the study filled up. */
12
+ Dismissed,
13
+
14
+ /** The person finished the study. */
15
+ Completed,
16
+ }
17
+
18
+ /**
19
+ * Anonymous lifecycle event for the host app (`onEvent`). Carries no titles, topics or answers.
20
+ * [type] is one of `shown`, `dismissed`, `completed`, `noFill`, `notified`.
21
+ */
22
+ public class FountisEvent(public val type: String, public val offerId: String?) {
23
+ override fun toString(): String = "FountisEvent($type, $offerId)"
24
+ }
25
+
26
+ /** Receives [FountisEvent]s on the main thread. */
27
+ public fun interface FountisEventListener {
28
+ public fun onEvent(event: FountisEvent)
29
+ }
30
+
31
+ /** Java-friendly result callback for `show(activity, callback)`; called on the main thread. */
32
+ public fun interface FountisResultCallback {
33
+ public fun onResult(result: FountisResult)
34
+ }
35
+
36
+ /**
37
+ * Java-friendly user-token provider. Called on a background thread, so a blocking call to your server is fine.
38
+ * Return `null` when nobody is signed in.
39
+ */
40
+ public fun interface FountisTokenProvider {
41
+ public fun getToken(): String?
42
+ }
43
+
44
+ // ---- internal models (parsed with org.json, no reflection) ----
45
+
46
+ internal class Condition(val attr: String, val op: String, val value: Any?)
47
+
48
+ internal class OfferReward(val mode: String, val units: Int?, val unitName: Any?) {
49
+ val isRewarded: Boolean get() = mode == "rewarded" && (units ?: 0) > 0
50
+
51
+ fun unitLabel(lang: String): String = when (val u = unitName) {
52
+ is String -> u
53
+ is Map<*, *> -> (u[lang] as? String) ?: (u["en"] as? String) ?: u.values.firstNotNullOfOrNull { it as? String } ?: ""
54
+ else -> ""
55
+ }
56
+ }
57
+
58
+ internal class Offer(
59
+ val offerId: String,
60
+ val conditions: List<Condition>,
61
+ val requiredAttrs: List<String>,
62
+ val loiMinutes: Int?,
63
+ val reward: OfferReward?,
64
+ val expiresAt: String?,
65
+ /** Open to guests (people with no signed token); only ever true on apps FOUNTIS allowed guests in. */
66
+ val guest: Boolean = false,
67
+ )
68
+
69
+ internal class SurveysConfig(val maxNotificationsPerDay: Int?, val quietHours: List<Int>?, val checkIntervalMinutes: Int?)
70
+
71
+ internal class SurveysResponse(
72
+ val appName: String?,
73
+ val config: SurveysConfig?,
74
+ val surveys: List<Offer>,
75
+ val guests: Boolean = false,
76
+ /** Device attestation for guest sessions (`app.attest`); off when the server sends nothing. */
77
+ val attest: AttestConfig = AttestConfig.OFF,
78
+ )
79
+
80
+ // ---- JSON helpers ----
81
+
82
+ /** Converts org.json values into plain Kotlin values (Map, List, String, Number, Boolean, null). */
83
+ internal fun jsonToKotlin(v: Any?): Any? = when (v) {
84
+ null, JSONObject.NULL -> null
85
+ is JSONObject -> v.keys().asSequence().associateWith { jsonToKotlin(v.opt(it)) }
86
+ is JSONArray -> (0 until v.length()).map { jsonToKotlin(v.opt(it)) }
87
+ else -> v
88
+ }
89
+
90
+ private fun JSONObject.optStringOrNull(name: String): String? =
91
+ if (has(name) && !isNull(name)) opt(name) as? String else null
92
+
93
+ private fun JSONObject.optIntOrNull(name: String): Int? =
94
+ if (has(name) && !isNull(name)) (opt(name) as? Number)?.toInt() else null
95
+
96
+ internal fun parseSurveys(text: String): SurveysResponse {
97
+ val root = JSONObject(text)
98
+ val cfg = root.optJSONObject("config")?.let { c ->
99
+ SurveysConfig(
100
+ maxNotificationsPerDay = c.optIntOrNull("max_notifications_per_day"),
101
+ quietHours = c.optJSONArray("quiet_hours")?.let { a -> (0 until a.length()).map { a.optInt(it) } },
102
+ checkIntervalMinutes = c.optIntOrNull("check_interval_minutes"),
103
+ )
104
+ }
105
+ val list = root.optJSONArray("surveys") ?: JSONArray()
106
+ val offers = ArrayList<Offer>()
107
+ for (i in 0 until list.length()) {
108
+ val o = list.optJSONObject(i) ?: continue
109
+ val id = o.optStringOrNull("offer_id") ?: continue
110
+ val conds = ArrayList<Condition>()
111
+ o.optJSONObject("conditions")?.optJSONArray("all")?.let { all ->
112
+ for (j in 0 until all.length()) {
113
+ val c = all.optJSONObject(j) ?: continue
114
+ conds.add(Condition(c.optString("attr"), c.optString("op"), jsonToKotlin(c.opt("value"))))
115
+ }
116
+ }
117
+ val attrs = o.optJSONArray("required_attrs")?.let { a -> (0 until a.length()).mapNotNull { a.optString(it).ifEmpty { null } } } ?: emptyList()
118
+ val reward = o.optJSONObject("reward")?.let { r ->
119
+ OfferReward(r.optString("mode"), r.optIntOrNull("units"), jsonToKotlin(r.opt("unit_name")))
120
+ }
121
+ offers.add(Offer(id, conds, attrs, o.optIntOrNull("loi_minutes"), reward, o.optStringOrNull("expires_at"), o.optBoolean("guest", false)))
122
+ }
123
+ val app = root.optJSONObject("app")
124
+ val attest = app?.optJSONObject("attest")?.let { a ->
125
+ // The project number is a string on the wire; a bare JSON number is accepted too.
126
+ val project = when (val p = a.opt("android_cloud_project")) {
127
+ is String -> p
128
+ is Number -> p.toLong().toString()
129
+ else -> null
130
+ }
131
+ AttestConfig(a.optString("mode", "off"), project)
132
+ } ?: AttestConfig.OFF
133
+ return SurveysResponse(app?.optStringOrNull("name"), cfg, offers, app?.optBoolean("guests", false) ?: false, attest)
134
+ }
135
+
136
+ internal const val TAG = "FountisConnect"
137
+
138
+ internal fun logd(message: String) {
139
+ try {
140
+ android.util.Log.d(TAG, message)
141
+ } catch (_: Throwable) {
142
+ // plain JVM unit tests have no android.util.Log
143
+ }
144
+ }
@@ -0,0 +1,109 @@
1
+ package org.fountis.connect
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.app.NotificationChannel
6
+ import android.app.NotificationManager
7
+ import android.app.PendingIntent
8
+ import android.content.Context
9
+ import android.content.pm.PackageManager
10
+ import android.os.Build
11
+ import androidx.core.app.NotificationCompat
12
+ import androidx.core.app.NotificationManagerCompat
13
+ import androidx.core.content.ContextCompat
14
+ import androidx.work.Constraints
15
+ import androidx.work.CoroutineWorker
16
+ import androidx.work.ExistingPeriodicWorkPolicy
17
+ import androidx.work.NetworkType
18
+ import androidx.work.PeriodicWorkRequestBuilder
19
+ import androidx.work.WorkManager
20
+ import androidx.work.WorkerParameters
21
+ import java.util.concurrent.TimeUnit
22
+
23
+ /** Periodic background check (WorkManager). Android's minimum period is 15 minutes; the SDK asks for the server's interval, 4 h by default. */
24
+ internal class RefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
25
+ override suspend fun doWork(): Result {
26
+ try {
27
+ Core.checkAndNotify()
28
+ } catch (e: kotlinx.coroutines.CancellationException) {
29
+ throw e
30
+ } catch (t: Throwable) {
31
+ logd("background check failed: $t")
32
+ }
33
+ return Result.success()
34
+ }
35
+ }
36
+
37
+ internal object Notifier {
38
+ const val WORK_NAME = "org.fountis.connect.refresh"
39
+ const val CHANNEL_ID = "org.fountis.connect.studies"
40
+ const val CHANNEL_NAME = "FOUNTIS studies"
41
+ const val NOTIFICATION_ID = 0x464F
42
+ /** Intent extra on the notification's launch intent: the offer id. */
43
+ const val EXTRA_OFFER = "fountis"
44
+
45
+ fun ensureChannel(context: Context) {
46
+ if (Build.VERSION.SDK_INT < 26) return
47
+ try {
48
+ val nm = context.getSystemService(NotificationManager::class.java)
49
+ if (nm.getNotificationChannel(CHANNEL_ID) == null) {
50
+ nm.createNotificationChannel(NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT))
51
+ }
52
+ } catch (t: Throwable) {
53
+ logd("channel not created: $t")
54
+ }
55
+ }
56
+
57
+ fun schedule(context: Context, minutes: Int?) {
58
+ try {
59
+ val interval = maxOf(minutes ?: 240, 15).toLong()
60
+ val req = PeriodicWorkRequestBuilder<RefreshWorker>(interval, TimeUnit.MINUTES)
61
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
62
+ .build()
63
+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, req)
64
+ } catch (t: Throwable) {
65
+ logd("could not schedule refresh: $t")
66
+ }
67
+ }
68
+
69
+ fun permissionGranted(context: Context): Boolean {
70
+ if (Build.VERSION.SDK_INT >= 33 &&
71
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
72
+ ) return false
73
+ return NotificationManagerCompat.from(context).areNotificationsEnabled()
74
+ }
75
+
76
+ fun cancel(context: Context) {
77
+ try {
78
+ NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
79
+ } catch (_: Throwable) {
80
+ }
81
+ }
82
+
83
+ /** Posts the one local notification. Tapping it opens the host app with the offer id as an intent extra. */
84
+ @SuppressLint("MissingPermission")
85
+ fun post(context: Context, title: String, body: String, offerId: String): Boolean {
86
+ return try {
87
+ val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
88
+ putExtra(EXTRA_OFFER, offerId)
89
+ }
90
+ val pi = launch?.let {
91
+ PendingIntent.getActivity(context, offerId.hashCode(), it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
92
+ }
93
+ val n = NotificationCompat.Builder(context, CHANNEL_ID)
94
+ .setSmallIcon(R.drawable.fountis_ic_notification)
95
+ .setContentTitle(title)
96
+ .setContentText(body)
97
+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))
98
+ .setPriority(NotificationCompat.PRIORITY_DEFAULT)
99
+ .setAutoCancel(true)
100
+ .setContentIntent(pi)
101
+ .build()
102
+ NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, n)
103
+ true
104
+ } catch (t: Throwable) {
105
+ logd("notification failed: $t")
106
+ false
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,70 @@
1
+ package org.fountis.connect
2
+
3
+ import android.content.Context
4
+ import com.google.android.gms.tasks.Task
5
+ import com.google.android.play.core.integrity.IntegrityManagerFactory
6
+ import com.google.android.play.core.integrity.StandardIntegrityException
7
+ import com.google.android.play.core.integrity.StandardIntegrityManager
8
+ import com.google.android.play.core.integrity.StandardIntegrityManager.PrepareIntegrityTokenRequest
9
+ import com.google.android.play.core.integrity.StandardIntegrityManager.StandardIntegrityTokenProvider
10
+ import com.google.android.play.core.integrity.StandardIntegrityManager.StandardIntegrityTokenRequest
11
+ import java.util.concurrent.Executor
12
+ import kotlin.coroutines.resume
13
+ import kotlin.coroutines.resumeWithException
14
+ import kotlinx.coroutines.CancellationException
15
+ import kotlinx.coroutines.suspendCancellableCoroutine
16
+
17
+ /**
18
+ * Play Integrity, Standard API. The only file that touches Google's classes. An app installed outside Google Play, or a
19
+ * device without Play Store or Play services, simply gets an [AttestUnavailable] here; nothing else changes for it.
20
+ *
21
+ * Play Integrity is not started until the first [prepare], which only happens for a guest of an app whose attestation
22
+ * mode is `report` or `enforce`.
23
+ */
24
+ internal class PlayIntegrityAttestor(context: Context) : Attestor {
25
+ private val appContext: Context = context.applicationContext
26
+
27
+ private val manager: StandardIntegrityManager by lazy { IntegrityManagerFactory.createStandard(appContext) }
28
+
29
+ @Volatile private var provider: StandardIntegrityTokenProvider? = null
30
+
31
+ override suspend fun prepare(cloudProjectNumber: Long) {
32
+ try {
33
+ val prepareRequest = PrepareIntegrityTokenRequest.builder().setCloudProjectNumber(cloudProjectNumber).build()
34
+ provider = manager.prepareIntegrityToken(prepareRequest).awaitTask()
35
+ } catch (e: CancellationException) {
36
+ throw e
37
+ } catch (t: Throwable) {
38
+ throw unavailableFor(t)
39
+ }
40
+ }
41
+
42
+ override suspend fun request(requestHash: String): String {
43
+ val p = provider ?: throw AttestUnavailable("error")
44
+ return try {
45
+ val tokenRequest = StandardIntegrityTokenRequest.builder().setRequestHash(requestHash).build()
46
+ p.request(tokenRequest).awaitTask().token()
47
+ } catch (e: CancellationException) {
48
+ throw e
49
+ } catch (t: Throwable) {
50
+ throw unavailableFor(t)
51
+ }
52
+ }
53
+
54
+ private fun unavailableFor(t: Throwable): AttestUnavailable {
55
+ if (t is AttestUnavailable) return t
56
+ // The Play Integrity classes missing at run time (for example stripped by a shrinker): this device cannot attest.
57
+ if (t is LinkageError) return AttestUnavailable("unsupported", t)
58
+ val errorCode = (t as? StandardIntegrityException)?.errorCode
59
+ return AttestUnavailable(attestCodeForPlayError(errorCode), t)
60
+ }
61
+ }
62
+
63
+ /** Callbacks run right where Google delivers them: they only resume the coroutine, so the main thread is not needed. */
64
+ private val DIRECT_EXECUTOR = Executor { it.run() }
65
+
66
+ private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->
67
+ addOnSuccessListener(DIRECT_EXECUTOR) { cont.resume(it) }
68
+ addOnFailureListener(DIRECT_EXECUTOR) { cont.resumeWithException(it) }
69
+ addOnCanceledListener(DIRECT_EXECUTOR) { cont.resumeWithException(AttestUnavailable("error")) }
70
+ }
@@ -0,0 +1,74 @@
1
+ package org.fountis.connect
2
+
3
+ import java.net.SocketTimeoutException
4
+ import kotlinx.coroutines.CancellationException
5
+ import kotlinx.coroutines.CoroutineScope
6
+ import kotlinx.coroutines.Deferred
7
+ import kotlinx.coroutines.async
8
+ import kotlinx.coroutines.launch
9
+ import kotlinx.coroutines.withTimeoutOrNull
10
+
11
+ /**
12
+ * The most one API request may take in total: opening the connection, sending the request and reading the whole
13
+ * response body. The web SDK aborts at the same 15 s. The HTTP client's own limits (15 s to connect, 20 s per read)
14
+ * are per step, so a server that keeps sending a byte at a time never trips them; this is the bound on the whole.
15
+ */
16
+ internal const val REQUEST_DEADLINE_MS: Long = 15_000L
17
+
18
+ /**
19
+ * A request that ran past its deadline. A [SocketTimeoutException] on purpose: it is what a read timeout throws, so
20
+ * every caller already treats it as an ordinary network failure (the study ends as noFill, `event()` swallows it).
21
+ */
22
+ internal class RequestTimeoutException(timeoutMs: Long) :
23
+ SocketTimeoutException("the request did not finish within $timeoutMs ms")
24
+
25
+ private class Done<T>(val value: T)
26
+
27
+ /**
28
+ * Runs the blocking [block] (one HTTP exchange) and stops waiting for it after [timeoutMs], whatever it is doing.
29
+ *
30
+ * Why not `withTimeout { withContext(Dispatchers.IO) { block() } }`: `withContext` waits for its block, and blocking
31
+ * socket code cannot be cancelled, so the caller would stay stuck behind a slow or trickling server. Instead the block
32
+ * runs in its own coroutine in [scope], which the caller does not wait for once it gives up. [scope] must have a
33
+ * `SupervisorJob` and a dispatcher that allows blocking calls (`Dispatchers.IO`).
34
+ *
35
+ * When the caller gives up (deadline passed, or the caller was cancelled) it also calls [abandon] on another thread,
36
+ * so the exchange can close its socket and free the thread. [abandon] is best effort: the caller is already released.
37
+ *
38
+ * Throws:
39
+ * - [RequestTimeoutException] when the block did not finish within [timeoutMs].
40
+ * - Whatever the block threw, unchanged, when it failed in time.
41
+ * - A [CancellationException] when the caller itself was cancelled.
42
+ */
43
+ internal suspend fun <T> callWithinDeadline(
44
+ scope: CoroutineScope,
45
+ timeoutMs: Long,
46
+ abandon: () -> Unit,
47
+ block: () -> T,
48
+ ): T {
49
+ val call = scope.async { block() }
50
+ // Done(...) so a legitimate null result is told apart from withTimeoutOrNull's null on timeout.
51
+ val done = try {
52
+ withTimeoutOrNull(timeoutMs) { Done(call.await()) }
53
+ } catch (e: CancellationException) {
54
+ // Only the caller can cancel here (the block never cancels itself, and nothing else cancels `call`).
55
+ giveUp(scope, call, abandon)
56
+ throw e
57
+ }
58
+ if (done == null) {
59
+ giveUp(scope, call, abandon)
60
+ throw RequestTimeoutException(timeoutMs)
61
+ }
62
+ return done.value
63
+ }
64
+
65
+ private fun giveUp(scope: CoroutineScope, call: Deferred<*>, abandon: () -> Unit) {
66
+ call.cancel()
67
+ // Off the caller's thread: closing a socket that another thread is reading may itself block on some JVMs.
68
+ scope.launch {
69
+ try {
70
+ abandon()
71
+ } catch (_: Throwable) {
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,45 @@
1
+ package org.fountis.connect
2
+
3
+ import android.content.Context
4
+ import java.util.Locale
5
+ import org.json.JSONObject
6
+
7
+ /** Reads the shared i18n JSON (the same files the engine uses, copied into assets) for the few host-side strings. */
8
+ internal object Strings {
9
+ private const val DIR = "fountis-connect/i18n"
10
+ private val cache = HashMap<String, Map<String, String>>()
11
+
12
+ @Synchronized
13
+ private fun table(context: Context, lang: String): Map<String, String> {
14
+ cache[lang]?.let { return it }
15
+ val t = HashMap<String, String>()
16
+ try {
17
+ val text = context.applicationContext.assets.open("$DIR/$lang.json").bufferedReader(Charsets.UTF_8).use { it.readText() }
18
+ val o = JSONObject(text)
19
+ for (k in o.keys()) (o.opt(k) as? String)?.let { t[k] = it }
20
+ } catch (_: Exception) {
21
+ }
22
+ cache[lang] = t
23
+ return t
24
+ }
25
+
26
+ fun get(context: Context, key: String, lang: String, vars: Map<String, String> = emptyMap()): String {
27
+ var s = table(context, lang)[key] ?: table(context, "en")[key] ?: key
28
+ for ((k, v) in vars) s = s.replace("{$k}", v)
29
+ return s
30
+ }
31
+
32
+ fun normalize(lang: String?): String {
33
+ val l = lang?.lowercase(Locale.ROOT) ?: return "en"
34
+ val two = when {
35
+ l.startsWith("kmr") -> "kmr"
36
+ l.startsWith("ckb") -> "ku"
37
+ else -> l.take(2)
38
+ }
39
+ return if (two in setOf("en", "ku", "kmr", "ar")) two else "en"
40
+ }
41
+
42
+ fun isRtl(lang: String): Boolean = lang in setOf("ku", "kmr", "ar")
43
+
44
+ fun deviceLang(): String = normalize(Locale.getDefault().toLanguageTag())
45
+ }
@@ -0,0 +1,72 @@
1
+ package org.fountis.connect
2
+
3
+ import kotlinx.coroutines.CancellationException
4
+ import kotlinx.coroutines.CoroutineScope
5
+ import kotlinx.coroutines.Dispatchers
6
+ import kotlinx.coroutines.async
7
+ import kotlinx.coroutines.currentCoroutineContext
8
+ import kotlinx.coroutines.ensureActive
9
+ import kotlinx.coroutines.withTimeoutOrNull
10
+
11
+ /** How long the host's token provider may take to answer. The React Native and Flutter wrappers use the same 10 s. */
12
+ internal const val TOKEN_PROVIDER_TIMEOUT_MS: Long = 10_000L
13
+
14
+ /**
15
+ * The token provider did not answer in time. A plain [Exception] on purpose, never a [CancellationException]: the SDK
16
+ * rethrows cancellation into the host's coroutine, and a slow provider must not look like the host being cancelled.
17
+ */
18
+ internal class TokenProviderTimeoutException : Exception("the token provider did not answer in time")
19
+
20
+ /**
21
+ * The token provider ended by cancelling itself (for example its own `withTimeout` fired and threw a
22
+ * `TimeoutCancellationException`) while the caller was still active. A plain failure, never a [CancellationException].
23
+ */
24
+ internal class TokenProviderFailedException(cause: Throwable) : Exception("the token provider was cancelled", cause)
25
+
26
+ private class Answer(val token: String?)
27
+
28
+ /**
29
+ * Asks the host's token provider for the signed user token, giving up after [timeoutMs].
30
+ *
31
+ * Why not `withTimeout { withContext(Dispatchers.IO) { provider() } }`: `withContext` waits for its block, and a
32
+ * blocking Java provider (or a suspension that ignores cancellation) cannot be cancelled, so the call would still
33
+ * hang and keep `Core.presenting` set for the rest of the process, turning every later run into `NoFill`. And
34
+ * `withTimeout` throws `TimeoutCancellationException`, a [CancellationException] the SDK would then rethrow into the
35
+ * host's coroutine.
36
+ *
37
+ * Instead the provider runs in its own coroutine in [scope] (which must have a `SupervisorJob`, so a failing provider
38
+ * stays in the `Deferred` and cannot cancel the scope). That coroutine is not a child of the caller, so the caller can
39
+ * stop waiting even if the provider never cooperates. The provider is cancelled when we give up, which only helps a
40
+ * cooperative one; a blocking one keeps its thread until it returns, but nothing waits for it any more.
41
+ *
42
+ * Returns the token, or `null` when the provider answered `null` (nobody is signed in).
43
+ *
44
+ * Throws:
45
+ * - [TokenProviderTimeoutException] when there was no answer within [timeoutMs]. That is a failure, never "signed
46
+ * out": the caller must show nothing and must not take the guest path.
47
+ * - [TokenProviderFailedException] when the provider threw a [CancellationException] of its own.
48
+ * - Whatever else the provider threw, unchanged.
49
+ * - A [CancellationException] only when the caller itself was cancelled, so cancellation propagates as usual.
50
+ */
51
+ internal suspend fun callTokenProvider(
52
+ scope: CoroutineScope,
53
+ timeoutMs: Long = TOKEN_PROVIDER_TIMEOUT_MS,
54
+ provider: suspend () -> String?,
55
+ ): String? {
56
+ val call = scope.async(Dispatchers.IO) { provider() }
57
+ // Answer(...) so a legitimate null answer is told apart from withTimeoutOrNull's null on timeout.
58
+ val answer = try {
59
+ withTimeoutOrNull(timeoutMs) { Answer(call.await()) }
60
+ } catch (e: CancellationException) {
61
+ call.cancel()
62
+ // The caller was cancelled: rethrow, and cancellation propagates as before.
63
+ currentCoroutineContext().ensureActive()
64
+ // Otherwise it was the provider (or the scope) that cancelled: an ordinary failure for the SDK.
65
+ throw TokenProviderFailedException(e)
66
+ }
67
+ if (answer == null) {
68
+ call.cancel()
69
+ throw TokenProviderTimeoutException()
70
+ }
71
+ return answer.token
72
+ }
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <vector xmlns:android="http://schemas.android.com/apk/res/android"
3
+ android:width="24dp"
4
+ android:height="24dp"
5
+ android:viewportWidth="24"
6
+ android:viewportHeight="24">
7
+ <!-- A ring with a dot: simple, monochrome, readable at 24dp. -->
8
+ <path
9
+ android:fillColor="#FFFFFFFF"
10
+ android:fillType="evenOdd"
11
+ android:pathData="M12,3a9,9 0,1 0,0 18a9,9 0,1 0,0 -18zM12,6a6,6 0,1 1,0 12a6,6 0,1 1,0 -12zM12,9.5a2.5,2.5 0,1 0,0 5a2.5,2.5 0,1 0,0 -5z" />
12
+ </vector>
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <resources>
3
+ <color name="fountis_page">#F2F5F4</color>
4
+
5
+ <!-- Full screen, edge to edge, no action bar. -->
6
+ <style name="FountisConnect.Survey" parent="@android:style/Theme.Material.Light.NoActionBar">
7
+ <item name="android:windowBackground">@color/fountis_page</item>
8
+ <item name="android:statusBarColor">@android:color/transparent</item>
9
+ <item name="android:navigationBarColor">@android:color/transparent</item>
10
+ <item name="android:windowDrawsSystemBarBackgrounds">true</item>
11
+ <item name="android:windowLightStatusBar">true</item>
12
+ </style>
13
+ </resources>
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <resources>
3
+ <style name="FountisConnect.Survey" parent="@android:style/Theme.Material.Light.NoActionBar">
4
+ <item name="android:windowBackground">@color/fountis_page</item>
5
+ <item name="android:statusBarColor">@android:color/transparent</item>
6
+ <item name="android:navigationBarColor">@android:color/transparent</item>
7
+ <item name="android:windowDrawsSystemBarBackgrounds">true</item>
8
+ <item name="android:windowLightStatusBar">true</item>
9
+ <item name="android:windowLightNavigationBar">true</item>
10
+ <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
11
+ </style>
12
+ </resources>
@@ -0,0 +1,18 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <uses-permission android:name="android.permission.INTERNET" />
4
+ <!-- Only asked at runtime (Android 13+) when the app calls enableNotifications(). -->
5
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
6
+
7
+ <application>
8
+ <!-- The full-screen FOUNTIS survey. Not exported; opened only by the SDK. -->
9
+ <activity
10
+ android:name="org.fountis.connect.FountisSurveyActivity"
11
+ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|uiMode|density|layoutDirection|locale|fontScale"
12
+ android:enableOnBackInvokedCallback="true"
13
+ android:exported="false"
14
+ android:launchMode="singleTop"
15
+ android:theme="@style/FountisConnect.Survey"
16
+ android:windowSoftInputMode="adjustResize" />
17
+ </application>
18
+ </manifest>