source: minor cleanup

This commit is contained in:
rifsxd
2025-01-01 21:19:50 +06:00
parent 9f30b48e55
commit 6695dfbb26
19 changed files with 132 additions and 352 deletions

View File

@@ -1,120 +0,0 @@
# Library for KernelSU's module WebUI
## Install
```sh
yarn add kernelsu
```
## API
### exec
Spawns a **root** shell and runs a command within that shell, passing the `stdout` and `stderr` to a Promise when complete.
- `command` `<string>` The command to run, with space-separated arguments.
- `options` `<Object>`
- `cwd` - Current working directory of the child process
- `env` - Environment key-value pairs
```javascript
import { exec } from 'kernelsu';
const { errno, stdout, stderr } = await exec('ls -l', { cwd: '/tmp' });
if (errno === 0) {
// success
console.log(stdout);
}
```
### spawn
Spawns a new process using the given `command` in **root** shell, with command-line arguments in `args`. If omitted, `args` defaults to an empty array.
Returns a `ChildProcess`, Instances of the ChildProcess represent spawned child processes.
- `command` `<string>` The command to run.
- `args` `<string[]>` List of string arguments.
- `options` `<Object>`:
- `cwd` `<string>` - Current working directory of the child process
- `env` `<Object>` - Environment key-value pairs
Example of running `ls -lh /data`, capturing `stdout`, `stderr`, and the exit code:
```javascript
import { spawn } from 'kernelsu';
const ls = spawn('ls', ['-lh', '/data']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('exit', (code) => {
console.log(`child process exited with code ${code}`);
});
```
#### ChildProcess
##### Event 'exit'
- `code` `<number>` The exit code if the child exited on its own.
The `'exit'` event is emitted after the child process ends. If the process exited, `code` is the final exit code of the process, otherwise null
##### Event 'error'
- `err` `<Error>` The error.
The `'error'` event is emitted whenever:
- The process could not be spawned.
- The process could not be killed.
##### `stdout`
A `Readable Stream` that represents the child process's `stdout`.
```javascript
const subprocess = spawn('ls');
subprocess.stdout.on('data', (data) => {
console.log(`Received chunk ${data}`);
});
```
#### `stderr`
A `Readable Stream` that represents the child process's `stderr`.
### fullScreen
Request the WebView enter/exit full screen.
```javascript
import { fullScreen } from 'kernelsu';
fullScreen(true);
```
### toast
Show a toast message.
```javascript
import { toast } from 'kernelsu';
toast('Hello, world!');
```
### moduleInfo
Get Module info.
```javascript
import { moduleInfo } from 'kernelsu';
// print moduleId in console
console.log(moduleInfo());
```

48
js/index.d.ts vendored
View File

@@ -1,48 +0,0 @@
interface ExecOptions {
cwd?: string,
env?: { [key: string]: string }
}
interface ExecResults {
errno: number,
stdout: string,
stderr: string
}
declare function exec(command: string): Promise<ExecResults>;
declare function exec(command: string, options: ExecOptions): Promise<ExecResults>;
interface SpawnOptions {
cwd?: string,
env?: { [key: string]: string }
}
interface Stdio {
on(event: 'data', callback: (data: string) => void)
}
interface ChildProcess {
stdout: Stdio,
stderr: Stdio,
on(event: 'exit', callback: (code: number) => void)
on(event: 'error', callback: (err: any) => void)
}
declare function spawn(command: string): ChildProcess;
declare function spawn(command: string, args: string[]): ChildProcess;
declare function spawn(command: string, options: SpawnOptions): ChildProcess;
declare function spawn(command: string, args: string[], options: SpawnOptions): ChildProcess;
declare function fullScreen(isFullScreen: boolean);
declare function toast(message: string);
declare function moduleInfo(): string;
export {
exec,
spawn,
fullScreen,
toast,
moduleInfo
}

View File

