@aivin-labs/cli 1.0.11 → 1.0.21
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 -288
- package/bin/cli.mjs +163 -17
- 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 +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- 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 +331 -52
- 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 +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -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/osSearch.mjs +107 -0
- 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/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- 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/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import axios from 'axios';
|
|
5
|
+
import { createHash } from 'crypto';
|
|
6
|
+
import { fetchWebUrl } from './context.mjs';
|
|
7
|
+
import { startPreviewServer } from './localPreview.mjs';
|
|
8
|
+
import { missionAuthHeaders, missionServerUrl, resolveWorkspace } from './workspace.mjs';
|
|
9
|
+
import { spawn } from 'child_process';
|
|
10
|
+
import { browserLogin, openBrowser, saveGlobalApiKey, tryFetchWhoami } from './auth.mjs';
|
|
11
|
+
import { LOCAL_BROWSERS, detectDefaultBrowserId, resolveBrowserInstall } from './localBrowser.mjs';
|
|
12
|
+
import { mascotLang } from './remote/mascot/strings.mjs';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `aivin open <tệp>` (04/11/2026) — mở tệp trên máy bằng Drive của Aivin (chưa đăng nhập: trang chỉ-xem, localPreview.mjs). Đã đăng nhập: tải lên workspace cá nhân (hoặc --workspace) rồi mở
|
|
16
|
+
* `<web>/drive?open_file=<id>&workspace_id=<ws>` (deep-link sẵn có của FE, FileShareHook.useOpenFileDeepLink).
|
|
17
|
+
*
|
|
18
|
+
* Drive là bản chính sau khi mở: cùng NỘI DUNG (sha256) đã tải trước đó → mở lại đúng tệp Drive cũ (giữ mọi chỉnh sửa trên Aivin);
|
|
19
|
+
* tệp trên máy đã đổi → tải thành tệp Drive MỚI, không ghi đè bản Drive (có thể đã sửa trên Aivin).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export const OPEN_INDEX_FILE = path.join(os.homedir(), '.aivin', 'opened-files.json');
|
|
23
|
+
const MAX_INDEX_ENTRIES = 500;
|
|
24
|
+
const DEFAULT_WEB_URL = 'https://brain.aivin.cloud';
|
|
25
|
+
|
|
26
|
+
export const OpenDisplay = Object.freeze({ WINDOW: 'window', TAB: 'tab', NONE: 'none' });
|
|
27
|
+
|
|
28
|
+
export const OpenFileError = Object.freeze({
|
|
29
|
+
NOT_FOUND: 'not_found',
|
|
30
|
+
NOT_A_FILE: 'not_a_file',
|
|
31
|
+
NOT_LOGGED_IN: 'not_logged_in',
|
|
32
|
+
UPLOAD_FAILED: 'upload_failed',
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
/** Chữ hiện cho người dùng (dòng lệnh + thông báo hệ điều hành), theo ngôn ngữ máy (mascotLang). */
|
|
36
|
+
const OPEN_TEXT = Object.freeze({
|
|
37
|
+
vi: {
|
|
38
|
+
[OpenFileError.NOT_FOUND]: 'Không tìm thấy tệp: {path}',
|
|
39
|
+
[OpenFileError.NOT_A_FILE]: 'Không phải tệp: {path}',
|
|
40
|
+
[OpenFileError.NOT_LOGGED_IN]: 'Máy này chưa đăng nhập Aivin — mở Terminal và chạy: aivin login',
|
|
41
|
+
[OpenFileError.UPLOAD_FAILED]: 'Tải "{name}" lên Drive không được: {reason}',
|
|
42
|
+
opening: 'Đang mở "{name}" trên Aivin…',
|
|
43
|
+
failed_title: 'Không mở được bằng AIVIN Bot',
|
|
44
|
+
},
|
|
45
|
+
en: {
|
|
46
|
+
[OpenFileError.NOT_FOUND]: 'File not found: {path}',
|
|
47
|
+
[OpenFileError.NOT_A_FILE]: 'Not a file: {path}',
|
|
48
|
+
[OpenFileError.NOT_LOGGED_IN]: 'This computer is not signed in to Aivin — open a terminal and run: aivin login',
|
|
49
|
+
[OpenFileError.UPLOAD_FAILED]: 'Could not upload "{name}" to Drive: {reason}',
|
|
50
|
+
opening: 'Opening "{name}" in Aivin…',
|
|
51
|
+
failed_title: 'Could not open with AIVIN Bot',
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export function openText(key, vars = {}, lang = mascotLang()) {
|
|
56
|
+
const table = OPEN_TEXT[lang] || OPEN_TEXT.en;
|
|
57
|
+
return String(table[key] ?? OPEN_TEXT.en[key] ?? key).replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ''));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class OpenFileFailure extends Error {
|
|
61
|
+
constructor(code, vars = {}, cause) {
|
|
62
|
+
super(openText(code, vars), cause ? { cause } : undefined);
|
|
63
|
+
this.code = code;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function fileSha256(buffer) {
|
|
68
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Khoá chỉ mục: cùng máy chủ + workspace + nội dung (đổi tài khoản / máy chủ không dùng nhầm tệp của nơi khác). */
|
|
72
|
+
export function indexKey({ baseUrl, workspaceId, sha256 }) {
|
|
73
|
+
return `${baseUrl}|${workspaceId}|${sha256}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function readOpenIndex(file = OPEN_INDEX_FILE) {
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
79
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
80
|
+
} catch {
|
|
81
|
+
return {};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Ghi chỉ mục, giữ tối đa MAX_INDEX_ENTRIES mục mở gần nhất. */
|
|
86
|
+
export function writeOpenIndex(index, file = OPEN_INDEX_FILE) {
|
|
87
|
+
const entries = Object.entries(index)
|
|
88
|
+
.sort((a, b) => String(b[1]?.opened_at || '').localeCompare(String(a[1]?.opened_at || '')))
|
|
89
|
+
.slice(0, MAX_INDEX_ENTRIES);
|
|
90
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
91
|
+
const tmp = `${file}.tmp`;
|
|
92
|
+
fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(entries), null, 2));
|
|
93
|
+
fs.renameSync(tmp, file);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function driveOpenUrl(webUrl, { fileId, workspaceId }) {
|
|
97
|
+
const params = new URLSearchParams({ open_file: fileId, workspace_id: workspaceId });
|
|
98
|
+
return `${String(webUrl).replace(/\/+$/, '')}/drive?${params.toString()}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function readLocalFile(filePath) {
|
|
102
|
+
const abs = path.resolve(filePath);
|
|
103
|
+
let stat;
|
|
104
|
+
try { stat = fs.statSync(abs); } catch (e) { throw new OpenFileFailure(OpenFileError.NOT_FOUND, { path: abs }, e); }
|
|
105
|
+
if (!stat.isFile()) throw new OpenFileFailure(OpenFileError.NOT_A_FILE, { path: abs });
|
|
106
|
+
return { abs, name: path.basename(abs), buffer: fs.readFileSync(abs) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Tệp Drive đã tải trước đó còn mở được không (bị xoá / mất quyền → tải lại). */
|
|
110
|
+
async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
|
|
111
|
+
try {
|
|
112
|
+
await axios.get(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/${encodeURIComponent(fileId)}`, { ...auth, timeout: 20_000 });
|
|
113
|
+
return true;
|
|
114
|
+
} catch (e) {
|
|
115
|
+
const status = e?.response?.status;
|
|
116
|
+
if (status === 404 || status === 403 || status === 400) return false;
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }) {
|
|
122
|
+
const form = new FormData();
|
|
123
|
+
form.append('file', new Blob([buffer]), name);
|
|
124
|
+
try {
|
|
125
|
+
const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
|
|
126
|
+
...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
|
|
127
|
+
});
|
|
128
|
+
const id = res.data?.id || res.data?._id;
|
|
129
|
+
if (!id) throw new Error('no file id in the upload response');
|
|
130
|
+
return String(id);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
const reason = e?.response?.data?.message || e?.message || e?.code || 'unknown error';
|
|
133
|
+
throw new OpenFileFailure(OpenFileError.UPLOAD_FAILED, { name, reason }, e);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function findReusable(serverUrl, auth, { index, key }) {
|
|
138
|
+
const hit = index[key];
|
|
139
|
+
if (!hit?.file_id) return null;
|
|
140
|
+
return (await driveFileExists(serverUrl, auth, { workspaceId: hit.workspace_id, fileId: hit.file_id })) ? hit.file_id : null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Cửa sổ ứng dụng (`--app=`): không thanh địa chỉ / tab, biểu tượng riêng trên taskbar. Chỉ dùng trình duyệt MẶC ĐỊNH và chỉ khi nó là Chromium —
|
|
145
|
+
* phiên đăng nhập Aivin nằm ở đó; trình duyệt khác sẽ bắt đăng nhập lại, nên Firefox / chưa rõ thì trả null (mở tab thường).
|
|
146
|
+
*/
|
|
147
|
+
export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), resolve = resolveBrowserInstall } = {}) {
|
|
148
|
+
const browser = LOCAL_BROWSERS.find((b) => b.id === defaultId);
|
|
149
|
+
const install = browser ? resolve(browser) : null;
|
|
150
|
+
return install ? { exe: install.exe, args: [`--app=${url}`] } : null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function openInWindow(url) {
|
|
154
|
+
const cmd = appWindowCommand(url);
|
|
155
|
+
if (!cmd) return openBrowser(url);
|
|
156
|
+
const child = spawn(cmd.exe, cmd.args, { detached: true, stdio: 'ignore' });
|
|
157
|
+
child.on('error', () => openBrowser(url));
|
|
158
|
+
child.unref();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function showUrl(url, mode) {
|
|
162
|
+
if (mode === OpenDisplay.WINDOW) openInWindow(url);
|
|
163
|
+
else if (mode === OpenDisplay.TAB) openBrowser(url);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function resolveWebUrl(serverUrl) {
|
|
167
|
+
return process.env.AIVIN_WEB_URL || (await fetchWebUrl(serverUrl)) || DEFAULT_WEB_URL;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
|
|
172
|
+
* `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
|
|
173
|
+
*/
|
|
174
|
+
export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE } = {}) {
|
|
175
|
+
if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
|
|
176
|
+
const local = readLocalFile(filePath);
|
|
177
|
+
const serverUrl = missionServerUrl();
|
|
178
|
+
const auth = missionAuthHeaders();
|
|
179
|
+
const ws = await resolveWorkspace(serverUrl, auth, workspace);
|
|
180
|
+
const workspaceId = String(ws.id || ws._id);
|
|
181
|
+
const sha256 = fileSha256(local.buffer);
|
|
182
|
+
const key = indexKey({ baseUrl: serverUrl, workspaceId, sha256 });
|
|
183
|
+
|
|
184
|
+
const index = readOpenIndex(indexFile);
|
|
185
|
+
const reusedId = await findReusable(serverUrl, auth, { index, key });
|
|
186
|
+
const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer });
|
|
187
|
+
|
|
188
|
+
index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
|
|
189
|
+
try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
|
|
190
|
+
|
|
191
|
+
const url = driveOpenUrl(await resolveWebUrl(serverUrl), { fileId, workspaceId });
|
|
192
|
+
showUrl(url, displayMode);
|
|
193
|
+
return { url, fileId, workspaceId, reused: !!reusedId, name: local.name };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const isAuthRejected = (error) => (error?.cause?.response?.status ?? error?.response?.status) === 401;
|
|
197
|
+
|
|
198
|
+
/** Nút đăng nhập trên trang xem: đăng nhập qua trình duyệt, lưu khoá, tải tệp lên Drive, trả link trình soạn để chính cửa sổ đó chuyển sang. */
|
|
199
|
+
async function loginAndUpload(filePath, workspace) {
|
|
200
|
+
const serverUrl = missionServerUrl();
|
|
201
|
+
if (!process.env.AIVIN_WEB_URL) process.env.AIVIN_WEB_URL = await resolveWebUrl(serverUrl);
|
|
202
|
+
const apiKey = await browserLogin();
|
|
203
|
+
saveGlobalApiKey(apiKey, serverUrl, await tryFetchWhoami(serverUrl, apiKey));
|
|
204
|
+
process.env.API_KEY = apiKey;
|
|
205
|
+
const { url } = await openLocalFile(filePath, { workspace, display: OpenDisplay.NONE });
|
|
206
|
+
return url;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let activePreviews = 0;
|
|
210
|
+
|
|
211
|
+
/** Chưa đăng nhập: trang chỉ-xem tại máy. Tiến trình sống tới khi mọi trang đã đóng. */
|
|
212
|
+
async function openViewOnly(filePath, { workspace, display: mode = OpenDisplay.WINDOW }) {
|
|
213
|
+
const abs = readLocalFile(filePath).abs;
|
|
214
|
+
activePreviews++;
|
|
215
|
+
const { url } = await startPreviewServer({
|
|
216
|
+
filePath: abs,
|
|
217
|
+
serverUrl: missionServerUrl(),
|
|
218
|
+
onLogin: () => loginAndUpload(abs, workspace),
|
|
219
|
+
onClosed: () => { if (--activePreviews === 0) process.exit(process.exitCode ?? 0); },
|
|
220
|
+
});
|
|
221
|
+
showUrl(url, mode);
|
|
222
|
+
return { url, name: path.basename(abs), viewOnly: true };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Lối vào của `aivin open`: đã đăng nhập → trình soạn trên Drive; chưa đăng nhập hoặc khoá đã bị thu hồi → trang chỉ-xem. */
|
|
226
|
+
export async function openFile(filePath, options = {}) {
|
|
227
|
+
if (!process.env.API_KEY) return openViewOnly(filePath, options);
|
|
228
|
+
try {
|
|
229
|
+
return await openLocalFile(filePath, options);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (!isAuthRejected(error)) throw error;
|
|
232
|
+
delete process.env.API_KEY;
|
|
233
|
+
return openViewOnly(filePath, options);
|
|
234
|
+
}
|
|
235
|
+
}
|