-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
3687 lines (3510 loc) · 138 KB
/
Copy pathmain.js
File metadata and controls
3687 lines (3510 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
149
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, dialog, Menu, nativeImage, clipboard } = require('electron');
const path = require('path');
const http = require('http');
const fs = require('fs');
const { randomUUID, createHash } = require('crypto');
const os = require('os');
const chokidar = require('chokidar');
// 让 Linux 程序坞/任务栏用 .desktop 的图标(需与 StartupWMClass 一致)
app.setName('MarkWrite');
const PORT_BASE = 3131;
const PORT_LAST = 3140;
const ROOT = __dirname;
const DEFAULT_WORKSPACE = path.join(os.homedir(), 'markwrite-docs');
const MARKWRITE_CFG_DIR = path.join(os.homedir(), '.config', 'markwrite');
const WORKSPACE_ROOT_FILE = path.join(MARKWRITE_CFG_DIR, 'workspace-root');
const SYNC_CONFIG_FILE = path.join(MARKWRITE_CFG_DIR, 'sync-servers.json');
const IDENTITY_FILE = path.join(MARKWRITE_CFG_DIR, 'identity.json');
let eventstoreKeyLib = null;
let workspaceRoot = DEFAULT_WORKSPACE;
let workspaceWatcher = null;
let workspaceChangeTimer = null;
let mainWindow = null;
/** 私钥字节 → 小写 hex(用于展示,不含 0x) */
function secretBytesToHex(bytes) {
if (!bytes) return '';
try {
const u8 = bytes instanceof Uint8Array ? bytes : Buffer.from(bytes);
return Buffer.from(u8).toString('hex');
} catch (_) {
return '';
}
}
const { render: renderMarkdown } = require('./md-renderer.js');
const {
fetchProfile: fetchEventstoreProfile,
saveProfile: saveEventstoreProfile,
registerUserOnServer,
invalidateEsclientModule,
loadEsclient,
} = require('./lib/eventstore-profile.js');
const { writeEventstoreConfigFromSync } = require('./lib/write-eventstore-config.js');
const bookEventstoreMap = require('./lib/book-eventstore-map.js');
/** 将当前 Sync 活跃服务器写入 eventstore-vendor/config.cjs 并清 require 缓存,确保 esclient 连到正确 esserver */
let lastSyncedEsserver = '';
function syncEventstoreVendorConfig() {
let nextEsserver = '';
try {
if (fs.existsSync(SYNC_CONFIG_FILE)) {
const raw = fs.readFileSync(SYNC_CONFIG_FILE, 'utf8');
const cfg = JSON.parse(raw);
const servers = Array.isArray(cfg && cfg.servers) ? cfg.servers : [];
const active = servers.find((s) => s.id === cfg.activeId) || servers[0] || null;
nextEsserver = active && typeof active.esserver === 'string' ? active.esserver.trim() : '';
}
} catch (_) {}
// 同一服务器不重复失效模块,尽量复用单例 WebSocket 连接
if (nextEsserver && nextEsserver === lastSyncedEsserver) return;
writeEventstoreConfigFromSync(SYNC_CONFIG_FILE);
invalidateEsclientModule();
lastSyncedEsserver = nextEsserver || '';
}
function readSyncConfigSafe() {
try {
if (!fs.existsSync(SYNC_CONFIG_FILE)) return { servers: [], activeId: null };
const raw = fs.readFileSync(SYNC_CONFIG_FILE, 'utf8');
const data = JSON.parse(raw);
return {
servers: Array.isArray(data.servers) ? data.servers : [],
activeId: typeof data.activeId === 'string' ? data.activeId : null,
};
} catch (_) {
return { servers: [], activeId: null };
}
}
function getActiveSyncServerId(syncCfg) {
const servers = Array.isArray(syncCfg && syncCfg.servers) ? syncCfg.servers : [];
return (syncCfg && syncCfg.activeId) || (servers[0] && servers[0].id) || 'default';
}
function normalizeIdentityRecord(v) {
const x = v && typeof v === 'object' ? v : {};
const pubkeyHex = typeof x.pubkeyHex === 'string'
? x.pubkeyHex.trim()
: (typeof x.pubkey === 'string' ? x.pubkey.trim() : '');
return {
pubkeyHex,
pubkeyEpub: typeof x.pubkeyEpub === 'string' ? x.pubkeyEpub.trim() : '',
// 兼容旧字段
pubkey: pubkeyHex,
privkey: typeof x.privkey === 'string' ? x.privkey.trim() : '',
};
}
function hasIdentityData(v) {
return !!(v && (v.pubkeyHex || v.pubkey || v.pubkeyEpub || v.privkey));
}
function readIdentityStoreRaw() {
try {
if (!fs.existsSync(IDENTITY_FILE)) return null;
const raw = fs.readFileSync(IDENTITY_FILE, 'utf8');
return JSON.parse(raw);
} catch (_) {
return null;
}
}
function readIdentityForServer(serverId) {
const sid = typeof serverId === 'string' && serverId.trim() ? serverId.trim() : 'default';
const raw = readIdentityStoreRaw();
if (!raw) return normalizeIdentityRecord({});
if (raw && typeof raw === 'object' && raw.byServer && typeof raw.byServer === 'object') {
return normalizeIdentityRecord(raw.byServer[sid] || {});
}
// 兼容旧格式(全局单身份)
const legacy = normalizeIdentityRecord(raw);
if (!hasIdentityData(legacy)) return legacy;
const legacyServerId = getActiveSyncServerId(readSyncConfigSafe());
return sid === legacyServerId ? legacy : normalizeIdentityRecord({});
}
function saveIdentityForServer(serverId, identity) {
const sid = typeof serverId === 'string' && serverId.trim() ? serverId.trim() : 'default';
const next = normalizeIdentityRecord(identity);
const raw = readIdentityStoreRaw();
const store = { version: 2, byServer: {} };
if (raw && typeof raw === 'object' && raw.byServer && typeof raw.byServer === 'object') {
Object.keys(raw.byServer).forEach((k) => {
store.byServer[k] = normalizeIdentityRecord(raw.byServer[k]);
});
} else if (raw && typeof raw === 'object') {
// 迁移旧格式:挂到当前 active server 下
const legacy = normalizeIdentityRecord(raw);
if (hasIdentityData(legacy)) {
const cfg = readSyncConfigSafe();
const legacyServerId = getActiveSyncServerId(cfg);
store.byServer[legacyServerId] = legacy;
}
}
if (hasIdentityData(next)) {
store.byServer[sid] = next;
} else {
delete store.byServer[sid];
}
if (!Object.keys(store.byServer).length) {
try {
if (fs.existsSync(IDENTITY_FILE)) fs.unlinkSync(IDENTITY_FILE);
} catch (_) {}
return;
}
fs.mkdirSync(MARKWRITE_CFG_DIR, { recursive: true });
fs.writeFileSync(IDENTITY_FILE, JSON.stringify(store, null, 2), 'utf8');
}
function createServer() {
const mime = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.wasm': 'application/wasm',
};
return http.createServer((req, res) => {
let pathname = 'index.html';
try {
const u = new URL(req.url || '/', 'http://127.0.0.1');
pathname = decodeURIComponent(u.pathname).replace(/^\//, '') || 'index.html';
if (pathname === '') pathname = 'index.html';
} catch (_) {}
// 供 OpenAgent 工具或外部回调:无文件名时润色/编辑结果直接应用到编辑器(POST 到此)
if (req.method === 'POST' && pathname === 'apply-content') {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
let content = '';
try {
const body = Buffer.concat(chunks).toString('utf8');
const json = JSON.parse(body);
content = typeof json.content === 'string' ? json.content : '';
} catch (_) {}
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents) {
mainWindow.webContents.send('apply-editor-content', content);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
});
return;
}
const filePath = path.join(ROOT, pathname);
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('Not Found');
return;
}
res.writeHead(500);
res.end(String(err));
return;
}
const ext = path.extname(pathname);
res.setHeader('Content-Type', mime[ext] || 'application/octet-stream');
res.end(data);
});
});
}
function createWindow(port) {
const iconPath = path.join(ROOT, 'assets', 'markwrite-icon.png');
let iconImage = null;
if (fs.existsSync(iconPath)) {
const img = nativeImage.createFromPath(iconPath);
if (!img.isEmpty()) iconImage = img;
}
mainWindow = new BrowserWindow({
width: 1280,
height: 1040,
icon: iconImage || undefined,
frame: false, // 使用自绘标题栏与边框
titleBarStyle: 'hidden', // macOS 上更贴合系统样式,其它平台会忽略
webPreferences: {
sandbox: false,
preload: path.join(__dirname, 'preload.js'),
webSecurity: true,
},
});
// Linux 程序坞/任务栏使用窗口图标;显式 setIcon 确保被 compositor 识别
if (iconImage) mainWindow.setIcon(iconImage);
mainWindow.loadURL(`http://127.0.0.1:${port}/index.html`);
// 右键菜单:支持复制/粘贴/全选(聊天区等可选中文字处右键即可复制)
mainWindow.webContents.on('context-menu', (_e, params) => {
const menu = Menu.buildFromTemplate([
{ role: 'copy', label: '复制' },
{ role: 'paste', label: '粘贴' },
{ type: 'separator' },
{ role: 'selectAll', label: '全选' },
]);
menu.popup({ window: mainWindow });
});
// 应用菜单改为完全由前端页面自绘,这里清空系统级菜单
Menu.setApplicationMenu(null);
}
/** Linux: 注册 .desktop 到 ~/.local/share/applications,程序坞用其 Icon 匹配 WM_CLASS */
function ensureLinuxDesktopFile() {
if (process.platform !== 'linux') return;
const iconPath = path.join(ROOT, 'assets', 'markwrite-icon.png');
if (!fs.existsSync(iconPath)) return;
const desktopDir = path.join(os.homedir(), '.local', 'share', 'applications');
try {
fs.mkdirSync(desktopDir, { recursive: true });
} catch (_) {}
const exe = process.execPath;
const quote = (s) => (s && s.includes(' ')) ? `"${s}"` : s;
const content = [
'[Desktop Entry]',
'Name=MarkWrite',
'Comment=Markdown editor with AI',
`Exec=${quote(exe)} ${quote(ROOT)}`,
`Icon=${iconPath}`,
'Type=Application',
'StartupWMClass=MarkWrite',
'Categories=Utility;TextEditor;',
].join('\n');
const desktopPath = path.join(desktopDir, 'markwrite.desktop');
try {
if (fs.readFileSync(desktopPath, 'utf8') !== content) {
fs.writeFileSync(desktopPath, content, 'utf8');
}
} catch (_) {}
}
ipcMain.handle('file:open', async () => {
const win = BrowserWindow.getFocusedWindow() || mainWindow;
loadWorkspaceRoot();
const defaultDir = workspaceRoot || DEFAULT_WORKSPACE;
const result = await dialog.showOpenDialog(win, {
defaultPath: defaultDir,
properties: ['openFile', 'openDirectory'],
filters: [
{ name: 'Markdown', extensions: ['md', 'markdown'] },
{ name: 'All', extensions: ['*'] },
],
});
if (result.canceled || !result.filePaths.length) return null;
const targetPath = result.filePaths[0];
try {
const stat = fs.statSync(targetPath);
if (stat.isDirectory()) {
return { directory: targetPath };
}
} catch (_) {}
const content = fs.readFileSync(targetPath, 'utf8');
return { filePath: targetPath, content };
});
ipcMain.handle('file:read', async (_, filePath) => {
if (!filePath || typeof filePath !== 'string') return null;
try {
const content = fs.readFileSync(filePath, 'utf8');
return { filePath, content };
} catch (_) {
return null;
}
});
ipcMain.handle('file:rename', async (_, oldPath, newName) => {
if (!oldPath || typeof oldPath !== 'string' || !newName || typeof newName !== 'string') {
return { ok: false, message: '参数无效' };
}
try {
const dir = path.dirname(oldPath);
const target = path.join(dir, newName.trim());
if (target === oldPath) return { ok: true, oldPath, newPath: target };
fs.renameSync(oldPath, target);
return { ok: true, oldPath, newPath: target };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
ipcMain.handle('file:delete', async (_, targetPath) => {
if (!targetPath || typeof targetPath !== 'string') {
return { ok: false, message: '参数无效' };
}
try {
if (!fs.existsSync(targetPath)) {
return { ok: true, deleted: false };
}
const stat = fs.statSync(targetPath);
if (stat.isDirectory()) {
fs.rmSync(targetPath, { recursive: true, force: true });
} else {
fs.unlinkSync(targetPath);
}
return { ok: true, deleted: true };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
ipcMain.handle('file:save', async (_, filePath, content) => {
if (!filePath) return false;
fs.writeFileSync(filePath, content, 'utf8');
return true;
});
// 保存到指定路径:相对路径以当前工作区根目录为基准(默认 ~/markwrite-docs 或左侧工作区)
ipcMain.handle('file:saveTo', async (_, targetPath, content) => {
if (!targetPath || typeof targetPath !== 'string') return null;
const p = targetPath.trim();
if (!p) return null;
try {
const root = workspaceRoot || DEFAULT_WORKSPACE;
const abs = path.isAbsolute(p) ? p : path.join(root, p);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content || '', 'utf8');
return abs;
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
});
ipcMain.handle('file:saveAs', async (_, content) => {
const win = BrowserWindow.getFocusedWindow() || mainWindow;
loadWorkspaceRoot();
const defaultDir = workspaceRoot || DEFAULT_WORKSPACE;
const defaultFile = path.join(defaultDir, 'untitled.md');
const result = await dialog.showSaveDialog(win, {
defaultPath: defaultFile,
filters: [
{ name: 'Markdown', extensions: ['md', 'markdown'] },
{ name: 'All', extensions: ['*'] },
],
});
if (result.canceled || !result.filePath) return null;
fs.writeFileSync(result.filePath, content, 'utf8');
return result.filePath;
});
// 上传图片:弹出文件选择对话框,将图片复制到项目根目录下的 uploads 目录,并返回供 Markdown 使用的相对路径
ipcMain.handle('image:upload', async () => {
const win = BrowserWindow.getFocusedWindow() || mainWindow;
const result = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [
{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'] },
{ name: 'All Files', extensions: ['*'] },
],
});
if (result.canceled || !result.filePaths.length) return null;
const src = result.filePaths[0];
try {
const stat = fs.statSync(src);
if (!stat.isFile()) return { error: '不是有效文件' };
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
const uploadsDir = path.join(ROOT, 'uploads');
try {
fs.mkdirSync(uploadsDir, { recursive: true });
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
const ext = path.extname(src) || '';
const base = path.basename(src, ext) || 'image';
const rand = Math.random().toString(36).slice(2, 8);
let destName = `${base}-${rand}${ext}`;
let destPath = path.join(uploadsDir, destName);
let tries = 0;
while (fs.existsSync(destPath) && tries < 5) {
const r = Math.random().toString(36).slice(2, 8);
destName = `${base}-${r}${ext}`;
destPath = path.join(uploadsDir, destName);
tries += 1;
}
try {
fs.copyFileSync(src, destPath);
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
// Web 访问路径:由内置 HTTP 服务器以 ROOT 为根提供静态文件
const webPath = `uploads/${destName}`;
return { ok: true, filePath: destPath, webPath };
});
// 从粘贴板数据保存图片:renderer 传入二进制数组和可选扩展名/原始文件名
ipcMain.handle('image:pasteBinary', async (_event, payload) => {
try {
if (!payload || !payload.data) return { error: 'no image data' };
const data = payload.data;
const extInput = payload.ext || '';
const nameInput = payload.name || '';
const uploadsDir = path.join(ROOT, 'uploads');
fs.mkdirSync(uploadsDir, { recursive: true });
const fromNameExt = path.extname(nameInput || '') || '';
let ext = extInput || fromNameExt || '.png';
if (ext[0] !== '.') ext = `.${ext}`;
const base = (nameInput && path.basename(nameInput, fromNameExt)) || 'pasted-image';
const rand = Math.random().toString(36).slice(2, 8);
let destName = `${base}-${rand}${ext}`;
let destPath = path.join(uploadsDir, destName);
let tries = 0;
while (fs.existsSync(destPath) && tries < 5) {
const r = Math.random().toString(36).slice(2, 8);
destName = `${base}-${r}${ext}`;
destPath = path.join(uploadsDir, destName);
tries += 1;
}
const buf = Buffer.from(data);
fs.writeFileSync(destPath, buf);
const webPath = `uploads/${destName}`;
return { ok: true, filePath: destPath, webPath };
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
});
// 直接从系统剪贴板读取图片(备用方案,防止 DOM 粘贴事件拿不到 image items)
ipcMain.handle('image:fromClipboard', async () => {
try {
const img = clipboard.readImage();
if (!img || img.isEmpty()) return { error: 'clipboard has no image' };
const uploadsDir = path.join(ROOT, 'uploads');
fs.mkdirSync(uploadsDir, { recursive: true });
const rand = Math.random().toString(36).slice(2, 8);
const destName = `clipboard-image-${rand}.png`;
const destPath = path.join(uploadsDir, destName);
const buf = img.toPNG();
fs.writeFileSync(destPath, buf);
const webPath = `uploads/${destName}`;
return { ok: true, filePath: destPath, webPath };
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
});
// 将文本写入系统剪贴板:用于 ESEC 复制按钮,避免浏览器剪贴板限制
ipcMain.handle('clipboard:writeText', async (_event, text) => {
try {
const v = typeof text === 'string' ? text : String(text || '');
if (!v.trim()) return { ok: false, message: 'empty' };
clipboard.writeText(v);
return { ok: true };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
// 默认/当前工作区:~/markwrite-docs,或由前端设置的工作区
function ensureDefaultWorkspace() {
try {
fs.mkdirSync(DEFAULT_WORKSPACE, { recursive: true });
} catch (_) {}
}
function notifyWorkspaceChanged() {
if (workspaceChangeTimer) clearTimeout(workspaceChangeTimer);
workspaceChangeTimer = setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
try {
mainWindow.webContents.send('workspace:changed');
} catch (_) {}
}
}, 400);
}
function setupWorkspaceWatcher() {
try {
if (workspaceWatcher) {
workspaceWatcher.close();
workspaceWatcher = null;
}
const root = workspaceRoot || DEFAULT_WORKSPACE;
if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) return;
// 监听当前工作区及其子目录;使用轮询方式,行为与 test.js 中一致
workspaceWatcher = chokidar.watch(root, {
persistent: true,
ignoreInitial: true,
depth: Infinity,
usePolling: true, // 与 test.js 一样,强制轮询,兼容性更好
interval: 800,
alwaysStat: true,
});
workspaceWatcher
.on('ready', () => {
// watcher 就绪
})
.on('add', () => {
notifyWorkspaceChanged();
})
.on('change', () => {
notifyWorkspaceChanged();
})
.on('addDir', () => {
notifyWorkspaceChanged();
})
.on('unlink', () => {
notifyWorkspaceChanged();
})
.on('unlinkDir', () => {
notifyWorkspaceChanged();
})
.on('error', () => {
// 监听错误时静默失败,避免打断应用
});
} catch (_) {
workspaceWatcher = null;
}
}
function loadWorkspaceRoot() {
ensureDefaultWorkspace();
try {
if (fs.existsSync(WORKSPACE_ROOT_FILE)) {
const p = (fs.readFileSync(WORKSPACE_ROOT_FILE, 'utf8') || '').trim();
// 若记录的是应用自身目录(旧版本遗留),则忽略,退回默认工作区
if (p && fs.existsSync(p) && fs.statSync(p).isDirectory() && !p.startsWith(ROOT)) {
workspaceRoot = p;
setupWorkspaceWatcher();
return;
}
}
} catch (_) {}
workspaceRoot = DEFAULT_WORKSPACE;
setupWorkspaceWatcher();
}
function setWorkspaceRoot(dirPath) {
ensureDefaultWorkspace();
const p = (dirPath || '').trim();
if (!p) return;
try {
const stat = fs.statSync(p);
if (!stat.isDirectory()) return;
workspaceRoot = p;
const cfgDir = path.dirname(WORKSPACE_ROOT_FILE);
fs.mkdirSync(cfgDir, { recursive: true });
fs.writeFileSync(WORKSPACE_ROOT_FILE, workspaceRoot, 'utf8');
} catch (_) {
workspaceRoot = DEFAULT_WORKSPACE;
}
setupWorkspaceWatcher();
}
/** 与 composeDrafts 内 isSafeDraftId 一致,供发布流程写回 meta(compose:createContent 在 app.whenReady 外注册) */
function isSafeComposeDraftIdForPublish(id) {
if (typeof id !== 'string') return false;
const t = id.trim();
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)) return true;
if (t.length < 4 || t.length > 200) return false;
if (t === '.' || t === '..') return false;
if (/[\/\\:\*\?"<>\|\x00-\x1f]/.test(t)) return false;
if (/^\s|\s$/.test(t) || /[. ]$/.test(t)) return false;
if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(t)) return false;
return true;
}
/**
* create_book 同步回调 { code:201, id:bookId } 或后续成功路径拿到 id 后,写回本地书籍草稿 meta / book-upload-sync。
*/
function persistBookRemoteIdToLocalDraft(draftFileId, remoteBookId) {
const did = String(draftFileId || '').trim();
const rid = String(remoteBookId || '').trim();
if (!did || !rid || !isSafeComposeDraftIdForPublish(did)) return;
loadWorkspaceRoot();
const root = (workspaceRoot || DEFAULT_WORKSPACE || '').trim();
const candidates = [];
if (root) candidates.push(path.join(root, '.markwrite', 'compose-drafts', did));
try {
candidates.push(path.join(app.getPath('userData'), 'compose-drafts', did));
} catch (_) {}
const metaName = 'meta.json';
const syncName = 'book-upload-sync.json';
for (const bookRoot of candidates) {
const metaPath = path.join(bookRoot, metaName);
try {
if (!fs.existsSync(metaPath)) continue;
let meta = {};
try {
meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
} catch (_) {
meta = {};
}
if (!meta || meta.mode !== 'book') continue;
meta.remoteId = rid;
meta.updatedAt = Date.now();
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8');
const syncPath = path.join(bookRoot, syncName);
let sync = {};
try {
if (fs.existsSync(syncPath)) sync = JSON.parse(fs.readFileSync(syncPath, 'utf8'));
} catch (_) {}
if (!sync || typeof sync !== 'object') sync = {};
sync.remoteId = rid;
fs.writeFileSync(syncPath, JSON.stringify(sync, null, 2), 'utf8');
console.log('[compose-publish] persisted book remoteId to local draft', { draftId: did, remoteId: rid });
return;
} catch (e) {
console.warn('[compose-publish] persist remoteId failed', e && e.message ? e.message : e);
}
}
}
ipcMain.handle('app:getDefaultWorkspace', async () => {
loadWorkspaceRoot();
return { path: workspaceRoot || DEFAULT_WORKSPACE };
});
ipcMain.handle('app:setWorkspaceRoot', async (_, dirPath) => {
if (dirPath && typeof dirPath === 'string') {
try {
setWorkspaceRoot(dirPath);
} catch (_) {}
}
return { path: workspaceRoot || DEFAULT_WORKSPACE };
});
// 列出目录内容:用于左侧文件树(无 dirPath 时使用当前工作区根目录)
ipcMain.handle('fs:listDir', async (_, dirPath) => {
try {
loadWorkspaceRoot();
const root = workspaceRoot || DEFAULT_WORKSPACE;
const target = dirPath && typeof dirPath === 'string' && dirPath.trim() !== ''
? (path.isAbsolute(dirPath) ? dirPath : path.join(root, dirPath.trim()))
: root;
const stat = fs.statSync(target);
if (!stat.isDirectory()) return { path: target, entries: [] };
const names = fs.readdirSync(target);
const entries = names.map((name) => {
const full = path.join(target, name);
let isDir = false;
try {
isDir = fs.statSync(full).isDirectory();
} catch (_) {}
return { name, path: full, isDir };
}).sort((a, b) => {
if (a.isDir && !b.isDir) return -1;
if (!a.isDir && b.isDir) return 1;
return a.name.localeCompare(b.name);
});
return { path: target, entries };
} catch (e) {
return { error: e && e.message ? e.message : String(e) };
}
});
ipcMain.handle('markdown:render', async (_, markdown) => {
try {
return renderMarkdown(markdown || '');
} catch (e) {
return `<p>渲染失败: ${e.message}</p>`;
}
});
// Sync & Servers 配置:读写 ~/.config/markwrite/sync-servers.json
ipcMain.handle('sync:getConfig', async () => {
try {
if (fs.existsSync(SYNC_CONFIG_FILE)) {
const raw = fs.readFileSync(SYNC_CONFIG_FILE, 'utf8');
const data = JSON.parse(raw);
if (Array.isArray(data.servers) && data.servers.length > 0) {
return {
servers: data.servers,
activeId: data.activeId || (data.servers[0] && data.servers[0].id) || null,
};
}
}
} catch (_) {}
// 默认返回一个本地配置
const fallback = {
servers: [
{
id: 'local',
name: '本地',
esserver: 'ws://127.0.0.1:8080/',
uploadpath: 'http://127.0.0.1:8081/uploads/',
sitename: '辰龙文档中心',
domain: 'http://localhost:5173',
},
],
activeId: 'local',
};
return fallback;
});
ipcMain.handle('sync:saveConfig', async (_event, payload) => {
try {
const cfgDir = MARKWRITE_CFG_DIR;
fs.mkdirSync(cfgDir, { recursive: true });
const toSave = {
servers: Array.isArray(payload && payload.servers) ? payload.servers : [],
activeId: payload && typeof payload.activeId === 'string' ? payload.activeId : null,
};
fs.writeFileSync(SYNC_CONFIG_FILE, JSON.stringify(toSave, null, 2), 'utf8');
writeEventstoreConfigFromSync(SYNC_CONFIG_FILE);
invalidateEsclientModule();
return { ok: true };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
ipcMain.handle('sync:getConnectionStatus', async () => {
try {
const syncCfg = readSyncConfigSafe();
const servers = Array.isArray(syncCfg.servers) ? syncCfg.servers : [];
const activeId = syncCfg.activeId || (servers[0] && servers[0].id) || null;
const activeServer = servers.find((s) => s.id === activeId) || servers[0] || null;
const esserver = activeServer && typeof activeServer.esserver === 'string' ? activeServer.esserver.trim() : '';
if (!esserver) {
return {
ok: false,
status: 'idle',
message: '未配置 esserver',
serverId: activeId || '',
serverName: activeServer && activeServer.name ? activeServer.name : '',
esserver: '',
};
}
syncEventstoreVendorConfig();
const mod = loadEsclient();
if (!mod || typeof mod.ensure_connected !== 'function') {
return {
ok: false,
status: 'disconnected',
message: 'esclient 缺少 ensure_connected',
serverId: activeId || '',
serverName: activeServer && activeServer.name ? activeServer.name : '',
esserver,
};
}
const r = await mod.ensure_connected(6000);
return {
ok: !!(r && r.ok),
status: r && r.ok ? 'connected' : 'disconnected',
message: r && r.message ? r.message : '',
serverId: activeId || '',
serverName: activeServer && activeServer.name ? activeServer.name : '',
esserver,
};
} catch (e) {
return {
ok: false,
status: 'disconnected',
message: e && e.message ? e.message : String(e),
serverId: '',
serverName: '',
esserver: '',
};
}
});
/** 主动断开当前 EventStore WebSocket(与状态栏「停止」一致) */
ipcMain.handle('sync:disconnect', async () => {
try {
syncEventstoreVendorConfig();
const mod = loadEsclient();
if (!mod || typeof mod.disconnect_eventstore !== 'function') {
return { ok: false, message: 'esclient 缺少 disconnect_eventstore' };
}
return mod.disconnect_eventstore();
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
// 身份配置:读写 ~/.config/markwrite/identity.json
ipcMain.handle('identity:get', async (_event, payload) => {
const syncCfg0 = readSyncConfigSafe();
const requestedServerId = payload && typeof payload.serverId === 'string' && payload.serverId.trim()
? payload.serverId.trim()
: getActiveSyncServerId(syncCfg0);
try {
const data = readIdentityForServer(requestedServerId);
if (hasIdentityData(data)) {
const pubkeyHex = typeof data.pubkeyHex === 'string' ? data.pubkeyHex : '';
let pubkeyEpub = typeof data.pubkeyEpub === 'string' ? data.pubkeyEpub : '';
try {
if (!pubkeyEpub && pubkeyHex) {
if (!eventstoreKeyLib) {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
eventstoreKeyLib = require('eventstore-tools/src/key');
}
if (eventstoreKeyLib && typeof eventstoreKeyLib.epubEncode === 'function') {
pubkeyEpub = eventstoreKeyLib.epubEncode(pubkeyHex);
}
}
} catch (_) {}
let privkeyHex = '';
const privkeyStr = typeof data.privkey === 'string' ? data.privkey.trim() : '';
if (privkeyStr && privkeyStr.startsWith('esec')) {
try {
if (!eventstoreKeyLib) {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
eventstoreKeyLib = require('eventstore-tools/src/key');
}
const decoded = eventstoreKeyLib.esecDecode(privkeyStr);
const privBytes = (decoded && (decoded.data || decoded)) || decoded;
privkeyHex = secretBytesToHex(privBytes);
} catch (_) {}
}
return {
serverId: requestedServerId,
pubkey: pubkeyEpub || pubkeyHex || '',
pubkeyHex,
pubkeyEpub,
privkey: typeof data.privkey === 'string' ? data.privkey : '',
privkeyHex,
};
}
} catch (_) {}
return {
serverId: requestedServerId,
pubkey: '',
pubkeyHex: '',
pubkeyEpub: '',
privkey: '',
privkeyHex: '',
};
});
ipcMain.handle('identity:save', async (_event, payload) => {
try {
if (!eventstoreKeyLib) {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
eventstoreKeyLib = require('eventstore-tools/src/key');
}
const syncCfg = readSyncConfigSafe();
const fallbackServerId = getActiveSyncServerId(syncCfg);
const serverId = payload && typeof payload.serverId === 'string' && payload.serverId.trim()
? payload.serverId.trim()
: fallbackServerId;
const rawPub = payload && typeof payload.pubkey === 'string' ? payload.pubkey.trim() : '';
const privkey = payload && typeof payload.privkey === 'string' ? payload.privkey.trim() : '';
// 退出登录:清空 pubkey+privkey 时直接删除文件,避免残留空 JSON 导致前端/状态不一致
if (!rawPub && !privkey) {
saveIdentityForServer(serverId, { pubkeyHex: '', pubkeyEpub: '', pubkey: '', privkey: '' });
return { ok: true, pubkeyHex: '', pubkeyEpub: '' };
}
let pubkeyHex = '';
let pubkeyEpub = '';
if (privkey) {
if (!privkey.startsWith('esec')) {
return { ok: false, message: 'ESEC 密钥应以 esec 开头' };
}
try {
const decoded = eventstoreKeyLib.esecDecode(privkey);
const privBytes = (decoded && (decoded.data || decoded)) || decoded;
pubkeyHex = eventstoreKeyLib.getPublicKey(privBytes);
if (typeof eventstoreKeyLib.epubEncode === 'function') {
pubkeyEpub = eventstoreKeyLib.epubEncode(pubkeyHex);
}
} catch (e) {
return { ok: false, message: '无效的 ESEC 密钥,无法解析' };
}
if (!pubkeyHex) {
return { ok: false, message: '无效的 ESEC 密钥' };
}
} else if (rawPub) {
try {
if (rawPub.startsWith('epub1') && typeof eventstoreKeyLib.epubDecode === 'function') {
const decoded = eventstoreKeyLib.epubDecode(rawPub);
pubkeyHex = typeof decoded === 'string' ? decoded : (decoded && decoded.data) || '';
pubkeyEpub = rawPub;
} else {
pubkeyHex = rawPub;
if (typeof eventstoreKeyLib.epubEncode === 'function') {
pubkeyEpub = eventstoreKeyLib.epubEncode(pubkeyHex);
}
}
} catch (e) {
return { ok: false, message: '无效的公钥格式' };
}
if (!pubkeyHex && !pubkeyEpub) {
return { ok: false, message: '无效的公钥格式' };
}
} else {
return { ok: false, message: '请填写 ESEC 密钥' };
}
const toSave = {
pubkeyHex,
pubkeyEpub,
// 兼容旧字段,保留 pubkey 为 hex
pubkey: pubkeyHex,
privkey,
};
saveIdentityForServer(serverId, toSave);
let privkeyHexOut = '';
if (privkey && privkey.startsWith('esec')) {
try {
const decoded = eventstoreKeyLib.esecDecode(privkey);
const privBytes = (decoded && (decoded.data || decoded)) || decoded;
privkeyHexOut = secretBytesToHex(privBytes);
} catch (_) {}
}
return { ok: true, pubkeyHex, pubkeyEpub, privkeyHex: privkeyHexOut };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
// 生成新的 ESEC 密钥对,并返回 { esec, pubkeyHex, epub }(不自动写入磁盘)
ipcMain.handle('identity:generate', async () => {
try {
if (!eventstoreKeyLib) {
// 延迟加载,避免启动时硬依赖失败
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
eventstoreKeyLib = require('eventstore-tools/src/key');
}
const { generateSecretKey, getPublicKey, esecEncode, epubEncode } = eventstoreKeyLib;
const privBytes = generateSecretKey();
const pubkeyHex = getPublicKey(privBytes);
const esec = esecEncode(privBytes);
const epub = epubEncode(pubkeyHex);
const privkeyHex = secretBytesToHex(privBytes);
return { ok: true, esec, pubkeyHex, epub, privkeyHex };
} catch (e) {
return { ok: false, message: e && e.message ? e.message : String(e) };
}
});
// 从 ESEC 推导公钥(hex + epub),供前端在粘贴时即时计算展示
ipcMain.handle('identity:deriveFromEsec', async (_event, esec) => {
try {
if (!eventstoreKeyLib) {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
eventstoreKeyLib = require('eventstore-tools/src/key');
}
const { esecDecode, getPublicKey, epubEncode } = eventstoreKeyLib;
const v = typeof esec === 'string' ? esec.trim() : '';
if (!v || !v.startsWith('esec')) return { ok: false, message: 'invalid esec' };
const decoded = esecDecode(v);