Skip to content

Commit

Permalink
Update ChromeXt front-end APIs
Browse files Browse the repository at this point in the history
Use less keywords for ChromeXt actions
  • Loading branch information
JingMatrix committed Jul 22, 2023
1 parent 165f297 commit 86eed09
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 60 deletions.
15 changes: 10 additions & 5 deletions app/src/main/assets/local_script.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ function GM_bootstrap() {
return;
}
let match;
while ((match = row.exec(GM_info.scriptMetaStr)) !== null) {
while ((match = row.exec(GM_info.scriptMetaStr.trim())) !== null) {
if (meta[match[1]]) {
if (typeof meta[match[1]] == "string") meta[match[1]] = [meta[match[1]]];
meta[match[1]].push(match[2]);
Expand Down Expand Up @@ -181,14 +181,14 @@ function runScript(meta) {
const detail = JSON.stringify({
detail: { uuid, id: GM_info.script.id },
});
script += `\nwindow.dispatchEvent(new CustomEvent('unsafe-eval', ${detail}));`;
script += `\nwindow.dispatchEvent(new CustomEvent('unsafe_eval', ${detail}));`;
ChromeXt(
JSON.stringify({
action: "unsafe-eval",
action: "unsafeEval",
payload: script,
})
);
await promiseListenerFactory("unsafe-eval", uuid);
await promiseListenerFactory("unsafe_eval", uuid);
}
}
meta.sync_code();
Expand Down Expand Up @@ -511,7 +511,12 @@ function GM_xmlhttpRequest(details) {

return {
abort: () => {
ChromeXt(JSON.stringify({ action: "abortRequest", payload: uuid }));
ChromeXt(
JSON.stringify({
action: "xmlhttpRequest",
payload: { uuid, abort: true },
})
);
},
};
}
Expand Down
100 changes: 48 additions & 52 deletions app/src/main/java/org/matrix/chromext/Listener.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,9 @@ object Listener {
val devToolClients = mutableMapOf<Pair<String, String>, Pair<DevToolClient, DevToolClient>>()
val allowedActions =
mapOf(
"front-end" to
listOf(
"inspectPages", "getIds", "getMeta", "updateMeta", "deleteScript", "extension"),
"front-end" to listOf("inspect_pages", "userscript", "extension"),
"devtools" to listOf("websocket"))

private fun parseArray(str: String): Array<String> {
val result = mutableListOf<String>()
val array = JSONArray(str)
for (i in 0 until array.length()) {
result.add(array.getString(i))
}
return result.toTypedArray()
}

private fun syncSharedPreference(
payload: String,
item: String,
Expand Down Expand Up @@ -100,8 +89,8 @@ object Listener {
}
}
}
"unsafe-eval" -> {
Chrome.evaluateJavascript(listOf(payload))
"unsafeEval" -> {
callback = payload
}
"scriptStorage" -> {
val detail = JSONObject(payload)
Expand Down Expand Up @@ -129,18 +118,18 @@ object Listener {
script.storage!!.remove(key)
}
}
"abortRequest" -> {
val uuid = payload.toDouble()
xmlhttpRequests.get(uuid)?.abort()
}
"xmlhttpRequest" -> {
val detail = JSONObject(payload)
val uuid = detail.getDouble("uuid")
val request =
XMLHttpRequest(
detail.getString("id"), detail.getJSONObject("request"), uuid, currentTab)
xmlhttpRequests.put(uuid, request)
thread { request.send() }
if (detail.optBoolean("abort")) {
xmlhttpRequests.get(uuid)?.abort()
} else {
val request =
XMLHttpRequest(
detail.getString("id"), detail.getJSONObject("request"), uuid, currentTab)
xmlhttpRequests.put(uuid, request)
thread { request.send() }
}
}
"userAgentSpoof" -> {
val loadUrlParams = UserScriptProxy.newLoadUrlParams(payload)
Expand Down Expand Up @@ -179,40 +168,47 @@ object Listener {
Chrome.evaluateJavascript(listOf(code), currentTab)
}
}
"getIds" -> {
val result = JSONArray()
ScriptDbManager.scripts.forEach { result.put(it.id) }
callback = "window.dispatchEvent(new CustomEvent('script_id', {detail: ${result}}));"
}
"getMeta" -> {
val ids = parseArray(payload)
val result = JSONArray()
ScriptDbManager.scripts.filter { ids.contains(it.id) }.forEach { result.put(it.meta) }
callback = "window.dispatchEvent(new CustomEvent('script_meta', {detail: ${result}}));"
}
"updateMeta" -> {
val data = JSONObject(payload)
val script = ScriptDbManager.scripts.filter { it.id == data.getString("id") }.first()
val newScript =
parseScript(data.getString("meta") + script.code, script.storage?.toString())!!
ScriptDbManager.insert(newScript)
ScriptDbManager.scripts.remove(script)
ScriptDbManager.scripts.add(newScript)
}
"deleteScript" -> {
val ids = parseArray(payload)
val dbHelper = ScriptDbHelper(Chrome.getContext())
val db = dbHelper.writableDatabase
db.delete("script", "id = ?", ids)
ScriptDbManager.scripts.removeAll(ScriptDbManager.scripts.filter { ids.contains(it.id) })
dbHelper.close()
"userscript" -> {
if (payload == "") {
val detail = JSONObject(mapOf("type" to "init"))
detail.put("ids", JSONArray(ScriptDbManager.scripts.map { it.id }))
callback = "window.dispatchEvent(new CustomEvent('userscript', {detail: ${detail}}));"
} else {
val data = JSONObject(payload)
if (data.has("meta")) {
val script = ScriptDbManager.scripts.filter { it.id == data.getString("id") }.first()
val newScript =
parseScript(data.getString("meta") + script.code, script.storage?.toString())
if (newScript != null) {
ScriptDbManager.insert(newScript)
ScriptDbManager.scripts.remove(script)
ScriptDbManager.scripts.add(newScript)
} else {
callback = "alert('Fail to update script metadata');"
}
} else if (data.has("ids")) {
val jsonArray = data.getJSONArray("ids")
val ids = Array(jsonArray.length()) { jsonArray.getString(it) }
val scripts = ScriptDbManager.scripts.filter { ids.contains(it.id) }
if (data.optBoolean("delete")) {
val dbHelper = ScriptDbHelper(Chrome.getContext())
val db = dbHelper.writableDatabase
db.delete("script", "id = ?", ids)
ScriptDbManager.scripts.removeAll(scripts)
dbHelper.close()
} else {
val result = JSONArray(scripts.map { it.meta })
callback =
"window.dispatchEvent(new CustomEvent('script_meta', {detail: ${result}}));"
}
}
}
}
"extension" -> {
if (payload == "") {
val code =
callback =
LocalFiles.script +
"window.dispatchEvent(new CustomEvent('extension', ${LocalFiles.start()}));"
Chrome.evaluateJavascript(listOf(code))
}
}
"websocket" -> {
Expand Down
16 changes: 14 additions & 2 deletions app/src/main/java/org/matrix/chromext/extension/LocalFiles.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import java.net.ServerSocket
import java.net.Socket
import java.net.URLConnection
import kotlin.concurrent.thread
import org.json.JSONArray
import org.json.JSONObject
import org.matrix.chromext.Chrome
import org.matrix.chromext.utils.Log
Expand Down Expand Up @@ -87,7 +88,18 @@ object LocalFiles {

fun start(): JSONObject {
extensions.keys.forEach { startServer(it) }
val info = JSONObject(extensions as Map<String, JSONObject>)
return JSONObject().put("detail", JSONObject(mapOf("type" to "init", "manifest" to info)))
val info =
if (extensions.keys.size == 0) {
Log.d("No extensions found")
JSONArray()
} else {
JSONArray(
extensions.map {
it.value.put("src", "http://localhost:" + it.value.get("port"))
it.value.remove("port")
it.value.put("id", it.key)
})
}
return JSONObject().put("detail", JSONObject(mapOf("type" to "init", "manifests" to info)))
}
}
2 changes: 1 addition & 1 deletion app/src/main/java/org/matrix/chromext/hook/Menu.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ object MenuHook : BaseHook() {
when (ctx.resources.getResourceName(id)) {
"org.matrix.chromext:id/extension_id" -> {
Log.toast(ctx, "WIP support for extensions")
Listener.on("extension")
Listener.startAction("{action: 'extension'}")
}
"org.matrix.chromext:id/install_script_id" -> {
if (getUrl().startsWith("https://raw.githubusercontent.com/")) {
Expand Down

0 comments on commit 86eed09

Please sign in to comment.