Download app/src/main/java/io/github/abrarul/modularai/plugin/PluginHost.kt from Abrarul8541/ModularAI-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 2.22 kB
-
https://huggingface.co/Abrarul8541/ModularAI-Terminal/resolve/1d3347cf7067ec9f9a607bc0212246abc66ffb4e/app/src/main/java/io/github/abrarul/modularai/plugin/PluginHost.kt
- Command line
-
hf download hf://Abrarul8541/ModularAI-Terminal@1d3347cf7067ec9f9a607bc0212246abc66ffb4e/app/src/main/java/io/github/abrarul/modularai/plugin/PluginHost.kt
-
curl -L -o PluginHost.kt https://huggingface.co/Abrarul8541/ModularAI-Terminal/resolve/1d3347cf7067ec9f9a607bc0212246abc66ffb4e/app/src/main/java/io/github/abrarul/modularai/plugin/PluginHost.kt
2.22 kB
| package io.github.abrarul.modularai.plugin | |
| import android.content.Context | |
| import io.github.abrarul.modularai.bridge.TermuxBridge | |
| import org.json.JSONObject | |
| import java.io.File | |
| /** | |
| * Plugin layout: filesDir/plugins/<id>/plugin.json + entry script. | |
| * plugin.json: {"id","name","version","entry":"run.sh","permissions":["net","shell"],"hooks":["on_capture","on_model_loaded"]} | |
| * A plugin only runs hooks for permissions the user has explicitly granted. | |
| */ | |
| data class Plugin( | |
| val id: String, val name: String, val version: String, | |
| val entry: String, val permissions: Set<String>, val hooks: Set<String>, val dir: File | |
| ) | |
| class PluginHost(private val ctx: Context) { | |
| private val root = File(ctx.filesDir, "plugins").apply { mkdirs() } | |
| private val granted = ctx.getSharedPreferences("plugin_grants", Context.MODE_PRIVATE) | |
| fun installed(): List<Plugin> = root.listFiles()?.mapNotNull { load(it) } ?: emptyList() | |
| private fun load(d: File): Plugin? = try { | |
| val j = JSONObject(File(d, "plugin.json").readText()) | |
| fun set(k: String) = j.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } ?: emptySet() | |
| Plugin(j.getString("id"), j.getString("name"), j.getString("version"), | |
| j.getString("entry"), set("permissions"), set("hooks"), d) | |
| } catch (_: Exception) { null } | |
| fun grant(id: String, perms: Set<String>) = granted.edit().putStringSet(id, perms).apply() | |
| fun isGranted(p: Plugin) = granted.getStringSet(p.id, emptySet())!!.containsAll(p.permissions) | |
| fun remove(p: Plugin) { p.dir.deleteRecursively(); granted.edit().remove(p.id).apply() } | |
| /** Fires [event]; payload is passed as the first script argument. */ | |
| fun emit(event: String, payload: String = "") { | |
| installed().filter { event in it.hooks && isGranted(it) }.forEach { p -> | |
| // Entry paths must stay inside the plugin dir. | |
| val entry = File(p.dir, p.entry).canonicalFile | |
| if (!entry.path.startsWith(p.dir.canonicalPath)) return@forEach | |
| if ("shell" in p.permissions) { | |
| TermuxBridge.run(ctx, "sh '${entry.path}' '$event' \"\$1\"", arrayOf("_", payload)) | |
| } | |
| } | |
| } | |
| } | |