@@ -1,119 +0,0 @@
let callbackCounter = 0;
function getUniqueCallbackName(prefix) {
return `${prefix}_callback_${Date.now()}_${callbackCounter++}`;
}
export function exec(command, options) {
if (typeof options === "undefined") {
options = {};
}
return new Promise((resolve, reject) => {
// Generate a unique callback function name
const callbackFuncName = getUniqueCallbackName("exec");
// Define the success callback function
window[callbackFuncName] = (errno, stdout, stderr) => {
resolve({ errno, stdout, stderr });
cleanup(callbackFuncName);
};
function cleanup(successName) {
delete window[successName];
}
try {
ksu.exec(command, JSON.stringify(options), callbackFuncName);
} catch (error) {
reject(error);
cleanup(callbackFuncName);
}
});
}
function Stdio() {
this.listeners = {};
}
Stdio.prototype.on = function (event, listener) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(listener);
};
Stdio.prototype.emit = function (event, ...args) {
if (this.listeners[event]) {
this.listeners[event].forEach((listener) => listener(...args));
}
};
function ChildProcess() {
this.listeners = {};
this.stdin = new Stdio();
this.stdout = new Stdio();
this.stderr = new Stdio();
}
ChildProcess.prototype.on = function (event, listener) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(listener);
};
ChildProcess.prototype.emit = function (event, ...args) {
if (this.listeners[event]) {
this.listeners[event].forEach((listener) => listener(...args));
}
};
export function spawn(command, args, options) {
if (typeof args === "undefined") {
args = [];
} else if (!(args instanceof Array)) {
// allow for (command, options) signature
options = args;
}
if (typeof options === "undefined") {
options = {};
}
const child = new ChildProcess();
const childCallbackName = getUniqueCallbackName("spawn");
window[childCallbackName] = child;
function cleanup(name) {
delete window[name];
}
child.on("exit", code => {
cleanup(childCallbackName);
});
try {
ksu.spawn(
command,
JSON.stringify(args),
JSON.stringify(options),
childCallbackName
);
} catch (error) {
child.emit("error", error);
cleanup(childCallbackName);
}
return child;
}
export function fullScreen(isFullScreen) {
ksu.fullScreen(isFullScreen);
}
export function toast(message) {
ksu.toast(message);
}
export function moduleInfo() {
return ksu.moduleInfo();
}

View File

@@ -1,26 +0,0 @@
{
"name": "kernelsu",
"version": "1.0.7",
"description": "Library for KernelSU's module WebUI",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "npm run test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tiann/KernelSU.git"
},
"keywords": [
"su",
"kernelsu",
"module",
"webui"
],
"author": "weishu",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/tiann/KernelSU/issues"
},
"homepage": "https://github.com/tiann/KernelSU#readme"
}

View File

@@ -45,14 +45,6 @@ ifndef KSU_NEXT_EXPECTED_HASH
KSU_NEXT_EXPECTED_HASH := 79e590113c4c4c0c222978e413a5faa801666957b1212a328e46c00c69821bf7
endif
ifndef KSU_EXPECTED_SIZE
KSU_EXPECTED_SIZE := 0x033b
endif
ifndef KSU_EXPECTED_HASH
KSU_EXPECTED_HASH := c371061b19d8c7d7d6133c6a9bafe198fa944e50c1b31c9d8daa8d7f1fc2d2d6
endif
ifdef KSU_MANAGER_PACKAGE
ccflags-y += -DKSU_MANAGER_PACKAGE=\"$(KSU_MANAGER_PACKAGE)\"
$(info -- KernelSU-Next Manager package name: $(KSU_MANAGER_PACKAGE))

View File

@@ -106,7 +106,7 @@ fun ExecuteModuleActionScreen(navigator: DestinationsNavigator, moduleId: String
val date = format.format(Date())
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"KernelSU_Next_module_action_log_${date}.log"
"KernelSU_module_action_log_${date}.log"
)
file.writeText(logContent.toString())
snackBarHost.showSnackbar("Log saved to ${file.absolutePath}")

View File

@@ -139,7 +139,7 @@ fun FlashScreen(navigator: DestinationsNavigator, flashIt: FlashIt) {
val date = format.format(Date())
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"KernelSU_Next_install_log_${date}.log"
"KernelSU_install_log_${date}.log"
)
file.writeText(logContent.toString())
snackBarHost.showSnackbar("Log saved to ${file.absolutePath}")

View File

