@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,321 +0,0 @@
1
- package org.fountis.connect
2
-
3
- import android.app.Activity
4
- import android.graphics.Color
5
- import android.os.Build
6
- import android.os.Bundle
7
- import android.view.View
8
- import android.view.ViewGroup
9
- import android.view.WindowManager
10
- import android.webkit.RenderProcessGoneDetail
11
- import android.webkit.WebResourceRequest
12
- import android.webkit.WebResourceResponse
13
- import android.webkit.WebSettings
14
- import android.webkit.WebView
15
- import android.webkit.WebViewClient
16
- import android.widget.FrameLayout
17
- import androidx.core.view.ViewCompat
18
- import androidx.core.view.WindowCompat
19
- import androidx.core.view.WindowInsetsCompat
20
- import androidx.webkit.WebMessageCompat
21
- import androidx.webkit.WebViewAssetLoader
22
- import androidx.webkit.WebViewCompat
23
- import androidx.webkit.WebViewFeature
24
- import kotlinx.coroutines.CoroutineScope
25
- import kotlinx.coroutines.Dispatchers
26
- import kotlinx.coroutines.SupervisorJob
27
- import kotlinx.coroutines.cancel
28
- import kotlinx.coroutines.launch
29
- import org.json.JSONObject
30
-
31
- /** How a study screen ended. */
32
- internal class Finish(
33
- /** "complete", "screen_out", "quota_full", or null when closed before the end. */
34
- val outcome: String?,
35
- /** A fatal API code (not_eligible, closed, ...) was shown. */
36
- val fatal: String?,
37
- /** The WebView could not be created; nothing was shown. */
38
- val unavailable: Boolean = false,
39
- )
40
-
41
- /** What the SDK hands to the activity (the activity cannot receive these through an Intent). */
42
- internal class SurveyPending(
43
- val initJson: String,
44
- val api: ApiClient,
45
- val attemptToken: String,
46
- val onFinish: (Finish) -> Unit,
47
- ) {
48
- /** The activity started (stops the SDK's start-up timeout). */
49
- @Volatile var attached = false
50
-
51
- /** The WebView exists and the study is on screen. */
52
- @Volatile var onShown: (() -> Unit)? = null
53
- }
54
-
55
- internal object SurveyHost {
56
- @Volatile var pending: SurveyPending? = null
57
- }
58
-
59
- internal object WebViewSupport {
60
- /**
61
- * The survey screens are built for Chromium 88 (January 2021): flex gap (84), aspect-ratio and :is/:where (88).
62
- * On Chromium 83 (the WebView on a stock API 30 emulator) the screens load but lose all their spacing, so an older
63
- * WebView gets a quiet noFill instead of a broken survey. Phones update WebView through Google Play.
64
- */
65
- private const val ORIGIN_MIN_CHROMIUM = 88
66
-
67
- /** WebView present, new enough (Chromium 88+) and able to do `addWebMessageListener`. */
68
- fun isSupported(context: android.content.Context): Boolean = try {
69
- val pkg = WebViewCompat.getCurrentWebViewPackage(context)
70
- val major = pkg?.versionName?.substringBefore('.')?.toIntOrNull()
71
- (major == null || major >= ORIGIN_MIN_CHROMIUM) &&
72
- WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
73
- } catch (t: Throwable) {
74
- logd("webview check failed: $t")
75
- false
76
- }
77
- }
78
-
79
- /**
80
- * The full-screen FOUNTIS study. Hosts the bundled survey engine in a locked-down WebView
81
- * (served from assets over `https://appassets.androidplatform.net`, no file or content access, every other
82
- * navigation blocked) and relays the engine's messages to the API; the engine itself never touches the network
83
- * in native mode. Opened only by the SDK.
84
- */
85
- public class FountisSurveyActivity : Activity() {
86
- private companion object {
87
- const val ORIGIN = "https://appassets.androidplatform.net"
88
- const val ENGINE_URL = "$ORIGIN/assets/fountis-connect/engine.html"
89
- val PAGE_COLOR = Color.parseColor("#F2F5F4")
90
- }
91
-
92
- private var pending: SurveyPending? = null
93
- private var webView: WebView? = null
94
- private var scope: CoroutineScope? = null
95
- private val inFlight = HashSet<String>()
96
- private var outcome: String? = null
97
- private var fatal: String? = null
98
- private var finished = false
99
-
100
- override fun onCreate(savedInstanceState: Bundle?) {
101
- super.onCreate(savedInstanceState)
102
- // The survey is hidden from screenshots, recents and screen sharing. Only a debuggable host app (never a
103
- // release build) may be captured, so CI can screenshot the sample on an emulator.
104
- val debuggable = (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) != 0
105
- if (!debuggable) window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
106
- val p = SurveyHost.pending
107
- SurveyHost.pending = null
108
- if (p == null) { // process was recreated: nothing to show
109
- finish()
110
- return
111
- }
112
- pending = p
113
- p.attached = true
114
- scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
115
-
116
- WindowCompat.setDecorFitsSystemWindows(window, false)
117
- val root = FrameLayout(this)
118
- root.setBackgroundColor(PAGE_COLOR)
119
- ViewCompat.setOnApplyWindowInsetsListener(root) { v, insets ->
120
- val b = insets.getInsets(
121
- WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout() or WindowInsetsCompat.Type.ime(),
122
- )
123
- v.setPadding(b.left, b.top, b.right, b.bottom)
124
- WindowInsetsCompat.CONSUMED
125
- }
126
- val wv = try {
127
- createWebView()
128
- } catch (t: Throwable) {
129
- logd("WebView unavailable: $t")
130
- finishWith(Finish(null, null, unavailable = true))
131
- return
132
- }
133
- webView = wv
134
- root.addView(wv, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
135
- setContentView(root)
136
- p.onShown?.invoke()
137
- WindowCompat.getInsetsController(window, root).apply {
138
- isAppearanceLightStatusBars = true
139
- isAppearanceLightNavigationBars = true
140
- }
141
- if (Build.VERSION.SDK_INT >= 33) {
142
- onBackInvokedDispatcher.registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT) { close() }
143
- }
144
- wv.loadUrl(ENGINE_URL)
145
- }
146
-
147
- @Deprecated("Deprecated in Java")
148
- override fun onBackPressed() {
149
- close() // back equals close
150
- }
151
-
152
- override fun onDestroy() {
153
- webView?.let {
154
- (it.parent as? ViewGroup)?.removeView(it)
155
- it.stopLoading()
156
- it.destroy()
157
- }
158
- webView = null
159
- scope?.cancel()
160
- finishWith(Finish(outcome, fatal)) // no-op when already finished
161
- super.onDestroy()
162
- }
163
-
164
- // ---- web view ----
165
-
166
- private fun createWebView(): WebView {
167
- val wv = WebView(this)
168
- wv.setBackgroundColor(PAGE_COLOR)
169
- wv.overScrollMode = View.OVER_SCROLL_NEVER
170
- val s = wv.settings
171
- s.javaScriptEnabled = true
172
- s.domStorageEnabled = false
173
- s.allowFileAccess = false
174
- s.allowContentAccess = false
175
- s.javaScriptCanOpenWindowsAutomatically = false
176
- s.setSupportMultipleWindows(false)
177
- s.setSupportZoom(false)
178
- s.builtInZoomControls = false
179
- s.mediaPlaybackRequiresUserGesture = true
180
- s.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
181
- s.setGeolocationEnabled(false)
182
-
183
- val loader = WebViewAssetLoader.Builder()
184
- .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
185
- .build()
186
- wv.webViewClient = object : WebViewClient() {
187
- override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
188
- loader.shouldInterceptRequest(request.url)
189
-
190
- // The engine is loaded with loadUrl(); every navigation it asks for after that is refused.
191
- override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = true
192
-
193
- override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
194
- logd("web content process gone")
195
- close()
196
- return true
197
- }
198
- }
199
- // Never addJavascriptInterface: the bridge is a web message listener limited to the asset-loader origin.
200
- WebViewCompat.addWebMessageListener(wv, "FountisBridge", setOf(ORIGIN)) { _, message, sourceOrigin, isMainFrame, _ ->
201
- if (isMainFrame && sourceOrigin.toString() == ORIGIN) onEngineMessage(message)
202
- }
203
- return wv
204
- }
205
-
206
- // ---- engine messages (same flow as the iOS SheetController) ----
207
-
208
- private fun onEngineMessage(message: WebMessageCompat) {
209
- try {
210
- val body = JSONObject(message.data ?: return)
211
- when (body.optString("type")) {
212
- "ready" -> send("window.FountisEngine && window.FountisEngine.init(${safeJs(pending?.initJson ?: "{}")})")
213
- "answer" -> {
214
- val code = body.optString("code", "")
215
- if (code.isNotEmpty()) handleAnswer(code, body.opt("value"))
216
- }
217
- "consent" -> handleConsent()
218
- "complete" -> handleComplete()
219
- "done" -> body.optString("outcome", "").takeIf { it.isNotEmpty() }?.let { outcome = it }
220
- "close" -> close()
221
- else -> Unit // progress, height: nothing to do on the host
222
- }
223
- } catch (t: Throwable) {
224
- logd("bad engine message: $t")
225
- }
226
- }
227
-
228
- /** JSON is valid JS except for U+2028/U+2029 inside strings on older engines. */
229
- private fun safeJs(json: String): String = json.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
230
-
231
- private fun send(js: String) {
232
- try {
233
- webView?.evaluateJavascript(js, null)
234
- } catch (t: Throwable) {
235
- logd("evaluateJavascript failed: $t")
236
- }
237
- }
238
-
239
- private fun reply(obj: JSONObject) = send("window.FountisEngine && window.FountisEngine.receive(${safeJs(obj.toString())})")
240
-
241
- private fun fail(error: Throwable) {
242
- if (error is ApiError) {
243
- if (error.isFatal) fatal = error.code
244
- reply(JSONObject().put("type", "error").put("message", error.message).put("code", error.code))
245
- } else {
246
- reply(JSONObject().put("type", "error").put("message", "network"))
247
- }
248
- }
249
-
250
- /** Runs [work] unless the same request is already in flight (the engine re-sends every 5 s). */
251
- private fun once(key: String, work: suspend () -> Unit) {
252
- if (!inFlight.add(key)) return
253
- scope?.launch {
254
- try {
255
- work()
256
- } catch (e: kotlinx.coroutines.CancellationException) {
257
- throw e
258
- } catch (t: Throwable) {
259
- fail(t)
260
- } finally {
261
- inFlight.remove(key)
262
- }
263
- } ?: inFlight.remove(key)
264
- }
265
-
266
- private fun jsonValue(v: Any?): Any? = when (v) {
267
- null -> JSONObject.NULL
268
- else -> v
269
- }
270
-
271
- private fun handleAnswer(code: String, value: Any?) {
272
- val p = pending ?: return
273
- val sig = "a:$code:" + jsonValue(value).toString()
274
- once(sig) {
275
- val r = p.api.putAnswer(code, jsonValue(value), p.attemptToken)
276
- reply(JSONObject().put("type", "ack").put("code", code).put("stop", r.opt("stop") ?: JSONObject.NULL))
277
- }
278
- }
279
-
280
- private fun handleConsent() {
281
- val p = pending ?: return
282
- once("consent") {
283
- p.api.consent(p.attemptToken)
284
- reply(JSONObject().put("type", "ack").put("code", "consent").put("stop", JSONObject.NULL))
285
- }
286
- }
287
-
288
- private fun handleComplete() {
289
- val p = pending ?: return
290
- once("complete") {
291
- val r = p.api.complete(p.attemptToken)
292
- val o = r.optString("outcome", "complete")
293
- outcome = o
294
- reply(JSONObject().put("type", "result").put("outcome", o).put("reward", r.opt("reward") ?: JSONObject.NULL))
295
- }
296
- }
297
-
298
- // ---- finishing ----
299
-
300
- private fun close() {
301
- finishWith(Finish(outcome, fatal))
302
- if (!isFinishing) finish()
303
- }
304
-
305
- private fun finishWith(f: Finish) {
306
- if (finished) return
307
- finished = true
308
- val p = pending
309
- pending = null
310
- if (p == null) {
311
- finish()
312
- return
313
- }
314
- try {
315
- p.onFinish(f)
316
- } catch (t: Throwable) {
317
- logd("finish callback failed: $t")
318
- }
319
- if (!isFinishing) finish()
320
- }
321
- }
@@ -1,143 +0,0 @@
1
- package org.fountis.connect
2
-
3
- import android.content.Context
4
- import java.io.File
5
- import java.util.Calendar
6
- import java.util.GregorianCalendar
7
- import org.json.JSONArray
8
- import org.json.JSONObject
9
-
10
- /**
11
- * One small JSON file in `noBackupFilesDir`: Android never copies that directory to cloud backup or to a new device,
12
- * so no backup rules are needed in the host app. Holds the notifications switch and, per person (keyed by
13
- * sha256(sub)), the offers already notified / dismissed / taken and the daily notification count. Never sent anywhere.
14
- */
15
- internal class StateStore(context: Context) {
16
- private val file = File(context.applicationContext.noBackupFilesDir, "org.fountis.connect.state.json")
17
- private var root: JSONObject? = null
18
-
19
- @Synchronized
20
- private fun load(): JSONObject {
21
- root?.let { return it }
22
- val r = try {
23
- JSONObject(file.readText(Charsets.UTF_8))
24
- } catch (_: Exception) {
25
- JSONObject()
26
- }
27
- root = r
28
- return r
29
- }
30
-
31
- @Synchronized
32
- private fun save() {
33
- try {
34
- val tmp = File(file.parentFile, file.name + ".tmp")
35
- tmp.writeText(load().toString(), Charsets.UTF_8)
36
- if (!tmp.renameTo(file)) {
37
- file.delete()
38
- tmp.renameTo(file)
39
- }
40
- } catch (e: Exception) {
41
- android.util.Log.d(TAG, "state not saved: $e")
42
- }
43
- }
44
-
45
- @Synchronized
46
- fun getBoolean(name: String): Boolean = load().optBoolean(name, false)
47
-
48
- @Synchronized
49
- fun setBoolean(name: String, v: Boolean) {
50
- load().put(name, v)
51
- save()
52
- }
53
-
54
- /**
55
- * The guest install id: 24 random bytes made on first use, kept here (never backed up, never a device identifier).
56
- * FOUNTIS stores only a hash of it.
57
- */
58
- @Synchronized
59
- fun installId(): String {
60
- val have = load().optString("guest.install_id", "")
61
- if (have.length >= 22) return have
62
- val bytes = ByteArray(24).also { java.security.SecureRandom().nextBytes(it) }
63
- val id = android.util.Base64.encodeToString(bytes, android.util.Base64.URL_SAFE or android.util.Base64.NO_PADDING or android.util.Base64.NO_WRAP)
64
- load().put("guest.install_id", id)
65
- save()
66
- return id
67
- }
68
-
69
- @Synchronized
70
- fun person(key: String): JSONObject = load().optJSONObject(key) ?: JSONObject()
71
-
72
- @Synchronized
73
- fun putPerson(key: String, v: JSONObject) {
74
- load().put(key, v)
75
- save()
76
- }
77
-
78
- @Synchronized
79
- fun remove(key: String) {
80
- load().remove(key)
81
- save()
82
- }
83
- }
84
-
85
- internal class LocalState(private val store: StateStore, subHash: String) {
86
- private val key = "s.$subHash"
87
-
88
- private fun list(o: JSONObject, name: String): MutableList<String> {
89
- val a = o.optJSONArray(name) ?: return mutableListOf()
90
- return (0 until a.length()).map { a.optString(it) }.toMutableList()
91
- }
92
-
93
- private fun today(): String {
94
- val c = GregorianCalendar()
95
- return "${c.get(Calendar.YEAR)}-${c.get(Calendar.MONTH) + 1}-${c.get(Calendar.DAY_OF_MONTH)}"
96
- }
97
-
98
- private fun add(id: String, name: String) {
99
- val o = store.person(key)
100
- val l = list(o, name)
101
- if (!l.contains(id)) l.add(id)
102
- while (l.size > 200) l.removeAt(0)
103
- o.put(name, JSONArray(l))
104
- store.putPerson(key, o)
105
- }
106
-
107
- fun markNotified(id: String) {
108
- add(id, "notified")
109
- val o = store.person(key)
110
- if (o.optString("day") != today()) {
111
- o.put("day", today())
112
- o.put("dayCount", 0)
113
- }
114
- o.put("dayCount", o.optInt("dayCount", 0) + 1)
115
- store.putPerson(key, o)
116
- }
117
-
118
- fun markDismissed(id: String) = add(id, "dismissed")
119
- fun markTaken(id: String) = add(id, "taken")
120
-
121
- val notificationsToday: Int
122
- get() {
123
- val o = store.person(key)
124
- return if (o.optString("day") == today()) o.optInt("dayCount", 0) else 0
125
- }
126
-
127
- /** For the explicit `show()`: only studies already finished are excluded. */
128
- fun isTaken(id: String): Boolean = list(store.person(key), "taken").contains(id)
129
-
130
- /** For notifications: anything the person has already seen, closed or finished. */
131
- fun isSuppressedForNotification(id: String): Boolean {
132
- val o = store.person(key)
133
- return list(o, "taken").contains(id) || list(o, "dismissed").contains(id) || list(o, "notified").contains(id)
134
- }
135
-
136
- /** For auto-show: finished or closed. */
137
- fun isSuppressedForAutoShow(id: String): Boolean {
138
- val o = store.person(key)
139
- return list(o, "taken").contains(id) || list(o, "dismissed").contains(id)
140
- }
141
-
142
- fun clear() = store.remove(key)
143
- }
@@ -1,167 +0,0 @@
1
- package org.fountis.connect
2
-
3
- import java.security.MessageDigest
4
- import java.util.Calendar
5
- import java.util.GregorianCalendar
6
- import java.util.TimeZone
7
- import org.json.JSONObject
8
-
9
- /** The decoded (never verified) token payload. The server verifies everything on POST /attempts. */
10
- internal class TokenInfo(val sub: String, val attrs: Map<String, Any?>, val expSeconds: Double?) {
11
- val lang: String? get() = attrs["lang"] as? String
12
-
13
- /**
14
- * Every attribute the token carries, in a fixed order, for the consent screen. FOUNTIS stores all of them when the
15
- * study opens, not only the ones the study's conditions use (`requiredAttrs`).
16
- */
17
- val carriedAttrs: List<String>
18
- get() {
19
- val order = listOf("gender", "birth_year", "governorate", "city", "lang")
20
- fun rank(k: String): Int = order.indexOf(k).let { if (it < 0) order.size else it }
21
- return attrs.filterValues { it != null }.keys.sortedWith(compareBy<String>({ rank(it) }, { it }))
22
- }
23
-
24
- /** First 8 bytes of sha256(sub) as hex: the key for this person's local state. */
25
- val subHash: String
26
- get() = MessageDigest.getInstance("SHA-256").digest(sub.toByteArray(Charsets.UTF_8))
27
- .take(8).joinToString("") { "%02x".format(it) }
28
-
29
- companion object {
30
- fun decode(token: String): TokenInfo? = try {
31
- val parts = token.split(".")
32
- if (parts.size < 2) null else {
33
- val o = JSONObject(String(base64UrlDecode(parts[1]), Charsets.UTF_8))
34
- val sub = o.optString("sub", "")
35
- if (sub.isEmpty()) null else TokenInfo(
36
- sub,
37
- (jsonToKotlin(o.optJSONObject("attrs")) as? Map<*, *>)?.entries
38
- ?.associate { it.key.toString() to it.value } ?: emptyMap(),
39
- if (o.has("exp") && !o.isNull("exp")) (o.opt("exp") as? Number)?.toDouble() else null,
40
- )
41
- }
42
- } catch (_: Exception) {
43
- null
44
- }
45
-
46
- /** android.util.Base64 is not available in JVM unit tests and java.util.Base64 needs API 26, so decode by hand. */
47
- fun base64UrlDecode(s: String): ByteArray {
48
- val out = java.io.ByteArrayOutputStream()
49
- var buf = 0
50
- var bits = 0
51
- for (ch in s) {
52
- val v = when (ch) {
53
- in 'A'..'Z' -> ch - 'A'
54
- in 'a'..'z' -> ch - 'a' + 26
55
- in '0'..'9' -> ch - '0' + 52
56
- '-', '+' -> 62
57
- '_', '/' -> 63
58
- else -> continue // padding or whitespace
59
- }
60
- buf = (buf shl 6) or v
61
- bits += 6
62
- if (bits >= 8) {
63
- bits -= 8
64
- out.write((buf shr bits) and 0xFF)
65
- }
66
- }
67
- return out.toByteArray()
68
- }
69
- }
70
- }
71
-
72
- internal object Matcher {
73
- /** Offer is offerable to this person: required attributes present, not expired, every condition holds. */
74
- fun matches(offer: Offer, token: TokenInfo, nowMillis: Long = System.currentTimeMillis()): Boolean {
75
- offer.expiresAt?.let { s -> parseDate(s)?.let { if (it < nowMillis) return false } }
76
- for (a in offer.requiredAttrs) if (token.attrs[a] == null) return false
77
- for (c in offer.conditions) if (!holds(c, token.attrs, nowMillis)) return false
78
- return true
79
- }
80
-
81
- /** Offer is offerable to a guest: the server marked it guest-eligible and it has not expired. */
82
- fun matchesGuest(offer: Offer, nowMillis: Long = System.currentTimeMillis()): Boolean {
83
- if (!offer.guest) return false
84
- offer.expiresAt?.let { s -> parseDate(s)?.let { if (it < nowMillis) return false } }
85
- return true
86
- }
87
-
88
- private fun yearOf(nowMillis: Long): Int =
89
- GregorianCalendar().apply { timeInMillis = nowMillis }.get(Calendar.YEAR)
90
-
91
- fun attrValue(name: String, attrs: Map<String, Any?>, nowMillis: Long): Any? {
92
- if (name == "age") {
93
- val by = (attrs["birth_year"] as? Number)?.toInt() ?: return null
94
- return yearOf(nowMillis) - by
95
- }
96
- return attrs[name]
97
- }
98
-
99
- private fun str(v: Any?): String? = when (v) {
100
- is String -> v
101
- is Number -> if (v.toDouble() == Math.floor(v.toDouble()) && !v.toDouble().isInfinite()) v.toLong().toString() else v.toString()
102
- is Boolean -> v.toString()
103
- else -> null
104
- }
105
-
106
- private fun num(v: Any?): Double? = when (v) {
107
- is Number -> v.toDouble()
108
- is String -> v.toDoubleOrNull()
109
- else -> null
110
- }
111
-
112
- fun holds(c: Condition, attrs: Map<String, Any?>, nowMillis: Long): Boolean {
113
- val v = attrValue(c.attr, attrs, nowMillis) ?: return false
114
- val s = str(v) ?: ""
115
- val n = num(v)
116
- fun same(x: Any?): Boolean = str(x) == s || (num(x) != null && num(x) == n)
117
- return when (c.op) {
118
- "in", "not_in" -> {
119
- val list = c.value as? List<*> ?: return false
120
- val hit = list.any { same(it) }
121
- if (c.op == "in") hit else !hit
122
- }
123
- "eq" -> same(c.value)
124
- "gte" -> n != null && num(c.value) != null && n >= num(c.value)!!
125
- "lte" -> n != null && num(c.value) != null && n <= num(c.value)!!
126
- "between" -> {
127
- val r = c.value as? List<*> ?: return false
128
- if (r.size != 2) return false
129
- val lo = num(r[0]) ?: return false
130
- val hi = num(r[1]) ?: return false
131
- n != null && n >= lo && n <= hi
132
- }
133
- else -> false
134
- }
135
- }
136
-
137
- private val ISO = Regex("""^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-]\d{2}(?::?\d{2})?)?$""")
138
-
139
- /** ISO 8601 to epoch millis, by hand: SimpleDateFormat's `X` needs API 24 and java.time needs API 26. */
140
- fun parseDate(s: String): Long? {
141
- val m = ISO.matchEntire(s.trim()) ?: return null
142
- val g = m.groupValues
143
- val cal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
144
- cal.clear()
145
- cal.set(g[1].toInt(), g[2].toInt() - 1, g[3].toInt(), g[4].toInt(), g[5].toInt(), g[6].toInt())
146
- var ms = cal.timeInMillis
147
- val z = g[7]
148
- if (z.isNotEmpty() && z != "Z") {
149
- val sign = if (z[0] == '-') -1 else 1
150
- val digits = z.substring(1).replace(":", "")
151
- val h = digits.substring(0, 2).toInt()
152
- val min = if (digits.length >= 4) digits.substring(2, 4).toInt() else 0
153
- ms -= sign * (h * 60L + min) * 60_000L
154
- }
155
- return ms
156
- }
157
-
158
- /** `quiet = [start, end]` hours in local time, wrapping midnight (e.g. [22, 9]). */
159
- fun inQuietHours(quiet: List<Int>?, nowMillis: Long = System.currentTimeMillis()): Boolean {
160
- if (quiet == null || quiet.size != 2) return false
161
- val h = GregorianCalendar().apply { timeInMillis = nowMillis }.get(Calendar.HOUR_OF_DAY)
162
- val s = quiet[0]
163
- val e = quiet[1]
164
- if (s == e) return false
165
- return if (s < e) h >= s && h < e else h >= s || h < e
166
- }
167
- }