feat: 实现电脑端被控与控制界面

This commit is contained in:
Nixevol
2026-10-12 07:06:49 +08:00
parent 9dcf8f4837
commit 12adf2951f
110 changed files with 12468 additions and 0 deletions
+4392
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "tapremly"
version = "0.1.0"
description = "TapRemly"
edition = "2021"
[lib]
name = "tapremly_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "2", features = [] }
[target.'cfg(windows)'.dependencies]
winreg = "0.55"
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"
strip = true
+11
View File
@@ -0,0 +1,11 @@
fn main() {
let attributes =
tauri_build::Attributes::new().app_manifest(tauri_build::AppManifest::new().commands(&[
"agent_endpoint",
"start_agent",
"stop_agent",
"autostart_get",
"autostart_set",
]));
tauri_build::try_build(attributes).expect("failed to run tauri-build");
}
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "主窗口",
"windows": ["main"],
"permissions": [
"core:default",
"allow-agent-endpoint",
"allow-start-agent",
"allow-stop-agent",
"allow-autostart-get",
"allow-autostart-set"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 868 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-agent-endpoint"
description = "Enables the agent_endpoint command without any pre-configured scope."
commands.allow = ["agent_endpoint"]
[[permission]]
identifier = "deny-agent-endpoint"
description = "Denies the agent_endpoint command without any pre-configured scope."
commands.deny = ["agent_endpoint"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-autostart-get"
description = "Enables the autostart_get command without any pre-configured scope."
commands.allow = ["autostart_get"]
[[permission]]
identifier = "deny-autostart-get"
description = "Denies the autostart_get command without any pre-configured scope."
commands.deny = ["autostart_get"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-autostart-set"
description = "Enables the autostart_set command without any pre-configured scope."
commands.allow = ["autostart_set"]
[[permission]]
identifier = "deny-autostart-set"
description = "Denies the autostart_set command without any pre-configured scope."
commands.deny = ["autostart_set"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-start-agent"
description = "Enables the start_agent command without any pre-configured scope."
commands.allow = ["start_agent"]
[[permission]]
identifier = "deny-start-agent"
description = "Denies the start_agent command without any pre-configured scope."
commands.deny = ["start_agent"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-stop-agent"
description = "Enables the stop_agent command without any pre-configured scope."
commands.allow = ["stop_agent"]
[[permission]]
identifier = "deny-stop-agent"
description = "Denies the stop_agent command without any pre-configured scope."
commands.deny = ["stop_agent"]
+404
View File
@@ -0,0 +1,404 @@
use std::fs;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;
use serde::Deserialize;
use serde::Serialize;
use tauri::Manager;
#[derive(Deserialize)]
struct AgentFile {
addr: String,
token: String,
pid: u32,
}
#[derive(Serialize)]
struct Endpoint {
running: bool,
addr: String,
token: String,
pid: u32,
}
fn data_dir() -> PathBuf {
if let Ok(home) = std::env::var("TAPREMLY_HOME") {
if !home.is_empty() {
return PathBuf::from(home);
}
}
#[cfg(windows)]
{
let local = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| {
let user = std::env::var("USERPROFILE").unwrap_or_default();
format!("{user}\\AppData\\Local")
});
return PathBuf::from(local).join("TapRemly");
}
#[cfg(not(windows))]
{
if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
if !xdg.is_empty() {
return PathBuf::from(xdg).join("tapremly");
}
}
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home)
.join(".local")
.join("share")
.join("tapremly")
}
}
fn read_file() -> Option<AgentFile> {
let raw = fs::read(data_dir().join("agent.json")).ok()?;
serde_json::from_slice(&raw).ok()
}
#[cfg(windows)]
#[link(name = "kernel32")]
extern "system" {
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut std::ffi::c_void;
fn GetExitCodeProcess(handle: *mut std::ffi::c_void, code: *mut u32) -> i32;
fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
fn TerminateProcess(handle: *mut std::ffi::c_void, code: u32) -> i32;
}
fn pid_alive(pid: u32) -> bool {
if pid == 0 {
return false;
}
#[cfg(windows)]
{
const QUERY: u32 = 0x1000;
const STILL_ACTIVE: u32 = 259;
unsafe {
let handle = OpenProcess(QUERY, 0, pid);
if handle.is_null() {
return false;
}
let mut code = 0u32;
let ok = GetExitCodeProcess(handle, &mut code);
CloseHandle(handle);
ok != 0 && code == STILL_ACTIVE
}
}
#[cfg(not(windows))]
{
Command::new("kill")
.args(["-0", &pid.to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
}
fn endpoint() -> Endpoint {
match read_file() {
Some(info) if pid_alive(info.pid) => Endpoint {
running: true,
addr: info.addr,
token: info.token,
pid: info.pid,
},
_ => Endpoint {
running: false,
addr: String::new(),
token: String::new(),
pid: 0,
},
}
}
fn find_agent(app: &tauri::AppHandle) -> Option<PathBuf> {
if let Ok(dir) = app.path().resource_dir() {
for name in ["tapremly-agent.exe", "tapremly-agent"] {
let path = dir.join(name);
if path.is_file() {
return Some(path);
}
}
}
let mut dirs = Vec::new();
if let Ok(exe) = std::env::current_exe() {
let mut dir = exe.parent().map(Path::to_path_buf);
for _ in 0..8 {
if let Some(current) = dir {
dirs.push(current.clone());
dir = current.parent().map(Path::to_path_buf);
}
}
}
if let Ok(cwd) = std::env::current_dir() {
dirs.push(cwd);
}
for dir in dirs {
for name in ["tapremly-agent.exe", "tapremly-agent"] {
let direct = dir.join(name);
if direct.is_file() {
return Some(direct);
}
let nested = dir.join("agent").join(name);
if nested.is_file() {
return Some(nested);
}
}
}
None
}
fn spawn_detached(exe: &Path) -> Result<(), String> {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
let flags = CREATE_NO_WINDOW
| DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
| CREATE_BREAKAWAY_FROM_JOB;
let mut cmd = Command::new(exe);
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(flags);
if cmd.spawn().is_err() {
let mut plain = Command::new(exe);
plain
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
plain.spawn().map_err(|err| err.to_string())?;
}
return Ok(());
}
#[cfg(not(windows))]
{
use std::os::unix::process::CommandExt;
let mut cmd = Command::new(exe);
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0);
cmd.spawn().map_err(|err| err.to_string())?;
Ok(())
}
}
fn http_stop(addr: &str, token: &str) -> Result<(), String> {
let mut stream = TcpStream::connect(addr).map_err(|err| err.to_string())?;
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.map_err(|err| err.to_string())?;
let req = format!(
"POST /v1/stop HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {token}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
stream
.write_all(req.as_bytes())
.map_err(|err| err.to_string())?;
let mut buf = [0u8; 128];
let _ = stream.read(&mut buf);
Ok(())
}
#[cfg(windows)]
fn force_kill(pid: u32) {
const TERMINATE: u32 = 0x0001;
unsafe {
let handle = OpenProcess(TERMINATE, 0, pid);
if !handle.is_null() {
TerminateProcess(handle, 1);
CloseHandle(handle);
}
}
}
#[cfg(not(windows))]
fn force_kill(pid: u32) {
let _ = Command::new("kill").args(["-9", &pid.to_string()]).status();
}
fn wait_dead(pid: u32) -> bool {
for _ in 0..30 {
if !pid_alive(pid) {
return true;
}
std::thread::sleep(Duration::from_millis(100));
}
false
}
#[cfg(windows)]
fn autostart_command(exe: &Path) -> String {
format!("\"{}\"", exe.display())
}
#[cfg(windows)]
fn autostart_key() -> Result<winreg::RegKey, String> {
use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
hkcu.open_subkey_with_flags(
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
KEY_READ | KEY_WRITE,
)
.map_err(|err| err.to_string())
}
#[tauri::command]
fn agent_endpoint() -> Endpoint {
endpoint()
}
#[tauri::command]
fn start_agent(app: tauri::AppHandle) -> Result<(), String> {
if endpoint().running {
return Ok(());
}
let exe = find_agent(&app).ok_or("找不到被控程序")?;
spawn_detached(&exe)?;
for _ in 0..40 {
if endpoint().running {
return Ok(());
}
std::thread::sleep(Duration::from_millis(100));
}
Err("被控没有启动".into())
}
#[tauri::command]
fn stop_agent() -> Result<(), String> {
let Some(info) = read_file() else {
return Ok(());
};
if !pid_alive(info.pid) {
return Ok(());
}
let _ = http_stop(&info.addr, &info.token);
if !wait_dead(info.pid) {
force_kill(info.pid);
let _ = wait_dead(info.pid);
}
Ok(())
}
#[tauri::command]
fn autostart_get() -> bool {
#[cfg(windows)]
{
let Ok(key) = autostart_key() else {
return false;
};
return key.get_value::<String, _>("TapRemly").is_ok();
}
#[cfg(target_os = "macos")]
{
return macos_plist().is_file();
}
#[cfg(all(not(windows), not(target_os = "macos")))]
{
linux_desktop().is_file()
}
}
#[tauri::command]
fn autostart_set(app: tauri::AppHandle, enable: bool) -> Result<(), String> {
let exe = find_agent(&app).ok_or("找不到被控程序")?;
#[cfg(windows)]
{
let key = autostart_key()?;
if enable {
key.set_value("TapRemly", &autostart_command(&exe))
.map_err(|err| err.to_string())?;
} else {
match key.delete_value("TapRemly") {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.to_string()),
}
}
return Ok(());
}
#[cfg(target_os = "macos")]
{
let path = macos_plist();
if enable {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).map_err(|err| err.to_string())?;
}
let body = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>asia.asio.tapremly.agent</string>
<key>ProgramArguments</key><array><string>{}</string></array>
<key>RunAtLoad</key><true/>
<key>LimitLoadToSessionType</key><string>Aqua</string>
</dict></plist>
"#,
exe.display()
);
fs::write(path, body).map_err(|err| err.to_string())?;
} else if path.exists() {
fs::remove_file(path).map_err(|err| err.to_string())?;
}
return Ok(());
}
#[cfg(all(not(windows), not(target_os = "macos")))]
{
let path = linux_desktop();
if enable {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).map_err(|err| err.to_string())?;
}
let body = format!(
"[Desktop Entry]\nType=Application\nName=TapRemly\nExec={}\nX-GNOME-Autostart-enabled=true\nNoDisplay=true\n",
exe.display()
);
fs::write(path, body).map_err(|err| err.to_string())?;
} else if path.exists() {
fs::remove_file(path).map_err(|err| err.to_string())?;
}
Ok(())
}
}
#[cfg(target_os = "macos")]
fn macos_plist() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home)
.join("Library")
.join("LaunchAgents")
.join("asia.asio.tapremly.agent.plist")
}
#[cfg(all(not(windows), not(target_os = "macos")))]
fn linux_desktop() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_default();
let dir = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| format!("{home}/.config"));
PathBuf::from(dir)
.join("autostart")
.join("tapremly-agent.desktop")
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
agent_endpoint,
start_agent,
stop_agent,
autostart_get,
autostart_set
])
.run(tauri::generate_context!())
.expect("启动失败");
}
+5
View File
@@ -0,0 +1,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
tapremly_lib::run();
}
+42
View File
@@ -0,0 +1,42 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "TapRemly",
"version": "0.1.0",
"identifier": "asia.asio.tapremly",
"build": {
"beforeDevCommand": "pnpm dev",
"devUrl": "http://127.0.0.1:1420",
"beforeBuildCommand": "pnpm build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"label": "main",
"title": "TapRemly",
"width": 1180,
"height": 780,
"minWidth": 960,
"minHeight": 640,
"resizable": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": ["nsis"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"resources": {
"../../agent/tapremly-agent.exe": "tapremly-agent.exe"
}
}
}