react-native-minimal-webview 0.0.0-stage → 1.0.1

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 +150 -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 +487 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -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 +197 -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 +303 -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 +259 -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 +96 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +453 -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 +137 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +33 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +105 -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 +59 -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 +15 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +22 -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 +701 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +201 -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 +16 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +24 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +32 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +115 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1173 -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 +158 -0
  80. package/ios/DocumentEnd.swift +22 -0
  81. package/ios/DownloadName.swift +10 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +310 -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 +38 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +96 -0
  90. package/ios/MinimalWebView+Navigation.swift +243 -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 +513 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +36 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +252 -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 +99 -4
  104. package/src/WebView.tsx +626 -0
  105. package/src/bridge/createBridge.ts +178 -0
  106. package/src/bridge/endpoint.ts +123 -0
  107. package/src/bridge/origins.ts +61 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +67 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +24 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +693 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +26 -0
  116. package/src/refStore.ts +165 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1240 -0
@@ -0,0 +1,303 @@
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 are reached: `getMethods()` returns nothing else. A key that can't be applied (no public
26
+ * setter for the value's type, a feature this device's WebView lacks, a method the core owns) is skipped and returned
27
+ * by [apply].
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 a function that returns the result as
112
+ * JSON, or throws a [PlatformException] for a value JSON can't carry. The result is the method's return value or, when
113
+ * no overload takes just [args], the value that the first overload with a trailing `ValueCallback` reports later.
114
+ * 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
+ /** The targets of [root] on [webView], or null for an unknown root. */
138
+ fun targets(webView: WebView, root: String): List<Target>? = when (root) {
139
+ "settings" -> listOf(
140
+ Target(WebSettings::class.java, webView.settings, null),
141
+ Target(WebSettingsCompat::class.java, null, webView.settings)
142
+ )
143
+ "webView" -> listOf(
144
+ Target(WebView::class.java, webView, null),
145
+ Target(WebViewCompat::class.java, null, webView),
146
+ // Any instance: its (webView, …) methods set the WebView's own settings.
147
+ Target(CookieManager::class.java, CookieManager.getInstance(), webView)
148
+ )
149
+ "cookieManager" -> listOf(Target(CookieManager::class.java, profileOf(webView)?.cookieManager ?: CookieManager.getInstance(), null))
150
+ "webStorage" -> listOf(Target(WebStorage::class.java, profileOf(webView)?.webStorage ?: WebStorage.getInstance(), null))
151
+ else -> null
152
+ }
153
+
154
+ /**
155
+ * Methods the core owns: its clients, listeners, scripts, loads and navigations, the WebView's lifetime and timers,
156
+ * and the process-wide debugging switch; the page's JS goes through `evaluate` and the bridge.
157
+ */
158
+ val OWNED = setOf(
159
+ "setWebViewClient", "setWebChromeClient", "setDownloadListener", "addJavascriptInterface",
160
+ "removeJavascriptInterface", "addWebMessageListener", "removeWebMessageListener", "addDocumentStartJavaScript",
161
+ "destroy", "removeAllViews", "pauseTimers", "resumeTimers", "loadUrl", "loadData", "loadDataWithBaseURL",
162
+ "postUrl", "reload", "goBack", "goForward", "goBackOrForward", "stopLoading", "evaluateJavascript",
163
+ "setWebContentsDebuggingEnabled", "setOnTouchListener", "setOnScrollChangeListener", "addNavigationListener"
164
+ )
165
+
166
+ /** The result of the first method [name] of [targets] that [accepts] and takes [values], or [NONE] when none does. */
167
+ private fun invokeFirst(targets: List<Target>, name: String, values: List<Any?>, accepts: (Method) -> Boolean): Any? {
168
+ for (target in targets) {
169
+ for (method in target.cls.methods) {
170
+ if (method.name != name || !accepts(method)) continue
171
+ val arguments = arguments(method, target, values) ?: continue
172
+ return invoke(method, target, arguments)
173
+ }
174
+ }
175
+ return NONE
176
+ }
177
+
178
+ private fun owned(name: String) =
179
+ if (name == "setWebContentsDebuggingEnabled") {
180
+ "owned by the core: use AndroidWebView.setWebContentsDebuggingEnabled"
181
+ } else {
182
+ "owned by the core"
183
+ }
184
+
185
+ /**
186
+ * Calls [key]'s setter on the first target that takes [value], running [before] just before it; returns the
187
+ * problem, or null when it was set.
188
+ */
189
+ private fun set(targets: List<Target>, key: String, value: Any?, before: () -> Unit = {}): String? {
190
+ if (key.isEmpty() || key.startsWith("_")) return "not a public setter"
191
+ val setter = "set" + key.replaceFirstChar { it.uppercaseChar() }
192
+ if (setter in OWNED) return owned(setter)
193
+ var seen = false
194
+ for (target in targets) {
195
+ for (method in target.cls.methods) {
196
+ if (method.name != setter) continue
197
+ seen = true
198
+ val args = arguments(method, target, listOf(value)) ?: continue
199
+ return try {
200
+ before()
201
+ invoke(method, target, args)
202
+ null
203
+ } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
204
+ e.message
205
+ }
206
+ }
207
+ }
208
+ return if (seen) "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}" else "no public setter"
209
+ }
210
+
211
+ /** The value of [key]'s getter on the first target that has one, or [NONE]. */
212
+ private fun read(targets: List<Target>, key: String): Any? {
213
+ val capital = key.replaceFirstChar { it.uppercaseChar() }
214
+ for (target in targets) {
215
+ for (method in target.cls.methods) {
216
+ val getter = method.name == "get$capital" || method.name == "is$capital"
217
+ if (!getter && (method.name != key || method.returnType == Void.TYPE)) continue
218
+ val args = arguments(method, target, emptyList()) ?: continue
219
+ return invoke(method, target, args)
220
+ }
221
+ }
222
+ return NONE
223
+ }
224
+
225
+ /** The method's arguments for [values], with the target's leading object first, or null when they don't fit. */
226
+ private fun arguments(method: Method, target: Target, values: List<Any?>): Array<Any?>? {
227
+ if (target.receiver == null && !Modifier.isStatic(method.modifiers)) return null
228
+ val types = method.parameterTypes
229
+ val leading = if (target.leading != null) listOf(target.leading) else emptyList()
230
+ if (types.size != leading.size + values.size) return null
231
+ if (leading.isNotEmpty() && !types[0].isInstance(target.leading)) return null
232
+ val args = arrayOfNulls<Any?>(types.size)
233
+ leading.forEachIndexed { i, value -> args[i] = value }
234
+ values.forEachIndexed { i, value ->
235
+ val coerced = coerce(value, types[leading.size + i])
236
+ if (coerced === NONE) return null
237
+ args[leading.size + i] = coerced
238
+ }
239
+ return args
240
+ }
241
+
242
+ /** [value] as the parameter [type] takes it, or [NONE]. JS numbers arrive as Double and fit every numeric type. */
243
+ private fun coerce(value: Any?, type: Class<*>): Any? {
244
+ if (value == null) return if (type.isPrimitive) NONE else null
245
+ return when (type.kotlin.javaObjectType) {
246
+ Boolean::class.javaObjectType -> value as? Boolean
247
+ Int::class.javaObjectType -> (value as? Number)?.let(::intOf)
248
+ Long::class.javaObjectType -> (value as? Number)?.toLong()
249
+ Float::class.javaObjectType -> (value as? Number)?.toFloat()
250
+ Double::class.javaObjectType -> (value as? Number)?.toDouble()
251
+ String::class.java, CharSequence::class.java -> value as? String
252
+ else -> if (value !is Boolean && type.isInstance(value)) value else null
253
+ } ?: NONE
254
+ }
255
+
256
+ /**
257
+ * [number] truncated to an int, or null outside `Int.MIN_VALUE..0xFFFFFFFF`. Above `Int.MAX_VALUE` it wraps, as
258
+ * Java's `(int) 0xFF000000L` does, so an ARGB color written as JS writes it, `0xFF000000`, is `-16777216`.
259
+ * Kotlin's `Double.toInt()` would clamp it to `Int.MAX_VALUE`.
260
+ */
261
+ private fun intOf(number: Number): Int? {
262
+ val whole = truncate(number.toDouble())
263
+ return if (whole >= Int.MIN_VALUE && whole <= UInt.MAX_VALUE.toDouble()) whole.toLong().toInt() else null
264
+ }
265
+
266
+ /** Invokes, unwrapping the target's own exception; a compat feature this WebView lacks reads as unsupported. */
267
+ private fun invoke(method: Method, target: Target, args: Array<Any?>): Any? = try {
268
+ method.invoke(target.receiver, *args)
269
+ } catch (e: InvocationTargetException) {
270
+ val cause = e.cause ?: e
271
+ throw if (cause is UnsupportedOperationException) {
272
+ PlatformException("unavailable", "not supported by this WebView")
273
+ } else {
274
+ problem("failed: $cause")
275
+ }
276
+ } catch (e: IllegalAccessException) {
277
+ throw problem("not accessible: ${e.message}")
278
+ }
279
+
280
+ private fun problem(reason: String) = PlatformException("native_error", reason)
281
+
282
+ private fun notFound(reason: String) = PlatformException("not_found", reason)
283
+
284
+ /**
285
+ * A getter's or method's result as JSON: primitives, strings, collections and maps of them; anything else is null.
286
+ * A non-finite number throws: JSON has none.
287
+ */
288
+ fun toJson(value: Any?): String = jsonable(value).let { if (it is String) JSONObject.quote(it) else it.toString() }
289
+
290
+ // Checked here at every depth: Android's org.json turns a nested non-finite number into a null toString().
291
+ private fun jsonable(value: Any?): Any = when (value) {
292
+ is Double, is Float -> if ((value as Number).toDouble().isFinite()) value else throw problem("$value is not JSON")
293
+ is Boolean, is Number, is String -> value
294
+ is Map<*, *> -> JSONObject(value.mapKeys { it.key.toString() }.mapValues { jsonable(it.value) })
295
+ is Collection<*> -> JSONArray(value.map(::jsonable))
296
+ is Array<*> -> JSONArray(value.map(::jsonable))
297
+ else -> JSONObject.NULL
298
+ }
299
+ }
300
+ }
301
+
302
+ /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code (`not_found`, `native_error` or `unavailable`). */
303
+ 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 or scroll) 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,259 @@
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
+ * The `kind` of a failed download other than `http`: `network` for an IOException from a [fetched] (http(s)) download,
162
+ * except [TooLarge]; `data` for everything else.
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, base64 bodies too (encodeURIComponent of the base64 text), and `;base64` matches in any
171
+ * case.
172
+ * Throws IllegalArgumentException for a URL without a comma or with bad base64.
173
+ */
174
+ fun decodeDataUrl(url: String): Pair<ByteArray, String> {
175
+ val comma = url.indexOf(',')
176
+ require(comma >= 0) { "a data: URL without a comma" }
177
+ val header = url.substring(0, comma).removePrefix("data:")
178
+ val body = percentDecode(url.substring(comma + 1))
179
+ // The MIME decoder skips what isn't base64 (whitespace above all), as android.util.Base64 does.
180
+ val bytes = if (header.endsWith(";base64", ignoreCase = true)) Base64.getMimeDecoder().decode(body) else body
181
+ return bytes to header.substringBefore(';').ifEmpty { "application/octet-stream" }
182
+ }
183
+
184
+ /**
185
+ * A blob chunk's bytes and MIME type, from FileReader's data: URL. Chromium reads an empty blob as a bare `data:`,
186
+ * which [decodeDataUrl] refuses (a page's own data: URL without a comma is malformed): that is no bytes.
187
+ */
188
+ fun decodeChunk(data: String): Pair<ByteArray, String> =
189
+ if (data == "data:") ByteArray(0) to "application/octet-stream" else decodeDataUrl(data)
190
+
191
+ /** [text]'s UTF-8 bytes with each `%XX` replaced by the byte XX. The result is not decoded as UTF-8 again. */
192
+ private fun percentDecode(text: String): ByteArray {
193
+ if ('%' !in text) return text.toByteArray() // a blob's chunks: spares two copies of megabytes
194
+ // Latin-1 maps each byte to one char and back, so the escapes are replaced in a string.
195
+ val latin1 = String(text.toByteArray(), Charsets.ISO_8859_1)
196
+ return PERCENT_ESCAPE.replace(latin1) { it.value.substring(1).toInt(16).toChar().toString() }.toByteArray(Charsets.ISO_8859_1)
197
+ }
198
+
199
+ /** `guessFileName` keeps a page's `.` or `..` (a directory: the save fails with EISDIR) and can be empty. */
200
+ fun safeName(name: String) = if (name.isEmpty() || name == "." || name == "..") "download" else name
201
+
202
+ /** Copies [input] to [output] and fails once more than [max] bytes came: the Content-Length can be missing or wrong. */
203
+ fun copyCapped(input: InputStream, output: OutputStream, max: Long) {
204
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
205
+ var total = 0L
206
+ while (true) {
207
+ val read = input.read(buffer)
208
+ if (read < 0) break
209
+ total += read
210
+ if (total > max) throw TooLarge()
211
+ output.write(buffer, 0, read)
212
+ }
213
+ }
214
+
215
+ /** Fetches [download] into [file] and returns its MIME type. [cookie] and [setCookie] are the WebView's cookie store. */
216
+ fun fetchTo(download: DownloadInfo, file: File, cookie: (String) -> String?, setCookie: (String, String) -> Unit): String {
217
+ val connection = connect(URL(download.url), download.userAgent, cookie, setCookie)
218
+ try {
219
+ if (connection.responseCode !in 200..299) throw HttpStatus(connection.responseCode)
220
+ if (connection.contentLengthLong > MAX_BYTES) throw TooLarge()
221
+ connection.inputStream.use { input -> file.outputStream().use { output -> copyCapped(input, output, MAX_BYTES) } }
222
+ return download.mimeType.ifEmpty { connection.contentType?.substringBefore(';') ?: "application/octet-stream" }
223
+ } finally {
224
+ connection.disconnect()
225
+ }
226
+ }
227
+
228
+ /** Whether a download follows a redirect [from] one URL [to] another: only to https, or from http to http. */
229
+ fun redirectAllowed(from: URL, to: URL) = to.protocol == "https" || (to.protocol == "http" && from.protocol == "http")
230
+
231
+ /**
232
+ * Opens [url] and follows its redirects (http to https too) by hand: each hop sends the cookies for its own URL and
233
+ * stores what the server sets back, as React Native's fetch does. A hop must be [redirectAllowed]: Chrome blocks an
234
+ * insecure download started from a secure one.
235
+ */
236
+ private fun connect(url: URL, userAgent: String, cookie: (String) -> String?, setCookie: (String, String) -> Unit): HttpURLConnection {
237
+ var current = url
238
+ repeat(MAX_REDIRECTS + 1) {
239
+ val at = current.toString()
240
+ val connection = current.openConnection() as HttpURLConnection
241
+ connection.instanceFollowRedirects = false
242
+ connection.connectTimeout = TIMEOUT_MS
243
+ connection.readTimeout = TIMEOUT_MS
244
+ connection.setRequestProperty("User-Agent", userAgent)
245
+ cookie(at)?.let { connection.setRequestProperty("Cookie", it) }
246
+ val code = connection.responseCode
247
+ // Header names come in any case (HTTP/2 lowercases them), and headerFields' keys keep it.
248
+ for ((key, values) in connection.headerFields) if (key.equals("Set-Cookie", ignoreCase = true)) values.forEach { setCookie(at, it) }
249
+ val location = connection.getHeaderField("Location")
250
+ if (code !in 300..399 || location == null) return connection
251
+ connection.disconnect()
252
+ val next = URL(current, location)
253
+ if (!redirectAllowed(current, next)) throw IOException("refused a redirect from ${current.protocol} to ${next.protocol}")
254
+ current = next
255
+ }
256
+ throw IOException("more than $MAX_REDIRECTS redirects")
257
+ }
258
+ }
259
+ }