@tokamakdev/platform-android-arm64 0.1.1-beta.100
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.
- package/android-arm64/build/entrypoint +404 -0
- package/android-arm64/build/min-sdk +1 -0
- package/android-arm64/lib/TokamakRuntime/libtokamak.a +4 -0
- package/android-arm64/lib/TokamakRuntime/link-libraries +1 -0
- package/android-arm64/native-shell/app/TokamakActivity.kt +163 -0
- package/android-arm64/native-shell/app/TokamakApplication.kt +221 -0
- package/android-arm64/native-shell/app/TokamakOrigin.kt +9 -0
- package/android-arm64/native-shell/app/TokamakPermissions.kt +78 -0
- package/android-arm64/native-shell/app/TokamakPluginBridge.kt +79 -0
- package/android-arm64/native-shell/app/TokamakPluginRequests.kt +57 -0
- package/android-arm64/native-shell/app/TokamakProxy.kt +65 -0
- package/android-arm64/native-shell/app/TokamakRuntime.kt +155 -0
- package/android-arm64/native-shell/app/TokamakWebChromeClient.kt +54 -0
- package/android-arm64/native-shell/app/TokamakWebViewClient.kt +103 -0
- package/android-arm64/native-shell/plugin/TokamakOwnerAuthentication.kt +73 -0
- package/android-arm64/native-shell/plugin/TokamakPlugin.kt +105 -0
- package/android-arm64/native-shell/plugin/TokamakPluginArguments.kt +23 -0
- package/android-arm64/platform-pack.json +33 -0
- package/package.json +17 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.app.Application
|
|
5
|
+
import android.content.Context
|
|
6
|
+
import android.content.pm.PackageManager
|
|
7
|
+
import android.os.SystemClock
|
|
8
|
+
import android.util.Log
|
|
9
|
+
import androidx.lifecycle.DefaultLifecycleObserver
|
|
10
|
+
import androidx.lifecycle.Lifecycle
|
|
11
|
+
import androidx.lifecycle.LifecycleOwner
|
|
12
|
+
import androidx.lifecycle.ProcessLifecycleOwner
|
|
13
|
+
import java.io.File
|
|
14
|
+
import java.util.concurrent.Executors
|
|
15
|
+
import org.json.JSONTokener
|
|
16
|
+
|
|
17
|
+
private const val HOST_METADATA = "tokamak.host"
|
|
18
|
+
private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
|
|
19
|
+
private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
|
|
20
|
+
|
|
21
|
+
/** How long the Worker has for `resume` and `suspend`. */
|
|
22
|
+
private const val LIFECYCLE_DEADLINE_MILLIS = 10_000L
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The tokamak process. Owns the runtime and native plugins, which outlive any activity, so a
|
|
26
|
+
* plugin can run Worker code when the system starts the app in the background.
|
|
27
|
+
*/
|
|
28
|
+
class TokamakApplication : Application(), TokamakPlugins {
|
|
29
|
+
/** The app's activity, or null while it has none. */
|
|
30
|
+
@Volatile
|
|
31
|
+
var activity: Activity? = null
|
|
32
|
+
|
|
33
|
+
/** Every plugin, by ID. */
|
|
34
|
+
val plugins: Map<String, TokamakPlugin> by lazy {
|
|
35
|
+
buildMap {
|
|
36
|
+
tokamakPlugins(this@TokamakApplication).forEach { plugin ->
|
|
37
|
+
check(put(plugin.id, plugin) == null) { "Duplicate plugin ID" }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
internal val permissionRequests = TokamakPermissions(this)
|
|
43
|
+
|
|
44
|
+
private val started = lazy(::startRuntime)
|
|
45
|
+
|
|
46
|
+
/** The running runtime, started on first use. Blocks while it starts. */
|
|
47
|
+
internal val runtime: TokamakRuntime by started
|
|
48
|
+
|
|
49
|
+
/** The Worker's calls and subscriptions on the plugins. Main thread only. */
|
|
50
|
+
private val workerRequests by lazy {
|
|
51
|
+
TokamakPluginRequests<Long>(plugins) { id, result -> runtime.reply(id, result.toString()) }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The plugins as the runtime calls them, on its own threads. */
|
|
55
|
+
private val workerPlugins =
|
|
56
|
+
object : TokamakRuntime.Plugins {
|
|
57
|
+
override fun call(id: Long, plugin: String, method: String, arguments: String) =
|
|
58
|
+
mainExecutor.execute { workerRequests.run(id, false, plugin, method, parse(arguments)) }
|
|
59
|
+
|
|
60
|
+
override fun subscribe(id: Long, plugin: String, method: String, arguments: String) =
|
|
61
|
+
mainExecutor.execute { workerRequests.run(id, true, plugin, method, parse(arguments)) }
|
|
62
|
+
|
|
63
|
+
override fun unsubscribe(id: Long) = mainExecutor.execute { workerRequests.cancel(id) }
|
|
64
|
+
|
|
65
|
+
private fun parse(arguments: String): Any? = JSONTokener(arguments).nextValue()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The host of the app origin, `https://<appHost>`. */
|
|
69
|
+
val appHost: String by lazy {
|
|
70
|
+
requireNotNull(metadata()?.getString(HOST_METADATA)) { "$HOST_METADATA is required" }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Delivers `resume` and `suspend` one at a time, in order. */
|
|
74
|
+
private val lifecycle = Executors.newSingleThreadExecutor()
|
|
75
|
+
|
|
76
|
+
override fun onCreate() {
|
|
77
|
+
super.onCreate()
|
|
78
|
+
ProcessLifecycleOwner.get().lifecycle.addObserver(
|
|
79
|
+
object : DefaultLifecycleObserver {
|
|
80
|
+
override fun onStart(owner: LifecycleOwner) = moved(foreground = true)
|
|
81
|
+
|
|
82
|
+
override fun onStop(owner: LifecycleOwner) = moved(foreground = false)
|
|
83
|
+
},
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
override fun plugin(id: String): TokamakPlugin? = plugins[id]
|
|
88
|
+
|
|
89
|
+
/** The host the plugin [id] sees, whose events the Worker's listeners receive as `<id>.<name>`. */
|
|
90
|
+
internal fun host(id: String): TokamakHost =
|
|
91
|
+
object : TokamakHost {
|
|
92
|
+
override val context: Context
|
|
93
|
+
get() = this@TokamakApplication
|
|
94
|
+
|
|
95
|
+
override val activity: Activity?
|
|
96
|
+
get() = this@TokamakApplication.activity
|
|
97
|
+
|
|
98
|
+
override val isInForeground: Boolean
|
|
99
|
+
get() = this@TokamakApplication.isInForeground
|
|
100
|
+
|
|
101
|
+
override fun requireForegroundActivity(): Activity =
|
|
102
|
+
this@TokamakApplication.requireForegroundActivity()
|
|
103
|
+
|
|
104
|
+
override fun wouldPrompt(permission: String): Boolean =
|
|
105
|
+
permissionRequests.wouldPrompt(permission)
|
|
106
|
+
|
|
107
|
+
override fun requestPermissions(
|
|
108
|
+
permissions: Set<String>,
|
|
109
|
+
callback: (Map<String, Boolean>) -> Unit,
|
|
110
|
+
) = permissionRequests.request(permissions, callback)
|
|
111
|
+
|
|
112
|
+
override fun emit(name: String, event: String, timeoutMillis: Long): String =
|
|
113
|
+
emitEvent("$id.$name", event, timeoutMillis)
|
|
114
|
+
|
|
115
|
+
override fun fetch(path: String, timeoutMillis: Long): ByteArray {
|
|
116
|
+
val deadline = SystemClock.elapsedRealtime() + timeoutMillis
|
|
117
|
+
val started = runtime
|
|
118
|
+
return started.fetch(path, deadline - SystemClock.elapsedRealtime())
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The activity to show UI in; throws `NeedsUIError` while the app is in the background. */
|
|
123
|
+
internal fun requireForegroundActivity(): Activity =
|
|
124
|
+
activity?.takeIf { isInForeground } ?: throw TokamakPluginError.needsUI()
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Whether the app is in the foreground, as the runtime records it, or until the runtime has
|
|
128
|
+
* started, whether an activity exists to start it in the foreground.
|
|
129
|
+
*/
|
|
130
|
+
private val isInForeground: Boolean
|
|
131
|
+
get() = if (started.isInitialized()) runtime.isForeground else activity != null
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Delivers the event [name] with the JSON [event] to the Worker's listeners and returns their
|
|
135
|
+
* reply as JSON. Starts the runtime when it is not running. Blocks.
|
|
136
|
+
*/
|
|
137
|
+
private fun emitEvent(name: String, event: String, timeoutMillis: Long): String {
|
|
138
|
+
val deadline = SystemClock.elapsedRealtime() + timeoutMillis
|
|
139
|
+
val started = runtime
|
|
140
|
+
return started.emit(name, event, deadline - SystemClock.elapsedRealtime())
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Records the app moving into or out of the foreground, once the runtime has started. */
|
|
144
|
+
private fun moved(foreground: Boolean) {
|
|
145
|
+
if (started.isInitialized()) record(runtime, foreground)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Records [foreground] in [runtime], delivering `resume` or `suspend` when it changed. */
|
|
149
|
+
private fun record(runtime: TokamakRuntime, foreground: Boolean) {
|
|
150
|
+
if (!runtime.setForeground(foreground)) return
|
|
151
|
+
val name = if (foreground) "resume" else "suspend"
|
|
152
|
+
lifecycle.execute {
|
|
153
|
+
runCatching { runtime.emit(name, "{}", LIFECYCLE_DEADLINE_MILLIS) }
|
|
154
|
+
.onFailure { Log.w("tokamak", "tokamak $name failed", it) }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Starts the runtime, which delivers `start` in the foreground when an activity started it,
|
|
160
|
+
* then records where the app has moved since.
|
|
161
|
+
*/
|
|
162
|
+
private fun startRuntime(): TokamakRuntime {
|
|
163
|
+
val metadata = metadata()
|
|
164
|
+
val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
|
|
165
|
+
val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
|
|
166
|
+
val startsInForeground = activity != null
|
|
167
|
+
val runtime =
|
|
168
|
+
if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
|
|
169
|
+
TokamakRuntime.startDevelopment(
|
|
170
|
+
stateDir(), appHost, endpoint, sessionToken, startsInForeground, workerPlugins,
|
|
171
|
+
)
|
|
172
|
+
} else {
|
|
173
|
+
TokamakRuntime.start(unpackApp(), stateDir(), storageDir(), appHost, startsInForeground, workerPlugins)
|
|
174
|
+
}
|
|
175
|
+
mainExecutor.execute {
|
|
176
|
+
record(runtime, ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
|
|
177
|
+
}
|
|
178
|
+
return runtime
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private fun metadata() =
|
|
182
|
+
packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA).metaData
|
|
183
|
+
|
|
184
|
+
/** Copy the packaged app out of the APK once per install, so the runtime can read it as files. */
|
|
185
|
+
private fun unpackApp(): File {
|
|
186
|
+
val app = File(noBackupFilesDir, "tokamak/app")
|
|
187
|
+
val unpacked = File(noBackupFilesDir, "tokamak/app.installed")
|
|
188
|
+
val installed = packageManager.getPackageInfo(packageName, 0).lastUpdateTime.toString()
|
|
189
|
+
if (unpacked.isFile && unpacked.readText() == installed) return app
|
|
190
|
+
app.deleteRecursively()
|
|
191
|
+
copyAsset("app", app)
|
|
192
|
+
unpacked.writeText(installed)
|
|
193
|
+
return app
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private fun copyAsset(source: String, destination: File) {
|
|
197
|
+
val entries = assets.list(source) ?: emptyArray()
|
|
198
|
+
if (entries.isEmpty()) {
|
|
199
|
+
destination.parentFile?.mkdirs()
|
|
200
|
+
assets.open(source).use { input ->
|
|
201
|
+
destination.outputStream().use(input::copyTo)
|
|
202
|
+
}
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
destination.mkdirs()
|
|
206
|
+
for (entry in entries) copyAsset("$source/$entry", File(destination, entry))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Runtime state, which backups leave out. */
|
|
210
|
+
private fun stateDir(): File = File(noBackupFilesDir, "tokamak/state").apply { mkdirs() }
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Stores behind storage bindings, which Auto Backup includes. tokamak keeps nothing else in the
|
|
214
|
+
* files directory, so everything else under `tokamak` there is removed.
|
|
215
|
+
*/
|
|
216
|
+
private fun storageDir(): File {
|
|
217
|
+
val root = File(filesDir, "tokamak")
|
|
218
|
+
root.listFiles()?.filter { it.name != "storage" }?.forEach { it.deleteRecursively() }
|
|
219
|
+
return File(root, "storage").apply { mkdirs() }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import android.net.Uri
|
|
4
|
+
|
|
5
|
+
/** Whether this URI is on the app origin, `https://<appHost>`. */
|
|
6
|
+
internal fun Uri.isAppOrigin(appHost: String): Boolean =
|
|
7
|
+
scheme.equals("https", ignoreCase = true) &&
|
|
8
|
+
host.equals(appHost, ignoreCase = true) &&
|
|
9
|
+
(port == -1 || port == 443)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.content.pm.PackageManager
|
|
5
|
+
|
|
6
|
+
private const val PREFERENCES = "tokamak.permissions"
|
|
7
|
+
private const val REFUSED = "refused"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Asks for runtime permissions in the app's activity one request at a time, as Android cancels a
|
|
11
|
+
* request made while another shows. Remembers the permissions the user has refused for good, as
|
|
12
|
+
* Android reports them the same way as permissions never asked for. Use it on the main thread.
|
|
13
|
+
*/
|
|
14
|
+
internal class TokamakPermissions(private val app: TokamakApplication) {
|
|
15
|
+
private class Request(val permissions: Set<String>, val callback: (Map<String, Boolean>) -> Unit)
|
|
16
|
+
|
|
17
|
+
private val queue = ArrayDeque<Request>()
|
|
18
|
+
private val preferences by lazy { app.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) }
|
|
19
|
+
|
|
20
|
+
/** Identifies the request showing, the head of [queue]. */
|
|
21
|
+
private var requestCode = 0
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Asks for [permissions], then passes [callback] whether each is granted. Answers at once when
|
|
25
|
+
* none would prompt; throws `NeedsUIError` when one would while the app is in the background.
|
|
26
|
+
*/
|
|
27
|
+
fun request(permissions: Set<String>, callback: (Map<String, Boolean>) -> Unit) {
|
|
28
|
+
val request = Request(permissions, callback)
|
|
29
|
+
if (permissions.none(::wouldPrompt)) return answer(request)
|
|
30
|
+
app.requireForegroundActivity()
|
|
31
|
+
queue.addLast(request)
|
|
32
|
+
if (queue.size == 1) askNext()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether asking for [permission] shows the system prompt. */
|
|
36
|
+
fun wouldPrompt(permission: String): Boolean =
|
|
37
|
+
!isGranted(permission) &&
|
|
38
|
+
(app.activity?.shouldShowRequestPermissionRationale(permission) == true || permission !in refused())
|
|
39
|
+
|
|
40
|
+
fun onRequestPermissionsResult(requestCode: Int) {
|
|
41
|
+
if (requestCode != this.requestCode || queue.isEmpty()) return
|
|
42
|
+
val answered = queue.removeFirst()
|
|
43
|
+
remember(answered.permissions)
|
|
44
|
+
askNext()
|
|
45
|
+
answer(answered)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Ends every request, answering with the permissions' current state. */
|
|
49
|
+
fun cancel() {
|
|
50
|
+
requestCode += 1
|
|
51
|
+
val cancelled = queue.toList()
|
|
52
|
+
queue.clear()
|
|
53
|
+
cancelled.forEach(::answer)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private fun askNext() {
|
|
57
|
+
val request = queue.firstOrNull() ?: return
|
|
58
|
+
val activity = app.activity ?: return cancel()
|
|
59
|
+
requestCode += 1
|
|
60
|
+
activity.requestPermissions(request.permissions.toTypedArray(), requestCode)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Records which of the answered [permissions] the user refused for good. */
|
|
64
|
+
private fun remember(permissions: Set<String>) {
|
|
65
|
+
val activity = app.activity ?: return
|
|
66
|
+
val refusedForGood =
|
|
67
|
+
permissions.filter { !isGranted(it) && !activity.shouldShowRequestPermissionRationale(it) }
|
|
68
|
+
preferences.edit().putStringSet(REFUSED, refused() - permissions + refusedForGood).apply()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private fun answer(request: Request) =
|
|
72
|
+
request.callback(request.permissions.associateWith(::isGranted))
|
|
73
|
+
|
|
74
|
+
private fun refused(): Set<String> = preferences.getStringSet(REFUSED, null).orEmpty()
|
|
75
|
+
|
|
76
|
+
private fun isGranted(permission: String): Boolean =
|
|
77
|
+
app.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
|
78
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.net.Uri
|
|
5
|
+
import android.webkit.WebView
|
|
6
|
+
import androidx.webkit.JavaScriptReplyProxy
|
|
7
|
+
import androidx.webkit.WebMessageCompat
|
|
8
|
+
import androidx.webkit.WebViewCompat
|
|
9
|
+
import org.json.JSONObject
|
|
10
|
+
|
|
11
|
+
/** Carries calls and subscriptions between the page and the app's plugins. */
|
|
12
|
+
internal class TokamakPluginBridge(
|
|
13
|
+
private val activity: Activity,
|
|
14
|
+
private val host: String,
|
|
15
|
+
plugins: Map<String, TokamakPlugin>,
|
|
16
|
+
) : WebViewCompat.WebMessageListener {
|
|
17
|
+
private data class RequestKey(val session: String, val id: Int)
|
|
18
|
+
|
|
19
|
+
private val requests = TokamakPluginRequests<RequestKey>(plugins, ::send)
|
|
20
|
+
private var activeSession: String? = null
|
|
21
|
+
private var replyProxy: JavaScriptReplyProxy? = null
|
|
22
|
+
|
|
23
|
+
fun install(webView: WebView) {
|
|
24
|
+
WebViewCompat.addWebMessageListener(
|
|
25
|
+
webView,
|
|
26
|
+
"__tokamakNative",
|
|
27
|
+
setOf("https://$host"),
|
|
28
|
+
this,
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
fun close() {
|
|
33
|
+
activeSession = null
|
|
34
|
+
replyProxy = null
|
|
35
|
+
requests.cancelAll()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
override fun onPostMessage(
|
|
39
|
+
view: WebView,
|
|
40
|
+
message: WebMessageCompat,
|
|
41
|
+
sourceOrigin: Uri,
|
|
42
|
+
isMainFrame: Boolean,
|
|
43
|
+
replyProxy: JavaScriptReplyProxy,
|
|
44
|
+
) {
|
|
45
|
+
if (!isMainFrame || !sourceOrigin.isAppOrigin(host)) return
|
|
46
|
+
val request = runCatching { JSONObject(message.data ?: return) }.getOrNull() ?: return
|
|
47
|
+
val session = request.optString("session")
|
|
48
|
+
if (session.isEmpty()) return
|
|
49
|
+
val type = request.optString("type")
|
|
50
|
+
if (type == "reset") {
|
|
51
|
+
close()
|
|
52
|
+
activeSession = session
|
|
53
|
+
this.replyProxy = replyProxy
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
val id = request.optInt("id", -1)
|
|
57
|
+
if (id < 0) return
|
|
58
|
+
val key = RequestKey(session, id)
|
|
59
|
+
when (type) {
|
|
60
|
+
"cancel" -> requests.cancel(key)
|
|
61
|
+
"call", "subscribe" ->
|
|
62
|
+
requests.run(
|
|
63
|
+
key,
|
|
64
|
+
type == "subscribe",
|
|
65
|
+
request.optString("plugin"),
|
|
66
|
+
request.optString("method"),
|
|
67
|
+
request.opt("arguments"),
|
|
68
|
+
)
|
|
69
|
+
else -> requests.fail(key, TokamakPluginError.notSupported("Plugin operation is not supported"))
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Passes [result] to the page that made the request [key], if it is still loaded. */
|
|
74
|
+
private fun send(key: RequestKey, result: JSONObject) =
|
|
75
|
+
activity.runOnUiThread {
|
|
76
|
+
if (activeSession != key.session) return@runOnUiThread
|
|
77
|
+
replyProxy?.postMessage(result.put("session", key.session).put("id", key.id).toString())
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import org.json.JSONObject
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Runs one caller's calls and subscriptions, the page's or the Worker's, on the app's plugins,
|
|
7
|
+
* keyed by [K]. [send] receives each result, on the thread the plugin replies on, as the JSON
|
|
8
|
+
* object the page's native transport receives without its session and ID. Use it on the main
|
|
9
|
+
* thread.
|
|
10
|
+
*/
|
|
11
|
+
internal class TokamakPluginRequests<K>(
|
|
12
|
+
private val plugins: Map<String, TokamakPlugin>,
|
|
13
|
+
private val send: (K, JSONObject) -> Unit,
|
|
14
|
+
) {
|
|
15
|
+
private val cancellations = mutableMapOf<K, () -> Unit>()
|
|
16
|
+
|
|
17
|
+
/** Calls [method] of [plugin], or subscribes to it when [subscribe]. */
|
|
18
|
+
fun run(key: K, subscribe: Boolean, plugin: String, method: String, arguments: Any?) {
|
|
19
|
+
val target = plugins[plugin]
|
|
20
|
+
if (target == null || method.isEmpty()) {
|
|
21
|
+
fail(key, TokamakPluginError.notSupported("Plugin is not supported"))
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
val reply: TokamakPluginReply = { result -> send(key, result(result, done = !subscribe)) }
|
|
25
|
+
try {
|
|
26
|
+
if (subscribe) {
|
|
27
|
+
cancellations[key] = target.subscribe(method, arguments, reply)
|
|
28
|
+
} else {
|
|
29
|
+
target.call(method, arguments, reply)
|
|
30
|
+
}
|
|
31
|
+
} catch (error: Exception) {
|
|
32
|
+
fail(key, error)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Ends the request [key] with [error]. */
|
|
37
|
+
fun fail(key: K, error: Throwable) = send(key, result(Result.failure(error), done = true))
|
|
38
|
+
|
|
39
|
+
/** Ends the subscription [key]. */
|
|
40
|
+
fun cancel(key: K) {
|
|
41
|
+
cancellations.remove(key)?.invoke()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Ends every subscription. */
|
|
45
|
+
fun cancelAll() {
|
|
46
|
+
val cancelAll = cancellations.values.toList()
|
|
47
|
+
cancellations.clear()
|
|
48
|
+
cancelAll.forEach { it() }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private fun result(result: Result<Any?>, done: Boolean): JSONObject {
|
|
52
|
+
val json = JSONObject().put("done", done)
|
|
53
|
+
val error = result.exceptionOrNull() ?: return json.put("value", JSONObject.wrap(result.getOrNull()))
|
|
54
|
+
val name = (error as? TokamakPluginError)?.errorName ?: "OperationError"
|
|
55
|
+
return json.put("error", JSONObject().put("name", name).put("message", error.message ?: error.javaClass.name))
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import androidx.webkit.ProxyConfig
|
|
4
|
+
import androidx.webkit.ProxyController
|
|
5
|
+
|
|
6
|
+
internal object TokamakProxy {
|
|
7
|
+
private var active: Request? = null
|
|
8
|
+
private var desired: Request? = null
|
|
9
|
+
private var changing = false
|
|
10
|
+
|
|
11
|
+
fun acquire(activity: TokamakActivity, host: String, port: Int) {
|
|
12
|
+
desired = Request(activity, host, port)
|
|
13
|
+
reconcile()
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
fun release(activity: TokamakActivity) {
|
|
17
|
+
if (desired?.activity === activity) desired = null
|
|
18
|
+
reconcile()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
private fun reconcile() {
|
|
22
|
+
if (changing || active === desired) return
|
|
23
|
+
val current = active
|
|
24
|
+
if (current != null) {
|
|
25
|
+
clear(current)
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
desired?.let(::set)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private fun clear(request: Request) {
|
|
32
|
+
changing = true
|
|
33
|
+
ProxyController.getInstance().clearProxyOverride(request.activity.mainExecutor) {
|
|
34
|
+
active = null
|
|
35
|
+
changing = false
|
|
36
|
+
reconcile()
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private fun set(request: Request) {
|
|
41
|
+
changing = true
|
|
42
|
+
ProxyController.getInstance().setProxyOverride(
|
|
43
|
+
proxyConfig(request),
|
|
44
|
+
request.activity.mainExecutor,
|
|
45
|
+
) {
|
|
46
|
+
active = request
|
|
47
|
+
changing = false
|
|
48
|
+
if (desired === request) request.activity.proxyReady()
|
|
49
|
+
reconcile()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private fun proxyConfig(request: Request): ProxyConfig =
|
|
54
|
+
ProxyConfig.Builder()
|
|
55
|
+
.addProxyRule("http://127.0.0.1:${request.port}")
|
|
56
|
+
.addBypassRule(request.host)
|
|
57
|
+
.setReverseBypassEnabled(true)
|
|
58
|
+
.build()
|
|
59
|
+
|
|
60
|
+
private class Request(
|
|
61
|
+
val activity: TokamakActivity,
|
|
62
|
+
val host: String,
|
|
63
|
+
val port: Int,
|
|
64
|
+
)
|
|
65
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
package com.tokamak.runtime
|
|
2
|
+
|
|
3
|
+
import java.io.File
|
|
4
|
+
|
|
5
|
+
/** The tokamak runtime, running for the life of the process. */
|
|
6
|
+
internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
7
|
+
/**
|
|
8
|
+
* The app's plugins, which the Worker calls. The runtime calls these methods on its own
|
|
9
|
+
* threads, and each call or subscription is answered with [reply]: once for a call, and once
|
|
10
|
+
* per value for a subscription.
|
|
11
|
+
*/
|
|
12
|
+
interface Plugins {
|
|
13
|
+
fun call(id: Long, plugin: String, method: String, arguments: String)
|
|
14
|
+
|
|
15
|
+
fun subscribe(id: Long, plugin: String, method: String, arguments: String)
|
|
16
|
+
|
|
17
|
+
fun unsubscribe(id: Long)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The loopback port the gateway bound. */
|
|
21
|
+
val port: Int
|
|
22
|
+
get() = nativePort(handle)
|
|
23
|
+
|
|
24
|
+
fun restoreGateway(): Int = nativeRestoreGateway(handle)
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Delivers the event [name] with the JSON [event] to the Worker's listeners, blocking until
|
|
28
|
+
* they return or [timeoutMillis] passes, and returns their reply as JSON.
|
|
29
|
+
*/
|
|
30
|
+
fun emit(name: String, event: String, timeoutMillis: Long): String =
|
|
31
|
+
nativeEmit(handle, name, event, timeoutMillis)
|
|
32
|
+
|
|
33
|
+
/** What the app serves at [path], blocking until it arrives or [timeoutMillis] passes. */
|
|
34
|
+
fun fetch(path: String, timeoutMillis: Long): ByteArray = nativeFetch(handle, path, timeoutMillis)
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Records whether the app is in the foreground, which the Worker's `getLifecycleStage()`
|
|
38
|
+
* reports from then on, and returns whether that changed.
|
|
39
|
+
*/
|
|
40
|
+
fun setForeground(foreground: Boolean): Boolean = nativeSetForeground(handle, foreground)
|
|
41
|
+
|
|
42
|
+
/** Whether the app is in the foreground, as last recorded. */
|
|
43
|
+
val isForeground: Boolean
|
|
44
|
+
get() = nativeIsForeground(handle)
|
|
45
|
+
|
|
46
|
+
/** Passes a plugin's JSON [result] to the Worker's call or subscription [id]. */
|
|
47
|
+
fun reply(id: Long, result: String) = nativeReply(handle, id, result)
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The authority a server certificate for [host] must chain to, or null
|
|
51
|
+
* when tokamak does not vouch for the host.
|
|
52
|
+
*/
|
|
53
|
+
fun serverAuthority(host: String): ByteArray? = nativeServerAuthority(handle, host)
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The client certificate and PKCS#8 private key, both DER, to present for
|
|
57
|
+
* [host]. Null when tokamak cannot authenticate the connection.
|
|
58
|
+
*/
|
|
59
|
+
fun clientIdentity(host: String, previousFailures: Int): Array<ByteArray>? =
|
|
60
|
+
nativeClientIdentity(handle, host, previousFailures)
|
|
61
|
+
|
|
62
|
+
companion object {
|
|
63
|
+
init {
|
|
64
|
+
System.loadLibrary("tokamak")
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Start the runtime, which delivers `start` with [foreground] and whose Worker calls
|
|
69
|
+
* [plugins], throwing when it cannot serve the app.
|
|
70
|
+
*/
|
|
71
|
+
fun start(
|
|
72
|
+
packagedDir: File,
|
|
73
|
+
stateDir: File,
|
|
74
|
+
storageDir: File,
|
|
75
|
+
host: String,
|
|
76
|
+
foreground: Boolean,
|
|
77
|
+
plugins: Plugins,
|
|
78
|
+
): TokamakRuntime =
|
|
79
|
+
TokamakRuntime(
|
|
80
|
+
nativeStart(packagedDir.path, stateDir.path, storageDir.path, host, foreground, plugins),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Start the runtime against a host development server, delivering `start` with
|
|
85
|
+
* [foreground], whose development Worker calls [plugins].
|
|
86
|
+
*/
|
|
87
|
+
fun startDevelopment(
|
|
88
|
+
stateDir: File,
|
|
89
|
+
host: String,
|
|
90
|
+
endpoint: String,
|
|
91
|
+
sessionToken: String,
|
|
92
|
+
foreground: Boolean,
|
|
93
|
+
plugins: Plugins,
|
|
94
|
+
): TokamakRuntime =
|
|
95
|
+
TokamakRuntime(
|
|
96
|
+
nativeStartDevelopment(stateDir.path, host, endpoint, sessionToken, foreground, plugins),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@JvmStatic
|
|
100
|
+
private external fun nativeStart(
|
|
101
|
+
packagedDir: String,
|
|
102
|
+
stateDir: String,
|
|
103
|
+
storageDir: String,
|
|
104
|
+
host: String,
|
|
105
|
+
foreground: Boolean,
|
|
106
|
+
plugins: Plugins,
|
|
107
|
+
): Long
|
|
108
|
+
|
|
109
|
+
@JvmStatic
|
|
110
|
+
private external fun nativeStartDevelopment(
|
|
111
|
+
stateDir: String,
|
|
112
|
+
host: String,
|
|
113
|
+
endpoint: String,
|
|
114
|
+
sessionToken: String,
|
|
115
|
+
foreground: Boolean,
|
|
116
|
+
plugins: Plugins,
|
|
117
|
+
): Long
|
|
118
|
+
|
|
119
|
+
@JvmStatic
|
|
120
|
+
private external fun nativeSetForeground(handle: Long, foreground: Boolean): Boolean
|
|
121
|
+
|
|
122
|
+
@JvmStatic
|
|
123
|
+
private external fun nativeIsForeground(handle: Long): Boolean
|
|
124
|
+
|
|
125
|
+
@JvmStatic
|
|
126
|
+
private external fun nativeReply(handle: Long, id: Long, result: String)
|
|
127
|
+
|
|
128
|
+
@JvmStatic
|
|
129
|
+
private external fun nativePort(handle: Long): Int
|
|
130
|
+
|
|
131
|
+
@JvmStatic
|
|
132
|
+
private external fun nativeRestoreGateway(handle: Long): Int
|
|
133
|
+
|
|
134
|
+
@JvmStatic
|
|
135
|
+
private external fun nativeEmit(
|
|
136
|
+
handle: Long,
|
|
137
|
+
name: String,
|
|
138
|
+
event: String,
|
|
139
|
+
timeoutMillis: Long,
|
|
140
|
+
): String
|
|
141
|
+
|
|
142
|
+
@JvmStatic
|
|
143
|
+
private external fun nativeFetch(handle: Long, path: String, timeoutMillis: Long): ByteArray
|
|
144
|
+
|
|
145
|
+
@JvmStatic
|
|
146
|
+
private external fun nativeServerAuthority(handle: Long, host: String): ByteArray?
|
|
147
|
+
|
|
148
|
+
@JvmStatic
|
|
149
|
+
private external fun nativeClientIdentity(
|
|
150
|
+
handle: Long,
|
|
151
|
+
host: String,
|
|
152
|
+
previousFailures: Int,
|
|
153
|
+
): Array<ByteArray>?
|
|
154
|
+
}
|
|
155
|
+
}
|