@@ -289,7 +289,7 @@ fun ModuleScreen(navigator: DestinationsNavigator) {
if (hasWebUi) {
webUILauncher.launch(
Intent(context, WebUIActivity::class.java)
.setData(Uri.parse("kernelsu-next://webui/$id"))
.setData(Uri.parse("kernelsu://webui/$id"))
.putExtra("id", id)
.putExtra("name", name)
)

View File

@@ -247,7 +247,7 @@ fun SettingScreen(navigator: DestinationsNavigator) {
.clickable {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH_mm")
val current = LocalDateTime.now().format(formatter)
exportBugreportLauncher.launch("KernelSU_Next_bugreport_${current}.tar.gz")
exportBugreportLauncher.launch("KernelSU_bugreport_${current}.tar.gz")
showBottomsheet = false
}
) {

View File

@@ -231,7 +231,7 @@ fun flashModule(
}
val cmd = "module install ${file.absolutePath}"
val result = flashWithIO("${getKsuDaemonPath()} $cmd", onStdout, onStderr)
Log.i("KernelSU-Next", "install module $uri result: $result")
Log.i("KernelSU", "install module $uri result: $result")
file.delete()
@@ -259,7 +259,7 @@ fun runModuleAction(
val result = shell.newJob().add("${getKsuDaemonPath()} module action $moduleId")
.to(stdoutCallback, stderrCallback).exec()
Log.i("KernelSU-Next", "Module runAction result: $result")
Log.i("KernelSU", "Module runAction result: $result")
return result.isSuccess
}
@@ -357,7 +357,7 @@ fun installBoot(
cmd += " -o $downloadsDir"
val result = flashWithIO("${getKsuDaemonPath()} $cmd", onStdout, onStderr)
Log.i("KernelSU-Next", "install boot result: ${result.isSuccess}")
Log.i("KernelSU", "install boot result: ${result.isSuccess}")
bootFile?.delete()
lkmFile?.delete()

View File

@@ -101,7 +101,7 @@ fun getBugreportFile(context: Context): File {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH_mm")
val current = LocalDateTime.now().format(formatter)
val targetFile = File(context.cacheDir, "KernelSU_Next_bugreport_${current}.tar.gz")
val targetFile = File(context.cacheDir, "KernelSU_bugreport_${current}.tar.gz")
shell.newJob().add("tar czf ${targetFile.absolutePath} -C ${bugreportDir.absolutePath} .").exec()
shell.newJob().add("rm -rf ${bugreportDir.absolutePath}").exec()

View File

@@ -39,9 +39,9 @@ class WebUIActivity : ComponentActivity() {
val name = intent.getStringExtra("name")!!
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
@Suppress("DEPRECATION")
setTaskDescription(ActivityManager.TaskDescription("KernelSU-Next - $name"))
setTaskDescription(ActivityManager.TaskDescription("KernelSUt - $name"))
} else {
val taskDescription = ActivityManager.TaskDescription.Builder().setLabel("KernelSU-Next - $name").build()
val taskDescription = ActivityManager.TaskDescription.Builder().setLabel("KernelSU - $name").build()
setTaskDescription(taskDescription)
}
@@ -52,7 +52,7 @@ class WebUIActivity : ComponentActivity() {
val webRoot = File("${moduleDir}/webroot")
val rootShell = createRootShell(true).also { this.rootShell = it }
val webViewAssetLoader = WebViewAssetLoader.Builder()
.setDomain("mui.kernelsu-next.org")
.setDomain("mui.kernelsu.org")
.addPathHandler(
"/",
SuFilePathHandler(this, webRoot, rootShell)
@@ -85,7 +85,7 @@ class WebUIActivity : ComponentActivity() {
webviewInterface = WebViewInterface(this@WebUIActivity, this, moduleDir)
addJavascriptInterface(webviewInterface, "ksu")
setWebViewClient(webViewClient)
loadUrl("https://mui.kernelsu-next.org/index.html")
loadUrl("https://mui.kernelsu.org/index.html")
}
setContentView(webView)

View File

@@ -17,5 +17,5 @@ dependencyResolutionManagement {
}
}
rootProject.name = "KernelSU-Next"
rootProject.name = "KernelSU"
include(":app")

101
scripts/ksunbot.py Normal file
View File

@@ -0,0 +1,101 @@
import asyncio
import os
import sys
from telethon import TelegramClient
from telethon.tl.functions.help import GetConfigRequest
API_ID = 611335
API_HASH = "d524b414d21f4d37f08684c1df41ac9c"
BOT_TOKEN = os.environ.get("BOT_TOKEN")
CHAT_ID = os.environ.get("CHAT_ID")
MESSAGE_THREAD_ID = os.environ.get("MESSAGE_THREAD_ID")
COMMIT_URL = os.environ.get("COMMIT_URL")
COMMIT_MESSAGE = os.environ.get("COMMIT_MESSAGE")
RUN_URL = os.environ.get("RUN_URL")
TITLE = os.environ.get("TITLE")
VERSION = os.environ.get("VERSION")
MSG_TEMPLATE = """
**{title}**
#ci_{version}
```
{commit_message}
```
[Commit]({commit_url})
[Workflow run]({run_url})
""".strip()
def get_caption():
msg = MSG_TEMPLATE.format(
title=TITLE,
version=VERSION,
commit_message=COMMIT_MESSAGE,
commit_url=COMMIT_URL,
run_url=RUN_URL,
)
if len(msg) > 1024:
return COMMIT_URL
return msg
def check_environ():
global CHAT_ID, MESSAGE_THREAD_ID
if BOT_TOKEN is None:
print("[-] Invalid BOT_TOKEN")
exit(1)
if CHAT_ID is None:
print("[-] Invalid CHAT_ID")
exit(1)
else:
CHAT_ID = int(CHAT_ID)
if COMMIT_URL is None:
print("[-] Invalid COMMIT_URL")
exit(1)
if COMMIT_MESSAGE is None:
print("[-] Invalid COMMIT_MESSAGE")
exit(1)
if RUN_URL is None:
print("[-] Invalid RUN_URL")
exit(1)
if TITLE is None:
print("[-] Invalid TITLE")
exit(1)
if VERSION is None:
print("[-] Invalid VERSION")
exit(1)
if MESSAGE_THREAD_ID is None:
print("[-] Invaild MESSAGE_THREAD_ID")
exit(1)
else:
MESSAGE_THREAD_ID = int(MESSAGE_THREAD_ID)
async def main():
print("[+] Uploading to telegram")
check_environ()
files = sys.argv[1:]
print("[+] Files:", files)
if len(files) <= 0:
print("[-] No files to upload")
exit(1)
print("[+] Logging in Telegram with bot")
script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
session_dir = os.path.join(script_dir, "ksubot")
async with await TelegramClient(session=session_dir, api_id=API_ID, api_hash=API_HASH).start(bot_token=BOT_TOKEN) as bot:
caption = [""] * len(files)
caption[-1] = get_caption()
print("[+] Caption: ")
print("---")
print(caption)
print("---")
print("[+] Sending")
await bot.send_file(entity=CHAT_ID, file=files, caption=caption, reply_to=MESSAGE_THREAD_ID, parse_mode="markdown")
print("[+] Done!")
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as e:
print(f"[-] An error occurred: {e}")

View File

@@ -212,7 +212,7 @@ pub fn restore(
flash: bool,
) -> Result<()> {
let tmpdir = tempfile::Builder::new()
.prefix("KernelSU-Next")
.prefix("KernelSU")
.tempdir()
.context("create temp dir failed")?;
let workdir = tmpdir.path();
@@ -235,7 +235,7 @@ pub fn restore(
ensure!(status.success(), "magiskboot unpack failed");
let is_kernelsu_patched = is_kernelsu_patched(&magiskboot, workdir)?;
ensure!(is_kernelsu_patched, "boot image is not patched by KernelSU-Next");
ensure!(is_kernelsu_patched, "boot image is not patched by KernelSU");
let mut new_boot = None;
let mut from_backup = false;
@@ -298,7 +298,7 @@ pub fn restore(
let output_dir = std::env::current_dir()?;
let now = chrono::Utc::now();
let output_image = output_dir.join(format!(
"kernelsu_next_restore_{}.img",
"kernelsu_restore_{}.img",
now.format("%Y%m%d_%H%M%S")
));
@@ -370,7 +370,7 @@ fn do_patch(
}
let tmpdir = tempfile::Builder::new()
.prefix("KernelSU-Next")
.prefix("KernelSU")
.tempdir()
.context("create temp dir failed")?;
let workdir = tmpdir.path();
@@ -460,7 +460,7 @@ fn do_patch(
"Cannot work with Magisk patched image"
);
println!("- Adding KernelSU-Next LKM");
println!("- Adding KernelSU LKM");
let is_kernelsu_patched = is_kernelsu_patched(&magiskboot, workdir)?;
let mut need_backup = false;
@@ -501,7 +501,7 @@ fn do_patch(
let output_dir = out.unwrap_or(std::env::current_dir()?);
let now = chrono::Utc::now();
let output_image = output_dir.join(format!(
"kernelsu_next_patched_{}.img",
"kernelsu_patched_{}.img",
now.format("%Y%m%d_%H%M%S")
));

View File

@@ -9,7 +9,7 @@ use log::LevelFilter;
use crate::{apk_sign, assets, debug, defs, init_event, ksucalls, module, utils};
/// KernelSU-Next userspace cli
/// KernelSU userspace cli
#[derive(Parser, Debug)]
#[command(author, version = defs::VERSION_NAME, about, long_about = None)]
struct Args {
@@ -19,7 +19,7 @@ struct Args {
#[derive(clap::Subcommand, Debug)]
enum Commands {
/// Manage KernelSU-Next modules
/// Manage KernelSU modules
Module {
#[command(subcommand)]
command: Module,
@@ -34,13 +34,13 @@ enum Commands {
/// Trigger `boot-complete` event
BootCompleted,
/// Install KernelSU-Next userspace component to system
/// Install KernelSU userspace component to system
Install {
#[arg(long, default_value = None)]
magiskboot: Option<PathBuf>,
},
/// Uninstall KernelSU-Next modules and itself(LKM Only)
/// Uninstall KernelSU modules and itself(LKM Only)
Uninstall {
/// magiskboot path, if not specified, will search from $PATH
#[arg(long, default_value = None)]
@@ -59,7 +59,7 @@ enum Commands {
command: Profile,
},
/// Patch boot or init_boot images to apply KernelSU-Next
/// Patch boot or init_boot images to apply KernelSU
BootPatch {
/// boot image path, if not specified, will try to find the boot image automatically
#[arg(short, long)]
@@ -98,7 +98,7 @@ enum Commands {
kmi: Option<String>,
},
/// Restore boot or init_boot images patched by KernelSU-Next
/// Restore boot or init_boot images patched by KernelSU
BootRestore {
/// boot image path, if not specified, will try to find the boot image automatically
#[arg(short, long)]
@@ -287,7 +287,7 @@ pub fn run() -> Result<()> {
android_logger::init_once(
Config::default()
.with_max_level(LevelFilter::Trace) // limit log level
.with_tag("KernelSU-Next"), // logs will show under mytag tag
.with_tag("KernelSU"), // logs will show under mytag tag
);
#[cfg(not(target_os = "android"))]

View File

@@ -1,6 +1,6 @@
#!/system/bin/sh
############################################
# KernelSU-Next installer script
# KernelSU installer script
# mostly from module_installer.sh
# and util_functions.sh in Magisk
############################################
@@ -371,7 +371,7 @@ install_module() {
set_permissions
else
print_title "$MODNAME" "by $MODAUTH"
print_title "Powered by KernelSU-Next"
print_title "Powered by KernelSU"
unzip -o "$ZIPFILE" customize.sh -d $MODPATH >&2

View File

@@ -43,7 +43,7 @@ pub fn grant_root(_global_mnt: bool) -> Result<()> {
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("KernelSU-Next\n\nUsage: {program} [options] [-] [user [argument...]]");
let brief = format!("KernelSU\n\nUsage: {program} [options] [-] [user [argument...]]");
print!("{}", opts.usage(&brief));
}
@@ -154,7 +154,7 @@ pub fn root_shell() -> Result<()> {
}
if matches.opt_present("v") {
println!("{}:KernelSU-Next", defs::VERSION_NAME);
println!("{}:KernelSU", defs::VERSION_NAME);
return Ok(());
}

View File

@@ -293,7 +293,7 @@ pub fn uninstall(magiskboot_path: Option<PathBuf>) -> Result<()> {
std::fs::remove_dir_all(defs::MODULE_UPDATE_TMP_DIR).ok();
println!("- Restore boot image..");
boot_patch::restore(None, magiskboot_path, true)?;
println!("- Uninstall KernelSU-Next manager..");
println!("- Uninstall KernelSU manager..");
Command::new("pm")
.args(["uninstall", "com.rifsxd.ksunext"])
.spawn()?;