@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,128 @@
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(val appName: String?, val config: SurveysConfig?, val surveys: List<Offer>, val guests: Boolean = false)
72
+
73
+ // ---- JSON helpers ----
74
+
75
+ /** Converts org.json values into plain Kotlin values (Map, List, String, Number, Boolean, null). */
76
+ internal fun jsonToKotlin(v: Any?): Any? = when (v) {
77
+ null, JSONObject.NULL -> null
78
+ is JSONObject -> v.keys().asSequence().associateWith { jsonToKotlin(v.opt(it)) }
79
+ is JSONArray -> (0 until v.length()).map { jsonToKotlin(v.opt(it)) }
80
+ else -> v
81
+ }
82
+
83
+ private fun JSONObject.optStringOrNull(name: String): String? =
84
+ if (has(name) && !isNull(name)) opt(name) as? String else null
85
+
86
+ private fun JSONObject.optIntOrNull(name: String): Int? =
87
+ if (has(name) && !isNull(name)) (opt(name) as? Number)?.toInt() else null
88
+
89
+ internal fun parseSurveys(text: String): SurveysResponse {
90
+ val root = JSONObject(text)
91
+ val cfg = root.optJSONObject("config")?.let { c ->
92
+ SurveysConfig(
93
+ maxNotificationsPerDay = c.optIntOrNull("max_notifications_per_day"),
94
+ quietHours = c.optJSONArray("quiet_hours")?.let { a -> (0 until a.length()).map { a.optInt(it) } },
95
+ checkIntervalMinutes = c.optIntOrNull("check_interval_minutes"),
96
+ )
97
+ }
98
+ val list = root.optJSONArray("surveys") ?: JSONArray()
99
+ val offers = ArrayList<Offer>()
100
+ for (i in 0 until list.length()) {
101
+ val o = list.optJSONObject(i) ?: continue
102
+ val id = o.optStringOrNull("offer_id") ?: continue
103
+ val conds = ArrayList<Condition>()
104
+ o.optJSONObject("conditions")?.optJSONArray("all")?.let { all ->
105
+ for (j in 0 until all.length()) {
106
+ val c = all.optJSONObject(j) ?: continue
107
+ conds.add(Condition(c.optString("attr"), c.optString("op"), jsonToKotlin(c.opt("value"))))
108
+ }
109
+ }
110
+ val attrs = o.optJSONArray("required_attrs")?.let { a -> (0 until a.length()).mapNotNull { a.optString(it).ifEmpty { null } } } ?: emptyList()
111
+ val reward = o.optJSONObject("reward")?.let { r ->
112
+ OfferReward(r.optString("mode"), r.optIntOrNull("units"), jsonToKotlin(r.opt("unit_name")))
113
+ }
114
+ offers.add(Offer(id, conds, attrs, o.optIntOrNull("loi_minutes"), reward, o.optStringOrNull("expires_at"), o.optBoolean("guest", false)))
115
+ }
116
+ val app = root.optJSONObject("app")
117
+ return SurveysResponse(app?.optStringOrNull("name"), cfg, offers, app?.optBoolean("guests", false) ?: false)
118
+ }
119
+
120
+ internal const val TAG = "FountisConnect"
121
+
122
+ internal fun logd(message: String) {
123
+ try {
124
+ android.util.Log.d(TAG, message)
125
+ } catch (_: Throwable) {
126
+ // plain JVM unit tests have no android.util.Log
127
+ }
128
+ }
@@ -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,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>
@@ -0,0 +1,113 @@
1
+ package org.fountis.connect.rn
2
+
3
+ import expo.modules.kotlin.Promise
4
+ import expo.modules.kotlin.modules.Module
5
+ import expo.modules.kotlin.modules.ModuleDefinition
6
+ import java.util.UUID
7
+ import java.util.concurrent.ConcurrentHashMap
8
+ import kotlinx.coroutines.CompletableDeferred
9
+ import kotlinx.coroutines.withTimeoutOrNull
10
+ import org.fountis.connect.FountisConnect
11
+ import org.fountis.connect.FountisEvent
12
+ import org.fountis.connect.FountisEventListener
13
+ import org.fountis.connect.FountisResult
14
+
15
+ /** JS bridge for the FOUNTIS Connect Android SDK. */
16
+ class FountisConnectModule : Module() {
17
+ private val tokenRequests = ConcurrentHashMap<String, CompletableDeferred<String?>>()
18
+ private val eventListener = FountisEventListener { e: FountisEvent ->
19
+ val body = mutableMapOf<String, Any?>("type" to e.type)
20
+ e.offerId?.let { body["offerId"] = it }
21
+ sendEvent("onFountisEvent", body)
22
+ }
23
+
24
+ override fun definition() = ModuleDefinition {
25
+ Name("FountisConnect")
26
+
27
+ Events("onFountisEvent", "onTokenRequest")
28
+
29
+ OnCreate {
30
+ FountisConnect.onEvent(eventListener)
31
+ // Optional: the config plugin can write the key into the manifest so the SDK starts with the app.
32
+ val ctx = appContext.reactContext ?: return@OnCreate
33
+ try {
34
+ val meta = ctx.packageManager
35
+ .getApplicationInfo(ctx.packageName, android.content.pm.PackageManager.GET_META_DATA).metaData
36
+ val key = meta?.getString("org.fountis.connect.KEY")
37
+ if (!key.isNullOrEmpty()) FountisConnect.start(ctx, key, meta?.getString("org.fountis.connect.API_BASE"))
38
+ } catch (_: Throwable) {
39
+ }
40
+ }
41
+
42
+ Function("start") { key: String, apiBase: String? ->
43
+ appContext.reactContext?.let { FountisConnect.start(it, key, apiBase) }
44
+ Unit
45
+ }
46
+
47
+ // JS owns the token function. The SDK asks for a token; we ask JS with an event and wait for resolveToken.
48
+ Function("setTokenProviderEnabled") { enabled: Boolean ->
49
+ if (enabled) {
50
+ FountisConnect.setUserToken {
51
+ val id = UUID.randomUUID().toString()
52
+ val d = CompletableDeferred<String?>()
53
+ tokenRequests[id] = d
54
+ try {
55
+ sendEvent("onTokenRequest", mapOf("id" to id))
56
+ // JS may not be running (a background check): give up after 10 s. That is a failure, not "signed out":
57
+ // an answer of null (nobody signed in) is wrapped so it cannot be mistaken for the timeout.
58
+ val answer = withTimeoutOrNull(10_000) { TokenAnswer(d.await()) }
59
+ ?: throw TokenUnavailableException("token provider timed out")
60
+ answer.token
61
+ } finally {
62
+ tokenRequests.remove(id)
63
+ }
64
+ }
65
+ }
66
+ }
67
+
68
+ Function("resolveToken") { id: String, token: String? ->
69
+ tokenRequests.remove(id)?.complete(token)
70
+ Unit
71
+ }
72
+
73
+ // The JS token function threw or rejected: the SDK gets an exception (noFill), not null (nobody is signed in).
74
+ Function("rejectToken") { id: String ->
75
+ tokenRequests.remove(id)?.completeExceptionally(TokenUnavailableException("token provider failed"))
76
+ Unit
77
+ }
78
+
79
+ Function("enableNotifications") {
80
+ appContext.currentActivity?.let { FountisConnect.enableNotifications(it) }
81
+ Unit
82
+ }
83
+
84
+ Function("setUserConsent") { granted: Boolean -> FountisConnect.setUserConsent(granted) }
85
+
86
+ Function("signOut") { FountisConnect.signOut() }
87
+
88
+ AsyncFunction("show") { promise: Promise ->
89
+ val activity = appContext.currentActivity
90
+ if (activity == null) {
91
+ promise.resolve("noFill")
92
+ } else {
93
+ FountisConnect.show(activity) { r: FountisResult ->
94
+ promise.resolve(
95
+ when (r) {
96
+ FountisResult.Completed -> "completed"
97
+ FountisResult.Dismissed -> "dismissed"
98
+ FountisResult.NoFill -> "noFill"
99
+ },
100
+ )
101
+ }
102
+ }
103
+ }
104
+
105
+ AsyncFunction("handlePush") { data: Map<String, String> -> FountisConnect.handlePush(data) }
106
+ }
107
+ }
108
+
109
+ /** Holds the token (null = nobody signed in) so a real answer of null differs from the timeout, which is also null. */
110
+ private class TokenAnswer(val token: String?)
111
+
112
+ /** The token could not be fetched. Not a CancellationException: the SDK rethrows those to the host app. */
113
+ private class TokenUnavailableException(message: String) : Exception(message)
package/app.plugin.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Expo config plugin for @fountispanel/connect-react-native.
3
+ *
4
+ * plugins: [["@fountispanel/connect-react-native", { key: "pk_test_..." }]]
5
+ *
6
+ * iOS: adds the `fetch` background mode and the background refresh task id to Info.plist.
7
+ * Android: nothing else is needed (permissions and the survey screen come with the library).
8
+ * `key` / `apiBase` are optional. With a key the SDK starts while the app launches, which iOS
9
+ * requires for background refresh. Without it, call start() from JS (background refresh stays off).
10
+ * The key is a publishable key (pk_...), safe to ship in the app.
11
+ */
12
+ const { withInfoPlist, withAndroidManifest, AndroidConfig, createRunOncePlugin } = require('expo/config-plugins');
13
+
14
+ const TASK_ID = 'org.fountis.connect.refresh';
15
+
16
+ function withFountisConnect(config, options = {}) {
17
+ config = withInfoPlist(config, (c) => {
18
+ const plist = c.modResults;
19
+ const modes = new Set(plist.UIBackgroundModes ?? []);
20
+ modes.add('fetch');
21
+ plist.UIBackgroundModes = [...modes];
22
+ const ids = new Set(plist.BGTaskSchedulerPermittedIdentifiers ?? []);
23
+ ids.add(TASK_ID);
24
+ plist.BGTaskSchedulerPermittedIdentifiers = [...ids];
25
+ if (options.key) plist.FountisConnectKey = options.key;
26
+ if (options.apiBase) plist.FountisConnectApiBase = options.apiBase;
27
+ return c;
28
+ });
29
+
30
+ config = withAndroidManifest(config, (c) => {
31
+ const app = AndroidConfig.Manifest.getMainApplicationOrThrow(c.modResults);
32
+ if (options.key) AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, 'org.fountis.connect.KEY', options.key);
33
+ if (options.apiBase) AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, 'org.fountis.connect.API_BASE', options.apiBase);
34
+ return c;
35
+ });
36
+
37
+ return config;
38
+ }
39
+
40
+ const pkg = require('./package.json');
41
+ module.exports = createRunOncePlugin(withFountisConnect, pkg.name, pkg.version);