forked from Blendman974/faceclaw
Fixes to EvenHub webview handling
This commit is contained in:
1 parent
f4751ad480
commit
60595d7321
21 files changed
+1001
-142
No files matched your search
@@ -1,32 +1,100 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import androidx.webkit.JavaScriptReplyProxy
|
||||
import androidx.webkit.WebMessageCompat
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
|
||||
/**
|
||||
* The object injected into a hosted EvenHub app's WebView as
|
||||
* window.__faceclawEvenHub. The document-start shim (served inline by
|
||||
* FaceclawEvenHubWebViewClient) wraps it in a promise-returning
|
||||
* window.flutter_inappwebview.callHandler, which is what the EvenHub SDK
|
||||
* actually talks to.
|
||||
* The host end of a hosted EvenHub app's bridge: window.__faceclawEvenHubPort,
|
||||
* a WebMessageListener object that WebView injects only into frames from the
|
||||
* app's own origin. Sites the app navigates to, and other-origin iframes it
|
||||
* embeds, never see it, and messages from the app's own subframes are dropped,
|
||||
* so only the app's main document reaches the host (its SDK storage, sensors,
|
||||
* glasses display and the Faceclaw extensions, API keys included). This
|
||||
* replaced an addJavascriptInterface object, which WebView exposes to every
|
||||
* frame of every page.
|
||||
*
|
||||
* JavascriptInterface methods run on a WebView-internal thread; everything
|
||||
* is bounced to the main thread before touching the NativeScript listener.
|
||||
* The transport script (webview.ts) wraps the port as window.__faceclawEvenHub,
|
||||
* whose postMessage(name, argsJson, id) and wakeTimers() the stock bridge shim
|
||||
* and the extensions call. Messages are JSON arrays: ["call", name, argsJson,
|
||||
* id] or ["wake"].
|
||||
*/
|
||||
class FaceclawEvenHubJsBridge(private val listener: FaceclawEvenHubListener) {
|
||||
class FaceclawEvenHubJsBridge private constructor(
|
||||
private val listener: FaceclawEvenHubListener
|
||||
) : WebViewCompat.WebMessageListener {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
@JavascriptInterface
|
||||
fun postMessage(handlerName: String?, argsJson: String?, callId: Int) {
|
||||
mainHandler.post {
|
||||
listener.onEvenAppMessage(handlerName, argsJson, callId)
|
||||
override fun onPostMessage(
|
||||
view: WebView,
|
||||
message: WebMessageCompat,
|
||||
sourceOrigin: Uri,
|
||||
isMainFrame: Boolean,
|
||||
replyProxy: JavaScriptReplyProxy
|
||||
) {
|
||||
if (!isMainFrame) return
|
||||
val parts = try {
|
||||
JSONArray(message.data ?: return)
|
||||
} catch (e: JSONException) {
|
||||
return
|
||||
}
|
||||
when (parts.optString(0)) {
|
||||
"call" -> {
|
||||
val name = parts.optString(1)
|
||||
val argsJson = parts.optString(2)
|
||||
val callId = parts.optInt(3)
|
||||
mainHandler.post { listener.onEvenAppMessage(name, argsJson, callId) }
|
||||
}
|
||||
// The page's timer shim has work due before the host's next tick.
|
||||
"wake" -> FaceclawEvenHubWebViewHost.getInstance().wakeTimers()
|
||||
}
|
||||
}
|
||||
|
||||
/** The page's timer shim has work due before the host's next tick. */
|
||||
@JavascriptInterface
|
||||
fun wakeTimers() {
|
||||
FaceclawEvenHubWebViewHost.getInstance().wakeTimers()
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
private const val OBJECT_NAME = "__faceclawEvenHubPort"
|
||||
|
||||
/**
|
||||
* The origin rule matching exactly [url]'s origin (default port elided),
|
||||
* or null when it isn't an http(s) URL with a host.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun originRule(url: String): String? {
|
||||
val uri = Uri.parse(url)
|
||||
val scheme = uri.scheme?.lowercase()
|
||||
val host = uri.host?.lowercase()
|
||||
if ((scheme != "http" && scheme != "https") || host.isNullOrEmpty()) return null
|
||||
val defaultPort = if (scheme == "https") 443 else 80
|
||||
return if (uri.port == -1 || uri.port == defaultPort) "$scheme://$host" else "$scheme://$host:${uri.port}"
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose the bridge to [webView]'s frames from [originRule]. Must run
|
||||
* before the WebView loads anything.
|
||||
*
|
||||
* @return null on success, else why the bridge could not be installed.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun install(webView: WebView, originRule: String, listener: FaceclawEvenHubListener): String? {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
|
||||
Log.w(TAG, "WebMessageListener unsupported; not exposing the EvenHub bridge")
|
||||
return "This Android System WebView is too old to run EvenHub apps safely. Update it, then reopen the app."
|
||||
}
|
||||
return try {
|
||||
WebViewCompat.addWebMessageListener(webView, OBJECT_NAME, setOf(originRule), FaceclawEvenHubJsBridge(listener))
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "bridge origin rule rejected: $originRule", e)
|
||||
"The app's address ($originRule) can't be used as a web origin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import androidx.webkit.ProfileStore
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Gives each EvenHub package its own WebView profile, so one app's browser
|
||||
* storage (cookies, localStorage, IndexedDB, caches, service workers) is out of
|
||||
* reach of every other app. That includes the storage of third-party sites an
|
||||
* app navigates to, such as a sign-in provider's session cookies, which in the
|
||||
* shared default profile any other app's WebView could reuse. The per-app fake
|
||||
* origins alone don't cover that, and `*.evenhub.invalid` hosts share a site,
|
||||
* so domain cookies would cross between packaged apps too.
|
||||
*
|
||||
* The profile persists across launches, and is shared by every instance of the
|
||||
* same package, like the iOS per-package WKWebsiteDataStore.
|
||||
*/
|
||||
class FaceclawEvenHubProfile private constructor() {
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
|
||||
/** Stable per package; the hash input matches the iOS data-store identifier's. */
|
||||
@JvmStatic
|
||||
fun nameFor(packageId: String): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest("com.faceclaw.ehpk:$packageId".toByteArray(Charsets.UTF_8))
|
||||
return "evenhub-" + digest.take(16).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a new WebView in [packageId]'s profile. Must run on the main thread
|
||||
* before anything else is done with the WebView.
|
||||
*
|
||||
* @return false when the WebView provider lacks multi-profile support,
|
||||
* leaving the WebView in the shared default profile.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun apply(webView: WebView, packageId: String): Boolean {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) {
|
||||
Log.w(TAG, "multi-profile WebView unsupported; $packageId shares the default profile")
|
||||
return false
|
||||
}
|
||||
val name = nameFor(packageId)
|
||||
ProfileStore.getInstance().getOrCreateProfile(name)
|
||||
WebViewCompat.setProfile(webView, name)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.faceclaw.app
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
@@ -33,6 +34,11 @@ import java.nio.charset.StandardCharsets
|
||||
* The shim is registered as a document-start script instead
|
||||
* (FaceclawEvenHubDocumentStart); injectOnPageStarted is the fallback for
|
||||
* WebView versions that lack that API.
|
||||
*
|
||||
* An app can crash its renderer, or the system can kill it for memory. Unless
|
||||
* every WebView that renderer served handles that, WebView aborts the whole
|
||||
* process, taking Faceclaw down with it; so onRenderProcessGone retires the
|
||||
* affected WebView and reports it instead.
|
||||
*/
|
||||
class FaceclawEvenHubWebViewClient(
|
||||
private val rootDir: String?,
|
||||
@@ -93,6 +99,15 @@ class FaceclawEvenHubWebViewClient(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
// Called on the main thread for each WebView the renderer served. This
|
||||
// one can't be used again: drop it, and the app shows as failed.
|
||||
Log.w(TAG, "renderer gone (crashed=${detail.didCrash()}) for $host")
|
||||
FaceclawEvenHubWebViewHost.getInstance().detach(view)
|
||||
listener.onRenderProcessGone(detail.didCrash())
|
||||
return true
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
|
||||
|
||||
@@ -59,8 +59,8 @@ import java.util.HashMap
|
||||
* requestAnimationFrame) with JS queues fired by window.__fcTick(), and this
|
||||
* host ticks those on the main thread regardless of screen state. The tick
|
||||
* returns when the page next has work, so an idle page isn't evaluated at
|
||||
* 60Hz; work scheduled between ticks wakes the host through
|
||||
* FaceclawEvenHubJsBridge.wakeTimers. The main Looper keeps running under the
|
||||
* 60Hz; work scheduled between ticks wakes the host through the bridge's
|
||||
* "wake" message (FaceclawEvenHubJsBridge). The main Looper keeps running under the
|
||||
* foreground service, so the tick survives the screen turning off. (Matches the
|
||||
* official Even app's approach.)
|
||||
*
|
||||
@@ -105,8 +105,12 @@ class FaceclawEvenHubWebViewHost {
|
||||
* the page wakes it. It also re-ticks after IDLE_POLL_MS regardless, so a
|
||||
* lost evaluateJavascript callback (e.g. mid-navigation) or a page whose
|
||||
* wake didn't reach us stalls its timers for at most that long.
|
||||
*
|
||||
* The tick only runs in the app's own documents ([appCheck], a JS
|
||||
* expression): after a navigation the WebView may show another site.
|
||||
*/
|
||||
private inner class Ticker(private val web: WebView) : Runnable {
|
||||
private inner class Ticker(private val web: WebView, appCheck: String) : Runnable {
|
||||
private val tickJs = "if ($appCheck) { $TICK_JS }"
|
||||
private var inFlight = false
|
||||
private var wakePending = false
|
||||
private var stopped = false
|
||||
@@ -114,7 +118,7 @@ class FaceclawEvenHubWebViewHost {
|
||||
override fun run() {
|
||||
if (stopped) return
|
||||
inFlight = true
|
||||
web.evaluateJavascript(TICK_JS) { result -> onTicked(result) }
|
||||
web.evaluateJavascript(tickJs) { result -> onTicked(result) }
|
||||
schedule(IDLE_POLL_MS)
|
||||
}
|
||||
|
||||
@@ -278,8 +282,11 @@ class FaceclawEvenHubWebViewHost {
|
||||
(web.context as? MutableContextWrapper)?.baseContext = activity
|
||||
}
|
||||
|
||||
/** Add a WebView to the host, full-size and rendering, hidden behind the UI. */
|
||||
fun attach(activity: Activity, web: WebView) {
|
||||
/**
|
||||
* Add a WebView to the host, full-size and rendering, hidden behind the UI.
|
||||
* [appCheck] is a JS expression that is true only in the app's own documents.
|
||||
*/
|
||||
fun attach(activity: Activity, web: WebView, appCheck: String) {
|
||||
ensureOverlay(activity)
|
||||
rebaseContext(web, activity)
|
||||
web.visibility = View.VISIBLE
|
||||
@@ -301,7 +308,7 @@ class FaceclawEvenHubWebViewHost {
|
||||
}
|
||||
if (!webViews.contains(web)) webViews.add(web)
|
||||
if (!tickers.containsKey(web)) {
|
||||
val ticker = Ticker(web)
|
||||
val ticker = Ticker(web, appCheck)
|
||||
tickers[web] = ticker
|
||||
mainHandler.postDelayed(ticker, TICK_MS)
|
||||
}
|
||||
@@ -348,9 +355,9 @@ class FaceclawEvenHubWebViewHost {
|
||||
return shown
|
||||
}
|
||||
|
||||
/** Remove and destroy a WebView (its app is closing). */
|
||||
/** Remove and destroy a WebView (its app is closing, or its renderer is gone). Idempotent. */
|
||||
fun detach(web: WebView) {
|
||||
webViews.remove(web)
|
||||
if (!webViews.remove(web)) return
|
||||
tickers.remove(web)?.stop()
|
||||
stack?.removeView(web)
|
||||
web.destroy()
|
||||
|
||||
Reference in new issue
Block a user