Abrarul8541 commited on
Commit
fe64f73
·
verified ·
1 Parent(s): b1f530e

Phase 4: Termux RUN_COMMAND bridge and su helper

Browse files
app/src/main/java/io/github/abrarul/modularai/bridge/TermuxBridge.kt ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package io.github.abrarul.modularai.bridge
2
+
3
+ import android.content.Context
4
+ import android.content.Intent
5
+ import android.content.pm.PackageManager
6
+
7
+ /**
8
+ * Requires: Termux installed, `allow-external-apps = true` in ~/.termux/termux.properties,
9
+ * and the user granting com.termux.permission.RUN_COMMAND to this app.
10
+ */
11
+ object TermuxBridge {
12
+ private const val PKG = "com.termux"
13
+ private const val SERVICE = "com.termux.app.RunCommandService"
14
+ private const val PREFIX = "/data/data/com.termux/files/usr"
15
+ private const val HOME = "/data/data/com.termux/files/home"
16
+
17
+ fun isInstalled(ctx: Context): Boolean = try {
18
+ ctx.packageManager.getPackageInfo(PKG, 0); true
19
+ } catch (_: PackageManager.NameNotFoundException) { false }
20
+
21
+ /** Runs [script] with bash inside Termux, in the background (no terminal session opened). */
22
+ fun run(ctx: Context, script: String, args: Array<String> = emptyArray()) {
23
+ val i = Intent("com.termux.RUN_COMMAND").apply {
24
+ setClassName(PKG, SERVICE)
25
+ putExtra("com.termux.RUN_COMMAND_PATH", "$PREFIX/bin/bash")
26
+ putExtra("com.termux.RUN_COMMAND_ARGUMENTS", arrayOf("-c", script) + args)
27
+ putExtra("com.termux.RUN_COMMAND_WORKDIR", HOME)
28
+ putExtra("com.termux.RUN_COMMAND_BACKGROUND", true)
29
+ }
30
+ ctx.startForegroundService(i)
31
+ }
32
+
33
+ /** Root is optional. Returns null when su is missing or denied. */
34
+ fun su(cmd: String): String? = try {
35
+ val p = ProcessBuilder("su", "-c", cmd).redirectErrorStream(true).start()
36
+ val out = p.inputStream.bufferedReader().readText()
37
+ if (p.waitFor() == 0) out else null
38
+ } catch (_: Exception) { null }
39
+ }