@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
|
@@ -1,393 +1,635 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Đầu nối Office qua COM (28/10/2026) — cùng tiến trình host với tầng giao diện (windowsHostSource.mjs), op `office`. Người dùng không cấu
|
|
3
|
-
* hình gì: máy có Excel / Word / Outlook (ProgID trong registry) thì CLI tự bật công cụ `office.*`.
|
|
4
|
-
*
|
|
5
|
-
* Tệp người dùng ĐANG MỞ trong Excel / Word → thao tác thẳng trên bản đó (người dùng thấy ngay, chỉ lưu khi được yêu cầu). Tệp chưa mở →
|
|
6
|
-
* mở bằng một bản Excel / Word ẨN riêng (chạy nền, không hiện cửa sổ), lưu rồi đóng. Gọi COM bằng reflection (C# 5, không cần interop).
|
|
7
|
-
* Không có `using` — ghép sau phần chính, dùng chung các `using` ở đầu tệp.
|
|
8
|
-
*/
|
|
9
|
-
export const OFFICE_CSHARP = String.raw`
|
|
10
|
-
namespace AivinGui {
|
|
11
|
-
public static class Office {
|
|
12
|
-
const int MAX_CELLS = 5000;
|
|
13
|
-
const int MAX_TEXT = 200000;
|
|
14
|
-
|
|
15
|
-
class Opened { public object App; public object Doc; public bool Own; }
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
var
|
|
29
|
-
return
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
static
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
if (
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
static
|
|
149
|
-
if (
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
if (
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Đầu nối Office qua COM (28/10/2026) — cùng tiến trình host với tầng giao diện (windowsHostSource.mjs), op `office`. Người dùng không cấu
|
|
3
|
+
* hình gì: máy có Excel / Word / Outlook (ProgID trong registry) thì CLI tự bật công cụ `office.*`.
|
|
4
|
+
*
|
|
5
|
+
* Tệp người dùng ĐANG MỞ trong Excel / Word → thao tác thẳng trên bản đó (người dùng thấy ngay, chỉ lưu khi được yêu cầu). Tệp chưa mở →
|
|
6
|
+
* mở bằng một bản Excel / Word ẨN riêng (chạy nền, không hiện cửa sổ), lưu rồi đóng. Gọi COM bằng reflection (C# 5, không cần interop).
|
|
7
|
+
* Không có `using` — ghép sau phần chính, dùng chung các `using` ở đầu tệp.
|
|
8
|
+
*/
|
|
9
|
+
export const OFFICE_CSHARP = String.raw`
|
|
10
|
+
namespace AivinGui {
|
|
11
|
+
public static class Office {
|
|
12
|
+
const int MAX_CELLS = 5000;
|
|
13
|
+
const int MAX_TEXT = 200000;
|
|
14
|
+
|
|
15
|
+
class Opened { public object App; public object Doc; public bool Own; public int Pid; }
|
|
16
|
+
|
|
17
|
+
// ── bản Excel / Word ẩn do host tạo: ghi PID để dọn khi host bị giết giữa chừng (02/11/2026) ─────────────────────────────
|
|
18
|
+
// Host bị kill giữa OpenWorkbook → bản ẩn (Visible=false) sống mãi, giữ khoá tệp. Mỗi bản ẩn host tạo ghi một dòng
|
|
19
|
+
// "pid|tên tiến trình|giờ khởi động (UTC ticks)" vào tệp AIVIN_GUI_ORPHANS; đóng xong thì xoá dòng. Lần host khởi động sau dọn dòng còn
|
|
20
|
+
// lại — CHỈ giết khi đúng PID + đúng tên + đúng giờ khởi động (PID không bị tái dùng) và tiến trình không có cửa sổ hiển thị nào (người
|
|
21
|
+
// dùng không đang dùng nó).
|
|
22
|
+
static readonly object OrphanLock = new object();
|
|
23
|
+
|
|
24
|
+
static string OrphanFile() { var p = Environment.GetEnvironmentVariable("AIVIN_GUI_ORPHANS"); return string.IsNullOrEmpty(p) ? null : p; }
|
|
25
|
+
|
|
26
|
+
static HashSet<int> PidsOf(string name) {
|
|
27
|
+
var s = new HashSet<int>();
|
|
28
|
+
foreach (var p in Process.GetProcessesByName(name)) { s.Add(p.Id); p.Dispose(); }
|
|
29
|
+
return s;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static long StartTicks(Process p) { return p.StartTime.ToUniversalTime().Ticks; }
|
|
33
|
+
|
|
34
|
+
static bool HasVisibleWindow(int pid) {
|
|
35
|
+
bool found = false;
|
|
36
|
+
Native.EnumWindows(delegate (IntPtr h, IntPtr l) {
|
|
37
|
+
uint wp; Native.GetWindowThreadProcessId(h, out wp);
|
|
38
|
+
if ((int)wp == pid && Native.IsWindowVisible(h)) { found = true; return false; }
|
|
39
|
+
return true;
|
|
40
|
+
}, IntPtr.Zero);
|
|
41
|
+
return found;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** PID của bản vừa tạo: Excel theo Hwnd của ứng dụng; không được thì tiến trình mới xuất hiện (đúng một) so với trước khi tạo. */
|
|
45
|
+
static int TrackOwn(string procName, HashSet<int> before, object app) {
|
|
46
|
+
int pid = 0;
|
|
47
|
+
if (procName == "EXCEL") {
|
|
48
|
+
try { uint p; Native.GetWindowThreadProcessId(new IntPtr(Convert.ToInt64(Get(app, "Hwnd"))), out p); pid = (int)p; } catch { }
|
|
49
|
+
}
|
|
50
|
+
if (pid == 0) {
|
|
51
|
+
var now = PidsOf(procName);
|
|
52
|
+
now.ExceptWith(before);
|
|
53
|
+
if (now.Count == 1) foreach (int p in now) pid = p;
|
|
54
|
+
}
|
|
55
|
+
string file = OrphanFile();
|
|
56
|
+
if (pid == 0 || file == null) return pid;
|
|
57
|
+
try {
|
|
58
|
+
long start;
|
|
59
|
+
using (var pr = Process.GetProcessById(pid)) start = StartTicks(pr);
|
|
60
|
+
lock (OrphanLock) { File.AppendAllText(file, pid + "|" + procName + "|" + start + Environment.NewLine); }
|
|
61
|
+
} catch { }
|
|
62
|
+
return pid;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static void UntrackOwn(int pid) {
|
|
66
|
+
string file = OrphanFile();
|
|
67
|
+
if (pid == 0 || file == null) return;
|
|
68
|
+
try {
|
|
69
|
+
lock (OrphanLock) {
|
|
70
|
+
if (!File.Exists(file)) return;
|
|
71
|
+
var keep = new List<string>();
|
|
72
|
+
foreach (var line in File.ReadAllLines(file)) if (line.Length > 0 && !line.StartsWith(pid + "|")) keep.Add(line);
|
|
73
|
+
if (keep.Count == 0) File.Delete(file); else File.WriteAllLines(file, keep.ToArray());
|
|
74
|
+
}
|
|
75
|
+
} catch { }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Lúc host khởi động: dọn bản ẩn mồ côi của host trước (xem trên). Trả số tiến trình đã dọn. */
|
|
79
|
+
public static int CleanupOrphans() {
|
|
80
|
+
string file = OrphanFile();
|
|
81
|
+
if (file == null || !File.Exists(file)) return 0;
|
|
82
|
+
int killed = 0;
|
|
83
|
+
lock (OrphanLock) {
|
|
84
|
+
foreach (var line in File.ReadAllLines(file)) {
|
|
85
|
+
var parts = line.Split('|');
|
|
86
|
+
int pid; long start;
|
|
87
|
+
if (parts.Length != 3 || !int.TryParse(parts[0], out pid) || !long.TryParse(parts[2], out start)) continue;
|
|
88
|
+
string name = parts[1];
|
|
89
|
+
if (name != "EXCEL" && name != "WINWORD") continue;
|
|
90
|
+
try {
|
|
91
|
+
using (var pr = Process.GetProcessById(pid)) {
|
|
92
|
+
if (!string.Equals(pr.ProcessName, name, StringComparison.OrdinalIgnoreCase) || StartTicks(pr) != start) continue;
|
|
93
|
+
if (HasVisibleWindow(pid)) continue;
|
|
94
|
+
pr.Kill();
|
|
95
|
+
killed++;
|
|
96
|
+
}
|
|
97
|
+
} catch { /* đã thoát / không đủ quyền */ }
|
|
98
|
+
}
|
|
99
|
+
try { File.Delete(file); } catch { }
|
|
100
|
+
}
|
|
101
|
+
return killed;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Quit bản ẩn do host tạo; Quit được thì bỏ khỏi danh sách mồ côi (Quit hỏng → giữ để lần khởi động sau dọn). */
|
|
105
|
+
static void QuitOwn(Opened o, bool word) {
|
|
106
|
+
bool quit = false;
|
|
107
|
+
try { if (word) Call(o.App, "Quit", 0); else Call(o.App, "Quit"); quit = true; } catch { }
|
|
108
|
+
Release(o.App);
|
|
109
|
+
if (quit) UntrackOwn(o.Pid);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── chống chèn công thức (formula injection) ──────────────────────────────────────────────────────────────
|
|
113
|
+
/** Chữ bắt đầu bằng = + - @ (hoặc tab / CR) mà KHÔNG cho phép công thức → ghi thành chữ (tiền tố '), Excel không hiểu là công thức. */
|
|
114
|
+
static object SafeCellValue(object v, bool formula) {
|
|
115
|
+
object j = JsonValue(v);
|
|
116
|
+
string s = j as string;
|
|
117
|
+
if (formula || string.IsNullOrEmpty(s)) return j;
|
|
118
|
+
// Số viết dạng chuỗi ("-5", "+3.5", "-1500000") vẫn để Excel đổi thành số như trước — chỉ chặn khi sau dấu là chữ / hàm / ô.
|
|
119
|
+
if (IsPlainNumber(s)) return j;
|
|
120
|
+
char c = s[0];
|
|
121
|
+
if (c == '=' || c == '+' || c == '-' || c == '@' || c == '\t' || c == '\r') return "'" + s;
|
|
122
|
+
return j;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** [+-]chữ số, dấu phân cách (. hoặc ,) nằm giữa hai chữ số, có thể thêm số mũ e±n hoặc % — "-1,500,000", "-1.234,5", "-5%", "-1e5". Có khoảng trắng ("+84 912…") vẫn là chữ. */
|
|
126
|
+
static bool IsPlainNumber(string s) {
|
|
127
|
+
int i = (s[0] == '+' || s[0] == '-') ? 1 : 0, end = s.Length, digits = 0;
|
|
128
|
+
if (end > i && s[end - 1] == '%') end--;
|
|
129
|
+
if (i >= end) return false;
|
|
130
|
+
for (; i < end; i++) {
|
|
131
|
+
char ch = s[i];
|
|
132
|
+
if (ch >= '0' && ch <= '9') { digits++; continue; }
|
|
133
|
+
bool digitAround = digits > 0 && i + 1 < end && s[i - 1] >= '0' && s[i - 1] <= '9' && s[i + 1] >= '0' && s[i + 1] <= '9';
|
|
134
|
+
if ((ch == '.' || ch == ',') && digitAround) continue;
|
|
135
|
+
if ((ch == 'e' || ch == 'E') && digits > 0) {
|
|
136
|
+
int k = i + 1;
|
|
137
|
+
if (k < end && (s[k] == '+' || s[k] == '-')) k++;
|
|
138
|
+
if (k >= end) return false;
|
|
139
|
+
for (; k < end; k++) if (s[k] < '0' || s[k] > '9') return false;
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
return digits > 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Sổ / tài liệu người dùng mở sẵn đang có chỉnh sửa chưa lưu (đọc TRƯỚC khi AI ghi). Không đọc được → coi là có (không lưu). */
|
|
148
|
+
static bool UserHasUnsavedEdits(Opened o, string path) {
|
|
149
|
+
if (o.Own) return false;
|
|
150
|
+
bool saved;
|
|
151
|
+
try { saved = Convert.ToBoolean(Get(o.Doc, "Saved")); } catch { return true; }
|
|
152
|
+
if (saved) { AiDirty.Remove(path); return false; }
|
|
153
|
+
return !AiDirty.Contains(path);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Tệp người dùng mở sẵn mà AI đã ghi nhưng chưa lưu: Saved=false lần sau là do chính AI, không phải chỉnh dở của người dùng. */
|
|
157
|
+
static readonly HashSet<string> AiDirty = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Sổ / tài liệu người dùng ĐANG MỞ (không do AI mở): mặc định KHÔNG lưu, chỉ lưu khi save=true — và kể cả save=true cũng không lưu nếu người
|
|
161
|
+
* dùng đang có chỉnh sửa dở (lưu lúc đó = lưu luôn phần dở của họ, 02/11/2026).
|
|
162
|
+
*/
|
|
163
|
+
static bool ShouldSave(Opened o, Dictionary<string, object> a, bool userDirty) {
|
|
164
|
+
return o.Own ? B(a, "save", true) : B(a, "force_save", false) || (!userDirty && B(a, "save", false));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
static void AddSaveState(Dictionary<string, object> res, Opened o, bool save, string app, bool userDirty, string path) {
|
|
168
|
+
res["saved"] = save;
|
|
169
|
+
if (!o.Own) { if (save) AiDirty.Remove(path); else AiDirty.Add(path); }
|
|
170
|
+
if (!o.Own && !save) {
|
|
171
|
+
res["unsaved"] = true;
|
|
172
|
+
if (userDirty) {
|
|
173
|
+
res["user_had_unsaved_edits"] = true;
|
|
174
|
+
res["hint"] = "The file the user has open in " + app + " already had unsaved changes (the user's own edits, or recalculated formulas), so it was NOT saved (saving would save those too) - ask the user to review and save it themselves, or call again with force_save: true only after the user confirms";
|
|
175
|
+
} else {
|
|
176
|
+
res["hint"] = "The change is in the file the user has open in " + app + " but NOT saved (saving would also save the user's own unsaved edits) - tell the user to review and save, or call again with save: true only if the user asked to save";
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
static string S(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToString(v) : null; }
|
|
182
|
+
static bool B(Dictionary<string, object> d, string k, bool def) { object v; try { return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToBoolean(v) : def; } catch { return def; } }
|
|
183
|
+
static int I(Dictionary<string, object> d, string k, int def) { object v; try { return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToInt32(v) : def; } catch { return def; } }
|
|
184
|
+
|
|
185
|
+
// Ứng dụng bận (đang sửa ô, hộp thoại, đang khởi động): COM từ luồng MTA không tự thử lại → thử lại tới BUSY_RETRY_MS (29/10/2026).
|
|
186
|
+
const uint RPC_E_CALL_REJECTED = 0x80010001;
|
|
187
|
+
const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A;
|
|
188
|
+
const int BUSY_RETRY_MS = 2000;
|
|
189
|
+
const int BUSY_RETRY_STEP_MS = 200;
|
|
190
|
+
|
|
191
|
+
static bool IsBusy(Exception e) {
|
|
192
|
+
var com = (e is TargetInvocationException && e.InnerException != null ? e.InnerException : e) as COMException;
|
|
193
|
+
return com != null && ((uint)com.ErrorCode == RPC_E_CALL_REJECTED || (uint)com.ErrorCode == RPC_E_SERVERCALL_RETRYLATER);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
static object Inv(object o, string n, BindingFlags f, object[] a) {
|
|
197
|
+
for (int waited = 0; ; waited += BUSY_RETRY_STEP_MS) {
|
|
198
|
+
try { return o.GetType().InvokeMember(n, f, null, o, a); }
|
|
199
|
+
catch (Exception e) {
|
|
200
|
+
if (IsBusy(e) && waited < BUSY_RETRY_MS) { Thread.Sleep(BUSY_RETRY_STEP_MS); continue; }
|
|
201
|
+
if (IsBusy(e)) throw new GuiError("OFFICE_BUSY", n + ": the app is busy (a cell is being edited or a dialog is open)");
|
|
202
|
+
if (e is TargetInvocationException) throw new GuiError("OFFICE_FAILED", n + ": " + (e.InnerException != null ? e.InnerException.Message : e.Message));
|
|
203
|
+
if (e is COMException) throw new GuiError("OFFICE_FAILED", n + ": " + e.Message);
|
|
204
|
+
throw;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Tệp đang mở ở bản Excel / Word khác (bận) nên bản ẩn chỉ mở được dạng chỉ đọc → báo rõ thay vì để bước lưu hỏng khó hiểu. */
|
|
210
|
+
static void RequireWritable(object doc, bool readOnly, string path, bool word) {
|
|
211
|
+
if (readOnly) return;
|
|
212
|
+
bool ro = false;
|
|
213
|
+
try { ro = Convert.ToBoolean(Get(doc, "ReadOnly")); } catch (GuiError) { }
|
|
214
|
+
if (!ro) return;
|
|
215
|
+
try { if (word) Call(doc, "Close", 0); else Call(doc, "Close", false); } catch (GuiError) { }
|
|
216
|
+
throw new GuiError("OFFICE_BUSY", "File is open in another Excel / Word window that is busy or locked: " + path + " - ask the user to finish editing there (press Enter or Esc, close dialogs) or close the file, then try again");
|
|
217
|
+
}
|
|
218
|
+
static object Get(object o, string n, params object[] a) { return Inv(o, n, BindingFlags.GetProperty | BindingFlags.InvokeMethod, a); }
|
|
219
|
+
static void Set(object o, string n, object v) { Inv(o, n, BindingFlags.SetProperty, new object[] { v }); }
|
|
220
|
+
static object Call(object o, string n, params object[] a) { return Inv(o, n, BindingFlags.InvokeMethod, a); }
|
|
221
|
+
static void Release(object o) { try { if (o != null && Marshal.IsComObject(o)) Marshal.ReleaseComObject(o); } catch { } }
|
|
222
|
+
static object Running(string progId) { try { return Marshal.GetActiveObject(progId); } catch { return null; } }
|
|
223
|
+
|
|
224
|
+
static object Create(string progId) {
|
|
225
|
+
Type t = Type.GetTypeFromProgID(progId);
|
|
226
|
+
if (t == null) throw new GuiError("OFFICE_NOT_INSTALLED", progId + " is not installed on this computer");
|
|
227
|
+
try { return Activator.CreateInstance(t); }
|
|
228
|
+
catch (COMException e) {
|
|
229
|
+
// 0x80080005: ứng dụng đang chạy ở mức quyền khác (mở bằng "Run as administrator") hoặc bản mới không còn COM (Outlook mới) — chạy
|
|
230
|
+
// thật 28/10/2026 trên máy có cả Outlook cổ điển đang mở lẫn Outlook mới.
|
|
231
|
+
if ((uint)e.ErrorCode == 0x80080005) throw new GuiError("OFFICE_UNAVAILABLE", progId + " is running with different permissions (e.g. opened as administrator) or is the new app without automation - ask the user to reopen it normally, or use the GUI");
|
|
232
|
+
throw new GuiError("OFFICE_UNAVAILABLE", progId + " could not start: " + e.Message);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
public static object Run(Dictionary<string, object> a) {
|
|
237
|
+
string op = S(a, "op") ?? "";
|
|
238
|
+
switch (op) {
|
|
239
|
+
case "excel.read": return ExcelRead(a);
|
|
240
|
+
case "excel.write": return ExcelWrite(a);
|
|
241
|
+
case "word.read": return WordRead(a);
|
|
242
|
+
case "word.edit": return WordEdit(a);
|
|
243
|
+
case "outlook.list": return OutlookList(a);
|
|
244
|
+
case "outlook.compose": return OutlookCompose(a);
|
|
245
|
+
default: throw new GuiError("INVALID_ARGS", "Unknown office op: " + op);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ── Excel ──────────────────────────────────────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
/** Sổ đang mở trong Excel của người dùng (so FullName) → dùng luôn; không thì mở bằng Excel ẩn riêng. */
|
|
252
|
+
static Opened OpenWorkbook(string path, bool create, bool readOnly) {
|
|
253
|
+
object app = Running("Excel.Application");
|
|
254
|
+
if (app != null) {
|
|
255
|
+
// Bản đang chạy không trả lời (treo / bận, RPC_E_SERVERCALL_RETRYLATER) → bỏ qua, mở bản ẩn riêng (29/10/2026: một Excel treo
|
|
256
|
+
// trên máy làm mọi lời gọi office.excel.* hỏng, Planner thử lại 12 lượt).
|
|
257
|
+
try {
|
|
258
|
+
object books = Get(app, "Workbooks");
|
|
259
|
+
int n = Convert.ToInt32(Get(books, "Count"));
|
|
260
|
+
for (int i = 1; i <= n; i++) {
|
|
261
|
+
object b = Get(books, "Item", i);
|
|
262
|
+
if (string.Equals(Convert.ToString(Get(b, "FullName")), path, StringComparison.OrdinalIgnoreCase)) { Release(books); return new Opened { App = app, Doc = b, Own = false }; }
|
|
263
|
+
Release(b);
|
|
264
|
+
}
|
|
265
|
+
Release(books);
|
|
266
|
+
} catch (GuiError) { }
|
|
267
|
+
Release(app);
|
|
268
|
+
}
|
|
269
|
+
var before = PidsOf("EXCEL");
|
|
270
|
+
object own = Create("Excel.Application");
|
|
271
|
+
var opened = new Opened { App = own, Own = true };
|
|
272
|
+
opened.Pid = TrackOwn("EXCEL", before, own);
|
|
273
|
+
try {
|
|
274
|
+
Set(own, "Visible", false);
|
|
275
|
+
Set(own, "DisplayAlerts", false);
|
|
276
|
+
object wbs = Get(own, "Workbooks");
|
|
277
|
+
object book;
|
|
278
|
+
if (File.Exists(path)) book = Call(wbs, "Open", path, 0, readOnly);
|
|
279
|
+
else if (create) { book = Call(wbs, "Add"); Call(book, "SaveAs", path); }
|
|
280
|
+
else throw new GuiError("NOT_FOUND", "File not found: " + path);
|
|
281
|
+
Release(wbs);
|
|
282
|
+
RequireWritable(book, readOnly, path, false);
|
|
283
|
+
opened.Doc = book;
|
|
284
|
+
return opened;
|
|
285
|
+
} catch { QuitOwn(opened, false); throw; }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
static void CloseWorkbook(Opened o, bool save) {
|
|
289
|
+
try {
|
|
290
|
+
if (save) Call(o.Doc, "Save");
|
|
291
|
+
if (o.Own) Call(o.Doc, "Close", false);
|
|
292
|
+
} finally {
|
|
293
|
+
Release(o.Doc);
|
|
294
|
+
if (o.Own) QuitOwn(o, false); else Release(o.App);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
static object SheetOf(object book, string name) {
|
|
299
|
+
if (!string.IsNullOrEmpty(name)) {
|
|
300
|
+
object sheets = Get(book, "Worksheets");
|
|
301
|
+
try { return Get(sheets, "Item", name); } catch (GuiError) { throw new GuiError("NOT_FOUND", "No sheet named: " + name); } finally { Release(sheets); }
|
|
302
|
+
}
|
|
303
|
+
return Get(book, "ActiveSheet");
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
static List<object> SheetNames(object book) {
|
|
307
|
+
var names = new List<object>();
|
|
308
|
+
object sheets = Get(book, "Worksheets");
|
|
309
|
+
int n = Convert.ToInt32(Get(sheets, "Count"));
|
|
310
|
+
for (int i = 1; i <= n; i++) { object s = Get(sheets, "Item", i); names.Add(Convert.ToString(Get(s, "Name"))); Release(s); }
|
|
311
|
+
Release(sheets);
|
|
312
|
+
return names;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
static object Cell(object v) {
|
|
316
|
+
if (v == null) return null;
|
|
317
|
+
if (v is double || v is string || v is bool) return v;
|
|
318
|
+
return Convert.ToString(v);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Value2 của vùng → mảng hàng (cắt ở MAX_CELLS ô). */
|
|
322
|
+
static List<object> Rows(object value, out bool truncated) {
|
|
323
|
+
truncated = false;
|
|
324
|
+
var rows = new List<object>();
|
|
325
|
+
var arr = value as object[,];
|
|
326
|
+
if (arr == null) { rows.Add(new List<object> { Cell(value) }); return rows; }
|
|
327
|
+
int cells = 0;
|
|
328
|
+
for (int r = arr.GetLowerBound(0); r <= arr.GetUpperBound(0); r++) {
|
|
329
|
+
var row = new List<object>();
|
|
330
|
+
for (int c = arr.GetLowerBound(1); c <= arr.GetUpperBound(1); c++) {
|
|
331
|
+
if (++cells > MAX_CELLS) { truncated = true; break; }
|
|
332
|
+
row.Add(Cell(arr[r, c]));
|
|
333
|
+
}
|
|
334
|
+
rows.Add(row);
|
|
335
|
+
if (truncated) break;
|
|
336
|
+
}
|
|
337
|
+
return rows;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
static object ExcelRead(Dictionary<string, object> a) {
|
|
341
|
+
Opened o = OpenWorkbook(S(a, "path"), false, true);
|
|
342
|
+
try {
|
|
343
|
+
object ws = SheetOf(o.Doc, S(a, "sheet"));
|
|
344
|
+
string range = S(a, "range");
|
|
345
|
+
object rng = string.IsNullOrEmpty(range) ? Get(ws, "UsedRange") : Get(ws, "Range", range);
|
|
346
|
+
bool truncated;
|
|
347
|
+
var res = new Dictionary<string, object> {
|
|
348
|
+
{ "path", S(a, "path") }, { "sheet", Convert.ToString(Get(ws, "Name")) }, { "sheets", SheetNames(o.Doc) },
|
|
349
|
+
{ "range", Convert.ToString(Get(rng, "Address", false, false)) }, { "rows", Rows(Get(rng, "Value2"), out truncated) },
|
|
350
|
+
{ "open_in_user_excel", !o.Own },
|
|
351
|
+
};
|
|
352
|
+
if (B(a, "formulas", false)) { bool t2; res["formulas"] = Rows(Get(rng, "Formula"), out t2); }
|
|
353
|
+
if (truncated) res["truncated"] = true;
|
|
354
|
+
Release(rng); Release(ws);
|
|
355
|
+
return res;
|
|
356
|
+
} finally { CloseWorkbook(o, false); }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
static object JsonValue(object v) {
|
|
360
|
+
if (v is decimal) return Convert.ToDouble(v);
|
|
361
|
+
if (v is int || v is long) return Convert.ToDouble(v);
|
|
362
|
+
return v;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Chữ "=..." chỉ thành công thức khi formula=true (người dùng / Planner cho phép tường minh); không thì ghi nguyên chữ. */
|
|
366
|
+
static void WriteCell(object ws, string addr, object v, bool formula) {
|
|
367
|
+
object r = Get(ws, "Range", addr);
|
|
368
|
+
string s = v as string;
|
|
369
|
+
if (formula && s != null && s.StartsWith("=")) Set(r, "Formula", s); else Set(r, "Value2", SafeCellValue(v, formula));
|
|
370
|
+
Release(r);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* cells {"B2": giá trị} và / hoặc range + values (mảng hàng). Đọc lại ô vừa ghi làm bằng chứng. Công thức chỉ khi formula=true. Sổ người
|
|
375
|
+
* dùng đang mở: không lưu trừ khi save=true (trả unsaved).
|
|
376
|
+
*/
|
|
377
|
+
static object ExcelWrite(Dictionary<string, object> a) {
|
|
378
|
+
string path = S(a, "path");
|
|
379
|
+
Opened o = OpenWorkbook(path, B(a, "create", false), false);
|
|
380
|
+
bool userDirty = UserHasUnsavedEdits(o, path);
|
|
381
|
+
bool save = ShouldSave(o, a, userDirty);
|
|
382
|
+
bool formula = B(a, "formula", false);
|
|
383
|
+
try {
|
|
384
|
+
object ws = SheetOf(o.Doc, S(a, "sheet"));
|
|
385
|
+
var written = new Dictionary<string, object>();
|
|
386
|
+
var cells = a.ContainsKey("cells") ? a["cells"] as Dictionary<string, object> : null;
|
|
387
|
+
if (cells != null) {
|
|
388
|
+
foreach (var kv in cells) {
|
|
389
|
+
WriteCell(ws, kv.Key, kv.Value, formula);
|
|
390
|
+
object r = Get(ws, "Range", kv.Key);
|
|
391
|
+
written[kv.Key] = Cell(Get(r, "Text"));
|
|
392
|
+
Release(r);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
var values = a.ContainsKey("values") ? a["values"] as object[] : null;
|
|
396
|
+
string range = S(a, "range");
|
|
397
|
+
if (values != null && !string.IsNullOrEmpty(range)) {
|
|
398
|
+
int rowsN = values.Length, colsN = 0;
|
|
399
|
+
foreach (var row in values) { var arr = row as object[]; if (arr != null && arr.Length > colsN) colsN = arr.Length; }
|
|
400
|
+
if (rowsN * colsN > MAX_CELLS) throw new GuiError("INVALID_ARGS", "Too many cells in one write (max " + MAX_CELLS + ")");
|
|
401
|
+
object start = Get(ws, "Range", range);
|
|
402
|
+
object target = Get(start, "Resize", rowsN, Math.Max(1, colsN));
|
|
403
|
+
var data = new object[rowsN, Math.Max(1, colsN)];
|
|
404
|
+
for (int r = 0; r < rowsN; r++) {
|
|
405
|
+
var arr = values[r] as object[];
|
|
406
|
+
for (int c = 0; arr != null && c < arr.Length; c++) data[r, c] = SafeCellValue(arr[c], formula);
|
|
407
|
+
}
|
|
408
|
+
Set(target, "Value2", data);
|
|
409
|
+
written[Convert.ToString(Get(target, "Address", false, false))] = rowsN + "x" + colsN;
|
|
410
|
+
Release(target); Release(start);
|
|
411
|
+
}
|
|
412
|
+
if (written.Count == 0) throw new GuiError("INVALID_ARGS", "Give cells {\"B2\": value} or range + values");
|
|
413
|
+
Release(ws);
|
|
414
|
+
var res = new Dictionary<string, object> { { "path", path }, { "written", written }, { "open_in_user_excel", !o.Own } };
|
|
415
|
+
AddSaveState(res, o, save, "Excel", userDirty, path);
|
|
416
|
+
return res;
|
|
417
|
+
} finally { CloseWorkbook(o, save); }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// ── Word ───────────────────────────────────────────────────────────────────────────────────
|
|
421
|
+
|
|
422
|
+
static Opened OpenDocument(string path, bool create, bool readOnly) {
|
|
423
|
+
object app = Running("Word.Application");
|
|
424
|
+
if (app != null) {
|
|
425
|
+
// Bản đang chạy không trả lời → bỏ qua, mở bản ẩn riêng (như OpenWorkbook).
|
|
426
|
+
try {
|
|
427
|
+
object docs = Get(app, "Documents");
|
|
428
|
+
int n = Convert.ToInt32(Get(docs, "Count"));
|
|
429
|
+
for (int i = 1; i <= n; i++) {
|
|
430
|
+
object d = Get(docs, "Item", i);
|
|
431
|
+
if (string.Equals(Convert.ToString(Get(d, "FullName")), path, StringComparison.OrdinalIgnoreCase)) { Release(docs); return new Opened { App = app, Doc = d, Own = false }; }
|
|
432
|
+
Release(d);
|
|
433
|
+
}
|
|
434
|
+
Release(docs);
|
|
435
|
+
} catch (GuiError) { }
|
|
436
|
+
Release(app);
|
|
437
|
+
}
|
|
438
|
+
var before = PidsOf("WINWORD");
|
|
439
|
+
object own = Create("Word.Application");
|
|
440
|
+
var opened = new Opened { App = own, Own = true };
|
|
441
|
+
opened.Pid = TrackOwn("WINWORD", before, own);
|
|
442
|
+
try {
|
|
443
|
+
Set(own, "Visible", false);
|
|
444
|
+
Set(own, "DisplayAlerts", 0);
|
|
445
|
+
object docs = Get(own, "Documents");
|
|
446
|
+
object doc;
|
|
447
|
+
if (File.Exists(path)) doc = Call(docs, "Open", path, false, readOnly, false);
|
|
448
|
+
else if (create) { doc = Call(docs, "Add"); Call(doc, "SaveAs2", path); }
|
|
449
|
+
else throw new GuiError("NOT_FOUND", "File not found: " + path);
|
|
450
|
+
Release(docs);
|
|
451
|
+
RequireWritable(doc, readOnly, path, true);
|
|
452
|
+
opened.Doc = doc;
|
|
453
|
+
return opened;
|
|
454
|
+
} catch { QuitOwn(opened, true); throw; }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
static void CloseDocument(Opened o, bool save) {
|
|
458
|
+
try {
|
|
459
|
+
if (save) Call(o.Doc, "Save");
|
|
460
|
+
if (o.Own) Call(o.Doc, "Close", 0);
|
|
461
|
+
} finally {
|
|
462
|
+
Release(o.Doc);
|
|
463
|
+
if (o.Own) QuitOwn(o, true); else Release(o.App);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
static object WordRead(Dictionary<string, object> a) {
|
|
468
|
+
Opened o = OpenDocument(S(a, "path"), false, true);
|
|
469
|
+
try {
|
|
470
|
+
object content = Get(o.Doc, "Content");
|
|
471
|
+
string text = Convert.ToString(Get(content, "Text")).Replace("\r", "\n");
|
|
472
|
+
int max = Math.Max(500, Math.Min(I(a, "max_chars", 20000), MAX_TEXT));
|
|
473
|
+
Release(content);
|
|
474
|
+
var res = new Dictionary<string, object> { { "path", S(a, "path") }, { "chars", text.Length }, { "text", text.Length > max ? text.Substring(0, max) : text }, { "open_in_user_word", !o.Own } };
|
|
475
|
+
if (text.Length > max) res["truncated"] = true;
|
|
476
|
+
return res;
|
|
477
|
+
} finally { CloseDocument(o, false); }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
static int CountOf(string text, string find) {
|
|
481
|
+
if (string.IsNullOrEmpty(find)) return 0;
|
|
482
|
+
int n = 0, i = 0;
|
|
483
|
+
while ((i = text.IndexOf(find, i, StringComparison.Ordinal)) >= 0) { n++; i += find.Length; }
|
|
484
|
+
return n;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Thay chữ (mọi chỗ, giữ định dạng của Word) và / hoặc thêm đoạn cuối tài liệu. */
|
|
488
|
+
static object WordEdit(Dictionary<string, object> a) {
|
|
489
|
+
string path = S(a, "path");
|
|
490
|
+
Opened o = OpenDocument(path, B(a, "create", false), false);
|
|
491
|
+
bool userDirty = UserHasUnsavedEdits(o, path);
|
|
492
|
+
bool save = ShouldSave(o, a, userDirty);
|
|
493
|
+
try {
|
|
494
|
+
var res = new Dictionary<string, object> { { "path", path }, { "open_in_user_word", !o.Own } };
|
|
495
|
+
AddSaveState(res, o, save, "Word", userDirty, path);
|
|
496
|
+
string find = S(a, "find"), replace = S(a, "replace"), append = S(a, "append");
|
|
497
|
+
if (!string.IsNullOrEmpty(find)) {
|
|
498
|
+
object content = Get(o.Doc, "Content");
|
|
499
|
+
int before = CountOf(Convert.ToString(Get(content, "Text")), find);
|
|
500
|
+
object finder = Get(content, "Find");
|
|
501
|
+
Call(finder, "Execute", find, true, false, false, false, false, true, 1, false, replace ?? "", 2);
|
|
502
|
+
Release(finder); Release(content);
|
|
503
|
+
object after = Get(o.Doc, "Content");
|
|
504
|
+
res["replaced"] = before - CountOf(Convert.ToString(Get(after, "Text")), find);
|
|
505
|
+
Release(after);
|
|
506
|
+
}
|
|
507
|
+
if (!string.IsNullOrEmpty(append)) {
|
|
508
|
+
object content = Get(o.Doc, "Content");
|
|
509
|
+
Call(content, "InsertParagraphAfter");
|
|
510
|
+
Call(content, "InsertAfter", append);
|
|
511
|
+
Release(content);
|
|
512
|
+
res["appended_chars"] = append.Length;
|
|
513
|
+
}
|
|
514
|
+
if (!res.ContainsKey("replaced") && !res.ContainsKey("appended_chars")) throw new GuiError("INVALID_ARGS", "Give find + replace and / or append");
|
|
515
|
+
return res;
|
|
516
|
+
} finally { CloseDocument(o, save); }
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ── Outlook ────────────────────────────────────────────────────────────────────────────────
|
|
520
|
+
|
|
521
|
+
/** Outlook đang chạy của người dùng, không thì host tự bật (created=true) — bản host bật phải Quit khi xong (02/11/2026). */
|
|
522
|
+
static object OutlookApp(out bool created) {
|
|
523
|
+
object running = Running("Outlook.Application");
|
|
524
|
+
created = running == null;
|
|
525
|
+
return running ?? Create("Outlook.Application");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
static int ComCount(object o, string collection) {
|
|
529
|
+
object c = null;
|
|
530
|
+
try { c = Get(o, collection); return Convert.ToInt32(Get(c, "Count")); } catch { return -1; } finally { Release(c); }
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const int OUTBOX_DRAIN_MS = 15000;
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Outlook do host bật: Quit khi xong — nhưng chỉ khi không có cửa sổ Outlook nào (người dùng có thể vừa mở Outlook, cùng một tiến trình)
|
|
537
|
+
* và (sau khi gửi) Hộp thư đi đã trống, không thì thư kẹt lại tới lần mở sau. Trả true khi đã Quit.
|
|
538
|
+
*/
|
|
539
|
+
static bool QuitOutlookIfOurs(object app, object ns, bool created, bool waitOutbox) {
|
|
540
|
+
if (!created) return false;
|
|
541
|
+
if (waitOutbox && ns != null) {
|
|
542
|
+
object outbox = null;
|
|
543
|
+
try {
|
|
544
|
+
try { Call(ns, "SendAndReceive", false); } catch (GuiError) { }
|
|
545
|
+
outbox = Call(ns, "GetDefaultFolder", 4);
|
|
546
|
+
var sw = Stopwatch.StartNew();
|
|
547
|
+
while (ComCount(outbox, "Items") > 0 && sw.ElapsedMilliseconds < OUTBOX_DRAIN_MS) Thread.Sleep(500);
|
|
548
|
+
if (ComCount(outbox, "Items") > 0) return false;
|
|
549
|
+
} catch (GuiError) { return false; } finally { Release(outbox); }
|
|
550
|
+
}
|
|
551
|
+
if (ComCount(app, "Explorers") != 0 || ComCount(app, "Inspectors") != 0) return false;
|
|
552
|
+
try { Call(app, "Quit"); return true; } catch (GuiError) { return false; }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
static object OutlookList(Dictionary<string, object> a) {
|
|
556
|
+
bool created;
|
|
557
|
+
object app = OutlookApp(out created);
|
|
558
|
+
object ns = null;
|
|
559
|
+
try {
|
|
560
|
+
ns = Call(app, "GetNamespace", "MAPI");
|
|
561
|
+
return OutlookListIn(ns, a);
|
|
562
|
+
} finally {
|
|
563
|
+
QuitOutlookIfOurs(app, ns, created, false);
|
|
564
|
+
Release(ns); Release(app);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
static object OutlookListIn(object ns, Dictionary<string, object> a) {
|
|
569
|
+
object folder = Call(ns, "GetDefaultFolder", S(a, "folder") == "sent" ? 5 : 6);
|
|
570
|
+
object items = Get(folder, "Items");
|
|
571
|
+
Call(items, "Sort", "[ReceivedTime]", true);
|
|
572
|
+
int limit = Math.Max(1, Math.Min(I(a, "limit", 20), 100));
|
|
573
|
+
bool unreadOnly = B(a, "unread_only", false);
|
|
574
|
+
int previewChars = Math.Max(0, Math.Min(I(a, "preview_chars", 300), 3000));
|
|
575
|
+
var list = new List<object>();
|
|
576
|
+
int n = Convert.ToInt32(Get(items, "Count"));
|
|
577
|
+
for (int i = 1; i <= n && list.Count < limit; i++) {
|
|
578
|
+
object it = null;
|
|
579
|
+
try {
|
|
580
|
+
it = Call(items, "Item", i);
|
|
581
|
+
if (unreadOnly && !true.Equals(Get(it, "UnRead"))) continue;
|
|
582
|
+
string body = Convert.ToString(Get(it, "Body") ?? "");
|
|
583
|
+
list.Add(new Dictionary<string, object> {
|
|
584
|
+
{ "subject", Convert.ToString(Get(it, "Subject")) }, { "from", Convert.ToString(Get(it, "SenderName")) },
|
|
585
|
+
{ "from_email", Convert.ToString(Get(it, "SenderEmailAddress")) }, { "received", Convert.ToDateTime(Get(it, "ReceivedTime")).ToString("s") },
|
|
586
|
+
{ "unread", true.Equals(Get(it, "UnRead")) }, { "preview", body.Length > previewChars ? body.Substring(0, previewChars) : body },
|
|
587
|
+
});
|
|
588
|
+
} catch (GuiError) { /* mục không phải thư (lịch họp…) */ } finally { Release(it); }
|
|
589
|
+
}
|
|
590
|
+
Release(items); Release(folder);
|
|
591
|
+
return new Dictionary<string, object> { { "folder", S(a, "folder") == "sent" ? "sent" : "inbox" }, { "messages", list } };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** Soạn thư: lưu vào Bản nháp (mặc định) hoặc gửi luôn (send). Outlook do host bật → Quit khi xong (sau khi Hộp thư đi trống). */
|
|
595
|
+
static object OutlookCompose(Dictionary<string, object> a) {
|
|
596
|
+
bool created;
|
|
597
|
+
object app = OutlookApp(out created);
|
|
598
|
+
object ns = null;
|
|
599
|
+
bool send = B(a, "send", false);
|
|
600
|
+
bool composed = false;
|
|
601
|
+
try {
|
|
602
|
+
var res = OutlookComposeIn(app, a, send);
|
|
603
|
+
composed = true;
|
|
604
|
+
if (created) {
|
|
605
|
+
try { ns = Call(app, "GetNamespace", "MAPI"); } catch (GuiError) { }
|
|
606
|
+
bool quit = QuitOutlookIfOurs(app, ns, true, send);
|
|
607
|
+
if (send && !quit) res["outbox_pending"] = true;
|
|
608
|
+
}
|
|
609
|
+
return res;
|
|
610
|
+
} finally {
|
|
611
|
+
if (created && !composed) QuitOutlookIfOurs(app, ns, true, false);
|
|
612
|
+
Release(ns); Release(app);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
static Dictionary<string, object> OutlookComposeIn(object app, Dictionary<string, object> a, bool send) {
|
|
617
|
+
object mail = Call(app, "CreateItem", 0);
|
|
618
|
+
try {
|
|
619
|
+
Set(mail, "To", S(a, "to") ?? "");
|
|
620
|
+
if (!string.IsNullOrEmpty(S(a, "cc"))) Set(mail, "CC", S(a, "cc"));
|
|
621
|
+
Set(mail, "Subject", S(a, "subject") ?? "");
|
|
622
|
+
Set(mail, "Body", S(a, "body") ?? "");
|
|
623
|
+
var files = a.ContainsKey("attachments") ? a["attachments"] as object[] : null;
|
|
624
|
+
if (files != null) {
|
|
625
|
+
object att = Get(mail, "Attachments");
|
|
626
|
+
foreach (var f in files) Call(att, "Add", Convert.ToString(f));
|
|
627
|
+
Release(att);
|
|
628
|
+
}
|
|
629
|
+
if (send) Call(mail, "Send"); else Call(mail, "Save");
|
|
630
|
+
return new Dictionary<string, object> { { "sent", send }, { "saved_to_drafts", !send }, { "to", S(a, "to") }, { "subject", S(a, "subject") }, { "attachments", files == null ? 0 : files.Length } };
|
|
631
|
+
} finally { Release(mail); }
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
`;
|