vanspod 0.4.13 → 0.4.15
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/README.md +4 -4
- package/dist/classroomApp.js +79 -0
- package/dist/commandRunner.js +1 -0
- package/dist/deviceConnection.js +166 -0
- package/dist/lineChanges.js +75 -0
- package/dist/localCommands.js +221 -0
- package/dist/localToolApproval.js +104 -0
- package/dist/localTools.js +209 -0
- package/dist/modelStatus.js +42 -1
- package/dist/page.js +126 -2
- package/dist/projectPath.js +86 -0
- package/dist/saveImage.js +111 -0
- package/dist/settingsActions.js +1 -1
- package/dist/start.js +54 -1
- package/dist/trayChannel.js +103 -0
- package/dist/version.js +1 -1
- package/dist/windowsEnvironmentSystem.js +1 -0
- package/package.json +1 -1
- package/scripts/tray.ps1 +268 -4
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.saveImage = saveImage;
|
|
7
|
+
// `save_image`: saves a generated image under `images/` in the Project Folder (ADR 0013).
|
|
8
|
+
// The Device-side contract is "save_image" in vans-mcp-server docs/device-relay-protocol.md.
|
|
9
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
10
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
11
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
12
|
+
const projectPath_1 = require("./projectPath");
|
|
13
|
+
const IMAGE_FOLDER = "images";
|
|
14
|
+
const NOT_SAVED = "沒有儲存圖片";
|
|
15
|
+
const EXTENSIONS = {
|
|
16
|
+
"image/png": [".png"],
|
|
17
|
+
"image/jpeg": [".jpg", ".jpeg"],
|
|
18
|
+
"image/webp": [".webp"],
|
|
19
|
+
"image/gif": [".gif"],
|
|
20
|
+
};
|
|
21
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
22
|
+
// Characters that Windows does not allow in a file name, and control characters.
|
|
23
|
+
const BAD_NAME_CHARS = /[<>:"|?*\u0000-\u001f]/g;
|
|
24
|
+
function invalid(message) {
|
|
25
|
+
return { ok: false, error: "invalid_arguments", message };
|
|
26
|
+
}
|
|
27
|
+
/** Only the base name, safe for Windows, with an extension that matches `mimeType`. */
|
|
28
|
+
function imageFileName(suggested, mimeType) {
|
|
29
|
+
const extensions = EXTENSIONS[mimeType];
|
|
30
|
+
const base = typeof suggested === "string" ? suggested.split(/[\\/]/).pop() : "";
|
|
31
|
+
let name = base.replace(BAD_NAME_CHARS, "").replace(/^[.\s]+|[.\s]+$/g, "");
|
|
32
|
+
if (!name)
|
|
33
|
+
name = "image";
|
|
34
|
+
if (!extensions.includes(node_path_1.default.extname(name).toLowerCase()))
|
|
35
|
+
name += extensions[0];
|
|
36
|
+
return name;
|
|
37
|
+
}
|
|
38
|
+
/** Width x height from the image header, or undefined when the header is not known. */
|
|
39
|
+
function dimensions(bytes, mimeType) {
|
|
40
|
+
if (mimeType === "image/png" && bytes.length >= 24)
|
|
41
|
+
return [bytes.readUInt32BE(16), bytes.readUInt32BE(20)];
|
|
42
|
+
if (mimeType === "image/gif" && bytes.length >= 10)
|
|
43
|
+
return [bytes.readUInt16LE(6), bytes.readUInt16LE(8)];
|
|
44
|
+
if (mimeType === "image/jpeg") {
|
|
45
|
+
// Walk the segments to the first start-of-frame marker (SOF0-SOF15, without DHT, JPG, DAC).
|
|
46
|
+
let at = 2;
|
|
47
|
+
while (at + 9 <= bytes.length && bytes[at] === 0xff) {
|
|
48
|
+
const marker = bytes[at + 1];
|
|
49
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
|
|
50
|
+
return [bytes.readUInt16BE(at + 7), bytes.readUInt16BE(at + 5)];
|
|
51
|
+
}
|
|
52
|
+
at += 2 + bytes.readUInt16BE(at + 2);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
function approvalBody(bytes, mimeType) {
|
|
58
|
+
const size = dimensions(bytes, mimeType);
|
|
59
|
+
const lines = [`類型:${mimeType}`, `大小:${bytes.length.toLocaleString("en-US")} 位元組`];
|
|
60
|
+
if (size)
|
|
61
|
+
lines.splice(1, 0, `尺寸:${size[0]} × ${size[1]} 像素`);
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
}
|
|
64
|
+
/** The name in `images/` with "-2", "-3", ... before the extension when the name is taken. */
|
|
65
|
+
function candidate(name, count) {
|
|
66
|
+
if (count === 1)
|
|
67
|
+
return name;
|
|
68
|
+
const extension = node_path_1.default.extname(name);
|
|
69
|
+
return `${name.slice(0, name.length - extension.length)}-${count}${extension}`;
|
|
70
|
+
}
|
|
71
|
+
async function saveImage(projectFolder, args, signal, context) {
|
|
72
|
+
const mimeType = args.mime_type;
|
|
73
|
+
if (typeof mimeType !== "string" || !Object.hasOwn(EXTENSIONS, mimeType)) {
|
|
74
|
+
return invalid("mime_type 必須是 image/png、image/jpeg、image/webp 或 image/gif。");
|
|
75
|
+
}
|
|
76
|
+
const data = typeof args.data === "string" ? args.data.replace(/\s/g, "") : "";
|
|
77
|
+
if (!data || data.length % 4 === 1 || !BASE64.test(data))
|
|
78
|
+
return invalid("data 必須是圖片內容的 base64 文字。");
|
|
79
|
+
const bytes = Buffer.from(data, "base64");
|
|
80
|
+
if (bytes.length === 0)
|
|
81
|
+
return invalid("data 必須是圖片內容的 base64 文字。");
|
|
82
|
+
const name = imageFileName(args.file_name, mimeType);
|
|
83
|
+
const refusal = await (0, localToolApproval_1.askApproval)(context.approver, {
|
|
84
|
+
tool: "save_image",
|
|
85
|
+
title: `儲存圖片 ${IMAGE_FOLDER}/${name}`,
|
|
86
|
+
body: approvalBody(bytes, mimeType),
|
|
87
|
+
folder: projectFolder,
|
|
88
|
+
}, signal, NOT_SAVED);
|
|
89
|
+
if (refusal)
|
|
90
|
+
return refusal;
|
|
91
|
+
for (let count = 1; count <= 1000; count++) {
|
|
92
|
+
// Resolve each time: `images` may be a link out of the Project Folder, or may change while the student decided.
|
|
93
|
+
const target = await (0, projectPath_1.resolveProjectPath)(projectFolder, `${IMAGE_FOLDER}/${candidate(name, count)}`, { allowMissing: true });
|
|
94
|
+
if (!target.ok)
|
|
95
|
+
return target;
|
|
96
|
+
if (target.exists)
|
|
97
|
+
continue;
|
|
98
|
+
try {
|
|
99
|
+
await promises_1.default.mkdir(node_path_1.default.dirname(target.absolute), { recursive: true });
|
|
100
|
+
// "wx" fails when the file exists, so a file made in the meantime is never overwritten.
|
|
101
|
+
await promises_1.default.writeFile(target.absolute, bytes, { flag: "wx" });
|
|
102
|
+
return { ok: true, result: { path: target.relative } };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code === "EEXIST")
|
|
106
|
+
continue;
|
|
107
|
+
return { ok: false, error: "failed", message: `無法儲存「${target.relative}」:${error instanceof Error ? error.message : "原因不明"}。` };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { ok: false, error: "failed", message: `${IMAGE_FOLDER}/ 裡同名的圖片太多,${NOT_SAVED}。` };
|
|
111
|
+
}
|
package/dist/settingsActions.js
CHANGED
|
@@ -5,7 +5,7 @@ exports.settingsActionsScript = `
|
|
|
5
5
|
var settingsBusy = false;
|
|
6
6
|
document.addEventListener("submit", async function (event) {
|
|
7
7
|
var form = event.target;
|
|
8
|
-
if (!form?.matches?.('form[action="/redeem"], form[action="/copy"], form[action="/clear"], form[action="/project-folder"], form[action="/pick-folder"], form[action="/switch"], form[action="/adapter"], form[action="/reload"], form[action="/environment-check"], form[action="/environment"]')) return;
|
|
8
|
+
if (!form?.matches?.('form[action="/redeem"], form[action="/copy"], form[action="/clear"], form[action="/local-tools"], form[action="/local-tool-approval"], form[action="/local-command-stop"], form[action="/project-folder"], form[action="/pick-folder"], form[action="/switch"], form[action="/adapter"], form[action="/reload"], form[action="/environment-check"], form[action="/environment"]')) return;
|
|
9
9
|
event.preventDefault();
|
|
10
10
|
if (settingsBusy || installBusy || installOpening || document.querySelector(".confirm-dialog")) return;
|
|
11
11
|
settingsBusy = true;
|
package/dist/start.js
CHANGED
|
@@ -7,6 +7,11 @@ exports.main = main;
|
|
|
7
7
|
const platformStorage_1 = require("./platformStorage");
|
|
8
8
|
const clientDetection_1 = require("./clientDetection");
|
|
9
9
|
const runtimeOptions_1 = require("./runtimeOptions");
|
|
10
|
+
const deviceConnection_1 = require("./deviceConnection");
|
|
11
|
+
const localTools_1 = require("./localTools");
|
|
12
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
13
|
+
const localCommands_1 = require("./localCommands");
|
|
14
|
+
const trayChannel_1 = require("./trayChannel");
|
|
10
15
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
11
16
|
const node_child_process_1 = require("node:child_process");
|
|
12
17
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
@@ -244,6 +249,7 @@ async function openTray(url) {
|
|
|
244
249
|
await promises_1.default.mkdir(directory, { recursive: true });
|
|
245
250
|
const script = await (0, desktop_1.materializeAsset)(directory, "tray.ps1");
|
|
246
251
|
const icon = await (0, desktop_1.materializeAsset)(directory, "brand-icon.ico");
|
|
252
|
+
const mascot = await (0, desktop_1.materializeAsset)(directory, "fadou-superhero.png");
|
|
247
253
|
return (0, node_child_process_1.spawn)("powershell.exe", [
|
|
248
254
|
"-STA",
|
|
249
255
|
"-NoProfile",
|
|
@@ -254,7 +260,10 @@ async function openTray(url) {
|
|
|
254
260
|
"-Url", url,
|
|
255
261
|
"-IconPath", icon,
|
|
256
262
|
"-StateFile", node_path_1.default.join((0, instance_1.managementDirectory)(), "runtime", "instance.json"),
|
|
257
|
-
|
|
263
|
+
"-MascotPath", mascot,
|
|
264
|
+
],
|
|
265
|
+
// stdin and stdout are the tray channel (src/trayChannel.ts).
|
|
266
|
+
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
258
267
|
}
|
|
259
268
|
let proxyAccepting = false;
|
|
260
269
|
function createProxy() {
|
|
@@ -400,6 +409,12 @@ async function main(instance) {
|
|
|
400
409
|
},
|
|
401
410
|
handle: (accepted, req, res) => dispatch(accepted, req, res),
|
|
402
411
|
});
|
|
412
|
+
// One Local Tool Approval queue for this Device. The page and the Approval Popup (tray) decide here.
|
|
413
|
+
const approvals = (0, localToolApproval_1.createApprovalQueue)();
|
|
414
|
+
// The bash commands of this VansPod run. Only memory: a restart starts an empty list.
|
|
415
|
+
const localCommands = (0, localCommands_1.createCommandLog)();
|
|
416
|
+
let trayChannel;
|
|
417
|
+
approvals.subscribe(() => trayChannel?.update());
|
|
403
418
|
app = new classroomApp_1.ClassroomApp({
|
|
404
419
|
detectClient: clientDetection_1.detectClient,
|
|
405
420
|
adapterSettings: (0, adapterSettings_1.createAdapterSettingsStorage)(settingsFile),
|
|
@@ -436,6 +451,14 @@ async function main(instance) {
|
|
|
436
451
|
},
|
|
437
452
|
proxy: createProxy(),
|
|
438
453
|
send: sendUpstream,
|
|
454
|
+
device: (0, deviceConnection_1.createDeviceConnection)({
|
|
455
|
+
url: process.env.CLASSROOM_DEVICE_RELAY_URL ?? "wss://mcp.vanscoding.com/device",
|
|
456
|
+
device: node_os_1.default.hostname(),
|
|
457
|
+
handle: (0, localTools_1.createLocalTools)({ projectFolder: () => app.view().projectFolder, system: localTools_1.localSystem, approver: approvals, commands: localCommands }),
|
|
458
|
+
onChange: () => trayChannel?.update(),
|
|
459
|
+
}),
|
|
460
|
+
approvals,
|
|
461
|
+
localCommands,
|
|
439
462
|
});
|
|
440
463
|
dispatch = async (accepted, req, res) => {
|
|
441
464
|
if (!/^(127\.0\.0\.1|localhost):\d+$/.test(req.headers.host ?? "")) {
|
|
@@ -538,6 +561,12 @@ async function main(instance) {
|
|
|
538
561
|
res.end(JSON.stringify((0, page_1.environmentStatus)(app.view())));
|
|
539
562
|
return;
|
|
540
563
|
}
|
|
564
|
+
if (req.method === "GET" && pathname === "/local-tool-approval-body") {
|
|
565
|
+
const answer = (0, page_1.localToolApprovalBodyResponse)(app, parsed.searchParams.get("id") ?? "");
|
|
566
|
+
res.writeHead(answer.status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
567
|
+
res.end(JSON.stringify(answer.body));
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
541
570
|
if (req.method === "GET" && pathname === "/model-status") {
|
|
542
571
|
res.writeHead(200, {
|
|
543
572
|
"Content-Type": "application/json; charset=utf-8",
|
|
@@ -703,6 +732,26 @@ async function main(instance) {
|
|
|
703
732
|
res.end(JSON.stringify({ ok }));
|
|
704
733
|
return;
|
|
705
734
|
}
|
|
735
|
+
if (req.method === "POST" && pathname === "/local-tools") {
|
|
736
|
+
const params = new URLSearchParams(await readBody(req));
|
|
737
|
+
await app.setLocalToolAccess(params.get("on") === "1");
|
|
738
|
+
goHome();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (req.method === "POST" && pathname === "/local-tool-approval") {
|
|
742
|
+
const params = new URLSearchParams(await readBody(req));
|
|
743
|
+
const decision = params.get("decision");
|
|
744
|
+
if (decision === "approve" || decision === "deny")
|
|
745
|
+
app.decideLocalToolApproval(params.get("id") ?? "", decision);
|
|
746
|
+
goHome();
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (req.method === "POST" && pathname === "/local-command-stop") {
|
|
750
|
+
const params = new URLSearchParams(await readBody(req));
|
|
751
|
+
app.stopLocalCommand(params.get("id") ?? "");
|
|
752
|
+
goHome();
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
706
755
|
if (req.method === "POST" && pathname === "/clear") {
|
|
707
756
|
const params = new URLSearchParams(await readBody(req));
|
|
708
757
|
await app.clearConnection();
|
|
@@ -867,6 +916,10 @@ async function main(instance) {
|
|
|
867
916
|
process.stderr.write(`系統匣圖示無法顯示:${trayError}\n`);
|
|
868
917
|
return undefined;
|
|
869
918
|
});
|
|
919
|
+
if (tray?.stdin && tray.stdout) {
|
|
920
|
+
const channel = trayChannel = (0, trayChannel_1.createTrayChannel)({ input: tray.stdout, output: tray.stdin, app });
|
|
921
|
+
tray.once("exit", () => channel.close());
|
|
922
|
+
}
|
|
870
923
|
}
|
|
871
924
|
if (runtimeOptions.desktop && !process.env.VANSPOD_WORKER_TOKEN)
|
|
872
925
|
(0, desktop_1.openBrowser)(home);
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TRAY_BODY_CHARS = void 0;
|
|
4
|
+
exports.createTrayChannel = createTrayChannel;
|
|
5
|
+
/** The popup shows this much of the body. On the page, 「顯示全部」 shows all of it. */
|
|
6
|
+
exports.TRAY_BODY_CHARS = 2_000;
|
|
7
|
+
function trayText(value, max) {
|
|
8
|
+
return value.length <= max ? value : `${value.slice(0, max)}\n…(內容太長,完整內容請看 VansPod 頁面)`;
|
|
9
|
+
}
|
|
10
|
+
/** JSON with every character outside printable ASCII escaped. */
|
|
11
|
+
function asciiJson(value) {
|
|
12
|
+
return JSON.stringify(value).replace(/[^\x20-\x7e]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
13
|
+
}
|
|
14
|
+
function createTrayChannel(options) {
|
|
15
|
+
const { input, output, app } = options;
|
|
16
|
+
let closed = false;
|
|
17
|
+
let lastState;
|
|
18
|
+
let buffer = "";
|
|
19
|
+
const send = (message) => {
|
|
20
|
+
if (closed || output.destroyed || output.writableEnded)
|
|
21
|
+
return;
|
|
22
|
+
try {
|
|
23
|
+
output.write(`${asciiJson(message)}\n`);
|
|
24
|
+
}
|
|
25
|
+
catch { /* the tray has gone */ }
|
|
26
|
+
};
|
|
27
|
+
const state = () => {
|
|
28
|
+
const local = app.view().localTools;
|
|
29
|
+
const shown = local?.approval;
|
|
30
|
+
return {
|
|
31
|
+
type: "state",
|
|
32
|
+
access: local?.on ?? false,
|
|
33
|
+
approval: shown ? {
|
|
34
|
+
id: shown.id,
|
|
35
|
+
tool: shown.tool,
|
|
36
|
+
title: trayText(shown.title, 200),
|
|
37
|
+
body: trayText(shown.body, exports.TRAY_BODY_CHARS),
|
|
38
|
+
folder: shown.folder,
|
|
39
|
+
device: shown.device,
|
|
40
|
+
secondsLeft: shown.secondsLeft,
|
|
41
|
+
waiting: shown.waiting,
|
|
42
|
+
} : null,
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
const update = () => {
|
|
46
|
+
if (closed)
|
|
47
|
+
return;
|
|
48
|
+
const current = state();
|
|
49
|
+
// secondsLeft alone does not make a new state: the tray counts down itself.
|
|
50
|
+
const key = JSON.stringify({ ...current, approval: current.approval && { ...current.approval, secondsLeft: 0 } });
|
|
51
|
+
if (key === lastState)
|
|
52
|
+
return;
|
|
53
|
+
lastState = key;
|
|
54
|
+
send(current);
|
|
55
|
+
};
|
|
56
|
+
const receive = async (line) => {
|
|
57
|
+
let message;
|
|
58
|
+
try {
|
|
59
|
+
message = JSON.parse(line.replace(/^/, "").trim());
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (!message || typeof message !== "object")
|
|
65
|
+
return;
|
|
66
|
+
const { type, id, decision, on } = message;
|
|
67
|
+
if (type === "decide" && typeof id === "string" && (decision === "approve" || decision === "deny")) {
|
|
68
|
+
app.decideLocalToolApproval(id, decision);
|
|
69
|
+
update();
|
|
70
|
+
}
|
|
71
|
+
else if (type === "access" && typeof on === "boolean") {
|
|
72
|
+
try {
|
|
73
|
+
await app.setLocalToolAccess(on);
|
|
74
|
+
}
|
|
75
|
+
catch { /* the state below tells the tray */ }
|
|
76
|
+
if (closed)
|
|
77
|
+
return;
|
|
78
|
+
const local = app.view().localTools;
|
|
79
|
+
if (on && !local?.on && local?.message)
|
|
80
|
+
send({ type: "refused", message: local.message });
|
|
81
|
+
update();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const onData = (chunk) => {
|
|
85
|
+
if (closed)
|
|
86
|
+
return;
|
|
87
|
+
buffer += chunk.toString();
|
|
88
|
+
const lines = buffer.split("\n");
|
|
89
|
+
buffer = lines.pop() ?? "";
|
|
90
|
+
for (const line of lines)
|
|
91
|
+
void receive(line);
|
|
92
|
+
};
|
|
93
|
+
input.on("data", onData);
|
|
94
|
+
output.on("error", () => { });
|
|
95
|
+
update();
|
|
96
|
+
return {
|
|
97
|
+
update,
|
|
98
|
+
close() {
|
|
99
|
+
closed = true;
|
|
100
|
+
input.off("data", onData);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.windowsEnvironmentSystem = void 0;
|
|
7
|
+
exports.resolveCommand = resolveCommand;
|
|
7
8
|
exports.createWindowsEnvironmentSystem = createWindowsEnvironmentSystem;
|
|
8
9
|
const node_child_process_1 = require("node:child_process");
|
|
9
10
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
package/package.json
CHANGED
package/scripts/tray.ps1
CHANGED
|
@@ -2,17 +2,135 @@ param(
|
|
|
2
2
|
[Parameter(Mandatory = $true)]
|
|
3
3
|
[string]$Url,
|
|
4
4
|
[Parameter(Mandatory = $true)][string]$IconPath,
|
|
5
|
-
[Parameter(Mandatory = $true)][string]$StateFile
|
|
5
|
+
[Parameter(Mandatory = $true)][string]$StateFile,
|
|
6
|
+
# 法鬥超人:Local Tool Access 打開時的系統匣圖示,也放在 Approval Popup 上。
|
|
7
|
+
[string]$MascotPath
|
|
6
8
|
)
|
|
7
9
|
|
|
10
|
+
# VansPod 用這個程序的 stdin 與 stdout 和系統匣溝通(src/trayChannel.ts):每行一個 JSON。
|
|
11
|
+
# 只有 VansPod 自己啟動的這個程序拿得到這兩條管線,所以只有它能從頁面以外決定 Local Tool Approval。
|
|
12
|
+
|
|
8
13
|
Add-Type -AssemblyName System.Windows.Forms
|
|
9
14
|
Add-Type -AssemblyName System.Drawing
|
|
15
|
+
Add-Type -ReferencedAssemblies System.Windows.Forms, System.Drawing -TypeDefinition @'
|
|
16
|
+
using System;
|
|
17
|
+
using System.Drawing;
|
|
18
|
+
using System.Reflection;
|
|
19
|
+
using System.Runtime.InteropServices;
|
|
20
|
+
using System.Windows.Forms;
|
|
21
|
+
|
|
22
|
+
namespace VansPodTray {
|
|
23
|
+
// 確認面板:不搶鍵盤(顯示與點擊都不會成為前景視窗)、不在工作列、永遠在最上層。
|
|
24
|
+
public class PopupForm : Form {
|
|
25
|
+
protected override bool ShowWithoutActivation { get { return true; } }
|
|
26
|
+
protected override CreateParams CreateParams {
|
|
27
|
+
get {
|
|
28
|
+
CreateParams p = base.CreateParams;
|
|
29
|
+
p.ExStyle |= 0x08000000 | 0x00000080 | 0x00000008; // WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST
|
|
30
|
+
return p;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
protected override void WndProc(ref Message m) {
|
|
34
|
+
if (m.Msg == 0x21) { m.Result = (IntPtr)3; return; } // WM_MOUSEACTIVATE -> MA_NOACTIVATE
|
|
35
|
+
base.WndProc(ref m);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 拿不到焦點的按鈕:只能用滑鼠按,Enter 與空白鍵都不會按到它。
|
|
40
|
+
public class MouseOnlyButton : Button {
|
|
41
|
+
public MouseOnlyButton() { SetStyle(ControlStyles.Selectable, false); TabStop = false; }
|
|
42
|
+
protected override bool ShowFocusCues { get { return false; } }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public static class TrayPlace {
|
|
46
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
47
|
+
struct NOTIFYICONIDENTIFIER { public uint cbSize; public IntPtr hWnd; public uint uID; public Guid guidItem; }
|
|
48
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
49
|
+
struct RECT { public int Left, Top, Right, Bottom; }
|
|
50
|
+
[DllImport("shell32.dll")]
|
|
51
|
+
static extern int Shell_NotifyIconGetRect(ref NOTIFYICONIDENTIFIER identifier, out RECT iconLocation);
|
|
52
|
+
|
|
53
|
+
// 系統匣圖示在螢幕上的位置;拿不到時是 Rectangle.Empty。
|
|
54
|
+
public static Rectangle IconBounds(NotifyIcon icon) {
|
|
55
|
+
try {
|
|
56
|
+
FieldInfo windowField = typeof(NotifyIcon).GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
|
|
57
|
+
FieldInfo idField = typeof(NotifyIcon).GetField("id", BindingFlags.NonPublic | BindingFlags.Instance);
|
|
58
|
+
NativeWindow window = (NativeWindow)windowField.GetValue(icon);
|
|
59
|
+
NOTIFYICONIDENTIFIER identifier = new NOTIFYICONIDENTIFIER();
|
|
60
|
+
identifier.cbSize = (uint)Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER));
|
|
61
|
+
identifier.hWnd = window.Handle;
|
|
62
|
+
identifier.uID = (uint)(int)idField.GetValue(icon);
|
|
63
|
+
RECT r;
|
|
64
|
+
if (Shell_NotifyIconGetRect(ref identifier, out r) != 0) return Rectangle.Empty;
|
|
65
|
+
return Rectangle.FromLTRB(r.Left, r.Top, r.Right, r.Bottom);
|
|
66
|
+
} catch { return Rectangle.Empty; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 面板放在系統匣圖示上方(工作列在上方時放下方),不超出工作區。
|
|
70
|
+
public static Point PopupLocation(Rectangle icon, Size popup) {
|
|
71
|
+
Screen screen = icon.IsEmpty ? Screen.PrimaryScreen : Screen.FromRectangle(icon);
|
|
72
|
+
Rectangle area = screen.WorkingArea;
|
|
73
|
+
Rectangle bounds = screen.Bounds;
|
|
74
|
+
const int gap = 12;
|
|
75
|
+
bool taskbarTop = area.Top > bounds.Top;
|
|
76
|
+
bool taskbarLeft = area.Left > bounds.Left;
|
|
77
|
+
int x = taskbarLeft ? area.Left + gap : area.Right - popup.Width - gap;
|
|
78
|
+
int y = taskbarTop ? area.Top + gap : area.Bottom - popup.Height - gap;
|
|
79
|
+
if (!icon.IsEmpty && area.IntersectsWith(Rectangle.Inflate(icon, 64, 64))) {
|
|
80
|
+
int center = icon.Left + icon.Width / 2;
|
|
81
|
+
if (center >= area.Left && center <= area.Right) x = center - popup.Width / 2;
|
|
82
|
+
}
|
|
83
|
+
x = Math.Max(area.Left + gap, Math.Min(x, area.Right - popup.Width - gap));
|
|
84
|
+
y = Math.Max(area.Top + gap, Math.Min(y, area.Bottom - popup.Height - gap));
|
|
85
|
+
return new Point(x, y);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
'@
|
|
10
90
|
|
|
11
91
|
$script:OpenUrl = $Url
|
|
12
92
|
$openPage = { Start-Process $script:OpenUrl }.GetNewClosure()
|
|
13
93
|
|
|
94
|
+
# ---- 和 VansPod 的管線 ----
|
|
95
|
+
$utf8 = New-Object System.Text.UTF8Encoding $false
|
|
96
|
+
$script:reader = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), $utf8)
|
|
97
|
+
$script:writer = New-Object System.IO.StreamWriter([Console]::OpenStandardOutput(), $utf8)
|
|
98
|
+
$script:writer.AutoFlush = $true
|
|
99
|
+
function Send-ToVansPod($message) {
|
|
100
|
+
try { $script:writer.WriteLine(($message | ConvertTo-Json -Compress)) } catch { }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
# ---- 系統匣圖示 ----
|
|
104
|
+
$offIcon = New-Object System.Drawing.Icon($IconPath)
|
|
105
|
+
$script:mascot = $null
|
|
106
|
+
$onIcon = $null
|
|
107
|
+
$size = [System.Windows.Forms.SystemInformation]::SmallIconSize
|
|
108
|
+
if ($MascotPath -and (Test-Path -LiteralPath $MascotPath)) {
|
|
109
|
+
try {
|
|
110
|
+
$script:mascot = [System.Drawing.Image]::FromFile($MascotPath)
|
|
111
|
+
$small = New-Object System.Drawing.Bitmap($script:mascot, $size.Width, $size.Height)
|
|
112
|
+
$onIcon = [System.Drawing.Icon]::FromHandle($small.GetHicon())
|
|
113
|
+
} catch { $onIcon = $null }
|
|
114
|
+
}
|
|
115
|
+
# Without the mascot, the "on" icon is the VansPod icon with a green dot, so "on" still looks different.
|
|
116
|
+
if (-not $onIcon) {
|
|
117
|
+
try {
|
|
118
|
+
$marked = New-Object System.Drawing.Bitmap($size.Width, $size.Height)
|
|
119
|
+
$graphics = [System.Drawing.Graphics]::FromImage($marked)
|
|
120
|
+
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
|
121
|
+
$graphics.DrawIcon($offIcon, (New-Object System.Drawing.Rectangle(0, 0, $size.Width, $size.Height)))
|
|
122
|
+
$dot = [Math]::Max(6, [int]($size.Width / 2))
|
|
123
|
+
$x = $size.Width - $dot
|
|
124
|
+
$y = $size.Height - $dot
|
|
125
|
+
$graphics.FillEllipse([System.Drawing.Brushes]::White, $x, $y, $dot, $dot)
|
|
126
|
+
$graphics.FillEllipse([System.Drawing.Brushes]::LimeGreen, $x + 1, $y + 1, $dot - 2, $dot - 2)
|
|
127
|
+
$graphics.Dispose()
|
|
128
|
+
$onIcon = [System.Drawing.Icon]::FromHandle($marked.GetHicon())
|
|
129
|
+
} catch { $onIcon = [System.Drawing.SystemIcons]::Shield }
|
|
130
|
+
}
|
|
131
|
+
|
|
14
132
|
$notify = New-Object System.Windows.Forms.NotifyIcon
|
|
15
|
-
$notify.Icon =
|
|
133
|
+
$notify.Icon = $offIcon
|
|
16
134
|
$notify.Text = "VansPod"
|
|
17
135
|
$notify.Visible = $true
|
|
18
136
|
$notify.add_MouseClick({ if ($_.Button -eq [System.Windows.Forms.MouseButtons]::Left) { & $openPage } }.GetNewClosure())
|
|
@@ -20,6 +138,10 @@ $notify.add_MouseClick({ if ($_.Button -eq [System.Windows.Forms.MouseButtons]::
|
|
|
20
138
|
$menu = New-Object System.Windows.Forms.ContextMenuStrip
|
|
21
139
|
$open = $menu.Items.Add("開啟 VansPod")
|
|
22
140
|
$open.add_Click($openPage)
|
|
141
|
+
$script:accessItem = New-Object System.Windows.Forms.ToolStripMenuItem("讓 Agent Builder 使用這台電腦")
|
|
142
|
+
$script:accessItem.add_Click({ Send-ToVansPod @{ type = 'access'; on = (-not $script:access) } })
|
|
143
|
+
[void]$menu.Items.Add($script:accessItem)
|
|
144
|
+
[void]$menu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator))
|
|
23
145
|
$stop = $menu.Items.Add("結束 VansPod")
|
|
24
146
|
$stop.add_Click({
|
|
25
147
|
try {
|
|
@@ -35,6 +157,148 @@ $stop.add_Click({
|
|
|
35
157
|
})
|
|
36
158
|
$notify.ContextMenuStrip = $menu
|
|
37
159
|
|
|
38
|
-
|
|
39
|
-
|
|
160
|
+
# ---- Approval Popup(確認面板) ----
|
|
161
|
+
$font = New-Object System.Drawing.Font("Microsoft JhengHei UI", 9)
|
|
162
|
+
$bold = New-Object System.Drawing.Font("Microsoft JhengHei UI", 10, [System.Drawing.FontStyle]::Bold)
|
|
163
|
+
$popup = New-Object VansPodTray.PopupForm
|
|
164
|
+
$popup.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
|
|
165
|
+
$popup.ControlBox = $false
|
|
166
|
+
$popup.Text = ""
|
|
167
|
+
$popup.ShowInTaskbar = $false
|
|
168
|
+
$popup.TopMost = $true
|
|
169
|
+
$popup.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
|
|
170
|
+
$popup.ClientSize = New-Object System.Drawing.Size(400, 318)
|
|
171
|
+
$popup.BackColor = [System.Drawing.Color]::White
|
|
172
|
+
$popup.Font = $font
|
|
173
|
+
$popup.KeyPreview = $true
|
|
174
|
+
$popup.add_KeyDown({ $_.Handled = $true; $_.SuppressKeyPress = $true })
|
|
175
|
+
|
|
176
|
+
$textLeft = 12
|
|
177
|
+
if ($script:mascot) {
|
|
178
|
+
$picture = New-Object System.Windows.Forms.PictureBox
|
|
179
|
+
$picture.Image = $script:mascot
|
|
180
|
+
$picture.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom
|
|
181
|
+
$picture.SetBounds(12, 10, 44, 44)
|
|
182
|
+
$popup.Controls.Add($picture)
|
|
183
|
+
$textLeft = 64
|
|
184
|
+
}
|
|
185
|
+
$heading = New-Object System.Windows.Forms.Label
|
|
186
|
+
$heading.Text = "Agent Builder 想要使用這台電腦"
|
|
187
|
+
$heading.Font = $bold
|
|
188
|
+
$heading.SetBounds($textLeft, 10, (388 - $textLeft), 22)
|
|
189
|
+
$popup.Controls.Add($heading)
|
|
190
|
+
$script:titleLabel = New-Object System.Windows.Forms.Label
|
|
191
|
+
$script:titleLabel.AutoEllipsis = $true
|
|
192
|
+
$script:titleLabel.SetBounds($textLeft, 34, (388 - $textLeft), 22)
|
|
193
|
+
$popup.Controls.Add($script:titleLabel)
|
|
194
|
+
$script:bodyBox = New-Object System.Windows.Forms.TextBox
|
|
195
|
+
$script:bodyBox.Multiline = $true
|
|
196
|
+
$script:bodyBox.ReadOnly = $true
|
|
197
|
+
$script:bodyBox.TabStop = $false
|
|
198
|
+
$script:bodyBox.ScrollBars = [System.Windows.Forms.ScrollBars]::Vertical
|
|
199
|
+
$script:bodyBox.Font = New-Object System.Drawing.Font("Consolas", 9)
|
|
200
|
+
$script:bodyBox.BackColor = [System.Drawing.Color]::FromArgb(246, 246, 246)
|
|
201
|
+
$script:bodyBox.SetBounds(12, 62, 376, 120)
|
|
202
|
+
$popup.Controls.Add($script:bodyBox)
|
|
203
|
+
$script:whereLabel = New-Object System.Windows.Forms.Label
|
|
204
|
+
$script:whereLabel.AutoEllipsis = $true
|
|
205
|
+
$script:whereLabel.SetBounds(12, 190, 376, 40)
|
|
206
|
+
$popup.Controls.Add($script:whereLabel)
|
|
207
|
+
$script:timeLabel = New-Object System.Windows.Forms.Label
|
|
208
|
+
$script:timeLabel.SetBounds(12, 234, 376, 20)
|
|
209
|
+
$popup.Controls.Add($script:timeLabel)
|
|
210
|
+
$script:denyButton = New-Object VansPodTray.MouseOnlyButton
|
|
211
|
+
$script:denyButton.Text = "拒絕"
|
|
212
|
+
$script:denyButton.SetBounds(176, 266, 100, 36)
|
|
213
|
+
$popup.Controls.Add($script:denyButton)
|
|
214
|
+
$script:approveButton = New-Object VansPodTray.MouseOnlyButton
|
|
215
|
+
$script:approveButton.Text = "允許"
|
|
216
|
+
$script:approveButton.Font = $bold
|
|
217
|
+
$script:approveButton.SetBounds(288, 266, 100, 36)
|
|
218
|
+
$popup.Controls.Add($script:approveButton)
|
|
219
|
+
# 沒有預設按鈕:AcceptButton 與 CancelButton 都不設定。
|
|
220
|
+
|
|
221
|
+
$script:access = $false
|
|
222
|
+
$script:shownId = $null
|
|
223
|
+
$script:deadline = [DateTime]::MinValue
|
|
224
|
+
$script:waiting = 0
|
|
225
|
+
|
|
226
|
+
function Set-Buttons([bool]$enabled) {
|
|
227
|
+
$script:denyButton.Enabled = $enabled
|
|
228
|
+
$script:approveButton.Enabled = $enabled
|
|
229
|
+
}
|
|
230
|
+
function Update-Time {
|
|
231
|
+
$left = [Math]::Max(0, [int][Math]::Ceiling(($script:deadline - [DateTime]::UtcNow).TotalSeconds))
|
|
232
|
+
$text = "剩下 {0}:{1:00}" -f [Math]::Floor($left / 60), ($left % 60)
|
|
233
|
+
if ($script:waiting -gt 0) { $text += " 還有 $($script:waiting) 個在排隊" }
|
|
234
|
+
$script:timeLabel.Text = $text
|
|
235
|
+
if ($left -le 0) { Set-Buttons $false }
|
|
236
|
+
}
|
|
237
|
+
function Send-Decision([string]$decision) {
|
|
238
|
+
if (-not $script:shownId) { return }
|
|
239
|
+
Set-Buttons $false
|
|
240
|
+
Send-ToVansPod @{ type = 'decide'; id = $script:shownId; decision = $decision }
|
|
241
|
+
}
|
|
242
|
+
$script:approveButton.add_Click({ Send-Decision 'approve' })
|
|
243
|
+
$script:denyButton.add_Click({ Send-Decision 'deny' })
|
|
40
244
|
|
|
245
|
+
function Show-State($state) {
|
|
246
|
+
$script:access = [bool]$state.access
|
|
247
|
+
$script:accessItem.Checked = $script:access
|
|
248
|
+
if ($script:access) { $notify.Icon = $onIcon; $notify.Text = "VansPod:Agent Builder 可以使用這台電腦" }
|
|
249
|
+
else { $notify.Icon = $offIcon; $notify.Text = "VansPod" }
|
|
250
|
+
$approval = $state.approval
|
|
251
|
+
if (-not $approval) {
|
|
252
|
+
$script:shownId = $null
|
|
253
|
+
$popup.Hide()
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
$script:waiting = [int]$approval.waiting
|
|
257
|
+
if ($approval.id -ne $script:shownId) {
|
|
258
|
+
$script:shownId = [string]$approval.id
|
|
259
|
+
$script:deadline = [DateTime]::UtcNow.AddSeconds([int]$approval.secondsLeft)
|
|
260
|
+
$script:titleLabel.Text = [string]$approval.title
|
|
261
|
+
$script:bodyBox.Text = ([string]$approval.body) -replace "`r?`n", "`r`n"
|
|
262
|
+
$script:whereLabel.Text = "電腦:$($approval.device)`r`n資料夾:$($approval.folder)"
|
|
263
|
+
Set-Buttons $true
|
|
264
|
+
}
|
|
265
|
+
Update-Time
|
|
266
|
+
if (-not $popup.Visible) {
|
|
267
|
+
$popup.Location = [VansPodTray.TrayPlace]::PopupLocation([VansPodTray.TrayPlace]::IconBounds($notify), $popup.Size)
|
|
268
|
+
$popup.Show()
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function Receive-Line([string]$line) {
|
|
273
|
+
try { $message = $line | ConvertFrom-Json } catch { return }
|
|
274
|
+
if ($message.type -eq 'state') { Show-State $message }
|
|
275
|
+
elseif ($message.type -eq 'refused') { $notify.ShowBalloonTip(5000, 'VansPod', [string]$message.message, [System.Windows.Forms.ToolTipIcon]::Info) }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
# 讀取在背景進行;計時器在 UI 執行緒上取出讀到的每一行。VansPod 關掉管線時,系統匣一起結束。
|
|
279
|
+
$script:pending = $script:reader.ReadLineAsync()
|
|
280
|
+
$pipeTimer = New-Object System.Windows.Forms.Timer
|
|
281
|
+
$pipeTimer.Interval = 100
|
|
282
|
+
$pipeTimer.add_Tick({
|
|
283
|
+
while ($script:pending -and $script:pending.IsCompleted) {
|
|
284
|
+
$line = $null
|
|
285
|
+
try { $line = $script:pending.Result } catch { }
|
|
286
|
+
if ($null -eq $line) { $script:pending = $null; [System.Windows.Forms.Application]::Exit(); return }
|
|
287
|
+
Receive-Line $line
|
|
288
|
+
$script:pending = $script:reader.ReadLineAsync()
|
|
289
|
+
}
|
|
290
|
+
})
|
|
291
|
+
$pipeTimer.Start()
|
|
292
|
+
$clock = New-Object System.Windows.Forms.Timer
|
|
293
|
+
$clock.Interval = 1000
|
|
294
|
+
$clock.add_Tick({ if ($script:shownId) { Update-Time } })
|
|
295
|
+
$clock.Start()
|
|
296
|
+
|
|
297
|
+
try { [System.Windows.Forms.Application]::Run() }
|
|
298
|
+
finally {
|
|
299
|
+
$pipeTimer.Stop(); $clock.Stop()
|
|
300
|
+
$popup.Dispose()
|
|
301
|
+
$notify.Visible = $false; $notify.Dispose(); $menu.Dispose()
|
|
302
|
+
if ($offIcon) { $offIcon.Dispose() }
|
|
303
|
+
if ($script:mascot) { $script:mascot.Dispose() }
|
|
304
|
+
}
|