react-native-minimal-webview 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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,306 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.webkit.CookieManager
4
+ import android.webkit.ValueCallback
5
+ import android.webkit.WebSettings
6
+ import android.webkit.WebStorage
7
+ import android.webkit.WebView
8
+ import androidx.webkit.WebSettingsCompat
9
+ import androidx.webkit.WebViewCompat
10
+ import org.json.JSONArray
11
+ import org.json.JSONObject
12
+ import java.lang.reflect.InvocationTargetException
13
+ import java.lang.reflect.Method
14
+ import java.lang.reflect.Modifier
15
+ import kotlin.math.truncate
16
+
17
+ /**
18
+ * The `android` settings prop, `{ settings: {…}, webView: {…} }`, applied by name through reflection, so a public
19
+ * setter this package doesn't know (one a newer SDK or androidx.webkit adds) needs no code here.
20
+ * `settings.textZoom: 120` calls `WebSettings.setTextZoom(120)`, else `WebSettingsCompat.setTextZoom(settings, 120)`.
21
+ * `webView.acceptThirdPartyCookies: true` calls `WebView.set…`, else `WebViewCompat.set…(webView, …)`, else
22
+ * `CookieManager.set…(webView, …)`. [get] reads through the matching getter and [call] invokes a method; for those two,
23
+ * `cookieManager` and `webStorage`, the WebView profile's, are roots as well.
24
+ *
25
+ * Only public SDK methods: `getMethods()` returns nothing else, and reflection on them is allowed. A key with no public
26
+ * setter for the value's type, a feature this device's WebView lacks (`UnsupportedOperationException`) or a method the
27
+ * core owns is reported and skipped; nothing here throws at the caller except [get] and [call], which reject.
28
+ */
29
+ internal class PlatformSettings(private val targets: (root: String) -> List<Target>?) {
30
+ /** `root.key` -> the last value applied or rejected, so an unchanged value is neither applied nor reported again. */
31
+ private val applied = mutableMapOf<String, Any?>()
32
+
33
+ /** `root.key` -> its getter's value before the first write ([NONE]: no getter), set back when the key is removed. */
34
+ private val originals = mutableMapOf<String, Any?>()
35
+
36
+ /** A receiver (null for statics) and, for compat and CookieManager methods, the root object passed first. */
37
+ internal class Target(val cls: Class<*>, val receiver: Any?, val leading: Any?)
38
+
39
+ /**
40
+ * Applies [settings], and sets a key applied before and missing now back to its value before the first write;
41
+ * returns the rejected keys with their reasons. [force] re-applies everything (a new WebView).
42
+ */
43
+ fun apply(settings: Map<String, Any?>?, force: Boolean = false): List<Map<String, String>> {
44
+ if (force) {
45
+ applied.clear()
46
+ originals.clear()
47
+ }
48
+ // Before the new values, so restoring one can't undo another that depends on it.
49
+ val rejected = restore(removedFrom = settings.orEmpty()).toMutableList()
50
+ for ((rootName, entries) in settings.orEmpty()) {
51
+ val targets = settingsTargets(rootName)
52
+ if (targets == null || entries !is Map<*, *>) {
53
+ rejected += mapOf("key" to rootName, "reason" to "unknown root: use settings or webView")
54
+ continue
55
+ }
56
+ for ((k, value) in entries) {
57
+ val key = k as? String ?: continue
58
+ val id = "$rootName.$key"
59
+ if (applied.containsKey(id) && applied[id] == value) continue
60
+ applied[id] = value
61
+ val problem = write(targets, id, key, value) ?: continue
62
+ rejected += mapOf("key" to id, "reason" to problem)
63
+ }
64
+ }
65
+ return rejected
66
+ }
67
+
68
+ /** The targets of a root the prop has, `settings` or `webView`; null for another. */
69
+ private fun settingsTargets(rootName: String) =
70
+ // Not targets() first: the other roots are the WebView profile's, which `webView.profile` may not have set yet.
71
+ if (rootName in listOf("settings", "webView")) targets(rootName) else null
72
+
73
+ /** [set], keeping the value it replaces the first time under [id]; returns the problem, or null when it was set. */
74
+ private fun write(targets: List<Target>, id: String, key: String, value: Any?): String? {
75
+ if (id in originals) return set(targets, key, value)
76
+ return set(targets, key, value) {
77
+ originals[id] = runCatching { read(targets, key) }.getOrDefault(NONE)
78
+ }?.also { originals.remove(id) }
79
+ }
80
+
81
+ /** Forgets each applied key [removedFrom] no longer has and sets its original value back; returns what failed. */
82
+ private fun restore(removedFrom: Map<String, Any?>): List<Map<String, String>> {
83
+ val present = removedFrom.flatMap { (rootName, entries) ->
84
+ (entries as? Map<*, *>)?.keys.orEmpty().map { "$rootName.$it" }
85
+ }.toSet()
86
+ return (applied.keys - present).mapNotNull { id ->
87
+ applied.remove(id)
88
+ if (id !in originals) return@mapNotNull null
89
+ val original = originals.remove(id)
90
+ val (rootName, key) = id.split('.', limit = 2)
91
+ // shortcut: a setter with no getter (geolocationEnabled, initialScale, backgroundColor) can't be restored; add
92
+ // the platform's defaults for those if one matters.
93
+ val problem = if (original === NONE) {
94
+ "removed, but it has no getter to restore it from: it keeps its value until the WebView is recreated"
95
+ } else {
96
+ set(targets(rootName).orEmpty(), key, original)?.let { "removed, but restoring it failed: $it" }
97
+ }
98
+ problem?.let { mapOf("key" to id, "reason" to it) }
99
+ }
100
+ }
101
+
102
+ /** `root.key`: the getter's value (`getKey`, `isKey` or a non-void `key()`), as JSON. Throws a [PlatformException]. */
103
+ fun get(path: String): String {
104
+ val (targets, key) = resolve(path)
105
+ val value = read(targets, key)
106
+ if (value === NONE) throw notFound("no public getter for $key")
107
+ return toJson(value)
108
+ }
109
+
110
+ /**
111
+ * `root.method` with [args], a public method the core doesn't own. [reply] gets the result as JSON: the method's
112
+ * return value, or, when no overload takes just [args], the value that the first overload with a trailing
113
+ * `ValueCallback` reports later. [reply] gets the JSON as a function that throws a [PlatformException] for a value
114
+ * JSON can't carry. Throws a [PlatformException].
115
+ */
116
+ fun call(path: String, args: List<Any?>, reply: (() -> String) -> Unit) {
117
+ val (targets, name) = resolve(path)
118
+ if (name in OWNED) throw problem("$name is ${owned(name)}")
119
+ val result = invokeFirst(targets, name, args) { true }
120
+ if (result !== NONE) return reply { toJson(result) }
121
+ // The callback runs later, outside the caller's try: the receiver converts, so it can reject instead of crashing.
122
+ val callback = ValueCallback<Any?> { value -> reply { toJson(value) } }
123
+ val awaiting = invokeFirst(targets, name, args + callback) { it.parameterTypes.lastOrNull() == ValueCallback::class.java }
124
+ if (awaiting === NONE) throw notFound("no public method $path takes these arguments")
125
+ }
126
+
127
+ /** The targets of `root.key` and the key; throws for a malformed path or an unknown root. */
128
+ private fun resolve(path: String): Pair<List<Target>, String> {
129
+ val parts = path.split('.', limit = 2)
130
+ if (parts.size != 2) throw notFound("use root.key")
131
+ return (targets(parts[0]) ?: throw notFound("unknown root: use settings, webView, cookieManager or webStorage")) to parts[1]
132
+ }
133
+
134
+ internal companion object {
135
+ private val NONE = Any()
136
+
137
+ /**
138
+ * The targets of [root] on [webView], or null for an unknown root. `cookieManager` and `webStorage` are the WebView
139
+ * profile's ([profileOf]).
140
+ */
141
+ fun targets(webView: WebView, root: String): List<Target>? = when (root) {
142
+ "settings" -> listOf(
143
+ Target(WebSettings::class.java, webView.settings, null),
144
+ Target(WebSettingsCompat::class.java, null, webView.settings)
145
+ )
146
+ "webView" -> listOf(
147
+ Target(WebView::class.java, webView, null),
148
+ Target(WebViewCompat::class.java, null, webView),
149
+ // Any instance: its (webView, …) methods set the WebView's own settings.
150
+ Target(CookieManager::class.java, CookieManager.getInstance(), webView)
151
+ )
152
+ "cookieManager" -> listOf(Target(CookieManager::class.java, profileOf(webView)?.cookieManager ?: CookieManager.getInstance(), null))
153
+ "webStorage" -> listOf(Target(WebStorage::class.java, profileOf(webView)?.webStorage ?: WebStorage.getInstance(), null))
154
+ else -> null
155
+ }
156
+
157
+ /**
158
+ * Methods the core owns: its clients, listeners, scripts, loads and navigations, the WebView's lifetime and timers,
159
+ * and the process-wide debugging switch; the page's JS goes through `evaluate` and the bridge.
160
+ */
161
+ val OWNED = setOf(
162
+ "setWebViewClient", "setWebChromeClient", "setDownloadListener", "addJavascriptInterface",
163
+ "removeJavascriptInterface", "addWebMessageListener", "removeWebMessageListener", "addDocumentStartJavaScript",
164
+ "destroy", "removeAllViews", "pauseTimers", "resumeTimers", "loadUrl", "loadData", "loadDataWithBaseURL",
165
+ "postUrl", "reload", "goBack", "goForward", "goBackOrForward", "stopLoading", "evaluateJavascript",
166
+ "setWebContentsDebuggingEnabled", "setOnTouchListener", "setOnScrollChangeListener", "addNavigationListener"
167
+ )
168
+
169
+ /** The result of the first method [name] of [targets] that [accepts] and takes [values], or [NONE] when none does. */
170
+ private fun invokeFirst(targets: List<Target>, name: String, values: List<Any?>, accepts: (Method) -> Boolean): Any? {
171
+ for (target in targets) {
172
+ for (method in target.cls.methods) {
173
+ if (method.name != name || !accepts(method)) continue
174
+ val arguments = arguments(method, target, values) ?: continue
175
+ return invoke(method, target, arguments)
176
+ }
177
+ }
178
+ return NONE
179
+ }
180
+
181
+ private fun owned(name: String) =
182
+ if (name == "setWebContentsDebuggingEnabled") {
183
+ "owned by the core: use AndroidWebView.setWebContentsDebuggingEnabled"
184
+ } else {
185
+ "owned by the core"
186
+ }
187
+
188
+ /**
189
+ * Calls [key]'s setter on the first target that takes [value], running [before] just before it; returns the
190
+ * problem, or null when it was set.
191
+ */
192
+ private fun set(targets: List<Target>, key: String, value: Any?, before: () -> Unit = {}): String? {
193
+ if (key.isEmpty() || key.startsWith("_")) return "not a public setter"
194
+ val setter = "set" + key.replaceFirstChar { it.uppercaseChar() }
195
+ if (setter in OWNED) return owned(setter)
196
+ var seen = false
197
+ for (target in targets) {
198
+ for (method in target.cls.methods) {
199
+ if (method.name != setter) continue
200
+ seen = true
201
+ val args = arguments(method, target, listOf(value)) ?: continue
202
+ return try {
203
+ before()
204
+ invoke(method, target, args)
205
+ null
206
+ } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
207
+ e.message
208
+ }
209
+ }
210
+ }
211
+ return if (seen) "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}" else "no public setter"
212
+ }
213
+
214
+ /** [key]'s getter value (`getKey`, `isKey` or a non-void `key()`) on the first target that has one, or [NONE]. */
215
+ private fun read(targets: List<Target>, key: String): Any? {
216
+ val capital = key.replaceFirstChar { it.uppercaseChar() }
217
+ for (target in targets) {
218
+ for (method in target.cls.methods) {
219
+ val getter = method.name == "get$capital" || method.name == "is$capital"
220
+ if (!getter && (method.name != key || method.returnType == Void.TYPE)) continue
221
+ val args = arguments(method, target, emptyList()) ?: continue
222
+ return invoke(method, target, args)
223
+ }
224
+ }
225
+ return NONE
226
+ }
227
+
228
+ /** The method's arguments for [values], with the target's leading object first, or null when they don't fit. */
229
+ private fun arguments(method: Method, target: Target, values: List<Any?>): Array<Any?>? {
230
+ if (target.receiver == null && !Modifier.isStatic(method.modifiers)) return null
231
+ val types = method.parameterTypes
232
+ val leading = if (target.leading != null) listOf(target.leading) else emptyList()
233
+ if (types.size != leading.size + values.size) return null
234
+ if (leading.isNotEmpty() && !types[0].isInstance(target.leading)) return null
235
+ val args = arrayOfNulls<Any?>(types.size)
236
+ leading.forEachIndexed { i, value -> args[i] = value }
237
+ values.forEachIndexed { i, value ->
238
+ val coerced = coerce(value, types[leading.size + i])
239
+ if (coerced === NONE) return null
240
+ args[leading.size + i] = coerced
241
+ }
242
+ return args
243
+ }
244
+
245
+ /** [value] as the parameter [type] takes it, or [NONE]. JS numbers arrive as Double and fit every numeric type. */
246
+ private fun coerce(value: Any?, type: Class<*>): Any? {
247
+ if (value == null) return if (type.isPrimitive) NONE else null
248
+ return when (type.kotlin.javaObjectType) {
249
+ Boolean::class.javaObjectType -> value as? Boolean
250
+ Int::class.javaObjectType -> (value as? Number)?.let(::intOf)
251
+ Long::class.javaObjectType -> (value as? Number)?.toLong()
252
+ Float::class.javaObjectType -> (value as? Number)?.toFloat()
253
+ Double::class.javaObjectType -> (value as? Number)?.toDouble()
254
+ String::class.java, CharSequence::class.java -> value as? String
255
+ else -> if (value !is Boolean && type.isInstance(value)) value else null
256
+ } ?: NONE
257
+ }
258
+
259
+ /**
260
+ * [number] truncated to an int, or null outside `Int.MIN_VALUE..0xFFFFFFFF`. Above `Int.MAX_VALUE` it wraps, as
261
+ * Java's `(int) 0xFF000000L` does, so an ARGB color written as JS writes it, `0xFF000000`, is `-16777216`.
262
+ * Kotlin's `Double.toInt()` would clamp it to `Int.MAX_VALUE`.
263
+ */
264
+ private fun intOf(number: Number): Int? {
265
+ val whole = truncate(number.toDouble())
266
+ return if (whole >= Int.MIN_VALUE && whole <= UInt.MAX_VALUE.toDouble()) whole.toLong().toInt() else null
267
+ }
268
+
269
+ /** Invokes, unwrapping the target's own exception; a compat feature this WebView lacks reads as unsupported. */
270
+ private fun invoke(method: Method, target: Target, args: Array<Any?>): Any? = try {
271
+ method.invoke(target.receiver, *args)
272
+ } catch (e: InvocationTargetException) {
273
+ val cause = e.cause ?: e
274
+ throw if (cause is UnsupportedOperationException) {
275
+ PlatformException("unavailable", "not supported by this WebView")
276
+ } else {
277
+ problem("failed: $cause")
278
+ }
279
+ } catch (e: IllegalAccessException) {
280
+ throw problem("not accessible: ${e.message}")
281
+ }
282
+
283
+ private fun problem(reason: String) = PlatformException("native_error", reason)
284
+
285
+ private fun notFound(reason: String) = PlatformException("not_found", reason)
286
+
287
+ /**
288
+ * A getter's or method's result as JSON: primitives, strings, lists and maps of them; anything else is null. A
289
+ * non-finite number throws: JSON has none.
290
+ */
291
+ fun toJson(value: Any?): String = jsonable(value).let { if (it is String) JSONObject.quote(it) else it.toString() }
292
+
293
+ // Checked here at every depth: Android's org.json turns a nested non-finite number into a null toString().
294
+ private fun jsonable(value: Any?): Any = when (value) {
295
+ is Double, is Float -> if ((value as Number).toDouble().isFinite()) value else throw problem("$value is not JSON")
296
+ is Boolean, is Number, is String -> value
297
+ is Map<*, *> -> JSONObject(value.mapKeys { it.key.toString() }.mapValues { jsonable(it.value) })
298
+ is List<*> -> JSONArray(value.map(::jsonable))
299
+ is Array<*> -> JSONArray(value.map(::jsonable))
300
+ else -> JSONObject.NULL
301
+ }
302
+ }
303
+ }
304
+
305
+ /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code. */
306
+ internal class PlatformException(val code: String, message: String) : IllegalArgumentException(message)
@@ -0,0 +1,76 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.content.Context
4
+ import android.view.MotionEvent
5
+ import android.view.ViewGroup
6
+ import android.widget.FrameLayout
7
+ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
8
+
9
+ /**
10
+ * The `pullToRefresh` prop. WebView sends no nested-scroll events, so it asks the WebView whether the document can
11
+ * scroll up, and on touch-down asks the page whether the element under the finger is inside an inner scroller
12
+ * (overflow: auto) that is already scrolled.
13
+ */
14
+ internal class PullToRefresh(private val owner: MinimalWebView) {
15
+ // The page's answer for the current touch; null while it is pending, which holds the pull off. The down event itself
16
+ // must see false: SwipeRefreshLayout only tracks a gesture whose down event it accepted.
17
+ private var innerScrolled: Boolean? = false
18
+ private var touches = 0
19
+
20
+ /** Holds the WebView. SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
21
+ val content = FrameLayout(owner.context)
22
+
23
+ /** Always around [content]; off until the first prop batch, then the prop sets `isEnabled`. */
24
+ val layout: SwipeRefreshLayout = Layout(owner.context).apply {
25
+ isEnabled = false
26
+ addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
27
+ setOnRefreshListener { owner.reload() }
28
+ setOnChildScrollUpCallback { _, _ -> owner.webView.canScrollVertically(-1) || innerScrolled != false }
29
+ }
30
+
31
+ private fun checkInnerScroller(x: Float, y: Float) {
32
+ val touch = ++touches
33
+ val density = owner.webView.resources.displayMetrics.density
34
+ owner.webView.evaluateJavascript("($INNER_SCROLLED)(${x / density}, ${y / density})") { result ->
35
+ if (touch == touches) innerScrolled = result == "true"
36
+ }
37
+ // A busy page answers late: don't hold the pull off for longer than this.
38
+ owner.mainHandler.postDelayed({ if (touch == touches && innerScrolled == null) innerScrolled = false }, ANSWER_TIMEOUT_MS)
39
+ }
40
+
41
+ /** A load ended: the spinner stops, or it would ignore the next pull. */
42
+ fun pageFinished() {
43
+ layout.isRefreshing = false
44
+ innerScrolled = false
45
+ }
46
+
47
+ private inner class Layout(context: Context) : SwipeRefreshLayout(context) {
48
+ override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
49
+ // Off: no pull, and no question to the page on every touch.
50
+ if (!isEnabled) return false
51
+ if (event.actionMasked != MotionEvent.ACTION_DOWN) return super.onInterceptTouchEvent(event)
52
+ innerScrolled = false
53
+ val intercepted = super.onInterceptTouchEvent(event)
54
+ if (owner.webView.canScrollVertically(-1)) {
55
+ // A scrolled document already ruled this gesture out, whatever the page says: don't ask it. Dropping the
56
+ // count makes a late answer or timeout from an earlier touch a no-op.
57
+ touches++
58
+ } else {
59
+ innerScrolled = null
60
+ checkInnerScroller(event.x, event.y)
61
+ }
62
+ return intercepted
63
+ }
64
+ }
65
+ }
66
+
67
+ private const val ANSWER_TIMEOUT_MS = 150L
68
+
69
+ /** True when the element at (x, y) has a scrolled ancestor that can scroll vertically (CSS pixels). */
70
+ private const val INNER_SCROLLED = """(x, y) => {
71
+ for (let e = document.elementFromPoint(x, y); e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
72
+ const overflow = getComputedStyle(e).overflowY;
73
+ if ((overflow === 'auto' || overflow === 'scroll') && e.scrollHeight > e.clientHeight && e.scrollTop > 0) return true;
74
+ }
75
+ return false;
76
+ }"""
@@ -0,0 +1,258 @@
1
+ package expo.modules.minimalwebview.requests
2
+
3
+ import android.net.Uri
4
+ import android.util.Log
5
+ import android.webkit.CookieManager
6
+ import androidx.webkit.URLUtilCompat
7
+ import expo.modules.minimalwebview.MinimalWebView
8
+ import expo.modules.minimalwebview.TAG
9
+ import expo.modules.minimalwebview.profileOf
10
+ import org.json.JSONArray
11
+ import org.json.JSONObject
12
+ import org.json.JSONTokener
13
+ import java.io.File
14
+ import java.io.IOException
15
+ import java.io.InputStream
16
+ import java.io.OutputStream
17
+ import java.net.HttpURLConnection
18
+ import java.net.URL
19
+ import java.util.Base64
20
+ import java.util.concurrent.ArrayBlockingQueue
21
+ import java.util.concurrent.Executors
22
+ import java.util.concurrent.TimeUnit
23
+
24
+ /** The server answered [code], not 2xx. */
25
+ internal class HttpStatus(val code: Int) : IOException("HTTP $code")
26
+
27
+ /** The file is above [Downloads.MAX_BYTES]. */
28
+ internal class TooLarge : IOException(Downloads.TOO_LARGE)
29
+
30
+ /** What WebView's DownloadListener reports. */
31
+ internal data class DownloadInfo(
32
+ val url: String,
33
+ val userAgent: String,
34
+ val contentDisposition: String,
35
+ val mimeType: String
36
+ )
37
+
38
+ /**
39
+ * The `onDownload` prop. WebView hands over only the URL, so http(s) is fetched again, through `HttpURLConnection` and
40
+ * the WebView profile's `CookieManager` rather than React Native's OkHttp, so the package builds without
41
+ * `react-android`. Nothing here may crash the app: the page controls the URL.
42
+ */
43
+ internal class Downloads(private val owner: MinimalWebView) {
44
+ private val io = Executors.newSingleThreadExecutor()
45
+
46
+ /** Returns true when the app's prop takes the download. */
47
+ fun onDownloadStart(download: DownloadInfo): Boolean {
48
+ if ("onDownload" !in owner.requestHandlers) return false
49
+ val name = safeName(URLUtilCompat.guessFileName(download.url, download.contentDisposition.ifEmpty { null }, download.mimeType))
50
+ when {
51
+ download.url.startsWith("blob:") -> readBlob(download.url, name)
52
+ download.url.startsWith("data:") -> save(name, download.url) { file -> append(file, decodeDataUrl(download.url)) }
53
+ download.url.startsWith("http:") || download.url.startsWith("https:") -> fetch(download, name)
54
+ else -> failed(name, download.url, IOException("unsupported URL scheme"))
55
+ }
56
+ return true
57
+ }
58
+
59
+ private fun fetch(download: DownloadInfo, name: String) {
60
+ val cookies = profileOf(owner.webView)?.cookieManager ?: CookieManager.getInstance()
61
+ save(name, download.url) { file -> fetchTo(download, file, cookies::getCookie, cookies::setCookie) }
62
+ }
63
+
64
+ /** Appends a decoded data: URL's bytes to [file], creating it, and returns its MIME type. */
65
+ private fun append(file: File, data: Pair<ByteArray, String>): String {
66
+ file.appendBytes(data.first)
67
+ return data.second
68
+ }
69
+
70
+ /**
71
+ * Runs [write] off the main thread (a download can be megabytes); it fills the file and returns its MIME type. One
72
+ * directory per download, so the same guessed name never overwrites a file already handed to the app. The event goes
73
+ * back on the main thread. [url] is the download's own URL, for the event.
74
+ */
75
+ private fun save(name: String, url: String, write: (File) -> String) {
76
+ val file = File(owner.webView.context.cacheDir, "downloads/${System.nanoTime()}/$name")
77
+ io.execute {
78
+ val result = try {
79
+ file.parentFile?.mkdirs()
80
+ write(file)
81
+ } catch (e: Exception) {
82
+ // a malformed data: URL or forged JSON from the page: no failure may reach the io thread
83
+ e
84
+ }
85
+ if (result is Exception) file.parentFile?.deleteRecursively() // no partial file stays in the cache
86
+ owner.mainHandler.post {
87
+ when (result) {
88
+ is String -> owner.emit(
89
+ "core", "onDownload",
90
+ mapOf("ok" to true, "uri" to Uri.fromFile(file).toString(), "filename" to name, "mimeType" to result, "url" to serverUrl(url))
91
+ )
92
+ is Exception -> failed(name, url, result)
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ /**
99
+ * WebView cannot fetch a blob: URL for us: the page reads it and returns it as data: URLs, [CHUNK_BYTES] at a time,
100
+ * each awaited on the io thread. A reply crosses as one Java string and is parsed twice, so a blob returned whole
101
+ * fills the heap several times over.
102
+ */
103
+ private fun readBlob(url: String, name: String) = save(name, url) { file ->
104
+ var offset = 0L
105
+ var type: String
106
+ do {
107
+ val (size, data) = readChunk(url, offset)
108
+ type = append(file, decodeChunk(data))
109
+ offset += CHUNK_BYTES
110
+ if (offset > MAX_BYTES) throw TooLarge() // the page's own size check can be forged
111
+ } while (offset < size)
112
+ type
113
+ }
114
+
115
+ /** Asks the page, from the io thread, for the blob's size and the data: URL of its [CHUNK_BYTES] at [offset]. */
116
+ private fun readChunk(url: String, offset: Long): Pair<Long, String> {
117
+ val script = """
118
+ fetch(${JSONObject.quote(url)}).then((r) => r.blob()).then((b) => new Promise((ok, fail) => {
119
+ if (b.size > $MAX_BYTES) return fail(new Error(${JSONObject.quote(TOO_LARGE)}));
120
+ const reader = new FileReader(); reader.onload = () => ok([b.size, reader.result]); reader.onerror = () => fail(reader.error);
121
+ reader.readAsDataURL(b.slice($offset, $offset + $CHUNK_BYTES, b.type));
122
+ }))
123
+ """.trimIndent()
124
+ val reply = ArrayBlockingQueue<Result<String>>(1)
125
+ owner.mainHandler.post { owner.evaluate(script) { reply.offer(it) } }
126
+ val result = reply.poll(TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) ?: throw IOException("the page did not read the blob in time")
127
+ val json = result.getOrElse { throw IOException("could not read the blob: ${it.message}") }
128
+ // A reply far longer than a chunk's data: URL is forged: refuse it before it is copied twice more.
129
+ if (json.length > CHUNK_BYTES / 3 * 4 + 1024) throw TooLarge()
130
+ val chunk = JSONTokener(json).nextValue() as? JSONArray ?: throw IOException("could not read the blob")
131
+ return chunk.getLong(0) to chunk.getString(1)
132
+ }
133
+
134
+ private fun failed(name: String, url: String, error: Exception) {
135
+ Log.w(TAG, "download of $name failed", error)
136
+ if (error is HttpStatus) {
137
+ return owner.emit("core", "onDownload", mapOf("ok" to false, "kind" to "http", "filename" to name, "url" to url, "statusCode" to error.code))
138
+ }
139
+ owner.emit(
140
+ "core", "onDownload",
141
+ mapOf("ok" to false, "kind" to kind(error, serverUrl(url) != null), "filename" to name, "url" to serverUrl(url), "description" to (error.message ?: error.toString()))
142
+ )
143
+ }
144
+
145
+ private fun serverUrl(url: String) = url.takeIf { it.startsWith("http:") || it.startsWith("https:") }
146
+
147
+ fun detach() {
148
+ io.shutdown()
149
+ }
150
+
151
+ internal companion object {
152
+ // The page picks the file, and an http(s) one fills the cache: above this a download fails instead.
153
+ const val MAX_BYTES = 100L * 1024 * 1024
154
+ const val TOO_LARGE = "larger than 100 MB"
155
+ const val CHUNK_BYTES = 4L * 1024 * 1024
156
+ const val MAX_REDIRECTS = 20 // OkHttp's, which React Native's fetch uses
157
+ const val TIMEOUT_MS = 30_000
158
+ private val PERCENT_ESCAPE = Regex("%[0-9A-Fa-f]{2}")
159
+
160
+ /**
161
+ * A failed download's `kind` other than `http`: everything but a [fetched] (http(s)) download's own IOException is
162
+ * the content's.
163
+ */
164
+ fun kind(error: Exception, fetched: Boolean) =
165
+ // shortcut: a disk error while an http(s) body streams reads as network; tell them apart if apps need to.
166
+ if (fetched && error is IOException && error !is TooLarge) "network" else "data"
167
+
168
+ /**
169
+ * A data: URL's bytes and its MIME type, application/octet-stream when it names none. As in a browser, the body is
170
+ * percent-decoded to bytes, even when base64 (encodeURIComponent of the base64 text), and `;base64` is in any case.
171
+ * Throws IllegalArgumentException for a URL without a comma or with bad base64.
172
+ */
173
+ fun decodeDataUrl(url: String): Pair<ByteArray, String> {
174
+ val comma = url.indexOf(',')
175
+ require(comma >= 0) { "a data: URL without a comma" }
176
+ val header = url.substring(0, comma).removePrefix("data:")
177
+ val body = percentDecode(url.substring(comma + 1))
178
+ // The MIME decoder skips what isn't base64 (whitespace above all), as android.util.Base64 does.
179
+ val bytes = if (header.endsWith(";base64", ignoreCase = true)) Base64.getMimeDecoder().decode(body) else body
180
+ return bytes to header.substringBefore(';').ifEmpty { "application/octet-stream" }
181
+ }
182
+
183
+ /**
184
+ * A blob chunk's bytes and MIME type, from FileReader's data: URL. Chromium reads an empty blob as a bare `data:`,
185
+ * which [decodeDataUrl] refuses (a page's own data: URL without a comma is malformed): that is no bytes.
186
+ */
187
+ fun decodeChunk(data: String): Pair<ByteArray, String> =
188
+ if (data == "data:") ByteArray(0) to "application/octet-stream" else decodeDataUrl(data)
189
+
190
+ /** [text]'s UTF-8 bytes, each `%` and two hex digits made the byte they name: not decoded as UTF-8 again. */
191
+ private fun percentDecode(text: String): ByteArray {
192
+ if ('%' !in text) return text.toByteArray() // a blob's chunks: spares two copies of megabytes
193
+ // Latin-1 maps each byte to one char and back, so the escapes are replaced in a string.
194
+ val latin1 = String(text.toByteArray(), Charsets.ISO_8859_1)
195
+ return PERCENT_ESCAPE.replace(latin1) { it.value.substring(1).toInt(16).toChar().toString() }.toByteArray(Charsets.ISO_8859_1)
196
+ }
197
+
198
+ /** `guessFileName` keeps a page's `.` or `..` (a directory: the save fails with EISDIR) and can be empty. */
199
+ fun safeName(name: String) = if (name.isEmpty() || name == "." || name == "..") "download" else name
200
+
201
+ /** Copies [input] to [output] and fails once more than [max] bytes came: the Content-Length can be missing or wrong. */
202
+ fun copyCapped(input: InputStream, output: OutputStream, max: Long) {
203
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
204
+ var total = 0L
205
+ while (true) {
206
+ val read = input.read(buffer)
207
+ if (read < 0) break
208
+ total += read
209
+ if (total > max) throw TooLarge()
210
+ output.write(buffer, 0, read)
211
+ }
212
+ }
213
+
214
+ /** Fetches [download] into [file] and returns its MIME type. [cookie] and [setCookie] are the WebView's cookie store. */
215
+ fun fetchTo(download: DownloadInfo, file: File, cookie: (String) -> String?, setCookie: (String, String) -> Unit): String {
216
+ val connection = connect(URL(download.url), download.userAgent, cookie, setCookie)
217
+ try {
218
+ if (connection.responseCode !in 200..299) throw HttpStatus(connection.responseCode)
219
+ if (connection.contentLengthLong > MAX_BYTES) throw TooLarge()
220
+ connection.inputStream.use { input -> file.outputStream().use { output -> copyCapped(input, output, MAX_BYTES) } }
221
+ return download.mimeType.ifEmpty { connection.contentType?.substringBefore(';') ?: "application/octet-stream" }
222
+ } finally {
223
+ connection.disconnect()
224
+ }
225
+ }
226
+
227
+ /** Whether a download follows a redirect [from] one URL [to] another: only to https, or from http to http. */
228
+ fun redirectAllowed(from: URL, to: URL) = to.protocol == "https" || (to.protocol == "http" && from.protocol == "http")
229
+
230
+ /**
231
+ * Opens [url] and follows its redirects (http to https too) by hand: each hop sends the cookies for its own URL and
232
+ * stores what the server sets back, as React Native's fetch does. A hop must be [redirectAllowed]: Chrome blocks an
233
+ * insecure download started from a secure one.
234
+ */
235
+ private fun connect(url: URL, userAgent: String, cookie: (String) -> String?, setCookie: (String, String) -> Unit): HttpURLConnection {
236
+ var current = url
237
+ repeat(MAX_REDIRECTS + 1) {
238
+ val at = current.toString()
239
+ val connection = current.openConnection() as HttpURLConnection
240
+ connection.instanceFollowRedirects = false
241
+ connection.connectTimeout = TIMEOUT_MS
242
+ connection.readTimeout = TIMEOUT_MS
243
+ connection.setRequestProperty("User-Agent", userAgent)
244
+ cookie(at)?.let { connection.setRequestProperty("Cookie", it) }
245
+ val code = connection.responseCode
246
+ // Header names come in any case (HTTP/2 lowercases them), and headerFields' keys keep it.
247
+ for ((key, values) in connection.headerFields) if (key.equals("Set-Cookie", ignoreCase = true)) values.forEach { setCookie(at, it) }
248
+ val location = connection.getHeaderField("Location")
249
+ if (code !in 300..399 || location == null) return connection
250
+ connection.disconnect()
251
+ val next = URL(current, location)
252
+ if (!redirectAllowed(current, next)) throw IOException("refused a redirect from ${current.protocol} to ${next.protocol}")
253
+ current = next
254
+ }
255
+ throw IOException("more than $MAX_REDIRECTS redirects")
256
+ }
257
+ }
258
+ }