@aivin-labs/cli 1.0.13 → 1.0.24
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 +325 -304
- package/bin/cli.mjs +97 -18
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +153 -129
- package/bin/lib/remote/callLedger.mjs +21 -0
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1025 -889
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +263 -251
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +21 -7
- package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
- package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +380 -16
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
- package/bin/lib/remote/deviceProfile.mjs +2 -4
- package/bin/lib/remote/fileIndexer.mjs +30 -14
- package/bin/lib/remote/folderRules.mjs +3 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +66 -24
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +3 -1
- package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/localPolicy.mjs +73 -7
- package/bin/lib/remote/mascot/ask.mjs +956 -768
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +26 -2
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +328 -49
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +643 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +459 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +79 -15
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/CLI.md +1545 -1504
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/package.json +75 -71
package/bin/cli.mjs
CHANGED
|
@@ -61,10 +61,14 @@ import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
|
|
|
61
61
|
import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
|
|
62
62
|
import { loadMascotSettings, saveMascotSettings } from './lib/remote/mascot/index.mjs';
|
|
63
63
|
import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.mjs';
|
|
64
|
-
import {
|
|
64
|
+
import { DESKTOP_WEBRTC_WORKER_ARG, runDesktopWebRtcWorker } from './lib/remote/desktop/webrtcWorker.mjs';
|
|
65
|
+
import { DemoScope, UiResult, showMascotDemo, showMascotUi } from './lib/remote/mascot/ui.mjs';
|
|
65
66
|
import { desktopAppStatus, installDesktopApp, uninstallDesktopApp } from './lib/remote/autoStart.mjs';
|
|
67
|
+
import { OpenDisplay, openFile, openText } from './lib/openFile.mjs';
|
|
68
|
+
import { OPEN_WITH_EXTENSIONS, SAFE_DEFAULT_EXTENSIONS, defaultAssociationsXml, openDefaultAppsSettings } from './lib/remote/desktop/fileAssociation.mjs';
|
|
69
|
+
import { showOSNotification } from './lib/remote/notify.mjs';
|
|
66
70
|
import { createMeetingManager, requestMeeting } from './lib/remote/meeting/index.mjs';
|
|
67
|
-
import { DEFAULT_HOTKEYS, hotkeyCandidates, parseHotkey, probeHotkey } from './lib/remote/mascot/hotkey.mjs';
|
|
71
|
+
import { DEFAULT_CHAT_HOTKEYS, DEFAULT_HOTKEYS, hotkeyCandidates, parseHotkey, probeHotkey } from './lib/remote/mascot/hotkey.mjs';
|
|
68
72
|
import { RESTART_EXIT_CODE, UPDATE_ROLLED_BACK, UpdateStatus, cleanupRetired, downloadRoot, installUpdate, isStandaloneBinary, saveUpdateSettings } from './lib/selfUpdate.mjs';
|
|
69
73
|
import {
|
|
70
74
|
createAutomationJob,
|
|
@@ -97,6 +101,7 @@ import {
|
|
|
97
101
|
pairWithCodeOnly,
|
|
98
102
|
listDevices,
|
|
99
103
|
unpairDevice,
|
|
104
|
+
assertHumanCommand,
|
|
100
105
|
isRemotePaused,
|
|
101
106
|
setRemotePaused,
|
|
102
107
|
getRecentLogs,
|
|
@@ -1031,14 +1036,23 @@ program
|
|
|
1031
1036
|
.command('ui')
|
|
1032
1037
|
.description('Show the Aivin mascot on this computer with its ask box (Windows) - starts the background listener if it is not running')
|
|
1033
1038
|
.option('--demo', 'Preview every mascot animation state without pairing or starting the listener')
|
|
1039
|
+
.option('--moods', 'With --demo: only the faces the mascot makes from the emoji of an answer (sad, cry, sheepish, happy...)')
|
|
1034
1040
|
.action(async (options) => {
|
|
1035
1041
|
const lang = mascotLang();
|
|
1036
1042
|
const say = (key, color = chalk.green) => console.log(color(mascotText(lang, key)));
|
|
1037
1043
|
if (options.demo) {
|
|
1038
|
-
const result = showMascotDemo(
|
|
1044
|
+
const result = showMascotDemo({
|
|
1045
|
+
scope: options.moods ? DemoScope.MOODS : DemoScope.ALL,
|
|
1046
|
+
onEarlyExit: () => {
|
|
1047
|
+
console.error(chalk.yellow('Cửa sổ demo đóng ngay: linh vật thật đang chạy (mỗi lúc chỉ một linh vật). Tắt nó bằng `aivin remote mascot off`, chạy lại demo, xong thì `aivin remote mascot on`.'));
|
|
1048
|
+
process.exitCode = 1;
|
|
1049
|
+
},
|
|
1050
|
+
});
|
|
1039
1051
|
if (result === UiResult.UNSUPPORTED) return say(MascotText.CMD_UNSUPPORTED, chalk.yellow);
|
|
1040
1052
|
if (result === UiResult.START_FAILED) { console.error(chalk.red('Không thể mở bản demo linh vật.')); process.exitCode = 1; return; }
|
|
1041
|
-
console.log(chalk.green(
|
|
1053
|
+
console.log(chalk.green(options.moods
|
|
1054
|
+
? '✓ Demo linh vật đang chạy qua 7 nét mặt theo emoji — đóng cửa sổ hoặc nhấn Ctrl+C để dừng.'
|
|
1055
|
+
: '✓ Demo linh vật đang chạy qua 8 trạng thái + 7 nét mặt theo emoji — đóng cửa sổ hoặc nhấn Ctrl+C để dừng.'));
|
|
1042
1056
|
return;
|
|
1043
1057
|
}
|
|
1044
1058
|
const result = await showMascotUi({ onStarting: () => say(MascotText.UI_STARTING, chalk.gray) });
|
|
@@ -1052,9 +1066,11 @@ program
|
|
|
1052
1066
|
|
|
1053
1067
|
program
|
|
1054
1068
|
.command('desktop [action]')
|
|
1055
|
-
.description('Aivin as a desktop app: install (Windows: system tray + Start menu; macOS: menu bar + Aivin.app; Linux: app menu + tray) and start it with the computer | uninstall | status (default)')
|
|
1069
|
+
.description('Aivin as a desktop app: install (Windows: system tray + Start menu; macOS: menu bar + Aivin.app; Linux: app menu + tray) and start it with the computer | uninstall | defaults (Windows: pick AIVIN Bot as default for file types) | status (default)')
|
|
1056
1070
|
.option('--no-autostart', "install: don't start Aivin with the computer (turn it on later from Aivin's menu or the system's startup settings)")
|
|
1057
1071
|
.option('--no-launch', "install: don't open Aivin now")
|
|
1072
|
+
.option('--export-xml <file>', 'defaults (Windows): write a default-associations file for IT (Group Policy / Intune) instead of opening Settings')
|
|
1073
|
+
.option('--all', 'defaults --export-xml: include Office formats, not only md/txt/csv')
|
|
1058
1074
|
.action((action = 'status', options) => {
|
|
1059
1075
|
// Chỗ bật / tắt khởi động cùng máy của từng hệ điều hành — cùng chỗ menu Aivin và `aivin remote enable|disable` đổi.
|
|
1060
1076
|
const startupWhere = { win32: 'Task Manager → Startup apps', darwin: 'System Settings → General → Login Items', linux: 'Startup Applications / Autostart' }[process.platform] || '';
|
|
@@ -1065,6 +1081,8 @@ program
|
|
|
1065
1081
|
console.log(chalk.green(`✅ Đã cài Aivin vào máy: ${where}.`));
|
|
1066
1082
|
console.log(chalk.gray(` Ứng dụng: ${res.exe}`));
|
|
1067
1083
|
console.log(chalk.gray(` Khởi động cùng máy: ${res.autostart ? 'bật' : 'tắt'} (đổi ở menu Aivin hoặc ${startupWhere})`));
|
|
1084
|
+
if (res.openWith?.registered) console.log(chalk.gray(' Mở tệp: chuột phải tệp → "Mở bằng AIVIN Bot", hoặc Open with → AIVIN Bot → Always để mở mặc định'));
|
|
1085
|
+
else if (res.openWith?.error) console.log(chalk.yellow(` ⚠️ Chưa thêm được "Mở bằng AIVIN Bot": ${res.openWith.error}`));
|
|
1068
1086
|
if (process.platform === 'linux' && !desktopAppStatus().tray) {
|
|
1069
1087
|
console.log(chalk.yellow(' ⚠️ Máy chưa có AppIndicator cho python3 nên không có biểu tượng khay — Aivin vẫn chạy nền. Cài: sudo apt install gir1.2-ayatanaappindicator3-0.1 (Ubuntu / Debian)'));
|
|
1070
1088
|
}
|
|
@@ -1076,7 +1094,19 @@ program
|
|
|
1076
1094
|
if (!res.removed) console.log(chalk.yellow(' ⚠️ Ứng dụng còn đang chạy nên chưa xoá hết được tệp — chạy lại lệnh này sau ít giây.'));
|
|
1077
1095
|
return;
|
|
1078
1096
|
}
|
|
1079
|
-
if (action
|
|
1097
|
+
if (action === 'defaults') {
|
|
1098
|
+
if (process.platform !== 'win32') throw new Error('`aivin desktop defaults` chỉ có trên Windows.');
|
|
1099
|
+
if (options.exportXml) {
|
|
1100
|
+
fs.writeFileSync(options.exportXml, defaultAssociationsXml(options.all ? OPEN_WITH_EXTENSIONS : SAFE_DEFAULT_EXTENSIONS));
|
|
1101
|
+
console.log(chalk.green(`✅ Đã ghi ${options.exportXml} — IT áp bằng Group Policy "Set a default associations configuration file" hoặc Intune.`));
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
openDefaultAppsSettings();
|
|
1105
|
+
console.log(chalk.green('✅ Đã mở Settings → Default apps → AIVIN Bot. Chọn AIVIN Bot cho từng loại tệp để nháy đúp là mở bằng Aivin.'));
|
|
1106
|
+
console.log(chalk.gray(` Nên chọn: ${SAFE_DEFAULT_EXTENSIONS.map((e) => `.${e}`).join(', ')}. Tệp Office dựng lại định dạng khi xuất, nên cân nhắc trước khi đặt mặc định.`));
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
if (action !== 'status') throw new Error('Dùng: aivin desktop install [--no-autostart] [--no-launch] | uninstall | defaults [--export-xml <tệp>] [--all] | status');
|
|
1080
1110
|
const st = desktopAppStatus();
|
|
1081
1111
|
if (st.supported === false) return console.log(chalk.gray(`Chưa có ứng dụng Aivin trên màn hình cho ${process.platform} — dùng \`aivin remote enable\`.`));
|
|
1082
1112
|
console.log(chalk.blue('🖥️ Aivin trên máy này:'));
|
|
@@ -1084,12 +1114,36 @@ program
|
|
|
1084
1114
|
if (st.installed) console.log(chalk.gray(` Tìm bằng: ${st.search || 'không'}`));
|
|
1085
1115
|
console.log(chalk.gray(` Khởi động cùng máy: ${st.startup.registered ? (st.startup.enabled ? 'bật' : `tắt (${startupWhere})`) : 'không'}`));
|
|
1086
1116
|
if (process.platform === 'linux') console.log(chalk.gray(` Biểu tượng khay: ${st.tray ? 'có' : 'không (thiếu python3 + AppIndicator) — vẫn chạy nền'}`));
|
|
1117
|
+
if (process.platform === 'win32') console.log(chalk.gray(` Mở bằng AIVIN Bot: ${st.openWith ? 'có (chuột phải tệp / Open with)' : 'chưa — aivin desktop install'}`));
|
|
1087
1118
|
} catch (error) {
|
|
1088
1119
|
console.error(chalk.red('❌'), error.message);
|
|
1089
1120
|
process.exit(1);
|
|
1090
1121
|
}
|
|
1091
1122
|
});
|
|
1092
1123
|
|
|
1124
|
+
program
|
|
1125
|
+
.command('open <files...>')
|
|
1126
|
+
.description('Open files from this computer in your Aivin Drive (uploads once; the same content reopens the same Drive file). Windows: `aivin desktop install` adds "Open with AIVIN Bot" to Explorer.')
|
|
1127
|
+
.option('-w, --workspace <id>', 'Workspace to upload into (default: your personal workspace)')
|
|
1128
|
+
.option('--tab', 'Open in a normal browser tab instead of its own window')
|
|
1129
|
+
.option('--print', 'Print the Drive link instead of opening anything')
|
|
1130
|
+
.action(async (files, options) => {
|
|
1131
|
+
// Gọi từ Explorer qua Aivin.exe --open (không có console) → báo bằng thông báo hệ điều hành.
|
|
1132
|
+
const toast = process.env.AIVIN_OPEN_UI === 'toast';
|
|
1133
|
+
for (const file of files) {
|
|
1134
|
+
try {
|
|
1135
|
+
if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('opening', { name: path.basename(file) }) });
|
|
1136
|
+
const display = options.print ? OpenDisplay.NONE : options.tab ? OpenDisplay.TAB : OpenDisplay.WINDOW;
|
|
1137
|
+
const res = await openFile(file, { workspace: options.workspace, display });
|
|
1138
|
+
console.log(options.print ? res.url : chalk.green(`✅ ${res.name} → ${res.url}${res.reused ? ' (Drive copy reused)' : ''}${res.viewOnly ? ' (view only, not signed in - closes with its window)' : ''}`));
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
console.error(chalk.red('❌'), error.message);
|
|
1141
|
+
if (toast) showOSNotification({ title: openText('failed_title'), body: error.message });
|
|
1142
|
+
process.exitCode = 1;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
});
|
|
1146
|
+
|
|
1093
1147
|
program
|
|
1094
1148
|
.command('update')
|
|
1095
1149
|
.description('Update aivin to the latest release (installs from get.aivin.vn; checks the release signature, the SHA256 and that the new build starts)')
|
|
@@ -1127,6 +1181,16 @@ program
|
|
|
1127
1181
|
}
|
|
1128
1182
|
});
|
|
1129
1183
|
|
|
1184
|
+
// Agent chạy CLI này trong lệnh shell của nó: không đổi việc ghép máy / luật tại máy, không giao việc mới (sandbox.mjs).
|
|
1185
|
+
program.hook('preAction', (_cmd, action) => {
|
|
1186
|
+
try {
|
|
1187
|
+
assertHumanCommand(action.parent?.name(), action.name());
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
console.error(chalk.red('❌'), error.message);
|
|
1190
|
+
process.exit(1);
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1130
1194
|
const remoteCommand = program
|
|
1131
1195
|
.command('remote')
|
|
1132
1196
|
.description('Let your Aivin agents work on this computer (Device Agent) - pair, run the listener, manage memory and safety')
|
|
@@ -1188,7 +1252,7 @@ remoteCommand
|
|
|
1188
1252
|
if (options.code) {
|
|
1189
1253
|
// Bộ cài (đã có khay): chỉ ghép — khay mở listener ngay khi thấy máy đã ghép.
|
|
1190
1254
|
const { creds, stopped } = await pairWithCodeOnly(options);
|
|
1191
|
-
console.log(chalk.green(`✅ Đã kết nối máy "${creds.name}" với tài khoản Aivin của bạn — quay lại Aivin để chọn máy này.`));
|
|
1255
|
+
console.log(chalk.green(`✅ Đã kết nối máy "${creds.name}" với tài khoản ${creds.account || 'Aivin của bạn'} — quay lại Aivin để chọn máy này.`));
|
|
1192
1256
|
if (stopped) console.log(chalk.gray(' Đã dừng phiên nhận việc cũ — Aivin mở lại bằng kết nối mới.'));
|
|
1193
1257
|
return;
|
|
1194
1258
|
}
|
|
@@ -1243,26 +1307,39 @@ remoteCommand
|
|
|
1243
1307
|
|
|
1244
1308
|
remoteCommand
|
|
1245
1309
|
.command('mascot [action] [combo]')
|
|
1246
|
-
.description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting; hotkey [combo|off|default] — the key combination that
|
|
1247
|
-
.
|
|
1310
|
+
.description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting; hotkey [combo|off|default] — the key combination for voice (default Alt+Shift+Space; off turns off both keys), with --chat the one that opens the ask box to type (default Alt+Space)')
|
|
1311
|
+
.option('--chat', 'hotkey: show or set the key that opens the ask box instead of the voice key')
|
|
1312
|
+
.action((action, combo, options) => {
|
|
1248
1313
|
const lang = mascotLang();
|
|
1249
1314
|
if (action === 'hotkey') {
|
|
1250
1315
|
try {
|
|
1251
|
-
const
|
|
1316
|
+
const settings = loadMascotSettings();
|
|
1317
|
+
const key = options.chat ? 'chat_hotkey' : 'hotkey';
|
|
1318
|
+
const otherKey = options.chat ? 'hotkey' : 'chat_hotkey';
|
|
1319
|
+
const defaults = options.chat ? DEFAULT_CHAT_HOTKEYS : DEFAULT_HOTKEYS;
|
|
1320
|
+
const name = options.chat ? 'Phím tắt mở ô hỏi' : 'Phím tắt nói chuyện';
|
|
1321
|
+
const setting = settings[key];
|
|
1252
1322
|
if (!combo) {
|
|
1253
|
-
const active = hotkeyCandidates(setting);
|
|
1254
|
-
if (
|
|
1255
|
-
return console.log(
|
|
1323
|
+
const active = hotkeyCandidates(setting, defaults);
|
|
1324
|
+
if (settings.hotkey === 'off') return console.log(`${name}: tắt (bật lại: aivin remote mascot hotkey default)`);
|
|
1325
|
+
if (!active.length) return console.log(`${name}: tắt (bật lại: aivin remote mascot hotkey --chat default)`);
|
|
1326
|
+
return console.log(`${name}: ${active[0].label}${setting ? '' : ' (mặc định)'} — không đăng ký được thì thử lần lượt: ${active.slice(1).map((h) => h.label).join(', ')}`);
|
|
1256
1327
|
}
|
|
1257
|
-
if (combo === 'off') {
|
|
1258
|
-
|
|
1328
|
+
if (combo === 'off') {
|
|
1329
|
+
saveMascotSettings({ [key]: 'off' });
|
|
1330
|
+
return console.log(chalk.green(options.chat ? '✅ Đã tắt phím tắt mở ô hỏi.' : '✅ Đã tắt phím tắt gọi linh vật (cả nói chuyện và mở ô hỏi).'));
|
|
1331
|
+
}
|
|
1332
|
+
if (combo === 'default') { saveMascotSettings({ [key]: null }); return console.log(chalk.green(`✅ ${name}: dùng mặc định ${defaults[0]}.`)); }
|
|
1259
1333
|
const hotkey = parseHotkey(combo);
|
|
1334
|
+
if (settings[otherKey] && settings[otherKey] !== 'off' && parseHotkey(settings[otherKey]).label === hotkey.label) {
|
|
1335
|
+
throw new Error(`${hotkey.label} đang dùng cho ${options.chat ? 'nói chuyện' : 'mở ô hỏi'} — chọn tổ hợp khác.`);
|
|
1336
|
+
}
|
|
1260
1337
|
const free = probeHotkey(hotkey);
|
|
1261
1338
|
if (free === false) {
|
|
1262
1339
|
console.log(chalk.yellow(`⚠️ ${hotkey.label} đang bị một ứng dụng khác (hoặc chính linh vật đang chạy) giữ — nếu không phải linh vật thì chọn tổ hợp khác.`));
|
|
1263
1340
|
}
|
|
1264
|
-
saveMascotSettings({
|
|
1265
|
-
return console.log(chalk.green(`✅
|
|
1341
|
+
saveMascotSettings({ [key]: hotkey.label });
|
|
1342
|
+
return console.log(chalk.green(`✅ ${name}: ${hotkey.label} — có hiệu lực khi linh vật khởi động lại (aivin remote start).`));
|
|
1266
1343
|
} catch (error) {
|
|
1267
1344
|
return remoteFail(error);
|
|
1268
1345
|
}
|
|
@@ -1975,5 +2052,7 @@ function resolveIsMain() {
|
|
|
1975
2052
|
}
|
|
1976
2053
|
|
|
1977
2054
|
if (resolveIsMain()) {
|
|
1978
|
-
|
|
2055
|
+
// Tiến trình con WebRTC của xem màn hình từ web (daemon tự gọi, không phải lệnh cho người dùng) — xem lib/remote/desktop/webrtcWorker.mjs.
|
|
2056
|
+
if (process.argv.includes(DESKTOP_WEBRTC_WORKER_ARG)) await runDesktopWebRtcWorker();
|
|
2057
|
+
else program.parse(process.argv);
|
|
1979
2058
|
}
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import http from 'http';
|
|
5
|
+
import axios from 'axios';
|
|
6
|
+
import { randomBytes } from 'crypto';
|
|
7
|
+
import { AIVIN_LOGO_PNG_BASE64 } from './remote/brand.mjs';
|
|
8
|
+
import { mascotLang } from './remote/mascot/strings.mjs';
|
|
9
|
+
import { PREVIEW_CACHE_DIR, contentKey, readCachedPdf, writeCachedPdf } from './previewCache.mjs';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Xem tệp khi CHƯA đăng nhập (04/11/2026): `aivin open` dựng một trang chỉ-xem trên 127.0.0.1, không tải tệp lên Drive.
|
|
13
|
+
* .pdf / .md / .txt / .csv hiển thị tại máy. Tệp Office cần đổi sang PDF nên đi qua `POST /fileshare/anonymous-preview` (không lưu ở máy chủ),
|
|
14
|
+
* chỉ sau khi người dùng đồng ý. Nút đăng nhập tải tệp lên Drive rồi chuyển cửa sổ sang trình soạn.
|
|
15
|
+
* Trang đóng thì tiến trình tự thoát (không còn nhịp ping).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const PreviewKind = Object.freeze({ PDF: 'pdf', MARKDOWN: 'markdown', TEXT: 'text', CSV: 'csv', OFFICE: 'office', UNSUPPORTED: 'unsupported' });
|
|
19
|
+
|
|
20
|
+
const KIND_BY_EXTENSION = Object.freeze({
|
|
21
|
+
pdf: PreviewKind.PDF,
|
|
22
|
+
md: PreviewKind.MARKDOWN,
|
|
23
|
+
markdown: PreviewKind.MARKDOWN,
|
|
24
|
+
txt: PreviewKind.TEXT,
|
|
25
|
+
csv: PreviewKind.CSV,
|
|
26
|
+
docx: PreviewKind.OFFICE, doc: PreviewKind.OFFICE, odt: PreviewKind.OFFICE, rtf: PreviewKind.OFFICE,
|
|
27
|
+
xlsx: PreviewKind.OFFICE, xls: PreviewKind.OFFICE, xlsm: PreviewKind.OFFICE, ods: PreviewKind.OFFICE,
|
|
28
|
+
pptx: PreviewKind.OFFICE, ppt: PreviewKind.OFFICE, odp: PreviewKind.OFFICE,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const SETTINGS_FILE = path.join(os.homedir(), '.aivin', 'open-settings.json');
|
|
32
|
+
const MAX_INLINE_TEXT_BYTES = 5 * 1024 * 1024;
|
|
33
|
+
const MAX_CSV_ROWS = 5000;
|
|
34
|
+
const HEARTBEAT_TIMEOUT_MS = 3 * 60_000;
|
|
35
|
+
const HEARTBEAT_INTERVAL_MS = 20_000;
|
|
36
|
+
const SHUTDOWN_AFTER_LOGIN_MS = 5_000;
|
|
37
|
+
const CONVERT_TIMEOUT_MS = 3 * 60_000;
|
|
38
|
+
const BUSY_RETRIES = 5;
|
|
39
|
+
const BUSY_RETRY_MS = 3_000;
|
|
40
|
+
const BUSY_CODE = 'FILESHARE.ANON_PREVIEW_BUSY';
|
|
41
|
+
|
|
42
|
+
const TEXT = Object.freeze({
|
|
43
|
+
vi: {
|
|
44
|
+
view_only: 'Chỉ xem',
|
|
45
|
+
login: 'Đăng nhập để sửa và dùng AI',
|
|
46
|
+
logging_in: 'Đang chờ đăng nhập trên trình duyệt…',
|
|
47
|
+
login_failed: 'Chưa đăng nhập được. Vui lòng thử lại.',
|
|
48
|
+
login_note: 'Sau khi đăng nhập, tệp được tải lên Drive của bạn để sửa.',
|
|
49
|
+
consent_title: 'Xem tệp này cần gửi lên máy chủ Aivin',
|
|
50
|
+
consent_body: 'Để hiển thị tệp Office, tệp được gửi tới máy chủ Aivin để đổi sang PDF. Máy chủ không lưu tệp và xoá ngay sau khi đổi xong.',
|
|
51
|
+
consent_remember: 'Không hỏi lại trên máy này',
|
|
52
|
+
consent_accept: 'Gửi và xem',
|
|
53
|
+
converting: 'Đang chuẩn bị tệp để xem…',
|
|
54
|
+
convert_failed: 'Không xem được tệp này.',
|
|
55
|
+
unsupported: 'Loại tệp này chưa xem được khi chưa đăng nhập. Hãy đăng nhập để mở tệp.',
|
|
56
|
+
truncated: 'Tệp quá dài, chỉ hiện phần đầu. Đăng nhập để xem toàn bộ.',
|
|
57
|
+
disconnected: 'Trang xem đã ngắt. Hãy mở lại tệp.',
|
|
58
|
+
},
|
|
59
|
+
en: {
|
|
60
|
+
view_only: 'View only',
|
|
61
|
+
login: 'Sign in to edit and use AI',
|
|
62
|
+
logging_in: 'Waiting for sign-in in your browser…',
|
|
63
|
+
login_failed: 'Sign-in did not complete. Please try again.',
|
|
64
|
+
login_note: 'After you sign in, the file is uploaded to your Drive for editing.',
|
|
65
|
+
consent_title: 'Viewing this file means sending it to the Aivin server',
|
|
66
|
+
consent_body: 'To display an Office file, it is sent to the Aivin server and converted to PDF. The server does not keep the file and discards it right after converting.',
|
|
67
|
+
consent_remember: "Don't ask again on this computer",
|
|
68
|
+
consent_accept: 'Send and view',
|
|
69
|
+
converting: 'Preparing your file…',
|
|
70
|
+
convert_failed: 'This file could not be displayed.',
|
|
71
|
+
unsupported: 'This file type cannot be viewed without signing in. Sign in to open it.',
|
|
72
|
+
truncated: 'This file is long, so only the beginning is shown. Sign in to see all of it.',
|
|
73
|
+
disconnected: 'The viewer has disconnected. Please open the file again.',
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const textFor = (lang) => TEXT[lang] || TEXT.en;
|
|
78
|
+
|
|
79
|
+
export function previewKind(fileName) {
|
|
80
|
+
const extension = path.extname(String(fileName || '')).slice(1).toLowerCase();
|
|
81
|
+
return KIND_BY_EXTENSION[extension] || PreviewKind.UNSUPPORTED;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function escapeHtml(value) {
|
|
85
|
+
return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// --- Dựng nội dung chữ. Mọi thứ escape TRƯỚC, sau đó mới thêm thẻ: nội dung tệp không bao giờ thành HTML / script. ---------------------------
|
|
89
|
+
|
|
90
|
+
function renderInline(escaped) {
|
|
91
|
+
return escaped
|
|
92
|
+
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
|
93
|
+
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
94
|
+
.replace(/(^|[\s(])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>')
|
|
95
|
+
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const isTableDivider = (line) => /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line) && line.includes('-');
|
|
99
|
+
const tableCells = (line) => line.trim().replace(/^\||\|$/g, '').split('|').map((cell) => renderInline(escapeHtml(cell.trim())));
|
|
100
|
+
|
|
101
|
+
function renderTable(lines, start) {
|
|
102
|
+
const head = tableCells(lines[start]);
|
|
103
|
+
let i = start + 2;
|
|
104
|
+
const rows = [];
|
|
105
|
+
while (i < lines.length && lines[i].includes('|')) rows.push(tableCells(lines[i++]));
|
|
106
|
+
const cells = (row, tag) => `<tr>${row.map((c) => `<${tag}>${c}</${tag}>`).join('')}</tr>`;
|
|
107
|
+
return { html: `<table>${cells(head, 'th')}${rows.map((r) => cells(r, 'td')).join('')}</table>`, next: i };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function renderList(lines, start, pattern, tag) {
|
|
111
|
+
const items = [];
|
|
112
|
+
let i = start;
|
|
113
|
+
while (i < lines.length && pattern.test(lines[i])) items.push(`<li>${renderInline(escapeHtml(lines[i++].replace(pattern, '')))}</li>`);
|
|
114
|
+
return { html: `<${tag}>${items.join('')}</${tag}>`, next: i };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function renderFence(lines, start) {
|
|
118
|
+
let i = start + 1;
|
|
119
|
+
const code = [];
|
|
120
|
+
while (i < lines.length && !lines[i].startsWith('```')) code.push(lines[i++]);
|
|
121
|
+
return { html: `<pre>${escapeHtml(code.join('\n'))}</pre>`, next: i + 1 };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const BULLET = /^\s*[-*+]\s+/;
|
|
125
|
+
const ORDERED = /^\s*\d+[.)]\s+/;
|
|
126
|
+
|
|
127
|
+
/** Markdown thường gặp: tiêu đề, danh sách, bảng, khối mã, trích dẫn, đậm / nghiêng, liên kết http(s). */
|
|
128
|
+
export function renderMarkdown(source) {
|
|
129
|
+
const lines = String(source).split(/\r?\n/);
|
|
130
|
+
const out = [];
|
|
131
|
+
let i = 0;
|
|
132
|
+
while (i < lines.length) {
|
|
133
|
+
const line = lines[i];
|
|
134
|
+
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
|
135
|
+
let block = null;
|
|
136
|
+
if (!line.trim()) { i++; continue; }
|
|
137
|
+
if (line.startsWith('```')) block = renderFence(lines, i);
|
|
138
|
+
else if (heading) block = { html: `<h${heading[1].length}>${renderInline(escapeHtml(heading[2]))}</h${heading[1].length}>`, next: i + 1 };
|
|
139
|
+
else if (/^\s*(-{3,}|\*{3,})\s*$/.test(line)) block = { html: '<hr>', next: i + 1 };
|
|
140
|
+
else if (line.includes('|') && isTableDivider(lines[i + 1] || '')) block = renderTable(lines, i);
|
|
141
|
+
else if (BULLET.test(line)) block = renderList(lines, i, BULLET, 'ul');
|
|
142
|
+
else if (ORDERED.test(line)) block = renderList(lines, i, ORDERED, 'ol');
|
|
143
|
+
else if (line.startsWith('>')) block = { html: `<blockquote>${renderInline(escapeHtml(line.replace(/^>\s?/, '')))}</blockquote>`, next: i + 1 };
|
|
144
|
+
else block = { html: `<p>${renderInline(escapeHtml(line))}</p>`, next: i + 1 };
|
|
145
|
+
out.push(block.html);
|
|
146
|
+
i = block.next;
|
|
147
|
+
}
|
|
148
|
+
return out.join('\n');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function detectCsvDelimiter(text) {
|
|
152
|
+
const firstLine = text.split(/\r?\n/, 1)[0] || '';
|
|
153
|
+
return [',', ';', '\t'].map((d) => [d, firstLine.split(d).length]).sort((a, b) => b[1] - a[1])[0][0];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** CSV theo RFC 4180: ô trong ngoặc kép có thể chứa dấu phân cách, xuống dòng, "" là một dấu ngoặc kép. */
|
|
157
|
+
export function parseCsv(text, { maxRows = MAX_CSV_ROWS } = {}) {
|
|
158
|
+
const delimiter = detectCsvDelimiter(text);
|
|
159
|
+
const rows = [];
|
|
160
|
+
let row = [];
|
|
161
|
+
let cell = '';
|
|
162
|
+
let quoted = false;
|
|
163
|
+
for (let i = 0; i < text.length && rows.length < maxRows; i++) {
|
|
164
|
+
const c = text[i];
|
|
165
|
+
if (quoted) {
|
|
166
|
+
if (c === '"' && text[i + 1] === '"') { cell += '"'; i++; } else if (c === '"') quoted = false;
|
|
167
|
+
else cell += c;
|
|
168
|
+
} else if (c === '"' && !cell) quoted = true;
|
|
169
|
+
else if (c === delimiter) { row.push(cell); cell = ''; } else if (c === '\n') { row.push(cell.replace(/\r$/, '')); rows.push(row); row = []; cell = ''; } else cell += c;
|
|
170
|
+
}
|
|
171
|
+
if ((cell || row.length) && rows.length < maxRows) { row.push(cell); rows.push(row); }
|
|
172
|
+
return rows;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function renderCsv(text) {
|
|
176
|
+
const rows = parseCsv(text);
|
|
177
|
+
const body = rows.map((row, i) => {
|
|
178
|
+
const tag = i === 0 ? 'th' : 'td';
|
|
179
|
+
return `<tr>${row.map((c) => `<${tag}>${escapeHtml(c)}</${tag}>`).join('')}</tr>`;
|
|
180
|
+
}).join('');
|
|
181
|
+
return { html: `<table>${body}</table>`, truncated: rows.length >= MAX_CSV_ROWS };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Nội dung chữ dựng sẵn cho trang (null với PDF / Office: hiện trong khung). */
|
|
185
|
+
export function renderInlineContent(kind, buffer) {
|
|
186
|
+
if (![PreviewKind.MARKDOWN, PreviewKind.TEXT, PreviewKind.CSV].includes(kind)) return null;
|
|
187
|
+
const sliced = buffer.length > MAX_INLINE_TEXT_BYTES;
|
|
188
|
+
const text = buffer.subarray(0, MAX_INLINE_TEXT_BYTES).toString('utf8').replace(/^/, '');
|
|
189
|
+
if (kind === PreviewKind.MARKDOWN) return { html: `<article>${renderMarkdown(text)}</article>`, truncated: sliced };
|
|
190
|
+
if (kind === PreviewKind.TEXT) return { html: `<pre class="plain">${escapeHtml(text)}</pre>`, truncated: sliced };
|
|
191
|
+
const csv = renderCsv(text);
|
|
192
|
+
return { html: csv.html, truncated: sliced || csv.truncated };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// --- Trang ------------------------------------------------------------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
const PAGE_CSS = `
|
|
198
|
+
:root { --bg:#f2f3f5; --card:#fff; --text:#1d2129; --muted:#4e5969; --line:#e5e6eb; --primary:#165dff; --primary-text:#fff; --warn:#cb2634; }
|
|
199
|
+
* { box-sizing:border-box; }
|
|
200
|
+
html, body { height:100%; margin:0; }
|
|
201
|
+
body { display:flex; flex-direction:column; background:var(--bg); color:var(--text); font:14px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; }
|
|
202
|
+
header { display:flex; align-items:center; gap:10px; padding:8px 16px; background:var(--card); border-bottom:1px solid var(--line); flex-wrap:wrap; }
|
|
203
|
+
header img { width:24px; height:24px; border-radius:6px; }
|
|
204
|
+
.name { font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; flex:0 1 auto; }
|
|
205
|
+
.badge { font-size:13px; color:var(--muted); background:var(--bg); border-radius:6px; padding:1px 8px; white-space:nowrap; }
|
|
206
|
+
.spacer { flex:1; }
|
|
207
|
+
button { font:inherit; border-radius:8px; padding:5px 14px; border:1px solid var(--line); background:var(--card); color:var(--text); cursor:pointer; transition:background .15s, opacity .15s; }
|
|
208
|
+
button.primary { background:var(--primary); border-color:var(--primary); color:var(--primary-text); }
|
|
209
|
+
button:disabled { opacity:.6; cursor:default; }
|
|
210
|
+
main { flex:1; min-height:0; overflow:auto; }
|
|
211
|
+
iframe { width:100%; height:100%; border:0; display:block; }
|
|
212
|
+
.doc { max-width:960px; margin:16px auto; padding:24px 32px; background:var(--card); border-radius:12px; overflow:auto; }
|
|
213
|
+
.wide { max-width:none; margin:16px; }
|
|
214
|
+
.plain { white-space:pre-wrap; word-break:break-word; margin:0; font:13px/1.6 ui-monospace,Consolas,monospace; }
|
|
215
|
+
pre { background:var(--bg); padding:12px; border-radius:8px; overflow:auto; }
|
|
216
|
+
code { background:var(--bg); padding:0 4px; border-radius:4px; }
|
|
217
|
+
table { border-collapse:collapse; font-size:13px; }
|
|
218
|
+
th, td { border:1px solid var(--line); padding:4px 10px; text-align:left; vertical-align:top; }
|
|
219
|
+
th { background:var(--bg); }
|
|
220
|
+
blockquote { margin:8px 0; padding-left:12px; border-left:3px solid var(--line); color:var(--muted); }
|
|
221
|
+
.card { max-width:480px; margin:48px auto; padding:24px; background:var(--card); border-radius:12px; }
|
|
222
|
+
.card h2 { margin:0 0 8px; font-size:16px; }
|
|
223
|
+
.card p { margin:0 0 16px; color:var(--muted); }
|
|
224
|
+
.card label { display:flex; gap:8px; align-items:center; margin-bottom:16px; }
|
|
225
|
+
.actions { display:flex; justify-content:flex-end; }
|
|
226
|
+
.notice { padding:6px 16px; background:#fff7e8; font-size:13px; }
|
|
227
|
+
.error { color:var(--warn); }
|
|
228
|
+
[hidden] { display:none !important; }
|
|
229
|
+
@media (prefers-color-scheme: dark) {
|
|
230
|
+
:root { --bg:#17171a; --card:#232324; --text:#e5e6eb; --muted:#a9aeb8; --line:#3a3a3d; --primary:#3c7eff; }
|
|
231
|
+
.notice { background:#3a2f16; }
|
|
232
|
+
}
|
|
233
|
+
`;
|
|
234
|
+
|
|
235
|
+
const PAGE_SCRIPT = `
|
|
236
|
+
const cfg = JSON.parse(document.getElementById('cfg').textContent);
|
|
237
|
+
const $ = (id) => document.getElementById(id);
|
|
238
|
+
const post = (name, body) => fetch(cfg.base + name, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
|
239
|
+
const show = (id) => { for (const s of ['consent', 'status', 'frame']) { const el = $(s); if (el) el.hidden = s !== id; } };
|
|
240
|
+
function showStatus(message, isError) { const el = $('status'); el.textContent = message; el.className = isError ? 'card error' : 'card'; show('status'); }
|
|
241
|
+
function showFile() { const f = $('frame'); f.src = cfg.base + 'file'; show('frame'); }
|
|
242
|
+
async function convert(remember) {
|
|
243
|
+
showStatus(cfg.t.converting);
|
|
244
|
+
try {
|
|
245
|
+
const res = await post('convert', { remember });
|
|
246
|
+
const data = await res.json();
|
|
247
|
+
if (data.ok) showFile(); else showStatus(data.message || cfg.t.convert_failed, true);
|
|
248
|
+
} catch { showStatus(cfg.t.disconnected, true); }
|
|
249
|
+
}
|
|
250
|
+
$('login').addEventListener('click', async () => {
|
|
251
|
+
const btn = $('login');
|
|
252
|
+
btn.disabled = true;
|
|
253
|
+
btn.textContent = cfg.t.logging_in;
|
|
254
|
+
try {
|
|
255
|
+
const data = await (await post('login')).json();
|
|
256
|
+
if (data.url) { location.href = data.url; return; }
|
|
257
|
+
btn.textContent = data.message || cfg.t.login_failed;
|
|
258
|
+
} catch { btn.textContent = cfg.t.disconnected; }
|
|
259
|
+
btn.disabled = false;
|
|
260
|
+
});
|
|
261
|
+
if ($('accept')) $('accept').addEventListener('click', () => convert($('remember').checked));
|
|
262
|
+
if (cfg.kind === 'pdf' || cfg.ready) showFile();
|
|
263
|
+
else if (cfg.kind === 'office' && cfg.consented) convert(false);
|
|
264
|
+
setInterval(() => { fetch(cfg.base + 'ping').catch(() => { const n = $('gone'); if (n) n.hidden = false; }); }, cfg.heartbeat);
|
|
265
|
+
`;
|
|
266
|
+
|
|
267
|
+
function consentCard(t) {
|
|
268
|
+
return `<section class="card" id="consent"><h2>${escapeHtml(t.consent_title)}</h2><p>${escapeHtml(t.consent_body)}</p>`
|
|
269
|
+
+ `<label><input type="checkbox" id="remember" checked>${escapeHtml(t.consent_remember)}</label>`
|
|
270
|
+
+ `<div class="actions"><button class="primary" id="accept">${escapeHtml(t.consent_accept)}</button></div></section>`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function mainContent({ kind, inline, consented, ready, t }) {
|
|
274
|
+
if (inline) return `<div class="doc${kind === PreviewKind.CSV ? ' wide' : ''}">${inline.html}</div>`;
|
|
275
|
+
if (kind === PreviewKind.UNSUPPORTED) return `<section class="card"><p>${escapeHtml(t.unsupported)}</p></section>`;
|
|
276
|
+
const consent = kind === PreviewKind.OFFICE && !consented && !ready ? consentCard(t) : '';
|
|
277
|
+
return `${consent}<section class="card" id="status" hidden></section><iframe id="frame" title="preview" hidden></iframe>`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** `<` trong JSON bị escape để tên tệp không đóng được thẻ script. */
|
|
281
|
+
const safeJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
|
|
282
|
+
|
|
283
|
+
export function previewPageHtml({ name, kind, inline, consented, ready = false, base, nonce, lang }) {
|
|
284
|
+
const t = textFor(lang);
|
|
285
|
+
const cfg = { base, kind, consented, ready, heartbeat: HEARTBEAT_INTERVAL_MS, t };
|
|
286
|
+
const truncated = inline?.truncated ? `<div class="notice">${escapeHtml(t.truncated)}</div>` : '';
|
|
287
|
+
return `<!doctype html><html lang="${escapeHtml(lang)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`
|
|
288
|
+
+ `<title>${escapeHtml(name)} - AIVIN Bot</title><link rel="icon" href="data:image/png;base64,${AIVIN_LOGO_PNG_BASE64}"><style>${PAGE_CSS}</style></head><body>`
|
|
289
|
+
+ `<header><img alt="" src="data:image/png;base64,${AIVIN_LOGO_PNG_BASE64}"><span class="name">${escapeHtml(name)}</span><span class="badge">${escapeHtml(t.view_only)}</span>`
|
|
290
|
+
+ `<span class="spacer"></span><button class="primary" id="login" title="${escapeHtml(t.login_note)}">${escapeHtml(t.login)}</button></header>`
|
|
291
|
+
+ `<div class="notice" id="gone" hidden>${escapeHtml(t.disconnected)}</div>${truncated}`
|
|
292
|
+
+ `<main>${mainContent({ kind, inline, consented, ready, t })}</main>`
|
|
293
|
+
+ `<script type="application/json" id="cfg">${safeJson(cfg)}</script><script nonce="${nonce}">${PAGE_SCRIPT}</script></body></html>`;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// --- Đồng ý + chuyển đổi trên cloud -----------------------------------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
export function hasOfficeConsent(file = SETTINGS_FILE) {
|
|
299
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')).office_preview_consent === true; } catch { return false; }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function saveOfficeConsent(file = SETTINGS_FILE) {
|
|
303
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
304
|
+
fs.writeFileSync(file, JSON.stringify({ office_preview_consent: true }, null, 2));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function errorBody(error) {
|
|
308
|
+
try { return JSON.parse(Buffer.from(error.response.data).toString('utf8')); } catch { return null; }
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
312
|
+
|
|
313
|
+
/** Máy chủ bận thì tự thử lại, người dùng chỉ thấy "đang chuẩn bị". */
|
|
314
|
+
export async function convertOfficeOnCloud({ serverUrl, name, buffer, post = axios.post, wait = sleep }) {
|
|
315
|
+
for (let attempt = 0; ; attempt++) {
|
|
316
|
+
const form = new FormData();
|
|
317
|
+
form.append('file', new Blob([buffer]), name);
|
|
318
|
+
try {
|
|
319
|
+
const res = await post(`${serverUrl}/fileshare/anonymous-preview`, form, { responseType: 'arraybuffer', timeout: CONVERT_TIMEOUT_MS, maxBodyLength: Infinity, maxContentLength: Infinity });
|
|
320
|
+
return Buffer.from(res.data);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
const body = errorBody(error);
|
|
323
|
+
if (body?.code === BUSY_CODE && attempt < BUSY_RETRIES) { await wait(BUSY_RETRY_MS); continue; }
|
|
324
|
+
throw new Error(body?.message || error?.code || error?.message, { cause: error });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// --- Máy chủ cục bộ ---------------------------------------------------------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'";
|
|
332
|
+
|
|
333
|
+
function readJsonBody(req, limit = 4096) {
|
|
334
|
+
return new Promise((resolve) => {
|
|
335
|
+
let raw = '';
|
|
336
|
+
req.on('data', (chunk) => { raw += chunk; if (raw.length > limit) req.destroy(); });
|
|
337
|
+
req.on('end', () => { try { resolve(JSON.parse(raw || '{}')); } catch { resolve({}); } });
|
|
338
|
+
req.on('error', () => resolve({}));
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function sendJson(res, status, body) {
|
|
343
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
344
|
+
res.end(JSON.stringify(body));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Chống DNS rebinding + trang web khác gọi vào cổng cục bộ: Host phải đúng, POST phải cùng nguồn. */
|
|
348
|
+
export function isTrustedRequest({ method, host, origin, port }) {
|
|
349
|
+
const self = `127.0.0.1:${port}`;
|
|
350
|
+
if (host !== self) return false;
|
|
351
|
+
return method === 'GET' || origin === `http://${self}`;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Mở máy chủ xem tệp. `onLogin()` đăng nhập + tải lên Drive, trả link trình soạn. `onClosed()` khi trang đã đóng.
|
|
356
|
+
* Trả `{ url, close }`.
|
|
357
|
+
*/
|
|
358
|
+
export async function startPreviewServer({ filePath, serverUrl, onLogin, onClosed = () => {}, lang = mascotLang(), settingsFile = SETTINGS_FILE, cacheDir = PREVIEW_CACHE_DIR, heartbeatTimeoutMs = HEARTBEAT_TIMEOUT_MS }) {
|
|
359
|
+
const name = path.basename(filePath);
|
|
360
|
+
const kind = previewKind(name);
|
|
361
|
+
const buffer = fs.readFileSync(filePath);
|
|
362
|
+
const inline = renderInlineContent(kind, buffer);
|
|
363
|
+
const token = randomBytes(24).toString('hex');
|
|
364
|
+
const base = `/${token}/`;
|
|
365
|
+
const t = textFor(lang);
|
|
366
|
+
const cacheKey = kind === PreviewKind.OFFICE ? contentKey(buffer) : null;
|
|
367
|
+
let pdf = kind === PreviewKind.PDF ? buffer : (cacheKey && readCachedPdf(cacheKey, { dir: cacheDir }));
|
|
368
|
+
const fromCache = kind === PreviewKind.OFFICE && !!pdf;
|
|
369
|
+
let lastSeen = Date.now();
|
|
370
|
+
let port = 0;
|
|
371
|
+
let closed = false;
|
|
372
|
+
|
|
373
|
+
const server = http.createServer();
|
|
374
|
+
const watchdog = setInterval(() => { if (Date.now() - lastSeen > heartbeatTimeoutMs) close(); }, 15_000);
|
|
375
|
+
function close() {
|
|
376
|
+
if (closed) return;
|
|
377
|
+
closed = true;
|
|
378
|
+
clearInterval(watchdog);
|
|
379
|
+
server.closeAllConnections?.();
|
|
380
|
+
server.close(() => onClosed());
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const handlers = {
|
|
384
|
+
'GET ': (req, res) => {
|
|
385
|
+
const nonce = randomBytes(16).toString('base64');
|
|
386
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Content-Security-Policy': `${PAGE_CSP}; script-src 'nonce-${nonce}'` });
|
|
387
|
+
res.end(previewPageHtml({ name, kind, inline, consented: hasOfficeConsent(settingsFile), ready: !!pdf, base, nonce, lang }));
|
|
388
|
+
},
|
|
389
|
+
'GET ping': (req, res) => sendJson(res, 200, { ok: true }),
|
|
390
|
+
'GET file': (req, res) => {
|
|
391
|
+
if (!pdf) return sendJson(res, 404, { ok: false });
|
|
392
|
+
res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
393
|
+
res.end(pdf);
|
|
394
|
+
},
|
|
395
|
+
'POST convert': async (req, res) => {
|
|
396
|
+
if (kind !== PreviewKind.OFFICE) return sendJson(res, 400, { ok: false });
|
|
397
|
+
const body = await readJsonBody(req);
|
|
398
|
+
try {
|
|
399
|
+
if (body.remember) saveOfficeConsent(settingsFile);
|
|
400
|
+
if (!pdf) {
|
|
401
|
+
pdf = await convertOfficeOnCloud({ serverUrl, name, buffer });
|
|
402
|
+
writeCachedPdf(cacheKey, pdf, { dir: cacheDir });
|
|
403
|
+
}
|
|
404
|
+
sendJson(res, 200, { ok: true });
|
|
405
|
+
} catch (error) {
|
|
406
|
+
sendJson(res, 200, { ok: false, message: error.message || t.convert_failed });
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
'POST login': async (req, res) => {
|
|
410
|
+
try {
|
|
411
|
+
const url = await onLogin();
|
|
412
|
+
sendJson(res, 200, { url });
|
|
413
|
+
setTimeout(close, SHUTDOWN_AFTER_LOGIN_MS).unref();
|
|
414
|
+
} catch (error) {
|
|
415
|
+
sendJson(res, 200, { message: error.message || t.login_failed });
|
|
416
|
+
}
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
server.on('request', (req, res) => {
|
|
421
|
+
lastSeen = Date.now();
|
|
422
|
+
const pathname = (req.url || '').split('?')[0];
|
|
423
|
+
if (!isTrustedRequest({ method: req.method, host: req.headers.host, origin: req.headers.origin, port }) || !pathname.startsWith(base)) {
|
|
424
|
+
res.writeHead(404).end();
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const handler = handlers[`${req.method} ${pathname.slice(base.length)}`];
|
|
428
|
+
if (!handler) { res.writeHead(404).end(); return; }
|
|
429
|
+
Promise.resolve(handler(req, res)).catch(() => { if (!res.headersSent) res.writeHead(500); res.end(); });
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
port = await new Promise((resolve, reject) => {
|
|
433
|
+
server.once('error', reject);
|
|
434
|
+
server.listen(0, '127.0.0.1', () => resolve(server.address().port));
|
|
435
|
+
});
|
|
436
|
+
return { url: `http://127.0.0.1:${port}${base}`, close, fromCache };
|
|
437
|
+
}
|