@aivin-labs/cli 1.0.21 → 1.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.mjs +67 -2
- package/bin/lib/remote/autoStart.mjs +6 -1
- package/bin/lib/remote/autoUpdate.mjs +153 -141
- package/bin/lib/remote/client.mjs +77 -5
- package/bin/lib/remote/constants.mjs +2 -0
- package/bin/lib/remote/desktop/castFileDrop.mjs +227 -0
- package/bin/lib/remote/desktop/castInput.mjs +17 -4
- package/bin/lib/remote/desktop/desktopCast.mjs +3 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +132 -20
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +37 -3
- package/bin/lib/remote/desktop/fileAssociation.mjs +104 -0
- package/bin/lib/remote/desktop/index.mjs +54 -5
- package/bin/lib/remote/desktop/strings.mjs +8 -0
- package/bin/lib/remote/desktop/traySource.mjs +72 -1
- package/bin/lib/remote/desktop/uninstall.mjs +96 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +191 -181
- package/bin/lib/remote/deviceProfile.mjs +2 -4
- package/bin/lib/remote/mascot/ask.mjs +983 -933
- package/bin/lib/remote/mascot/askHostSource.mjs +4 -2
- package/bin/lib/remote/mascot/fileChips.mjs +2 -2
- package/bin/lib/remote/mascot/index.mjs +69 -5
- package/bin/lib/remote/mascot/strings.mjs +18 -0
- package/bin/lib/remote/sandbox.mjs +3 -3
- package/bin/lib/remote/workFolder.mjs +100 -0
- package/docs/CLI.md +1576 -1545
- package/package.json +75 -75
|
@@ -140,6 +140,8 @@ export const ServerFeature = Object.freeze({
|
|
|
140
140
|
CHAT_CANCEL: 'chat_cancel',
|
|
141
141
|
/** Mở phiên chat mới cho linh vật (`device:chat_new`). */
|
|
142
142
|
CHAT_NEW: 'chat_new',
|
|
143
|
+
/** Giao thêm việc khi lượt trước chưa xong (`device:chat` + `parallel`) — chạy ở phiên riêng, kết quả tới bằng báo chủ động. */
|
|
144
|
+
CHAT_PARALLEL: 'chat_parallel',
|
|
143
145
|
});
|
|
144
146
|
|
|
145
147
|
/** Nhóm giới hạn song song trên máy — mỗi công cụ thuộc một nhóm. */
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { randomBytes } from 'crypto';
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Nhận tệp người xem kéo thả / dán vào màn hình máy (Desktop Scenecast), đi peer-to-peer qua kênh WebRTC `aivin-desktop-files`.
|
|
9
|
+
* Không phải "thả vào ứng dụng" thật (trình duyệt không giả lập được thao tác thả OLE): tệp lưu vào thư mục Tải về, Explorer mở chọn sẵn tệp cuối.
|
|
10
|
+
* Chỉ nhận lúc được thao tác (`checkAllowed` — chủ máy chưa tạm dừng, AI không đang bấm). Không ghi đè tệp có sẵn; gắn Mark-of-the-Web để
|
|
11
|
+
* Windows cảnh báo như tệp tải từ Internet khi mở. Giới hạn bộ nhớ nằm ở phía gửi: chỉ gửi tiếp khi máy đã báo ghi xong (`ack`).
|
|
12
|
+
*
|
|
13
|
+
* Người xem → máy: `begin {id, name, size}` · khúc nhị phân · `end {id, reveal}` · `cancel {id}`.
|
|
14
|
+
* Máy → người xem: `accepted {id}` · `ack {id, bytes}` · `saved {id, name, path}` · `rejected {id, reason}` · `failed {id, reason}`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const FileDropReason = Object.freeze({
|
|
18
|
+
PAUSED: 'paused',
|
|
19
|
+
AI_ACTIVE: 'ai_active',
|
|
20
|
+
INVALID: 'invalid',
|
|
21
|
+
TOO_LARGE: 'too_large',
|
|
22
|
+
NO_SPACE: 'no_space',
|
|
23
|
+
TIMEOUT: 'timeout',
|
|
24
|
+
WRITE_FAILED: 'write_failed',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const MAX_DROP_BYTES = 8 * 1024 ** 3;
|
|
28
|
+
const DEFAULT_DIR = path.join(os.homedir(), 'Downloads');
|
|
29
|
+
const ACK_EVERY_BYTES = 256 * 1024;
|
|
30
|
+
const IDLE_TIMEOUT_MS = 60_000;
|
|
31
|
+
/** Chừa lại khi kiểm chỗ trống: ổ đầy sát nút làm Windows và ứng dụng khác lỗi theo. */
|
|
32
|
+
const FREE_SPACE_MARGIN_BYTES = 64 * 1024 ** 2;
|
|
33
|
+
const MAX_NAME_CHARS = 200;
|
|
34
|
+
const MAX_ID_CHARS = 64;
|
|
35
|
+
const PART_PREFIX = '.aivin-drop-';
|
|
36
|
+
const STALE_PART_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
const ZONE_IDENTIFIER = '[ZoneTransfer]\r\nZoneId=3\r\n';
|
|
38
|
+
|
|
39
|
+
/** Tên tệp an toàn trên Windows: bỏ đường dẫn, ký tự cấm, ký tự đảo chiều (giả đuôi `gpj.exe`), tên thiết bị. */
|
|
40
|
+
export function safeDropName(raw) {
|
|
41
|
+
const base = String(raw ?? '').split(/[\\/]/).pop();
|
|
42
|
+
// eslint-disable-next-line no-control-regex
|
|
43
|
+
let name = base.replace(/[--]/g, '').replace(/[<>:"|?*\x00-\x1f]/g, '_').replace(/[. ]+$/, '').trim();
|
|
44
|
+
if (!name || name === '.' || name === '..') name = 'file';
|
|
45
|
+
if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(name)) name = `_${name}`;
|
|
46
|
+
if (name.length > MAX_NAME_CHARS) {
|
|
47
|
+
const ext = path.extname(name).slice(0, 20);
|
|
48
|
+
name = name.slice(0, MAX_NAME_CHARS - ext.length) + ext;
|
|
49
|
+
}
|
|
50
|
+
return name;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Giữ chỗ tên còn trống bằng tạo tệp độc quyền (`wx`) rồi mới đổi tên đè lên — không có khoảng hở để ghi đè tệp của người khác. */
|
|
54
|
+
async function reserveName(dir, name) {
|
|
55
|
+
const { name: stem, ext } = path.parse(name);
|
|
56
|
+
for (let n = 0; n < 1000; n++) {
|
|
57
|
+
const dest = path.join(dir, n ? `${stem} (${n})${ext}` : name);
|
|
58
|
+
try {
|
|
59
|
+
await (await fs.promises.open(dest, 'wx')).close();
|
|
60
|
+
return dest;
|
|
61
|
+
} catch (e) {
|
|
62
|
+
if (e?.code !== 'EEXIST') throw e;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
throw new Error('No free file name');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function removeStaleParts(dir, now) {
|
|
69
|
+
const names = await fs.promises.readdir(dir).catch(() => []);
|
|
70
|
+
await Promise.all(names.filter((n) => n.startsWith(PART_PREFIX) && n.endsWith('.part')).map(async (n) => {
|
|
71
|
+
const file = path.join(dir, n);
|
|
72
|
+
const st = await fs.promises.stat(file).catch(() => null);
|
|
73
|
+
if (st && now() - st.mtimeMs > STALE_PART_MS) await fs.promises.rm(file, { force: true }).catch(() => undefined);
|
|
74
|
+
}));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Mở Explorer chọn sẵn tệp vừa nhận: người xem thấy trên màn hình và kéo tiếp vào ứng dụng đích. Không chạy tệp. */
|
|
78
|
+
export function revealInExplorer(file, spawnImpl = spawn) {
|
|
79
|
+
try {
|
|
80
|
+
// Explorer tự tách `/select,"…"`, không theo cách Node đặt ngoặc kép cho cả tham số.
|
|
81
|
+
const child = spawnImpl('explorer.exe', [`/select,"${file}"`], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true });
|
|
82
|
+
child.on?.('error', () => {});
|
|
83
|
+
child.unref?.();
|
|
84
|
+
} catch { /* không mở được thì tệp vẫn đã lưu, FE báo đường dẫn */ }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createCastFileDrop({
|
|
88
|
+
dir = DEFAULT_DIR, reply = () => {}, checkAllowed = () => null, onSaved = () => {},
|
|
89
|
+
maxBytes = MAX_DROP_BYTES, idleMs = IDLE_TIMEOUT_MS, statfs = fs.promises.statfs, now = Date.now,
|
|
90
|
+
} = {}) {
|
|
91
|
+
/** Mỗi người xem một lần gửi; mọi bước đi tuần tự theo `queue` — khúc tới trong lúc đang ghi / đang mở tệp phải chờ. */
|
|
92
|
+
const viewers = new Map();
|
|
93
|
+
const stateOf = (viewerId) => {
|
|
94
|
+
if (!viewers.has(viewerId)) viewers.set(viewerId, { queue: Promise.resolve(), active: null });
|
|
95
|
+
return viewers.get(viewerId);
|
|
96
|
+
};
|
|
97
|
+
const enqueue = (viewerId, step) => {
|
|
98
|
+
const state = stateOf(viewerId);
|
|
99
|
+
state.queue = state.queue.then(() => step(state)).catch(() => undefined);
|
|
100
|
+
return state.queue;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
async function discard(state) {
|
|
104
|
+
const active = state.active;
|
|
105
|
+
if (!active) return;
|
|
106
|
+
state.active = null;
|
|
107
|
+
clearTimeout(active.timer);
|
|
108
|
+
await active.handle.close().catch(() => undefined);
|
|
109
|
+
await fs.promises.rm(active.part, { force: true }).catch(() => undefined);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function fail(viewerId, state, reason) {
|
|
113
|
+
const id = state.active?.id;
|
|
114
|
+
await discard(state);
|
|
115
|
+
if (id) reply(viewerId, { t: 'failed', id, reason });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function touch(viewerId, state) {
|
|
119
|
+
const active = state.active;
|
|
120
|
+
clearTimeout(active.timer);
|
|
121
|
+
active.timer = setTimeout(() => {
|
|
122
|
+
void enqueue(viewerId, (s) => (s.active === active ? fail(viewerId, s, FileDropReason.TIMEOUT) : undefined));
|
|
123
|
+
}, idleMs);
|
|
124
|
+
active.timer.unref?.();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function hasRoom(size) {
|
|
128
|
+
try {
|
|
129
|
+
const st = await statfs(dir);
|
|
130
|
+
return Number(st.bavail) * Number(st.bsize) >= size + FREE_SPACE_MARGIN_BYTES;
|
|
131
|
+
} catch {
|
|
132
|
+
return true; // Không đo được (Bun bản cũ, ổ lạ): cứ ghi, đầy thì lỗi ghi báo sau.
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function begin(viewerId, state, msg) {
|
|
137
|
+
const id = typeof msg.id === 'string' && msg.id && msg.id.length <= MAX_ID_CHARS ? msg.id : null;
|
|
138
|
+
if (!id) return;
|
|
139
|
+
const rejected = (reason) => reply(viewerId, { t: 'rejected', id, reason });
|
|
140
|
+
// Lần gửi trước chưa xong mà người xem đã gửi mới: họ vừa nối lại, không còn ai chờ tệp dở kia.
|
|
141
|
+
await discard(state);
|
|
142
|
+
const size = Number(msg.size);
|
|
143
|
+
if (!Number.isSafeInteger(size) || size < 0 || typeof msg.name !== 'string') return rejected(FileDropReason.INVALID);
|
|
144
|
+
if (size > maxBytes) return rejected(FileDropReason.TOO_LARGE);
|
|
145
|
+
const blocked = checkAllowed();
|
|
146
|
+
if (blocked) return rejected(blocked);
|
|
147
|
+
try {
|
|
148
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
149
|
+
if (!await hasRoom(size)) return rejected(FileDropReason.NO_SPACE);
|
|
150
|
+
await removeStaleParts(dir, now);
|
|
151
|
+
const part = path.join(dir, `${PART_PREFIX}${randomBytes(8).toString('hex')}.part`);
|
|
152
|
+
const handle = await fs.promises.open(part, 'wx');
|
|
153
|
+
state.active = { id, name: safeDropName(msg.name), size, part, handle, written: 0, ackedAt: 0, timer: null };
|
|
154
|
+
} catch {
|
|
155
|
+
return rejected(FileDropReason.WRITE_FAILED);
|
|
156
|
+
}
|
|
157
|
+
touch(viewerId, state);
|
|
158
|
+
reply(viewerId, { t: 'accepted', id });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function writeChunk(viewerId, state, chunk) {
|
|
162
|
+
const active = state.active;
|
|
163
|
+
if (!active) return; // Khúc còn trên đường của lần đã huỷ.
|
|
164
|
+
const blocked = checkAllowed();
|
|
165
|
+
if (blocked) return fail(viewerId, state, blocked);
|
|
166
|
+
if (active.written + chunk.length > active.size) return fail(viewerId, state, FileDropReason.INVALID);
|
|
167
|
+
try {
|
|
168
|
+
let offset = 0;
|
|
169
|
+
while (offset < chunk.length) {
|
|
170
|
+
const { bytesWritten } = await active.handle.write(chunk, offset, chunk.length - offset);
|
|
171
|
+
offset += bytesWritten;
|
|
172
|
+
}
|
|
173
|
+
} catch (e) {
|
|
174
|
+
return fail(viewerId, state, e?.code === 'ENOSPC' ? FileDropReason.NO_SPACE : FileDropReason.WRITE_FAILED);
|
|
175
|
+
}
|
|
176
|
+
active.written += chunk.length;
|
|
177
|
+
touch(viewerId, state);
|
|
178
|
+
if (active.written - active.ackedAt >= ACK_EVERY_BYTES) {
|
|
179
|
+
active.ackedAt = active.written;
|
|
180
|
+
reply(viewerId, { t: 'ack', id: active.id, bytes: active.written });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function end(viewerId, state, msg) {
|
|
185
|
+
const active = state.active;
|
|
186
|
+
if (!active || msg.id !== active.id) return;
|
|
187
|
+
if (active.written !== active.size) return fail(viewerId, state, FileDropReason.INVALID);
|
|
188
|
+
state.active = null;
|
|
189
|
+
clearTimeout(active.timer);
|
|
190
|
+
let dest = null;
|
|
191
|
+
try {
|
|
192
|
+
await active.handle.close();
|
|
193
|
+
dest = await reserveName(dir, active.name);
|
|
194
|
+
await fs.promises.rename(active.part, dest);
|
|
195
|
+
} catch {
|
|
196
|
+
await active.handle.close().catch(() => undefined);
|
|
197
|
+
await fs.promises.rm(active.part, { force: true }).catch(() => undefined);
|
|
198
|
+
if (dest) await fs.promises.rm(dest, { force: true }).catch(() => undefined);
|
|
199
|
+
return reply(viewerId, { t: 'failed', id: active.id, reason: FileDropReason.WRITE_FAILED });
|
|
200
|
+
}
|
|
201
|
+
// Ổ không phải NTFS không có luồng phụ: bỏ qua, tệp vẫn nhận xong.
|
|
202
|
+
if (process.platform === 'win32') await fs.promises.writeFile(`${dest}:Zone.Identifier`, ZONE_IDENTIFIER).catch(() => undefined);
|
|
203
|
+
reply(viewerId, { t: 'saved', id: active.id, name: path.basename(dest), path: dest });
|
|
204
|
+
onSaved({ viewerId, path: dest, name: path.basename(dest), bytes: active.size, reveal: msg.reveal === true });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function message(viewerId, msg) {
|
|
208
|
+
if (msg?.t === 'begin') return enqueue(viewerId, (s) => begin(viewerId, s, msg));
|
|
209
|
+
if (msg?.t === 'end') return enqueue(viewerId, (s) => end(viewerId, s, msg));
|
|
210
|
+
if (msg?.t === 'cancel') return enqueue(viewerId, (s) => (s.active?.id === msg.id ? discard(s) : undefined));
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const chunk = (viewerId, data) => enqueue(viewerId, (s) => writeChunk(viewerId, s, data));
|
|
215
|
+
|
|
216
|
+
/** Người xem rời: bỏ tệp dở. Không còn ai nhận tin nên không báo. */
|
|
217
|
+
function close(viewerId) {
|
|
218
|
+
if (!viewers.has(viewerId)) return Promise.resolve();
|
|
219
|
+
const done = enqueue(viewerId, (s) => discard(s));
|
|
220
|
+
viewers.delete(viewerId);
|
|
221
|
+
return done;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const closeAll = () => Promise.all([...viewers.keys()].map(close));
|
|
225
|
+
|
|
226
|
+
return { message, chunk, close, closeAll };
|
|
227
|
+
}
|
|
@@ -69,16 +69,26 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
|
|
|
69
69
|
let lastHumanAt = null;
|
|
70
70
|
let accepted = 0;
|
|
71
71
|
let window = { start: 0, count: 0 };
|
|
72
|
+
/** Nút chuột người xem đang giữ trên máy: gói nhả của chúng luôn được qua cổng, không thì nút kẹt xuống tới hết phiên. */
|
|
73
|
+
const heldButtons = new Set();
|
|
72
74
|
const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
73
75
|
|
|
74
76
|
function accept(raw) {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
+
const releasing = raw?.action === 'mouseup' && heldButtons.has(Number(raw.button) || 0);
|
|
78
|
+
const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE : null;
|
|
79
|
+
if (blocked && !releasing) return { ok: false, reason: blocked };
|
|
77
80
|
const t = now();
|
|
78
81
|
if (t - window.start >= 1000) window = { start: t, count: 0 };
|
|
79
|
-
if (++window.count > maxPerSec) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
|
|
82
|
+
if (++window.count > maxPerSec && !releasing) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
|
|
80
83
|
const cmd = sanitizeCastInput(raw);
|
|
81
84
|
if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
|
|
85
|
+
if (cmd.action === 'mousedown') heldButtons.add(cmd.button ?? 0);
|
|
86
|
+
if (cmd.action === 'mouseup') heldButtons.delete(cmd.button ?? 0);
|
|
87
|
+
if (blocked) {
|
|
88
|
+
// Chỉ nhả nút, không kéo con trỏ khỏi chỗ AI đang bấm; không tính là người đang thao tác.
|
|
89
|
+
const { x: _x, y: _y, rx: _rx, ry: _ry, ...release } = cmd;
|
|
90
|
+
return { ok: true, cmd: release };
|
|
91
|
+
}
|
|
82
92
|
lastHumanAt = t;
|
|
83
93
|
accepted++;
|
|
84
94
|
return { ok: true, cmd };
|
|
@@ -94,5 +104,8 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
|
|
|
94
104
|
/** Số thao tác đã nhận từ lần gọi trước (nhật ký phiên trên máy) — đọc xong đặt lại 0. */
|
|
95
105
|
function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
|
|
96
106
|
|
|
97
|
-
|
|
107
|
+
/** Máy vừa nhả hết nút (`release_all`): AI sắp bấm hoặc người xem đã rời. Trả có đang giữ nút nào không để nơi gọi biết cần gửi lệnh nhả. */
|
|
108
|
+
function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
|
|
109
|
+
|
|
110
|
+
return { accept, waitHumanIdle, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
|
|
98
111
|
}
|
|
@@ -86,6 +86,7 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
|
|
|
86
86
|
onMeta,
|
|
87
87
|
onCursor,
|
|
88
88
|
onCursorShape,
|
|
89
|
+
onInputFocus,
|
|
89
90
|
onCapture,
|
|
90
91
|
rawPipe = false,
|
|
91
92
|
onReady,
|
|
@@ -174,6 +175,8 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
|
|
|
174
175
|
onCursor?.({ x: msg.x, y: msg.y, visible: msg.visible, shape: msg.shape });
|
|
175
176
|
} else if (msg.t === 'cursor_shape') {
|
|
176
177
|
onCursorShape?.({ id: msg.id, png: msg.png, hotX: msg.hotX, hotY: msg.hotY });
|
|
178
|
+
} else if (msg.t === 'input_focus') {
|
|
179
|
+
onInputFocus?.({ editable: msg.editable === true });
|
|
177
180
|
} else if (msg.t === 'capture') {
|
|
178
181
|
onCapture?.({ mode: msg.mode, reason: msg.reason });
|
|
179
182
|
} else if (msg.t === 'error') {
|
|
@@ -27,6 +27,7 @@ using System.Runtime.InteropServices;
|
|
|
27
27
|
using System.Text;
|
|
28
28
|
using System.Threading;
|
|
29
29
|
using System.Web.Script.Serialization;
|
|
30
|
+
using System.Windows.Automation;
|
|
30
31
|
using System.Windows.Forms;
|
|
31
32
|
|
|
32
33
|
namespace AivinDesktopCast {
|
|
@@ -37,6 +38,27 @@ namespace AivinDesktopCast {
|
|
|
37
38
|
[DllImport("user32.dll")] public static extern void keybd_event(byte bVk, ushort bScan, uint dwFlags, UIntPtr dwExtraInfo);
|
|
38
39
|
[DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
|
|
39
40
|
|
|
41
|
+
// Gõ chữ: keybd_event chỉ mang được 1 byte mã quét (BYTE bScan) → chữ ngoài Latin-1 (ư ơ đ ạ ế…) bị cắt thành ký tự rác.
|
|
42
|
+
// SendInput + KEYEVENTF_UNICODE mang đủ 16 bit mỗi đơn vị UTF-16.
|
|
43
|
+
[StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
44
|
+
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
45
|
+
[StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
46
|
+
[StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public INPUTUNION u; }
|
|
47
|
+
[DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
|
|
48
|
+
public const uint INPUT_KEYBOARD = 1;
|
|
49
|
+
|
|
50
|
+
// Ô nhập chữ đang có tiêu điểm: cửa sổ trước mặt có caret hệ thống (ô Win32, Office, Chromium / Edge đều tạo caret cho trợ năng).
|
|
51
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
52
|
+
public struct RECT { public int left; public int top; public int right; public int bottom; }
|
|
53
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
54
|
+
public struct GUITHREADINFO {
|
|
55
|
+
public int cbSize; public uint flags; public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture;
|
|
56
|
+
public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret; public RECT rcCaret;
|
|
57
|
+
}
|
|
58
|
+
[DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO info);
|
|
59
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
60
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr pid);
|
|
61
|
+
|
|
40
62
|
[StructLayout(LayoutKind.Sequential)]
|
|
41
63
|
public struct POINT { public int x; public int y; }
|
|
42
64
|
|
|
@@ -509,6 +531,9 @@ namespace AivinDesktopCast {
|
|
|
509
531
|
}
|
|
510
532
|
} catch {
|
|
511
533
|
running = false;
|
|
534
|
+
} finally {
|
|
535
|
+
// Dừng phiên hoặc daemon chết (stdin đóng) lúc người xem đang kéo: không để nút chuột / phím bổ trợ kẹt xuống trên máy.
|
|
536
|
+
ReleaseHeldInput();
|
|
512
537
|
}
|
|
513
538
|
}
|
|
514
539
|
|
|
@@ -635,9 +660,35 @@ namespace AivinDesktopCast {
|
|
|
635
660
|
}
|
|
636
661
|
}
|
|
637
662
|
|
|
663
|
+
// Nút + phím bổ trợ đang giữ qua mousedown (chỉ luồng đọc lệnh đụng tới). Gói mouseup không đủ để biết cần nhả gì: người xem có thể thả Ctrl trước khi thả chuột.
|
|
664
|
+
static readonly List<int> heldButtons = new List<int>();
|
|
665
|
+
static readonly List<byte> heldModifiers = new List<byte>();
|
|
666
|
+
|
|
667
|
+
static void MouseButton(int button, bool down) {
|
|
668
|
+
uint flag = button == 2 ? (down ? Native.MOUSEEVENTF_RIGHTDOWN : Native.MOUSEEVENTF_RIGHTUP)
|
|
669
|
+
: button == 1 ? (down ? Native.MOUSEEVENTF_MIDDLEDOWN : Native.MOUSEEVENTF_MIDDLEUP)
|
|
670
|
+
: (down ? Native.MOUSEEVENTF_LEFTDOWN : Native.MOUSEEVENTF_LEFTUP);
|
|
671
|
+
Native.mouse_event(flag, 0, 0, 0, 0);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
static void ReleaseHeldModifiers() {
|
|
675
|
+
ReleaseModifiers(heldModifiers);
|
|
676
|
+
heldModifiers.Clear();
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
static void ReleaseHeldInput() {
|
|
680
|
+
for (int i = heldButtons.Count - 1; i >= 0; i--) MouseButton(heldButtons[i], false);
|
|
681
|
+
heldButtons.Clear();
|
|
682
|
+
ReleaseHeldModifiers();
|
|
683
|
+
}
|
|
684
|
+
|
|
638
685
|
static void HandleInput(Dictionary<string, object> cmd) {
|
|
639
686
|
try {
|
|
640
687
|
string action = cmd.ContainsKey("action") ? Convert.ToString(cmd["action"]) : "";
|
|
688
|
+
if (action == "release_all") {
|
|
689
|
+
ReleaseHeldInput();
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
641
692
|
double rx = cmd.ContainsKey("x") ? Convert.ToDouble(cmd["x"]) : 0;
|
|
642
693
|
double ry = cmd.ContainsKey("y") ? Convert.ToDouble(cmd["y"]) : 0;
|
|
643
694
|
var mods = ExtractModifiers(cmd);
|
|
@@ -677,6 +728,7 @@ namespace AivinDesktopCast {
|
|
|
677
728
|
} finally {
|
|
678
729
|
ReleaseModifiers(mods);
|
|
679
730
|
}
|
|
731
|
+
if (button == 0) ProbeInputFocus();
|
|
680
732
|
} else if (action == "dblclick") {
|
|
681
733
|
Native.SetCursorPos(targetX, targetY);
|
|
682
734
|
Thread.Sleep(10);
|
|
@@ -704,20 +756,22 @@ namespace AivinDesktopCast {
|
|
|
704
756
|
} else if (action == "mousedown") {
|
|
705
757
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
706
758
|
Native.SetCursorPos(targetX, targetY);
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
759
|
+
var newMods = new List<byte>();
|
|
760
|
+
for (int i = 0; i < mods.Count; i++) {
|
|
761
|
+
if (!heldModifiers.Contains(mods[i])) newMods.Add(mods[i]);
|
|
762
|
+
}
|
|
763
|
+
PressModifiers(newMods);
|
|
764
|
+
heldModifiers.AddRange(newMods);
|
|
765
|
+
MouseButton(button, true);
|
|
766
|
+
if (!heldButtons.Contains(button)) heldButtons.Add(button);
|
|
711
767
|
} else if (action == "mouseup") {
|
|
712
768
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
ReleaseModifiers(mods);
|
|
720
|
-
}
|
|
769
|
+
// Gói không toạ độ = chỉ nhả tại chỗ (AI đang bấm trên máy): không kéo con trỏ đi.
|
|
770
|
+
if (cmd.ContainsKey("rx") || cmd.ContainsKey("x")) Native.SetCursorPos(targetX, targetY);
|
|
771
|
+
MouseButton(button, false);
|
|
772
|
+
heldButtons.Remove(button);
|
|
773
|
+
if (heldButtons.Count == 0) ReleaseHeldModifiers();
|
|
774
|
+
if (button == 0) ProbeInputFocus();
|
|
721
775
|
} else if (action == "scroll") {
|
|
722
776
|
int deltaY = cmd.ContainsKey("deltaY") ? Convert.ToInt32(cmd["deltaY"]) : 0;
|
|
723
777
|
int deltaX = cmd.ContainsKey("deltaX") ? Convert.ToInt32(cmd["deltaX"]) : 0;
|
|
@@ -731,13 +785,7 @@ namespace AivinDesktopCast {
|
|
|
731
785
|
}
|
|
732
786
|
} else if (action == "type") {
|
|
733
787
|
string text = cmd.ContainsKey("text") ? Convert.ToString(cmd["text"]) : "";
|
|
734
|
-
if (!string.IsNullOrEmpty(text))
|
|
735
|
-
for (int i = 0; i < text.Length; i++) {
|
|
736
|
-
char c = text[i];
|
|
737
|
-
Native.keybd_event(0, (ushort)c, Native.KEYEVENTF_UNICODE, UIntPtr.Zero);
|
|
738
|
-
Native.keybd_event(0, (ushort)c, Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
|
|
739
|
-
}
|
|
740
|
-
}
|
|
788
|
+
if (!string.IsNullOrEmpty(text)) TypeUnicode(text);
|
|
741
789
|
} else if (action == "key") {
|
|
742
790
|
string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
|
|
743
791
|
HandleSpecialKey(key);
|
|
@@ -764,6 +812,70 @@ namespace AivinDesktopCast {
|
|
|
764
812
|
}
|
|
765
813
|
}
|
|
766
814
|
|
|
815
|
+
/** Gõ nguyên văn: mỗi đơn vị UTF-16 một cặp nhấn / nhả KEYEVENTF_UNICODE (cặp đại diện của emoji đi liền nhau), gửi theo lô. */
|
|
816
|
+
static void TypeUnicode(string text) {
|
|
817
|
+
const int chunk = 64;
|
|
818
|
+
int size = Marshal.SizeOf(typeof(Native.INPUT));
|
|
819
|
+
int start = 0;
|
|
820
|
+
while (start < text.Length) {
|
|
821
|
+
int end = Math.Min(text.Length, start + chunk);
|
|
822
|
+
// Không cắt đôi một cặp đại diện giữa hai lô.
|
|
823
|
+
if (end < text.Length && char.IsHighSurrogate(text[end - 1])) end--;
|
|
824
|
+
var inputs = new Native.INPUT[(end - start) * 2];
|
|
825
|
+
for (int i = start; i < end; i++) {
|
|
826
|
+
int k = (i - start) * 2;
|
|
827
|
+
inputs[k].type = Native.INPUT_KEYBOARD;
|
|
828
|
+
inputs[k].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE };
|
|
829
|
+
inputs[k + 1].type = Native.INPUT_KEYBOARD;
|
|
830
|
+
inputs[k + 1].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP };
|
|
831
|
+
}
|
|
832
|
+
Native.SendInput((uint)inputs.Length, inputs, size);
|
|
833
|
+
start = end;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
static int focusProbeSeq = 0;
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Sau cú nhấp trái của người xem: chờ ứng dụng nhận tiêu điểm rồi báo ô đang chọn có phải ô nhập chữ (có caret) không —
|
|
841
|
+
* trình duyệt trên điện thoại dựa vào đó tự mở bàn phím ảo. Chạy luồng riêng, không giữ hàng thao tác.
|
|
842
|
+
*/
|
|
843
|
+
static void ProbeInputFocus() {
|
|
844
|
+
int seq = Interlocked.Increment(ref focusProbeSeq);
|
|
845
|
+
ThreadPool.QueueUserWorkItem(_ => {
|
|
846
|
+
try {
|
|
847
|
+
Thread.Sleep(150);
|
|
848
|
+
if (seq != focusProbeSeq) return;
|
|
849
|
+
var info = new Native.GUITHREADINFO();
|
|
850
|
+
info.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
|
|
851
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
852
|
+
uint tid = fg == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(fg, IntPtr.Zero);
|
|
853
|
+
bool editable = (tid != 0 && Native.GetGUIThreadInfo(tid, ref info) && info.hwndCaret != IntPtr.Zero) || FocusedIsTextInput();
|
|
854
|
+
var msg = new Dictionary<string, object>();
|
|
855
|
+
msg["t"] = "input_focus";
|
|
856
|
+
msg["editable"] = editable;
|
|
857
|
+
Out.Send(msg);
|
|
858
|
+
} catch {
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** Chromium / Edge / Electron chỉ tạo caret hệ thống khi bật trợ năng → hỏi UI Automation: ô Edit, hoặc ô có giá trị sửa được. */
|
|
864
|
+
static bool FocusedIsTextInput() {
|
|
865
|
+
try {
|
|
866
|
+
var fe = AutomationElement.FocusedElement;
|
|
867
|
+
if (fe == null) return false;
|
|
868
|
+
var ct = fe.Current.ControlType;
|
|
869
|
+
if (ct == ControlType.Edit) return true;
|
|
870
|
+
if (ct == ControlType.ComboBox || ct == ControlType.Document) {
|
|
871
|
+
object vp;
|
|
872
|
+
if (fe.TryGetCurrentPattern(ValuePattern.Pattern, out vp)) return !((ValuePattern)vp).Current.IsReadOnly;
|
|
873
|
+
}
|
|
874
|
+
} catch {
|
|
875
|
+
}
|
|
876
|
+
return false;
|
|
877
|
+
}
|
|
878
|
+
|
|
767
879
|
static void HandleSpecialKey(string key) {
|
|
768
880
|
byte vk = KeyNameToVk(key);
|
|
769
881
|
if (vk != 0) {
|
|
@@ -780,7 +892,7 @@ export const DESKTOP_CAST_PS1 = String.raw`
|
|
|
780
892
|
$ErrorActionPreference = 'Stop'
|
|
781
893
|
$dll = $env:AIVIN_CAST_DLL
|
|
782
894
|
$src = $env:AIVIN_CAST_SRC
|
|
783
|
-
$refs = @('System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions', 'System.Core')
|
|
895
|
+
$refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions', 'System.Core')
|
|
784
896
|
foreach ($r in $refs) { Add-Type -AssemblyName $r }
|
|
785
897
|
if ($dll -and (Test-Path -LiteralPath $dll)) {
|
|
786
898
|
Add-Type -Path $dll
|
|
@@ -9,6 +9,9 @@ const MAX_BUFFERED_BYTES = 512 * 1024;
|
|
|
9
9
|
/** Kênh thao tác chuột / phím người xem → máy: tin cậy + đúng thứ tự (nhả chuột không được đến trước nhấn), đi thẳng peer-to-peer. */
|
|
10
10
|
export const INPUT_CHANNEL = 'aivin-desktop-input';
|
|
11
11
|
const MAX_INPUT_MESSAGE_BYTES = 8 * 1024;
|
|
12
|
+
/** Kênh tệp người xem kéo thả / dán vào màn hình (castFileDrop.mjs): tin cậy + đúng thứ tự, tách khỏi kênh thao tác để tệp lớn không làm trễ chuột. */
|
|
13
|
+
export const FILE_CHANNEL = 'aivin-desktop-files';
|
|
14
|
+
const MAX_FILE_CHUNK_BYTES = 256 * 1024;
|
|
12
15
|
|
|
13
16
|
const MAX_CURSOR_SHAPES = 64;
|
|
14
17
|
/** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
|
|
@@ -64,7 +67,7 @@ export function unpackDesktopFrame(packet) {
|
|
|
64
67
|
}
|
|
65
68
|
}
|
|
66
69
|
|
|
67
|
-
export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onPeerReady = () => {}, onCursorMode = () => {}, loadRuntime } = {}) {
|
|
70
|
+
export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onFile = () => {}, onFileChunk = () => {}, onPeerReady = () => {}, onCursorMode = () => {}, loadRuntime } = {}) {
|
|
68
71
|
const peers = new Map();
|
|
69
72
|
/** Hình con trỏ đã thấy trong phiên — người xem nối sau vẫn nhận đủ (bộ quay chỉ gửi mỗi hình một lần). */
|
|
70
73
|
const cursorShapes = new Map();
|
|
@@ -101,11 +104,25 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
101
104
|
const pc = new RTCPeerConnection({ iceServers });
|
|
102
105
|
const channel = pc.createDataChannel('aivin-desktop-frames', { ordered: false, maxRetransmits: 0 });
|
|
103
106
|
const inputChannel = pc.createDataChannel(INPUT_CHANNEL, { ordered: true });
|
|
107
|
+
const fileChannel = pc.createDataChannel(FILE_CHANNEL, { ordered: true });
|
|
104
108
|
const VideoSource = wrtc?.nonstandard?.RTCVideoSource || wrtc?.default?.nonstandard?.RTCVideoSource;
|
|
105
109
|
if (VideoSource && !videoSource) videoSource = new VideoSource({ isScreencast: true });
|
|
106
110
|
const track = videoSource ? videoSource.createTrack() : null;
|
|
107
111
|
if (track) pc.addTrack(track);
|
|
108
|
-
const peer = { pc, channel, inputChannel, track, video: !!track, sessionId, viewerId, iceServers, videoBitrate, attempt, retryTimer: null, open: false, dropped: 0 };
|
|
112
|
+
const peer = { pc, channel, inputChannel, fileChannel, track, video: !!track, sessionId, viewerId, iceServers, videoBitrate, attempt, retryTimer: null, open: false, dropped: 0 };
|
|
113
|
+
fileChannel.binaryType = 'arraybuffer';
|
|
114
|
+
fileChannel.onmessage = ({ data }) => {
|
|
115
|
+
if (typeof data !== 'string') {
|
|
116
|
+
const bytes = Buffer.from(data);
|
|
117
|
+
if (bytes.length <= MAX_FILE_CHUNK_BYTES) onFileChunk(viewerId, bytes);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (data.length > MAX_INPUT_MESSAGE_BYTES) return;
|
|
121
|
+
let msg;
|
|
122
|
+
try { msg = JSON.parse(data); } catch { return; }
|
|
123
|
+
// Mã phiên lấy từ peer như kênh thao tác.
|
|
124
|
+
onFile(viewerId, msg, peer.sessionId);
|
|
125
|
+
};
|
|
109
126
|
inputChannel.onmessage = ({ data }) => {
|
|
110
127
|
const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
|
|
111
128
|
if (text.length > MAX_INPUT_MESSAGE_BYTES) return;
|
|
@@ -208,6 +225,22 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
208
225
|
for (const peer of peers.values()) if (peer.localCursor) sendShape(peer, shape);
|
|
209
226
|
}
|
|
210
227
|
|
|
228
|
+
/** Ô đang có tiêu điểm trên máy có phải ô nhập chữ không (sau cú nhấp của người xem) — trình duyệt điện thoại tự mở / đóng bàn phím ảo. */
|
|
229
|
+
function pushInputFocus(focus) {
|
|
230
|
+
const packet = JSON.stringify({ t: 'input_focus', editable: focus?.editable === true });
|
|
231
|
+
for (const peer of peers.values()) {
|
|
232
|
+
if (peer.inputChannel?.readyState !== 'open') continue;
|
|
233
|
+
try { peer.inputChannel.send(packet); } catch { /* kênh vừa đóng */ }
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Trả lời đúng người xem đang gửi tệp. */
|
|
238
|
+
function replyFile(viewerId, msg) {
|
|
239
|
+
const channel = peers.get(String(viewerId || ''))?.fileChannel;
|
|
240
|
+
if (channel?.readyState !== 'open') return;
|
|
241
|
+
try { channel.send(JSON.stringify(msg)); } catch { /* kênh vừa đóng */ }
|
|
242
|
+
}
|
|
243
|
+
|
|
211
244
|
/** Mọi người xem đều có video và tự vẽ con trỏ → bộ quay thôi lồng con trỏ vào khung. */
|
|
212
245
|
function localCursor() {
|
|
213
246
|
return peers.size > 0 && [...peers.values()].every(p => p.video && p.open && p.localCursor);
|
|
@@ -233,10 +266,11 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
233
266
|
clearTimeout(peer.retryTimer);
|
|
234
267
|
try { peer.channel.close(); } catch { /* already closed */ }
|
|
235
268
|
try { peer.inputChannel?.close(); } catch { /* already closed */ }
|
|
269
|
+
try { peer.fileChannel?.close(); } catch { /* already closed */ }
|
|
236
270
|
try { peer.track?.stop(); } catch { /* already stopped */ }
|
|
237
271
|
try { peer.pc.close(); } catch { /* already closed */ }
|
|
238
272
|
}
|
|
239
273
|
|
|
240
274
|
function closeAll() { for (const id of [...peers.keys()]) close(id); cursorShapes.clear(); }
|
|
241
|
-
return { start, signal, push, pushRaw, pushCursor, pushCursorShape, localCursor, needsJpeg, hasVideo, anyOpen, needsFallback, close, closeAll };
|
|
275
|
+
return { start, signal, push, pushRaw, pushCursor, pushCursorShape, pushInputFocus, replyFile, localCursor, needsJpeg, hasVideo, anyOpen, needsFallback, close, closeAll };
|
|
242
276
|
}
|