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
Vendored
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TapRemly</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+26
View File
@@ -0,0 +1,26 @@
{
"name": "tapremly",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2.8.0",
"naive-ui": "^2.42.0",
"pinia": "^3.0.3",
"vue": "^3.5.22",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.8.0",
"@types/node": "^24.5.2",
"@vitejs/plugin-vue": "^6.0.1",
"typescript": "~5.9.2",
"vite": "^7.1.5",
"vue-tsc": "^3.0.7"
}
}
+1362
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
allowBuilds:
esbuild: true
+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"
}
}
}
+25
View File
@@ -0,0 +1,25 @@
<template>
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme-overrides="theme">
<n-dialog-provider>
<n-message-provider>
<Shell />
</n-message-provider>
</n-dialog-provider>
</n-config-provider>
</template>
<script setup lang="ts">
import { NConfigProvider, NDialogProvider, NMessageProvider, dateZhCN, zhCN, type GlobalThemeOverrides } from 'naive-ui'
import Shell from './Shell.vue'
const theme: GlobalThemeOverrides = {
common: {
primaryColor: '#0f6e82',
primaryColorHover: '#14859c',
primaryColorPressed: '#0c596a',
primaryColorSuppl: '#0f6e82',
borderRadius: '6px',
fontFamily: '"Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
},
}
</script>
+129
View File
@@ -0,0 +1,129 @@
<template>
<div class="shell">
<header class="topbar">
<span class="brand">TapRemly</span>
<span class="top-status">{{ store.running ? store.connText : '未运行' }}</span>
<n-button v-if="!store.running" type="primary" size="small" :loading="busy" @click="start">启动被控</n-button>
<n-button v-else size="small" :loading="busy" @click="stop">停止被控</n-button>
<n-checkbox :checked="store.autostart" :disabled="!desktop" @update:checked="toggleAuto">开机启动</n-checkbox>
<HelpTip text="登录这台电脑时只启动被控,不打开这个窗口。" />
<span class="spacer"></span>
<n-button quaternary size="small" :type="route.path === '/' ? 'primary' : 'default'" @click="router.push('/')">设备</n-button>
<n-button quaternary size="small" :type="route.path === '/trust' ? 'primary' : 'default'" @click="router.push('/trust')">信任</n-button>
<n-button quaternary size="small" :type="route.path === '/commands' ? 'primary' : 'default'" @click="router.push('/commands')">本机命令</n-button>
<n-badge :value="unread" :max="99">
<n-button quaternary size="small" @click="messages = true">消息</n-button>
</n-badge>
<n-button size="small" @click="host = true">本机</n-button>
</header>
<div class="body">
<DeviceList />
<main class="pane">
<router-view />
</main>
</div>
<HostDialog v-model:show="host" />
<n-modal v-model:show="messages" preset="card" title="消息" style="width: 480px" :segmented="{ content: true }">
<div class="modal-body">
<div v-if="store.inbox.length === 0" class="empty">还没有文字</div>
<div v-for="item in reversedInbox" :key="item.id + item.at" class="msg-row">
<div class="muted">{{ store.nameOf(item.from) }} · {{ formatTime(item.at) }}</div>
<div class="msg-text">{{ item.text }}</div>
</div>
</div>
</n-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NBadge, NButton, NCheckbox, NModal, useMessage } from 'naive-ui'
import DeviceList from './components/DeviceList.vue'
import HelpTip from './components/HelpTip.vue'
import HostDialog from './components/HostDialog.vue'
import { api, autostartSet, canAutostart, startAgent, stopAgent } from './api'
import { useAppStore } from './stores/app'
import { formatTime } from './types'
const store = useAppStore()
const route = useRoute()
const router = useRouter()
const message = useMessage()
const host = ref(false)
const messages = ref(false)
const busy = ref(false)
const desktop = canAutostart()
const seen = new Set<string>()
let primed = false
let timer = 0
const unread = computed(() => store.inbox.filter((item) => !item.read).length)
const reversedInbox = computed(() => [...store.inbox].reverse())
watch(
() => store.inbox,
(items) => {
if (!primed) {
items.forEach((item) => seen.add(item.id || item.at + item.text))
primed = true
return
}
for (const item of items) {
const key = item.id || item.at + item.text
if (seen.has(key)) continue
seen.add(key)
message.info(item.text)
}
},
)
watch(messages, (open) => {
if (open && store.running) {
api('/v1/inbox/read', { method: 'POST' }).catch(() => undefined)
}
})
async function start() {
busy.value = true
try {
await startAgent()
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有启动')
} finally {
busy.value = false
}
}
async function stop() {
busy.value = true
try {
await stopAgent()
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有停止')
} finally {
busy.value = false
}
}
async function toggleAuto(value: boolean) {
try {
await autostartSet(value)
store.autostart = value
} catch (err) {
message.error(err instanceof Error ? err.message : '没有保存')
}
}
onMounted(async () => {
await store.refreshAutostart()
await store.tick()
timer = window.setInterval(() => {
store.tick().catch(() => undefined)
}, 2000)
})
onUnmounted(() => window.clearInterval(timer))
</script>
+118
View File
@@ -0,0 +1,118 @@
import { invoke } from '@tauri-apps/api/core'
export class ApiError extends Error {}
interface Endpoint {
running: boolean
addr: string
token: string
pid: number
}
let cache: Endpoint | null = null
function inTauri() {
return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
}
async function readEndpoint(): Promise<Endpoint | null> {
if (inTauri()) {
const info = await invoke<Endpoint>('agent_endpoint')
return info.running ? info : null
}
if (!import.meta.env.DEV) return null
const res = await fetch('/__agent')
if (!res.ok) return null
const info = (await res.json()) as Endpoint
return info.running ? info : null
}
export async function connectAgent(force = false) {
if (!force && cache?.running) return true
cache = await readEndpoint()
return !!cache
}
export function agentRunning() {
return !!cache?.running
}
export async function api<T>(path: string, init: RequestInit = {}, allowRetry = true): Promise<T> {
const ready = await connectAgent(!cache)
if (!ready || !cache) throw new ApiError('被控未运行')
let res: Response
try {
res = await fetch(`http://${cache.addr}${path}`, {
...init,
headers: {
...(init.body ? { 'Content-Type': 'application/json' } : {}),
Authorization: `Bearer ${cache.token}`,
...(init.headers || {}),
},
})
} catch (err) {
cache = null
if (allowRetry) return api<T>(path, init, false)
throw new ApiError('被控未运行')
}
if (res.status === 401 && allowRetry) {
cache = null
return api<T>(path, init, false)
}
const text = await res.text()
let data: { error?: string } = {}
if (text) {
try {
data = JSON.parse(text) as { error?: string }
} catch {
throw new ApiError('没有成功')
}
}
if (!res.ok) throw new ApiError(data.error || '没有成功')
return data as T
}
export async function startAgent() {
if (inTauri()) {
await invoke('start_agent')
} else if (import.meta.env.DEV) {
const res = await fetch('/__agent/start', { method: 'POST' })
if (!res.ok) throw new ApiError('找不到被控程序')
for (let i = 0; i < 40; i++) {
await new Promise((r) => setTimeout(r, 100))
if (await connectAgent(true)) return
}
throw new ApiError('被控没有启动')
} else {
throw new ApiError('请从桌面图标打开')
}
cache = null
await connectAgent(true)
}
export async function stopAgent() {
if (inTauri()) {
await invoke('stop_agent')
} else {
try {
await api('/v1/stop', { method: 'POST' }, false)
} catch {
await fetch('/__agent/stop', { method: 'POST' }).catch(() => undefined)
}
}
cache = null
}
export async function autostartGet() {
if (!inTauri()) return false
return invoke<boolean>('autostart_get')
}
export async function autostartSet(enable: boolean) {
if (!inTauri()) throw new ApiError('请使用桌面上的程序设置开机启动')
await invoke('autostart_set', { enable })
}
export function canAutostart() {
return inTauri()
}
+48
View File
@@ -0,0 +1,48 @@
<template>
<n-modal :show="show" preset="card" title="复制到其他设备" style="width: 420px" :segmented="{ content: true, footer: 'soft' }" @update:show="emit('update:show', $event)">
<div class="modal-body">
<div v-if="others.length === 0" class="empty">没有其他设备</div>
<n-checkbox-group v-else v-model:value="picked">
<div v-for="item in others" :key="item.endpoint_id" style="margin: 6px 0">
<n-checkbox :value="item.endpoint_id">{{ item.name }}</n-checkbox>
</div>
</n-checkbox-group>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="emit('update:show', false)">取消</n-button>
<n-button type="primary" :disabled="picked.length === 0" @click="ok">确定</n-button>
</div>
</template>
</n-modal>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NCheckbox, NCheckboxGroup, NModal } from 'naive-ui'
import type { Device } from '../types'
const props = defineProps<{
show: boolean
devices: Device[]
current: string
}>()
const emit = defineEmits<{
'update:show': [boolean]
confirm: [string[]]
}>()
const picked = ref<string[]>([])
const others = computed(() => props.devices.filter((item) => item.endpoint_id && item.endpoint_id !== props.current))
watch(
() => props.show,
(open) => {
if (open) picked.value = []
},
)
function ok() {
emit('confirm', picked.value)
}
</script>
+210
View File
@@ -0,0 +1,210 @@
<template>
<aside class="list">
<div class="list-head">
<span class="list-title">设备</span>
<span class="spacer"></span>
<n-button size="tiny" @click="openAdd">添加设备</n-button>
<n-button size="tiny" @click="openGroup">新建分组</n-button>
</div>
<div class="list-search">
<n-input v-model:value="query" size="small" clearable placeholder="搜索名称或端编号" />
</div>
<div class="list-scroll">
<div v-if="!store.running" class="empty">被控没有在运行。启动后可以看见设备。</div>
<div v-else-if="!store.accountUser" class="empty">
登录账号后可以看见设备。
<div style="margin-top: 8px"><n-button size="small" type="primary" @click="emitLogin">登录</n-button></div>
</div>
<div v-else-if="store.deviceError" class="empty">{{ store.deviceError }}</div>
<div v-else-if="store.devices.length === 0" class="empty">
还没有设备。
<div style="margin-top: 8px"><n-button size="small" type="primary" @click="openAdd">添加设备</n-button></div>
</div>
<template v-else>
<div v-if="ungrouped.length || !query.trim()" class="group-head"><span class="group-name">未分组</span></div>
<button
v-for="item in ungrouped"
:key="item.id"
type="button"
class="device-row"
:class="{ active: store.selectedId === item.id }"
@click="choose(item.id)"
>
<span class="device-main">
<span class="device-name">{{ item.name }}</span>
<span class="device-id">{{ item.endpoint_id }}</span>
</span>
<span class="pill" :class="item.presence">{{ presenceText(item.presence) }}</span>
</button>
<section v-for="group in visibleGroups" :key="group.id">
<div class="group-head">
<span class="group-name">{{ group.name }}</span>
<span class="spacer"></span>
<n-button text size="tiny" @click="rename(group)">重命名</n-button>
<n-button text size="tiny" @click="remove(group)">删除</n-button>
</div>
<button
v-for="item in group.devices"
:key="item.id"
type="button"
class="device-row"
:class="{ active: store.selectedId === item.id }"
@click="choose(item.id)"
>
<span class="device-main">
<span class="device-name">{{ item.name }}</span>
<span class="device-id">{{ item.endpoint_id }}</span>
</span>
<span class="pill" :class="item.presence">{{ presenceText(item.presence) }}</span>
</button>
</section>
<div v-if="query.trim() && ungrouped.length === 0 && visibleGroups.length === 0" class="empty">没有匹配的设备</div>
</template>
</div>
<n-modal v-model:show="addShow" preset="card" title="添加设备" style="width: 440px" :segmented="{ content: true, footer: 'soft' }">
<div class="modal-body">
<n-form label-placement="left" label-width="72">
<n-form-item label="名称"><n-input v-model:value="addName" maxlength="40" /></n-form-item>
<n-form-item label="端编号">
<n-input v-model:value="addEndpoint" placeholder="对方的端编号,留空则登记这台电脑" />
</n-form-item>
</n-form>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="addShow = false">取消</n-button>
<n-button type="primary" :disabled="!addName.trim()" :loading="saving" @click="add">添加</n-button>
</div>
</template>
</n-modal>
<n-modal v-model:show="groupShow" preset="card" :title="groupId ? '重命名分组' : '新建分组'" style="width: 400px" :segmented="{ content: true, footer: 'soft' }">
<div class="modal-body">
<n-form label-placement="left" label-width="72">
<n-form-item label="名称"><n-input v-model:value="groupName" maxlength="40" /></n-form-item>
</n-form>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="groupShow = false">取消</n-button>
<n-button type="primary" :disabled="!groupName.trim()" :loading="saving" @click="saveGroup">保存</n-button>
</div>
</template>
</n-modal>
</aside>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NForm, NFormItem, NInput, NModal, useDialog, useMessage } from 'naive-ui'
import { api } from '../api'
import { useAppStore } from '../stores/app'
import { presenceText, type Group } from '../types'
const store = useAppStore()
const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const query = ref('')
const addShow = ref(false)
const addName = ref('')
const addEndpoint = ref('')
const groupShow = ref(false)
const groupName = ref('')
const groupId = ref('')
const saving = ref(false)
const knownGroups = computed(() => new Set(store.groups.map((item) => item.id)))
const filtered = computed(() => {
const text = query.value.trim().toLowerCase()
return store.devices.filter((item) => !text || item.name.toLowerCase().includes(text) || item.endpoint_id.toLowerCase().includes(text))
})
const ungrouped = computed(() => filtered.value.filter((item) => !item.group_id || !knownGroups.value.has(item.group_id)))
const visibleGroups = computed(() =>
store.groups
.map((group) => ({ ...group, devices: filtered.value.filter((item) => item.group_id === group.id) }))
.filter((group) => group.devices.length > 0 || !query.value.trim()),
)
function choose(id: string) {
store.selectedId = id
router.push('/')
}
function emitLogin() {
window.dispatchEvent(new CustomEvent('tapremly-open-host'))
}
function openAdd() {
addName.value = ''
addEndpoint.value = ''
addShow.value = true
}
function openGroup() {
groupId.value = ''
groupName.value = ''
groupShow.value = true
}
function rename(group: Group) {
groupId.value = group.id
groupName.value = group.name
groupShow.value = true
}
function remove(group: Group) {
dialog.warning({
title: '删除分组',
content: '删除后,这个分组里的设备会回到未分组。',
positiveText: '删除',
negativeText: '取消',
onPositiveClick: async () => {
try {
await api(`/v1/groups/${encodeURIComponent(group.id)}`, { method: 'DELETE' })
await store.refreshDevices()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有删除')
}
},
})
}
async function add() {
saving.value = true
try {
await api('/v1/devices', {
method: 'POST',
body: JSON.stringify({ name: addName.value.trim(), endpoint_id: addEndpoint.value.trim() }),
})
addShow.value = false
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有添加')
} finally {
saving.value = false
}
}
async function saveGroup() {
saving.value = true
try {
if (groupId.value) {
await api(`/v1/groups/${encodeURIComponent(groupId.value)}`, {
method: 'PATCH',
body: JSON.stringify({ name: groupName.value.trim() }),
})
} else {
await api('/v1/groups', { method: 'POST', body: JSON.stringify({ name: groupName.value.trim() }) })
}
groupShow.value = false
await store.refreshDevices()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有保存')
} finally {
saving.value = false
}
}
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<n-tooltip>
<template #trigger>
<button type="button" class="help" aria-label="说明">?</button>
</template>
{{ text }}
</n-tooltip>
</template>
<script setup lang="ts">
import { NTooltip } from 'naive-ui'
defineProps<{ text: string }>()
</script>
+207
View File
@@ -0,0 +1,207 @@
<template>
<n-modal :show="show" preset="card" title="本机" style="width: 520px" :segmented="{ content: true, footer: 'soft' }" @update:show="emit('update:show', $event)">
<div class="modal-body">
<n-form label-placement="left" label-width="88">
<n-form-item label="账号">
<n-input v-model:value="username" :disabled="!!store.accountUser" placeholder="用户名" />
</n-form-item>
<n-form-item v-if="!store.accountUser" label="密码">
<n-input v-model:value="password" type="password" show-password-on="click" />
</n-form-item>
<n-form-item label=" ">
<n-button v-if="!store.accountUser" type="primary" :loading="busy" @click="loginAccount">登录</n-button>
<span v-else class="inline">已登录 {{ store.accountUser }} <n-button size="small" @click="logoutAccount">退出</n-button></span>
</n-form-item>
<n-form-item label="服务器地址">
<n-input v-model:value="serverUrl" />
</n-form-item>
<n-form-item label="连接地址">
<n-input v-model:value="nixUrl" />
</n-form-item>
<n-form-item label=" ">
<n-button :loading="busy" @click="saveAddress">保存地址</n-button>
</n-form-item>
<n-form-item label="端编号">
<n-input v-model:value="endpointId" :disabled="store.loggedIn" />
</n-form-item>
<n-form-item v-if="!store.loggedIn" label="密码">
<n-input v-model:value="endpointPassword" type="password" show-password-on="click" />
</n-form-item>
<n-form-item label=" ">
<n-button v-if="!store.loggedIn" type="primary" :loading="busy" @click="loginEndpoint">登录</n-button>
<span v-else class="inline">已登录 {{ store.endpointId }} <n-button size="small" @click="logoutEndpoint">退出</n-button></span>
</n-form-item>
<n-form-item label="本机名称">
<n-input v-model:value="selfName" maxlength="40" placeholder="登记到账号时使用" />
</n-form-item>
<n-form-item label=" ">
<n-button :loading="busy" :disabled="!store.accountUser" @click="provision">登记这台电脑</n-button>
</n-form-item>
</n-form>
<div class="section-head">
<span class="section-title">本机记录</span>
</div>
<div v-if="logs.length === 0" class="muted">还没有记录</div>
<div v-for="(item, index) in logs" :key="index" class="log-row">
<div>{{ item.ok ? '成功' : '失败' }} · {{ item.summary }}</div>
<div class="muted">{{ formatTime(item.at) }} {{ item.detail }}</div>
</div>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="emit('update:show', false)">关闭</n-button>
</div>
</template>
</n-modal>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { NButton, NForm, NFormItem, NInput, NModal, useMessage } from 'naive-ui'
import { api } from '../api'
import { useAppStore } from '../stores/app'
import { formatTime, type LogItem } from '../types'
const props = defineProps<{ show: boolean }>()
const emit = defineEmits<{ 'update:show': [boolean] }>()
const store = useAppStore()
const message = useMessage()
const username = ref('')
const password = ref('')
const serverUrl = ref(store.serverUrl)
const nixUrl = ref(store.nixUrl)
const endpointId = ref(store.endpointId)
const endpointPassword = ref('')
const selfName = ref('')
const busy = ref(false)
const logs = ref<LogItem[]>([])
watch(
() => props.show,
(open) => {
if (!open) return
serverUrl.value = store.serverUrl
nixUrl.value = store.nixUrl
endpointId.value = store.endpointId
password.value = ''
endpointPassword.value = ''
loadLogs()
},
)
async function loadLogs() {
if (!store.running) {
logs.value = []
return
}
try {
const res = await api<{ items: LogItem[] }>('/v1/logs')
logs.value = [...(res.items || [])].reverse()
} catch {
logs.value = []
}
}
async function loginAccount() {
busy.value = true
try {
await saveUrls()
await api('/v1/account/login', {
method: 'POST',
body: JSON.stringify({ username: username.value.trim(), password: password.value }),
})
password.value = ''
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有登录')
} finally {
busy.value = false
}
}
async function logoutAccount() {
busy.value = true
try {
await api('/v1/account', { method: 'DELETE' })
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有退出')
} finally {
busy.value = false
}
}
async function saveAddress() {
busy.value = true
try {
await saveUrls()
message.success('已保存')
} catch (err) {
message.error(err instanceof Error ? err.message : '没有保存')
} finally {
busy.value = false
}
}
async function saveUrls() {
if (!store.running) throw new Error('被控未运行')
await api('/v1/settings', {
method: 'PUT',
body: JSON.stringify({ server_url: serverUrl.value.trim(), nixmsg_url: nixUrl.value.trim() }),
})
await store.refreshStatus()
}
async function loginEndpoint() {
busy.value = true
try {
await saveUrls()
await api('/v1/session', {
method: 'POST',
body: JSON.stringify({
endpoint_id: endpointId.value.trim(),
password: endpointPassword.value,
nixmsg_url: nixUrl.value.trim(),
}),
})
endpointPassword.value = ''
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有登录')
} finally {
busy.value = false
}
}
async function logoutEndpoint() {
busy.value = true
try {
await api('/v1/session', { method: 'DELETE' })
await store.tick()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有退出')
} finally {
busy.value = false
}
}
async function provision() {
busy.value = true
try {
await api('/v1/devices', { method: 'POST', body: JSON.stringify({ name: selfName.value.trim() || '这台电脑' }) })
await store.tick()
message.success('已登记')
} catch (err) {
message.error(err instanceof Error ? err.message : '没有登记')
} finally {
busy.value = false
}
}
function openFromList() {
emit('update:show', true)
}
onMounted(() => window.addEventListener('tapremly-open-host', openFromList))
onUnmounted(() => window.removeEventListener('tapremly-open-host', openFromList))
</script>
+56
View File
@@ -0,0 +1,56 @@
<template>
<n-modal :show="show" preset="card" :title="title" style="width: 480px" :segmented="{ content: true, footer: 'soft' }" @update:show="emit('update:show', $event)">
<div class="modal-body">
<n-form label-placement="left" label-width="88">
<n-form-item label="名称">
<n-input v-model:value="name" maxlength="40" />
</n-form-item>
<n-form-item label="发送前确认">
<n-switch v-model:value="confirm" />
</n-form-item>
<n-form-item label="命令" label-placement="top">
<n-input v-model:value="shell" type="textarea" placeholder="要在对方执行的内容" :autosize="{ minRows: 4, maxRows: 8 }" />
</n-form-item>
</n-form>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="emit('update:show', false)">取消</n-button>
<n-button type="primary" :disabled="!shell.trim() || !name.trim()" @click="save">保存</n-button>
</div>
</template>
</n-modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { NButton, NForm, NFormItem, NInput, NModal, NSwitch } from 'naive-ui'
const props = defineProps<{
show: boolean
title: string
initial?: { name: string; shell: string; confirm: boolean } | null
}>()
const emit = defineEmits<{
'update:show': [boolean]
save: [{ name: string; shell: string; confirm: boolean }]
}>()
const name = ref('')
const shell = ref('')
const confirm = ref(false)
watch(
() => props.show,
(open) => {
if (!open) return
name.value = props.initial?.name || ''
shell.value = props.initial?.shell || ''
confirm.value = props.initial?.confirm || false
},
)
function save() {
emit('save', { name: name.value.trim(), shell: shell.value.trim(), confirm: confirm.value })
}
</script>
+7
View File
@@ -0,0 +1,7 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './styles.css'
createApp(App).use(createPinia()).use(router).mount('#app')
+13
View File
@@ -0,0 +1,13 @@
import { createRouter, createWebHistory } from 'vue-router'
import DevicePane from './views/DevicePane.vue'
import TrustView from './views/TrustView.vue'
import CommandsView from './views/CommandsView.vue'
export default createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: DevicePane },
{ path: '/trust', component: TrustView },
{ path: '/commands', component: CommandsView },
],
})
+139
View File
@@ -0,0 +1,139 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { api, autostartGet, connectAgent } from '../api'
import type { CmdResult, Device, Group, InboxItem, Status } from '../types'
export const useAppStore = defineStore('app', () => {
const running = ref(false)
const connText = ref('未连接')
const endpointId = ref('')
const loggedIn = ref(false)
const serverUrl = ref('http://127.0.0.1:8080')
const nixUrl = ref('ws://127.0.0.1:7443/mqtt')
const accountUser = ref('')
const maxTtl = ref(2592000)
const maxSchedule = ref(31536000)
const autostart = ref(false)
const devices = ref<Device[]>([])
const groups = ref<Group[]>([])
const deviceError = ref('')
const selectedId = ref('')
const inbox = ref<InboxItem[]>([])
const results = ref<CmdResult[]>([])
const untrusted = ref<Record<string, boolean>>({})
const selected = computed(() => devices.value.find((item) => item.id === selectedId.value) || null)
function nameOf(endpoint: string) {
return devices.value.find((item) => item.endpoint_id === endpoint)?.name || endpoint
}
async function refreshStatus() {
const alive = await connectAgent(true)
running.value = alive
if (!alive) {
connText.value = '未连接'
return
}
const status = await api<Status>('/v1/status')
connText.value = status.conn_text || '未连接'
endpointId.value = status.endpoint_id || ''
loggedIn.value = status.logged_in
serverUrl.value = status.server_url || serverUrl.value
nixUrl.value = status.nixmsg_url || nixUrl.value
accountUser.value = status.account_user || ''
maxTtl.value = status.max_ttl_seconds || 2592000
maxSchedule.value = status.max_schedule_seconds || 31536000
}
async function refreshDevices() {
if (!running.value) {
devices.value = []
groups.value = []
deviceError.value = ''
return
}
try {
const [deviceRes, groupRes] = await Promise.all([
api<{ items: Device[] }>('/v1/devices'),
api<{ items: Group[] }>('/v1/groups'),
])
devices.value = deviceRes.items || []
groups.value = groupRes.items || []
deviceError.value = ''
if (selectedId.value && !devices.value.some((item) => item.id === selectedId.value)) {
selectedId.value = ''
}
} catch (err) {
devices.value = []
groups.value = []
deviceError.value = err instanceof Error ? err.message : '没有成功'
}
}
async function refreshInbox() {
if (!running.value) {
inbox.value = []
return
}
const res = await api<{ items: InboxItem[] }>('/v1/inbox')
inbox.value = res.items || []
}
async function refreshResults() {
if (!running.value) return
const res = await api<{ items: CmdResult[] }>('/v1/results')
const next = { ...untrusted.value }
for (const item of res.items || []) {
if (item.error === 'not_trusted') next[item.remote] = true
else if (item.ok) next[item.remote] = false
}
untrusted.value = next
results.value = res.items || []
}
async function refreshAutostart() {
try {
autostart.value = await autostartGet()
} catch {
autostart.value = false
}
}
async function tick() {
try {
await refreshStatus()
if (!running.value) return
await Promise.all([refreshDevices(), refreshInbox(), refreshResults()])
} catch {
running.value = false
}
}
return {
running,
connText,
endpointId,
loggedIn,
serverUrl,
nixUrl,
accountUser,
maxTtl,
maxSchedule,
autostart,
devices,
groups,
deviceError,
selectedId,
selected,
inbox,
results,
untrusted,
nameOf,
refreshStatus,
refreshDevices,
refreshInbox,
refreshAutostart,
tick,
}
})
+342
View File
@@ -0,0 +1,342 @@
html,
body,
#app {
height: 100%;
margin: 0;
overflow: hidden;
color: #1f2933;
background: #f3f5f7;
}
button,
input,
textarea {
font: inherit;
}
.shell {
height: 100%;
display: grid;
grid-template-rows: 52px minmax(0, 1fr);
}
.topbar {
display: flex;
align-items: center;
gap: 10px;
padding: 0 14px;
background: #fff;
border-bottom: 1px solid #e4e7eb;
}
.brand {
font-size: 16px;
font-weight: 650;
letter-spacing: 0.2px;
}
.top-status {
color: #52606d;
font-size: 13px;
min-width: 4em;
}
.spacer {
flex: 1;
}
.body {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
min-height: 0;
}
.pane {
min-height: 0;
min-width: 0;
}
.list {
height: 100%;
display: flex;
flex-direction: column;
background: #fff;
border-right: 1px solid #e4e7eb;
}
.list-head,
.page-head,
.section-head,
.trust-head {
display: flex;
align-items: center;
gap: 8px;
min-height: 48px;
padding: 8px 12px;
}
.list-head {
border-bottom: 1px solid #eef0f2;
}
.list-title,
.page-title,
.section-title {
font-size: 15px;
font-weight: 650;
}
.list-search {
padding: 8px 12px 4px;
}
.list-scroll,
.page-scroll,
.trust-scroll,
.drawer-scroll {
min-height: 0;
overflow: auto;
}
.list-scroll {
flex: 1;
padding: 4px 8px 16px;
}
.group-head {
display: flex;
align-items: center;
gap: 6px;
margin: 10px 4px 4px;
color: #52606d;
font-size: 12px;
}
.group-name {
font-weight: 650;
}
.device-row,
.sc-row,
.trust-row,
.log-row,
.msg-row {
display: flex;
align-items: center;
gap: 8px;
border-radius: 8px;
}
.device-row {
width: 100%;
text-align: left;
border: 0;
background: transparent;
padding: 8px 10px;
cursor: pointer;
}
.device-row:hover,
.sc-row:hover,
.trust-row:hover {
background: #f4f7f8;
}
.device-row.active {
background: #e7f3f6;
}
.device-main {
min-width: 0;
flex: 1;
}
.device-name,
.sc-name,
.msg-text {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.device-id,
.sc-shell,
.muted {
color: #7b8794;
font-size: 12px;
}
.pill {
flex: none;
font-size: 12px;
border-radius: 999px;
padding: 1px 8px;
}
.pill.online {
color: #0f6b3a;
background: #e5f6ec;
}
.pill.offline,
.pill.unknown {
color: #52606d;
background: #eef0f2;
}
.empty {
margin: 28px 16px;
color: #52606d;
line-height: 1.6;
}
.page {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.page-head {
background: #fff;
border-bottom: 1px solid #eef0f2;
}
.send {
flex: none;
background: #fff;
padding: 12px 16px 10px;
border-bottom: 1px solid #e4e7eb;
}
.send-line {
display: flex;
align-items: center;
gap: 12px;
margin-top: 8px;
flex-wrap: wrap;
}
.send-line .grow {
flex: 1;
}
.warn {
margin-top: 8px;
color: #9a3412;
font-size: 13px;
}
.hint {
margin-top: 6px;
color: #52606d;
font-size: 12px;
}
.bad {
color: #b42318;
font-size: 12px;
}
.page-scroll {
flex: 1;
padding: 8px 16px 24px;
}
.section {
margin-top: 8px;
}
.section-head {
padding-left: 0;
padding-right: 0;
}
.sc-row {
padding: 8px 10px;
cursor: pointer;
}
.sc-name {
flex: none;
max-width: 40%;
font-weight: 600;
}
.sc-shell {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.help {
width: 16px;
height: 16px;
padding: 0;
border: 1px solid #c5ced6;
border-radius: 50%;
background: #fff;
color: #52606d;
font-size: 11px;
line-height: 14px;
cursor: help;
}
.modal-body {
max-height: min(62vh, 520px);
overflow: auto;
padding-right: 2px;
}
.modal-actions,
.row-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.trust,
.commands {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
background: #f3f5f7;
}
.trust-scroll,
.commands .page-scroll {
flex: 1;
padding: 4px 16px 12px;
}
.trust-add {
flex: none;
display: flex;
gap: 8px;
padding: 12px 16px;
background: #fff;
border-top: 1px solid #e4e7eb;
}
.trust-row,
.log-row,
.msg-row {
padding: 8px 0;
border-bottom: 1px solid #eef0f2;
}
.log-row,
.msg-row {
align-items: flex-start;
flex-direction: column;
gap: 2px;
}
.inline {
display: flex;
align-items: center;
gap: 6px;
}
+91
View File
@@ -0,0 +1,91 @@
export interface Device {
id: string
name: string
endpoint_id: string
group_id: string
online: boolean
presence: 'online' | 'offline' | 'unknown' | string
}
export interface Group {
id: string
name: string
}
export interface Shortcut {
id: string
name: string
shell: string
confirm: boolean
remote_id?: string
}
export interface Status {
running: boolean
conn: string
conn_text: string
endpoint_id: string
logged_in: boolean
server_url: string
nixmsg_url: string
account_user: string
has_device_token: boolean
max_ttl_seconds: number
max_schedule_seconds: number
}
export interface InboxItem {
id: string
from: string
text: string
at: string
read: boolean
}
export interface CmdResult {
id: string
remote: string
ok: boolean
error?: string
duplicate?: boolean
at: string
}
export interface LogItem {
at: string
summary: string
ok: boolean
detail: string
}
export interface RemoteShortcuts {
items: Shortcut[]
synced_at: string
syncing: boolean
}
export interface RemoteLogs {
items: LogItem[]
synced_at: string
syncing: boolean
error?: string
server_items: LogItem[]
}
export function presenceText(value: string) {
if (value === 'online') return '在线'
if (value === 'offline') return '不在线'
return '未知'
}
export function formatTime(iso: string) {
if (!iso) return ''
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return ''
return date.toLocaleString('zh-CN', {
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
+109
View File
@@ -0,0 +1,109 @@
<template>
<section class="commands">
<div class="page-head">
<span class="page-title">本机命令</span>
<HelpTip text="其他设备打开这台电脑时,会看到这里的命令。" />
<span class="spacer"></span>
<n-button size="small" :disabled="!store.running" @click="openCreate">添加</n-button>
</div>
<div class="page-scroll">
<div v-if="!store.running" class="empty">请先启动被控。</div>
<div v-else-if="items.length === 0" class="empty">还没有发布给其他设备的命令。</div>
<div v-for="item in items" :key="item.id" class="sc-row" @click="edit(item)" @contextmenu.prevent="openMenu($event, item)">
<span class="sc-name">{{ item.name }}</span>
<span class="sc-shell">{{ item.shell }}</span>
</div>
</div>
<n-dropdown trigger="manual" placement="bottom-start" :show="menu.show" :x="menu.x" :y="menu.y" :options="menuOptions" @clickoutside="menu.show = false" @select="onMenu" />
<ShortcutDialog v-model:show="editShow" :title="editing ? '编辑快捷命令' : '添加快捷命令'" :initial="editing" @save="save" />
</section>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { NButton, NDropdown, useDialog, useMessage } from 'naive-ui'
import HelpTip from '../components/HelpTip.vue'
import ShortcutDialog from '../components/ShortcutDialog.vue'
import { api } from '../api'
import { useAppStore } from '../stores/app'
import type { Shortcut } from '../types'
const store = useAppStore()
const message = useMessage()
const dialog = useDialog()
const items = ref<Shortcut[]>([])
const editShow = ref(false)
const editing = ref<Shortcut | null>(null)
const menu = reactive({ show: false, x: 0, y: 0, item: null as Shortcut | null })
const menuOptions = [
{ label: '编辑', key: 'edit' },
{ label: '删除', key: 'delete' },
]
async function load() {
if (!store.running) {
items.value = []
return
}
const res = await api<{ items: Shortcut[] }>('/v1/shortcuts/published')
items.value = res.items || []
}
function openCreate() {
editing.value = null
editShow.value = true
}
function edit(item: Shortcut) {
editing.value = item
editShow.value = true
}
function openMenu(event: MouseEvent, item: Shortcut) {
menu.show = true
menu.x = event.clientX
menu.y = event.clientY
menu.item = item
}
function onMenu(key: string) {
menu.show = false
const item = menu.item
if (!item) return
if (key === 'edit') {
editing.value = item
editShow.value = true
return
}
dialog.warning({
title: '删除快捷命令',
content: `删除「${item.name}」?`,
positiveText: '删除',
negativeText: '取消',
onPositiveClick: async () => {
await api(`/v1/shortcuts/published/${encodeURIComponent(item.id)}`, { method: 'DELETE' })
await load()
},
})
}
async function save(form: { name: string; shell: string; confirm: boolean }) {
try {
if (editing.value) {
await api(`/v1/shortcuts/published/${encodeURIComponent(editing.value.id)}`, {
method: 'PATCH',
body: JSON.stringify(form),
})
} else {
await api('/v1/shortcuts/published', { method: 'POST', body: JSON.stringify(form) })
}
editShow.value = false
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有保存')
}
}
watch(() => store.running, () => load().catch(() => undefined))
onMounted(() => load().catch(() => undefined))
</script>
+425
View File
@@ -0,0 +1,425 @@
<template>
<section class="page">
<template v-if="device">
<div class="page-head">
<n-button text @click="store.selectedId = ''">返回</n-button>
<span class="page-title">{{ device.name }}</span>
<span class="pill" :class="device.presence">{{ presenceText(device.presence) }}</span>
<span class="spacer"></span>
<n-button size="small" @click="openLogs">日志</n-button>
</div>
<div class="send">
<n-tabs v-model:value="tab" type="line" size="small">
<n-tab-pane name="shell" tab="命令">
<n-input v-model:value="shell" type="textarea" placeholder="输入要在对方执行的 shell" :autosize="{ minRows: 4, maxRows: 8 }" />
<n-button text :disabled="!shell.trim()" style="margin-top: 6px" @click="saveCurrent">存为本端快捷命令</n-button>
</n-tab-pane>
<n-tab-pane name="text" tab="文字">
<n-input v-model:value="text" type="textarea" placeholder="输入要显示在对方设备上的文字" :autosize="{ minRows: 4, maxRows: 8 }" />
</n-tab-pane>
</n-tabs>
<div class="send-line">
<n-radio-group v-model:value="mode" size="small">
<n-radio value="now">立即</n-radio>
<n-radio value="later">定时</n-radio>
</n-radio-group>
<HelpTip text="到了选定的时间再发出。如果时间已经过了,会马上发出。" />
<n-date-picker v-if="mode === 'later'" v-model:value="sendAt" type="datetime" size="small" />
<span class="inline">
<n-switch v-model:value="keep" size="small" />
<span>离线保留</span>
<HelpTip text="对方不在线时先留下,上线后再执行。有效期从开始投递的时刻算起。定时要到了设定时刻才开始计算。" />
</span>
<n-select v-if="keep" v-model:value="preset" size="small" style="width: 120px" :options="ttlOptions" />
<n-input-number v-if="keep && preset === 0" v-model:value="customAmount" size="small" :min="1" style="width: 90px" />
<n-select v-if="keep && preset === 0" v-model:value="customUnit" size="small" style="width: 88px" :options="unitOptions" />
<span class="grow"></span>
<n-button type="primary" :disabled="!canSend" :loading="sending" @click="sendCurrent">发送</n-button>
</div>
<div v-if="ttlError || timeError" class="bad">{{ ttlError || timeError }}</div>
<div v-if="untrusted" class="warn">对方尚未信任本机,命令不会执行</div>
<div v-if="note" class="hint">{{ note }}</div>
</div>
<div class="page-scroll">
<div class="section">
<div class="section-head">
<span class="section-title">远端快捷命令</span>
<span v-if="remote.syncing" class="muted">同步中</span>
<span v-else-if="remote.synced_at" class="muted">同步于 {{ formatTime(remote.synced_at) }}</span>
</div>
<div v-if="remote.items.length === 0" class="muted">还没有同步到命令</div>
<div v-for="item in remote.items" :key="item.id" class="sc-row" @click="runShortcut(item, true)" @contextmenu.prevent="openMenu($event, item, true)">
<span class="sc-name">{{ item.name }}</span>
<span class="sc-shell">{{ item.shell }}</span>
</div>
</div>
<div class="section">
<div class="section-head">
<span class="section-title">本端快捷命令</span>
<span class="spacer"></span>
<n-button size="tiny" @click="openCreate">添加</n-button>
</div>
<div v-if="localItems.length === 0" class="muted">还没有为本机保存的命令</div>
<div v-for="item in localItems" :key="item.id" class="sc-row" @click="runShortcut(item, false)" @contextmenu.prevent="openMenu($event, item, false)">
<span class="sc-name">{{ item.name }}</span>
<span class="sc-shell">{{ item.shell }}</span>
</div>
</div>
</div>
</template>
<div v-else class="empty">从左侧选择一台设备。</div>
<n-dropdown
trigger="manual"
placement="bottom-start"
:show="menu.show"
:x="menu.x"
:y="menu.y"
:options="menuOptions"
@clickoutside="menu.show = false"
@select="onMenu"
/>
<ShortcutDialog v-model:show="editShow" :title="editing?.id ? '编辑快捷命令' : '添加快捷命令'" :initial="editing" @save="saveShortcut" />
<CopyDialog v-model:show="copyShow" :devices="store.devices" :current="device?.endpoint_id || ''" @confirm="copyTo" />
<n-drawer v-model:show="logShow" :width="420" placement="right">
<n-drawer-content title="日志" closable>
<div v-if="logs.syncing" class="muted">同步中</div>
<div v-if="logs.error === 'not_trusted'" class="warn">对方尚未信任本机</div>
<div v-else-if="shownLogs.length === 0" class="empty">还没有记录</div>
<div v-if="!logs.syncing && logs.items.length === 0 && logs.server_items.length" class="muted">对方不在线,只显示最近的记录</div>
<div v-if="logs.synced_at && logs.items.length" class="muted">同步于 {{ formatTime(logs.synced_at) }}</div>
<div v-for="(item, index) in shownLogs" :key="index" class="log-row">
<div>{{ item.ok ? '成功' : '失败' }} · {{ item.summary }}</div>
<div class="muted">{{ formatTime(item.at) }} {{ item.detail }}</div>
</div>
</n-drawer-content>
</n-drawer>
</section>
</template>
<script setup lang="ts">
import { computed, onUnmounted, reactive, ref, watch } from 'vue'
import {
NButton,
NDatePicker,
NDrawer,
NDrawerContent,
NDropdown,
NInput,
NInputNumber,
NRadio,
NRadioGroup,
NSelect,
NSwitch,
NTabPane,
NTabs,
useDialog,
useMessage,
} from 'naive-ui'
import CopyDialog from '../components/CopyDialog.vue'
import HelpTip from '../components/HelpTip.vue'
import ShortcutDialog from '../components/ShortcutDialog.vue'
import { api } from '../api'
import { useAppStore } from '../stores/app'
import { formatTime, presenceText, type LogItem, type RemoteLogs, type RemoteShortcuts, type Shortcut } from '../types'
const store = useAppStore()
const message = useMessage()
const dialog = useDialog()
const device = computed(() => store.selected)
const tab = ref<'shell' | 'text'>('shell')
const shell = ref('')
const text = ref('')
const mode = ref<'now' | 'later'>('now')
const sendAt = ref<number | null>(null)
const keep = ref(false)
const preset = ref(86400)
const customAmount = ref(1)
const customUnit = ref(3600)
const sending = ref(false)
const note = ref('')
const localItems = ref<Shortcut[]>([])
const remote = ref<RemoteShortcuts>({ items: [], synced_at: '', syncing: false })
const editShow = ref(false)
const editing = ref<Shortcut | null>(null)
const fromInput = ref(false)
const copyShow = ref(false)
const copyItem = ref<Shortcut | null>(null)
const copyFromRemote = ref(false)
const logShow = ref(false)
const logs = ref<RemoteLogs>({ items: [], synced_at: '', syncing: false, server_items: [] })
const menu = reactive({ show: false, x: 0, y: 0, item: null as Shortcut | null, fromRemote: false })
let timer = 0
const unitOptions = [
{ label: '小时', value: 3600 },
{ label: '天', value: 86400 },
]
const ttlOptions = computed(() => {
const all = [
{ label: '1 小时', value: 3600 },
{ label: '1 天', value: 86400 },
{ label: '7 天', value: 604800 },
{ label: '30 天', value: 2592000 },
{ label: '自定义', value: 0 },
]
return all.filter((item) => item.value === 0 || item.value <= store.maxTtl)
})
const ttlSeconds = computed(() => {
if (!keep.value) return undefined
if (preset.value === 0) return Math.round(customAmount.value * customUnit.value)
return preset.value
})
const ttlError = computed(() => {
if (!keep.value) return ''
if (!ttlSeconds.value || ttlSeconds.value <= 0) return '请填写有效期'
if (ttlSeconds.value > store.maxTtl) return '有效期太长,请缩短'
return ''
})
const timeError = computed(() => {
if (mode.value !== 'later') return ''
if (!sendAt.value) return '请选择时间'
if (sendAt.value > Date.now() + store.maxSchedule * 1000) return '时间太远,请选近一些'
return ''
})
const canSend = computed(() => {
if (!store.running || sending.value || ttlError.value || timeError.value) return false
return tab.value === 'shell' ? !!shell.value.trim() : !!text.value.trim()
})
const untrusted = computed(() => (device.value ? !!store.untrusted[device.value.endpoint_id] : false))
const menuOptions = computed(() => {
const items: { label: string; key: string }[] = []
if (!menu.fromRemote) items.push({ label: '编辑', key: 'edit' }, { label: '删除', key: 'delete' })
items.push({ label: '复制到其他设备', key: 'copy' })
return items
})
const shownLogs = computed(() => (logs.value.items.length ? logs.value.items : logs.value.server_items))
function delivery() {
return {
send_at_ms: mode.value === 'later' && sendAt.value ? sendAt.value : undefined,
keep: keep.value,
ttl_seconds: keep.value ? ttlSeconds.value : undefined,
}
}
async function loadLists() {
const current = device.value
if (!current || !store.running) return
const [localRes, remoteRes] = await Promise.all([
api<{ items: Shortcut[] }>(`/v1/shortcuts/local?remote=${encodeURIComponent(current.endpoint_id)}`),
api<RemoteShortcuts>(`/v1/shortcuts/remote?remote=${encodeURIComponent(current.endpoint_id)}`),
])
localItems.value = localRes.items || []
remote.value = { items: remoteRes.items || [], synced_at: remoteRes.synced_at || '', syncing: !!remoteRes.syncing }
}
async function refreshRemote() {
const current = device.value
if (!current || !store.running) return
try {
await api('/v1/shortcuts/remote/refresh', {
method: 'POST',
body: JSON.stringify({ remote: current.endpoint_id }),
})
} catch {
// 对方不在线时仍显示上次同步的内容
}
await loadLists()
}
watch(
() => device.value?.endpoint_id,
async (id) => {
note.value = ''
localItems.value = []
remote.value = { items: [], synced_at: '', syncing: false }
if (!id) return
await loadLists().catch(() => undefined)
await refreshRemote()
},
{ immediate: true },
)
watch(
() => store.running,
(ok) => {
window.clearInterval(timer)
if (!ok) return
timer = window.setInterval(() => {
loadLists().catch(() => undefined)
if (logShow.value) loadLogs().catch(() => undefined)
}, 2000)
if (device.value) refreshRemote().catch(() => undefined)
},
{ immediate: true },
)
onUnmounted(() => window.clearInterval(timer))
async function sendCurrent() {
const current = device.value
if (!current) return
sending.value = true
try {
const payload =
tab.value === 'shell'
? { remote: current.endpoint_id, kind: 'shell', shell: shell.value.trim(), ...delivery() }
: { remote: current.endpoint_id, kind: 'text', text: text.value.trim(), ...delivery() }
const res = await api<{ id: string; note?: string }>('/v1/send', { method: 'POST', body: JSON.stringify(payload) })
note.value = res.note || '已发送'
} catch (err) {
message.error(err instanceof Error ? err.message : '没有发送')
} finally {
sending.value = false
}
}
async function saveCurrent() {
if (!shell.value.trim()) return
fromInput.value = true
editing.value = { id: '', name: '', shell: shell.value.trim(), confirm: false }
editShow.value = true
}
function openCreate() {
fromInput.value = false
editing.value = null
editShow.value = true
}
async function saveShortcut(form: { name: string; shell: string; confirm: boolean }) {
const current = device.value
if (!current) return
try {
if (editing.value?.id) {
await api(`/v1/shortcuts/local/${encodeURIComponent(editing.value.id)}`, {
method: 'PATCH',
body: JSON.stringify(form),
})
} else {
await api('/v1/shortcuts/local', {
method: 'POST',
body: JSON.stringify({ remote_id: current.endpoint_id, ...form }),
})
if (fromInput.value) shell.value = ''
}
editShow.value = false
await loadLists()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有保存')
}
}
function openMenu(event: MouseEvent, item: Shortcut, fromRemote: boolean) {
menu.show = true
menu.x = event.clientX
menu.y = event.clientY
menu.item = item
menu.fromRemote = fromRemote
}
function onMenu(key: string) {
menu.show = false
const item = menu.item
if (!item) return
if (key === 'edit') {
editing.value = item
editShow.value = true
} else if (key === 'delete') {
dialog.warning({
title: '删除快捷命令',
content: `删除「${item.name}」?`,
positiveText: '删除',
negativeText: '取消',
onPositiveClick: async () => {
await api(`/v1/shortcuts/local/${encodeURIComponent(item.id)}`, { method: 'DELETE' })
await loadLists()
},
})
} else if (key === 'copy') {
copyItem.value = item
copyFromRemote.value = menu.fromRemote
copyShow.value = true
}
}
async function copyTo(targets: string[]) {
const current = device.value
const item = copyItem.value
if (!current || !item) return
try {
await api('/v1/shortcuts/copy', {
method: 'POST',
body: JSON.stringify({
remote_id: current.endpoint_id,
shortcut_id: item.id,
from_remote: copyFromRemote.value,
targets,
}),
})
copyShow.value = false
message.success('已复制')
} catch (err) {
message.error(err instanceof Error ? err.message : '没有复制')
}
}
function runShortcut(item: Shortcut, fromRemote: boolean) {
const go = () => sendShortcut(item, fromRemote)
if (!item.confirm) {
go()
return
}
dialog.warning({
title: '确定执行',
content: `确定执行「${item.name}」?`,
positiveText: '确定',
negativeText: '取消',
onPositiveClick: go,
})
}
async function sendShortcut(item: Shortcut, fromRemote: boolean) {
const current = device.value
if (!current) return
try {
const res = await api<{ note?: string }>('/v1/send', {
method: 'POST',
body: JSON.stringify({
remote: current.endpoint_id,
kind: fromRemote ? 'remote' : 'local',
shortcut_id: item.id,
...delivery(),
}),
})
note.value = res.note || '已发送'
} catch (err) {
message.error(err instanceof Error ? err.message : '没有发送')
}
}
async function loadLogs() {
const current = device.value
if (!current) return
const res = await api<RemoteLogs>(`/v1/logs/remote?remote=${encodeURIComponent(current.endpoint_id)}`)
logs.value = {
items: res.items || [],
synced_at: res.synced_at || '',
syncing: !!res.syncing,
error: res.error,
server_items: res.server_items || [],
}
}
async function openLogs() {
logShow.value = true
const current = device.value
if (!current) return
try {
await api('/v1/logs/fetch', { method: 'POST', body: JSON.stringify({ remote: current.endpoint_id }) })
await loadLogs()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有打开')
}
}
</script>
+68
View File
@@ -0,0 +1,68 @@
<template>
<section class="trust">
<div class="trust-head">
<span class="page-title">信任</span>
</div>
<div class="trust-scroll">
<p class="muted">这里添加的设备可以命令本机。</p>
<div v-if="!store.running" class="empty">请先启动被控。</div>
<div v-else-if="items.length === 0" class="empty">还没有信任的设备。</div>
<div v-for="id in items" :key="id" class="trust-row">
<span>{{ store.nameOf(id) }}</span>
<span v-if="store.nameOf(id) !== id" class="device-id">{{ id }}</span>
<n-button size="tiny" @click="remove(id)">移除</n-button>
</div>
</div>
<form class="trust-add" @submit.prevent="add">
<n-input v-model:value="endpoint" placeholder="端编号" />
<n-button type="primary" attr-type="submit" :disabled="!endpoint.trim() || !store.running">添加</n-button>
</form>
</section>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { NButton, NInput, useMessage } from 'naive-ui'
import { api } from '../api'
import { useAppStore } from '../stores/app'
const store = useAppStore()
const message = useMessage()
const endpoint = ref('')
const items = ref<string[]>([])
async function load() {
if (!store.running) {
items.value = []
return
}
try {
const res = await api<{ items: string[] }>('/v1/trust')
items.value = res.items || []
} catch (err) {
message.error(err instanceof Error ? err.message : '没有读取')
}
}
async function add() {
try {
await api('/v1/trust', { method: 'POST', body: JSON.stringify({ endpoint_id: endpoint.value.trim() }) })
endpoint.value = ''
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有添加')
}
}
async function remove(id: string) {
try {
await api(`/v1/trust/${encodeURIComponent(id)}`, { method: 'DELETE' })
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : '没有移除')
}
}
watch(() => store.running, load)
onMounted(load)
</script>
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts", "src/**/*.vue", "env.d.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"types": ["node"]
},
"include": ["vite.config.ts"]
}
+82
View File
@@ -0,0 +1,82 @@
import { defineConfig, type Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawn } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const here = path.dirname(fileURLToPath(import.meta.url))
function agentFile() {
if (process.env.TAPREMLY_HOME) return path.join(process.env.TAPREMLY_HOME, 'agent.json')
const local = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
return path.join(local, 'TapRemly', 'agent.json')
}
function alive(pid: number) {
if (!pid) return false
try {
process.kill(pid, 0)
return true
} catch (err) {
return (err as NodeJS.ErrnoException).code === 'EPERM'
}
}
function readInfo() {
try {
const info = JSON.parse(fs.readFileSync(agentFile(), 'utf8')) as { addr?: string; token?: string; pid?: number }
const pid = Number(info.pid || 0)
if (!info.addr || !info.token || !alive(pid)) return { running: false, addr: '', token: '', pid: 0 }
return { running: true, addr: info.addr, token: info.token, pid }
} catch {
return { running: false, addr: '', token: '', pid: 0 }
}
}
function agentDev(): Plugin {
return {
name: 'tapremly-agent-dev',
configureServer(server) {
server.middlewares.use('/__agent', (req, res) => {
if (req.method === 'POST' && req.url?.startsWith('/start')) {
const exe = path.resolve(here, '../agent/tapremly-agent.exe')
if (!fs.existsSync(exe)) {
res.statusCode = 404
res.end('找不到被控程序')
return
}
const child = spawn(exe, [], { detached: true, stdio: 'ignore', windowsHide: true })
child.unref()
res.end('ok')
return
}
if (req.method === 'POST' && req.url?.startsWith('/stop')) {
const info = readInfo()
if (info.running) {
fetch(`http://${info.addr}/v1/stop`, {
method: 'POST',
headers: { Authorization: `Bearer ${info.token}` },
}).catch(() => undefined)
}
res.end('ok')
return
}
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify(readInfo()))
})
},
}
}
export default defineConfig({
plugins: [vue(), agentDev()],
clearScreen: false,
server: {
host: '127.0.0.1',
port: 1420,
strictPort: true,
},
envPrefix: ['VITE_', 'TAURI_'],
})