-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1046 lines (957 loc) · 34.1 KB
/
Copy pathserver.js
File metadata and controls
1046 lines (957 loc) · 34.1 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 express = require('express');
const path = require('path');
const fs = require('fs');
const fsp = require('fs/promises');
const ROOT = __dirname;
const DATA_DIR = process.env.VERCEL ? '/tmp/wechat-workflow' : ROOT;
if (process.env.VERCEL) process.env.DATA_DIR = DATA_DIR;
const matter = require('gray-matter');
const { render } = require('./scripts/lib/markdownToHtml');
const { handleImages } = require('./scripts/lib/imageHandler');
const { listTemplates } = require('./scripts/lib/templateLoader');
const { generateCover, generateInline, getApiKey } = require('./scripts/lib/imageGen');
const { PROMPT_PRESETS } = require('./scripts/lib/imageGen');
const wechatApi = require('./scripts/lib/wechatApi');
const blobStorage = require('./scripts/lib/blobStorage');
const DATA_SRC = ROOT;
const CONFIG_PATH = path.join(DATA_DIR, 'config.json');
const CONFIG_SRC = path.join(DATA_SRC, 'config.json');
const DRAFTS_DIR = path.join(DATA_DIR, 'articles', 'drafts');
const READY_DIR = path.join(DATA_DIR, 'articles', 'ready');
const PUBLISHED_DIR = path.join(DATA_DIR, 'articles', 'published');
const TOPICS_DIR = path.join(DATA_DIR, 'topics');
const PUBLIC_DIR = path.join(ROOT, 'public');
function ensureDataDirs() {
fs.mkdirSync(DRAFTS_DIR, { recursive: true });
fs.mkdirSync(READY_DIR, { recursive: true });
fs.mkdirSync(PUBLISHED_DIR, { recursive: true });
fs.mkdirSync(TOPICS_DIR, { recursive: true });
}
function bootstrapData() {
ensureDataDirs();
if (DATA_DIR !== ROOT) {
if (!fs.existsSync(CONFIG_PATH) && fs.existsSync(CONFIG_SRC)) {
fs.copyFileSync(CONFIG_SRC, CONFIG_PATH);
}
listTemplates();
}
}
bootstrapData();
const CONFIG_FIELDS = {
default_template: { type: 'string', default: 'minimal' },
output_dir: { type: 'string', default: 'articles/ready' },
image_strategy: { type: 'string', default: 'local-warn', enum: ['local-keep', 'local-warn', 'cdn-replace'] },
wechat: {
type: 'object',
fields: {
app_id: { type: 'string', secret: false },
app_secret: { type: 'string', secret: true }
}
},
imageGen: {
type: 'object',
fields: {
enabled: { type: 'boolean', default: true },
provider: { type: 'string', default: 'agnes' },
model: { type: 'string', default: 'agnes-image-2.1-flash' },
defaultSize: { type: 'string', default: '1024x768' },
apiKey: { type: 'string', secret: true }
}
}
};
const MASK = '••••••••';
function readConfig() {
return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
}
function maskConfig(cfg) {
const out = JSON.parse(JSON.stringify(cfg));
for (const section of ['wechat', 'imageGen']) {
const block = CONFIG_FIELDS[section];
if (!block || !block.fields) continue;
for (const [k, def] of Object.entries(block.fields)) {
if (def.secret && out[section] && out[section][k]) {
const v = out[section][k];
if (typeof v === 'string' && v.length > 0) {
out[section][k] = MASK;
}
}
}
}
return out;
}
function configSummary(cfg) {
const wechatOk = !!(cfg.wechat && cfg.wechat.app_id && cfg.wechat.app_secret) || !!(process.env.WECHAT_APP_ID && process.env.WECHAT_APP_SECRET);
const imageGenConfigured = !!getApiKey();
return {
wechat_configured: wechatOk,
imageGen_configured: imageGenConfigured,
imageGen_provider: cfg.imageGen?.provider || 'agnes',
imageGen_model: cfg.imageGen?.model || 'agnes-image-2.1-flash'
};
}
function applyConfigUpdate(target, update, schema, pathParts = []) {
for (const [key, value] of Object.entries(update)) {
const def = schema[key];
if (!def) {
throw new Error(`Unknown field: ${[...pathParts, key].join('.')}`);
}
if (def.type === 'object' && def.fields) {
target[key] = target[key] || {};
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
applyConfigUpdate(target[key], value, def.fields, [...pathParts, key]);
} else if (value === null) {
delete target[key];
} else {
throw new Error(`Field ${[...pathParts, key].join('.')} must be an object`);
}
continue;
}
if (value === null || value === '') {
target[key] = '';
continue;
}
if (def.type === 'string') {
if (typeof value !== 'string') {
throw new Error(`Field ${[...pathParts, key].join('.')} must be a string`);
}
if (def.enum && !def.enum.includes(value)) {
throw new Error(`Field ${[...pathParts, key].join('.')} must be one of: ${def.enum.join(', ')}`);
}
target[key] = value;
} else if (def.type === 'boolean') {
target[key] = !!value;
} else if (def.type === 'number') {
const n = Number(value);
if (Number.isNaN(n)) throw new Error(`Field ${[...pathParts, key].join('.')} must be a number`);
target[key] = n;
}
}
}
function updateConfig(partial) {
const current = readConfig();
applyConfigUpdate(current, partial, CONFIG_FIELDS);
fs.writeFileSync(CONFIG_PATH, JSON.stringify(current, null, 2) + '\n', 'utf-8');
const srcPath = path.resolve(ROOT, 'config.json');
const cached = require.cache[srcPath];
if (cached) Object.assign(cached.exports, current);
wechatApi.resetAccessToken();
return current;
}
function slugify(s) {
return String(s || 'untitled')
.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fff-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'untitled';
}
const ARTICLE_PREFIX = 'articles/drafts/';
const articleBlobMeta = new Map();
const TOPIC_PREFIX = 'topics/';
const topicBlobMeta = new Map();
const TOPIC_STATUSES = ['idea', 'researching', 'writing', 'done', 'published', 'shelved'];
const TOPIC_STATUS_LABELS = {
idea: '想法',
researching: '预研',
writing: '写作中',
done: '已完成',
published: '已发布',
shelved: '搁置'
};
const TOPIC_PRIORITIES = ['P0', 'P1', 'P2', 'P3'];
const TOPIC_PRIORITY_LABELS = { P0: 'P0 紧急', P1: 'P1 高', P2: 'P2 中', P3: 'P3 低' };
const BLOB_NOT_CONFIGURED_ERROR = 'Blob Storage not configured — set BLOB_STORE_ID env var';
function requireBlob() {
if (!blobStorage.isBlobEnabled()) {
const err = new Error(BLOB_NOT_CONFIGURED_ERROR);
err.code = 'BLOB_NOT_CONFIGURED';
throw err;
}
}
function safeSlug(slug) {
return String(slug || '').replace(/[^a-zA-Z0-9\u4e00-\u9fff_-]/g, '');
}
function articlePathname(slug) {
return `${ARTICLE_PREFIX}${slug}.md`;
}
function normalizeDate(d) {
if (!d) return '';
if (d instanceof Date) return d.toISOString();
return String(d);
}
function articleFromFrontmatter(slug, fm, fallbackUpdatedAt) {
return {
slug,
filename: `${slug}.md`,
title: fm.title || slug,
author: fm.author || '',
date: normalizeDate(fm.date),
tags: fm.tags || [],
status: fm.status || 'draft',
updatedAt: fallbackUpdatedAt || new Date().toISOString()
};
}
async function refreshArticleBlobMeta() {
articleBlobMeta.clear();
const result = await blobStorage.list({ prefix: ARTICLE_PREFIX });
for (const b of result.blobs) {
const m = b.pathname.match(/^articles\/drafts\/(.+)\.md$/);
if (!m) continue;
articleBlobMeta.set(m[1], { url: b.url, pathname: b.pathname, uploadedAt: b.uploadedAt instanceof Date ? b.uploadedAt.toISOString() : String(b.uploadedAt || '') });
}
return articleBlobMeta;
}
async function fetchBlobText(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`Fetch ${url} → ${res.status}`);
return res.text();
}
async function listArticles() {
requireBlob();
await refreshArticleBlobMeta();
const items = [];
for (const [slug, meta] of articleBlobMeta) {
try {
const text = await fetchBlobText(meta.url);
const parsed = matter(text);
items.push(articleFromFrontmatter(slug, parsed.data, meta.uploadedAt));
} catch (err) {
items.push(articleFromFrontmatter(slug, {}, meta.uploadedAt));
}
}
items.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
return items;
}
async function readArticle(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) return null;
if (!articleBlobMeta.has(safe)) {
await refreshArticleBlobMeta();
}
const meta = articleBlobMeta.get(safe);
if (!meta) return null;
const text = await fetchBlobText(meta.url);
const parsed = matter(text);
return {
slug: safe,
title: parsed.data.title || safe,
author: parsed.data.author || '',
date: normalizeDate(parsed.data.date),
tags: parsed.data.tags || [],
status: parsed.data.status || 'draft',
cover: parsed.data.cover || '',
content: parsed.content,
frontmatter: parsed.data
};
}
async function writeArticle(slug, payload) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) throw new Error('Invalid slug');
const fm = {
title: payload.title || safe,
slug: safe,
author: payload.author || '',
date: payload.date || new Date().toISOString().slice(0, 10),
tags: payload.tags || [],
status: payload.status || 'draft'
};
if (payload.cover !== undefined) fm.cover = payload.cover;
const content = payload.content || '';
const body = matter.stringify(content, fm);
const pathname = articlePathname(safe);
const buffer = Buffer.from(body, 'utf-8');
const result = await blobStorage.put(pathname, buffer, {
access: 'public',
contentType: 'text/markdown',
allowOverwrite: true
});
articleBlobMeta.set(safe, { url: result.url, pathname: result.pathname, uploadedAt: result.uploadedAt instanceof Date ? result.uploadedAt.toISOString() : String(result.uploadedAt || new Date().toISOString()) });
return { slug: safe, pathname: result.pathname, url: result.url };
}
async function deleteArticle(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!articleBlobMeta.has(safe)) {
await refreshArticleBlobMeta();
}
const meta = articleBlobMeta.get(safe);
if (meta) {
await blobStorage.del(meta.url);
articleBlobMeta.delete(safe);
}
return { slug: safe, deleted: true };
}
async function articleExists(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) return false;
if (!articleBlobMeta.has(safe)) {
await refreshArticleBlobMeta();
}
return articleBlobMeta.has(safe);
}
// === Topic helpers ===
function normalizeTopicStatus(s) {
if (Array.isArray(s) && s.length) s = s[0];
if (typeof s !== 'string') return 'idea';
const v = s.trim().toLowerCase();
if (TOPIC_STATUSES.includes(v)) return v;
const inv = Object.fromEntries(Object.entries(TOPIC_STATUS_LABELS).map(([k, v]) => [v, k]));
return inv[s.trim()] || 'idea';
}
function normalizeTopicPriority(p) {
if (Array.isArray(p) && p.length) p = p[0];
if (typeof p !== 'string') return 'P2';
const v = p.trim().toUpperCase();
if (TOPIC_PRIORITIES.includes(v)) return v;
return 'P2';
}
function topicPathname(slug) {
return `${TOPIC_PREFIX}${slug}.md`;
}
function topicFromFrontmatter(slug, fm, fallbackUpdatedAt) {
return {
slug,
title: fm.title || slug,
summary: fm.summary || '',
source: fm.source || '',
status: normalizeTopicStatus(fm.status),
priority: normalizeTopicPriority(fm.priority),
linkedArticle: fm.linkedArticle || '',
tags: fm.tags || [],
createdAt: normalizeDate(fm.createdAt),
updatedAt: normalizeDate(fm.updatedAt) || fallbackUpdatedAt || new Date().toISOString()
};
}
async function refreshTopicBlobMeta() {
topicBlobMeta.clear();
const result = await blobStorage.list({ prefix: TOPIC_PREFIX });
for (const b of result.blobs) {
const m = b.pathname.match(/^topics\/(.+)\.md$/);
if (!m) continue;
topicBlobMeta.set(m[1], { url: b.url, pathname: b.pathname, uploadedAt: b.uploadedAt instanceof Date ? b.uploadedAt.toISOString() : String(b.uploadedAt || '') });
}
return topicBlobMeta;
}
async function listTopics() {
requireBlob();
await refreshTopicBlobMeta();
const items = [];
for (const [slug, meta] of topicBlobMeta) {
try {
const text = await fetchBlobText(meta.url);
const parsed = matter(text);
items.push(topicFromFrontmatter(slug, parsed.data, meta.uploadedAt));
} catch (err) {
items.push(topicFromFrontmatter(slug, {}, meta.uploadedAt));
}
}
items.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
return items;
}
async function readTopic(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) return null;
if (!topicBlobMeta.has(safe)) {
await refreshTopicBlobMeta();
}
const meta = topicBlobMeta.get(safe);
if (!meta) return null;
const text = await fetchBlobText(meta.url);
const parsed = matter(text);
return {
slug: safe,
title: parsed.data.title || safe,
summary: parsed.data.summary || '',
source: parsed.data.source || '',
status: normalizeTopicStatus(parsed.data.status),
priority: normalizeTopicPriority(parsed.data.priority),
linkedArticle: parsed.data.linkedArticle || '',
tags: parsed.data.tags || [],
content: parsed.content || '',
frontmatter: parsed.data,
createdAt: normalizeDate(parsed.data.createdAt),
updatedAt: normalizeDate(parsed.data.updatedAt) || meta.uploadedAt || ''
};
}
async function writeTopic(slug, payload) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) throw new Error('Invalid slug');
const now = new Date().toISOString();
const fm = {
title: payload.title || safe,
summary: payload.summary || '',
source: payload.source || '',
status: normalizeTopicStatus(payload.status),
priority: normalizeTopicPriority(payload.priority),
linkedArticle: payload.linkedArticle || '',
tags: payload.tags || [],
createdAt: payload.createdAt || now,
updatedAt: now
};
const content = payload.content || '';
const body = matter.stringify(content, fm);
const pathname = topicPathname(safe);
const buffer = Buffer.from(body, 'utf-8');
const result = await blobStorage.put(pathname, buffer, {
access: 'public',
contentType: 'text/markdown',
allowOverwrite: true
});
topicBlobMeta.set(safe, { url: result.url, pathname: result.pathname, uploadedAt: result.uploadedAt instanceof Date ? result.uploadedAt.toISOString() : String(result.uploadedAt || now) });
return { slug: safe, pathname: result.pathname, url: result.url };
}
async function deleteTopic(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!topicBlobMeta.has(safe)) {
await refreshTopicBlobMeta();
}
const meta = topicBlobMeta.get(safe);
if (meta) {
await blobStorage.del(meta.url);
topicBlobMeta.delete(safe);
}
return { slug: safe, deleted: true };
}
async function topicExists(slug) {
requireBlob();
const safe = safeSlug(slug);
if (!safe) return false;
if (!topicBlobMeta.has(safe)) {
await refreshTopicBlobMeta();
}
return topicBlobMeta.has(safe);
}
function renderMarkdown(content, template) {
const cfg = readConfig();
const tpl = template || cfg.default_template || 'minimal';
const rawHtml = render(content, tpl);
return handleImages(rawHtml, DRAFTS_DIR);
}
function buildArticleHtml(article, contentHtml) {
const title = article.title || 'Untitled';
const author = article.author || '';
const date = article.date || '';
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${esc(title)}</title>
</head>
<body>
<section class="article-header" style="text-align:center;padding:20px 0 10px;">
<h1 style="font-size:22px;font-weight:700;margin:0 0 8px;">${esc(title)}</h1>
${author ? `<p style="color:#999;font-size:14px;margin:0 0 4px;">${esc(author)}</p>` : ''}
${date ? `<p style="color:#999;font-size:14px;margin:0;">${esc(date)}</p>` : ''}
</section>
${contentHtml}
</body>
</html>`;
}
const app = express();
app.use(express.json({ limit: '2mb' }));
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});
app.get('/api/health', (req, res) => {
res.json({
ok: true,
version: '1.0.0',
uptime: process.uptime(),
...configSummary(readConfig()),
blob_storage: blobStorage.isBlobEnabled() ? 'enabled' : 'disabled'
});
});
app.get('/api/config', (req, res) => {
const cfg = readConfig();
res.json({
config: maskConfig(cfg),
summary: configSummary(cfg),
fields: CONFIG_FIELDS
});
});
app.put('/api/config', (req, res) => {
try {
const update = req.body || {};
if (typeof update !== 'object' || Array.isArray(update)) {
return res.status(400).json({ error: 'Body must be a JSON object' });
}
const updated = updateConfig(update);
res.json({ ok: true, config: maskConfig(updated), summary: configSummary(updated) });
} catch (err) {
res.status(400).json({ error: err.message || 'Update failed' });
}
});
app.get('/api/templates', (req, res) => {
res.json(listTemplates());
});
app.get('/api/articles', async (req, res, next) => {
try { res.json(await listArticles()); }
catch (err) { next(err); }
});
app.get('/api/articles/:slug', async (req, res, next) => {
try {
const article = await readArticle(req.params.slug);
if (!article) return res.status(404).json({ error: 'Not found' });
res.json(article);
} catch (err) { next(err); }
});
app.post('/api/articles', async (req, res, next) => {
try {
const { title, author, content, tags, status } = req.body || {};
const slug = slugify(req.body?.slug || title);
if (await articleExists(slug)) {
return res.status(409).json({ error: `Article "${slug}" already exists` });
}
const result = await writeArticle(slug, {
title: title || slug,
author: author || '',
content: content || '',
tags: tags || [],
status: status || 'draft',
date: new Date().toISOString().slice(0, 10)
});
res.status(201).json({ ok: true, slug: result.slug });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.put('/api/articles/:slug', async (req, res, next) => {
try {
const existing = await readArticle(req.params.slug);
if (!existing) return res.status(404).json({ error: 'Not found' });
const payload = {
...existing,
...(req.body || {}),
slug: existing.slug
};
await writeArticle(existing.slug, payload);
res.json({ ok: true, slug: existing.slug });
} catch (err) {
next(err);
}
});
app.delete('/api/articles/:slug', async (req, res, next) => {
try {
const result = await deleteArticle(req.params.slug);
res.json({ ok: true, ...result });
} catch (err) { next(err); }
});
app.get('/api/topics/meta', (req, res) => {
res.json({
statuses: TOPIC_STATUSES.map(s => ({ value: s, label: TOPIC_STATUS_LABELS[s] })),
priorities: TOPIC_PRIORITIES.map(p => ({ value: p, label: TOPIC_PRIORITY_LABELS[p] }))
});
});
app.get('/api/topics', async (req, res, next) => {
try { res.json(await listTopics()); }
catch (err) { next(err); }
});
app.get('/api/topics/:slug', async (req, res, next) => {
try {
const topic = await readTopic(req.params.slug);
if (!topic) return res.status(404).json({ error: 'Not found' });
res.json(topic);
} catch (err) { next(err); }
});
app.post('/api/topics', async (req, res, next) => {
try {
const body = req.body || {};
const title = (body.title || '').trim();
if (!title) return res.status(400).json({ error: 'title is required' });
const status = normalizeTopicStatus(body.status);
const priority = normalizeTopicPriority(body.priority);
const slug = slugify(body.slug || title);
if (await topicExists(slug)) {
return res.status(409).json({ error: `Topic "${slug}" already exists` });
}
const result = await writeTopic(slug, {
title,
summary: body.summary || '',
source: body.source || '',
status,
priority,
linkedArticle: body.linkedArticle || '',
tags: body.tags || [],
content: body.content || ''
});
res.status(201).json({ ok: true, slug: result.slug });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.put('/api/topics/:slug', async (req, res, next) => {
try {
const existing = await readTopic(req.params.slug);
if (!existing) return res.status(404).json({ error: 'Not found' });
const body = req.body || {};
const payload = {
...existing,
...body,
slug: existing.slug,
status: normalizeTopicStatus(body.status || existing.status),
priority: normalizeTopicPriority(body.priority || existing.priority)
};
if (typeof body.title === 'string' && body.title.trim()) {
payload.title = body.title.trim();
}
await writeTopic(existing.slug, payload);
res.json({ ok: true, slug: existing.slug });
} catch (err) {
next(err);
}
});
app.delete('/api/topics/:slug', async (req, res, next) => {
try {
const result = await deleteTopic(req.params.slug);
res.json({ ok: true, ...result });
} catch (err) { next(err); }
});
app.post('/api/render', async (req, res, next) => {
try {
const { content, template, slug, mode } = req.body || {};
if (typeof content !== 'string') {
return res.status(400).json({ error: 'content must be a string' });
}
let article = { title: '', author: '', date: '' };
if (slug) {
const a = await readArticle(slug);
if (a) article = a;
} else if (req.body && req.body.frontmatter) {
article = { ...article, ...req.body.frontmatter };
}
const contentHtml = renderMarkdown(content, template);
const fullHtml = buildArticleHtml(article, contentHtml);
if (mode === 'editor') {
const { marked } = require('marked');
const { loadTemplates } = require('./scripts/lib/templateLoader');
const templates = loadTemplates();
const tpl = templates[template] || templates[Object.keys(templates)[0]];
const rawHtml = marked.parse(content, { gfm: true, breaks: false });
const css = Object.entries(tpl.styles || {})
.map(([sel, style]) => {
const tag = sel === 'pre_code' ? 'pre code' : sel;
return `#editor-content ${tag} { ${style} }`;
}).join('\n');
return res.json({ ok: true, html: rawHtml, css, contentHtml });
}
res.json({ ok: true, html: fullHtml, contentHtml });
} catch (err) { next(err); }
});
app.post('/api/convert', async (req, res, next) => {
try {
const { slug, template } = req.body || {};
if (!slug) return res.status(400).json({ error: 'slug required' });
const article = await readArticle(slug);
if (!article) return res.status(404).json({ error: 'Article not found' });
const cfg = readConfig();
const tpl = template || cfg.default_template || 'minimal';
const contentHtml = renderMarkdown(article.content, tpl);
const fullHtml = buildArticleHtml(article, contentHtml);
fs.mkdirSync(READY_DIR, { recursive: true });
const outPath = path.join(READY_DIR, `${article.slug}.${tpl}.html`);
fs.writeFileSync(outPath, fullHtml, 'utf-8');
res.json({ ok: true, path: outPath, slug: article.slug, template: tpl });
} catch (err) { next(err); }
});
app.post('/api/publish', async (req, res) => {
try {
const { slug, template } = req.body || {};
if (!slug) return res.status(400).json({ error: 'slug required' });
const article = await readArticle(slug);
if (!article) return res.status(404).json({ error: 'Article not found' });
const cfg = readConfig();
const tpl = template || cfg.default_template || 'minimal';
const contentHtml = renderMarkdown(article.content, tpl);
const fullHtml = buildArticleHtml(article, contentHtml);
const wechatConfigured = !!(cfg.wechat && cfg.wechat.app_id && cfg.wechat.app_secret);
if (!wechatConfigured) {
fs.mkdirSync(PUBLISHED_DIR, { recursive: true });
const outPath = path.join(PUBLISHED_DIR, `${article.slug}.${tpl}.html`);
fs.writeFileSync(outPath, fullHtml, 'utf-8');
return res.json({
ok: true,
mode: 'simulated',
message: 'WeChat credentials not configured. Saved to articles/published/.',
path: outPath,
slug: article.slug
});
}
try {
const draft = await wechatApi.publishDraft(
article.title,
contentHtml,
article.content.slice(0, 100),
''
);
res.json({ ok: true, mode: 'live', draft, slug: article.slug });
} catch (err) {
res.status(502).json({ error: err.message, mode: 'simulated_fallback' });
}
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.get('/api/assets', async (req, res, next) => {
try {
requireBlob();
const result = await blobStorage.list();
const assets = result.blobs.map(b => {
const segments = b.pathname.split('/');
const type = segments.length > 1 ? segments[0] : 'misc';
const name = segments[segments.length - 1];
return {
name,
type,
url: b.url,
pathname: b.pathname,
size: b.size,
uploadedAt: b.uploadedAt instanceof Date ? b.uploadedAt.toISOString() : String(b.uploadedAt || ''),
contentType: b.contentType || 'image/png',
storage: 'blob'
};
});
assets.sort((a, b) => (b.uploadedAt || '').localeCompare(a.uploadedAt || ''));
res.json(assets);
} catch (err) {
next(err);
}
});
app.post('/api/generate-image', async (req, res) => {
try {
const { type, title, description, template, promptOptions } = req.body || {};
if (!['cover', 'inline'].includes(type)) {
return res.status(400).json({ error: 'type must be "cover" or "inline"' });
}
if (!getApiKey()) {
return res.status(400).json({
code: 'API_KEY_MISSING',
error: 'AI 配图密钥未配置',
hint: '请在设置页面填写 imageGen.apiKey,或 export AGNES_API_KEY=sk-xxx 后重启服务'
});
}
const tpl = template || readConfig().default_template || 'minimal';
const opts = (promptOptions && typeof promptOptions === 'object') ? promptOptions : null;
const result = type === 'cover'
? await generateCover(title || 'untitled', description, tpl, opts)
: await generateInline(description || 'illustration', tpl, opts);
res.json({
ok: true,
type: result.type,
template: tpl,
path: result.path,
url: result.url,
storage: result.storage,
promptOptions: opts || null
});
} catch (err) {
res.status(500).json({ code: 'GENERATE_FAILED', error: err.message });
}
});
// ========== LLM Chat Endpoints ==========
const LLM_API_KEY = () => process.env.AGNES_API_KEY;
const LLM_BASE_URL = () => 'https://apihub.agnes-ai.com/v1';
const LLM_MODEL = () => 'agnes-2.0-flash';
app.post('/api/chat/stream', async (req, res) => {
try {
const { messages, skill } = req.body || {};
const apiKey = LLM_API_KEY();
if (!apiKey) {
return res.status(503).json({ error: 'AGNES not configured — set AGNES_API_KEY env var', code: 'AGNES_NOT_CONFIGURED' });
}
const baseUrl = LLM_BASE_URL();
const model = LLM_MODEL();
const systemPrompts = {
chat: '你是一个有用的写作助手。请用中文回答。',
polish: '你是一个文字润色助手。请改进给定文本,保持原意不变。只返回润色后的文本,不要加解释。',
research: '你是一个研究助手。请围绕给定主题提供关键要点和见解,用要点列表形式返回。'
};
const sysContent = systemPrompts[skill] || systemPrompts.chat;
const allMessages = [{ role: 'system', content: sysContent }, ...(messages || [])];
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders();
const response = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({ model, messages: allMessages, stream: true })
});
if (!response.ok) {
const errBody = await response.text().catch(() => '');
const msg = `LLM API error: ${response.status}${errBody ? ' - ' + errBody.slice(0,200) : ''}`;
res.write(`data: ${JSON.stringify({ error: msg })}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6).trim();
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content || '';
if (content) {
res.write(`data: ${JSON.stringify({ content })}\n\n`);
}
} catch (e) { /* skip malformed chunks */ }
}
}
res.write('data: [DONE]\n\n');
res.end();
} catch (err) {
console.error('[chat/stream]', err);
if (!res.headersSent) return res.status(503).json({ error: err.message });
try {
res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
} catch (_) { /* ignore */ }
}
});
app.post('/api/chat/skills/polish', async (req, res) => {
try {
const { text } = req.body || {};
if (!text) return res.status(400).json({ error: 'text required' });
const apiKey = LLM_API_KEY();
if (!apiKey) return res.status(503).json({ error: 'LLM not configured', code: 'LLM_NOT_CONFIGURED' });
const response = await fetch(`${LLM_BASE_URL()}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
model: LLM_MODEL(),
messages: [
{ role: 'system', content: '你是一个文字润色助手。改进给定文本,保持原意,只返回润色结果。' },
{ role: 'user', content: text }
]
})
});
if (!response.ok) {
const errBody = await response.text().catch(() => '');
return res.status(502).json({ error: `LLM API error: ${response.status}`, detail: errBody.slice(0,200) });
}
const data = await response.json();
const polished = data.choices?.[0]?.message?.content || text;
res.json({ ok: true, result: polished });
} catch (err) {
res.status(503).json({ error: err.message });
}
});
app.post('/api/chat/skills/research', async (req, res) => {
try {
const { topic } = req.body || {};
if (!topic) return res.status(400).json({ error: 'topic required' });
const apiKey = LLM_API_KEY();
if (!apiKey) return res.status(503).json({ error: 'LLM not configured', code: 'LLM_NOT_CONFIGURED' });
const response = await fetch(`${LLM_BASE_URL()}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
model: LLM_MODEL(),
messages: [
{ role: 'system', content: '你是一个研究助手。围绕给定主题提供关键要点,用编号列表返回,每行一个要点。' },
{ role: 'user', content: topic }
]
})
});
if (!response.ok) {
const errBody = await response.text().catch(() => '');
return res.status(502).json({ error: `LLM API error: ${response.status}`, detail: errBody.slice(0,200) });
}
const data = await response.json();
const result = data.choices?.[0]?.message?.content || '';
res.json({ ok: true, result });
} catch (err) {
res.status(503).json({ error: err.message });
}
});
app.get('/api/prompt-presets', (req, res) => {
res.json({ presets: PROMPT_PRESETS });
});
function isoDate(d) {
return d.toISOString().slice(0, 10);
}
function isValidDate(s) {
return typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && !isNaN(new Date(s).getTime());
}
function resolveStatsRange(query) {
const today = new Date();
today.setUTCHours(0, 0, 0, 0);
if (query.start && query.end) {
if (!isValidDate(query.start) || !isValidDate(query.end)) {
const err = new Error('start/end must be YYYY-MM-DD');
err.status = 400;
throw err;
}
if (query.start > query.end) {
const err = new Error('start must be on or before end');
err.status = 400;
throw err;
}
return { start: query.start, end: query.end };
}
const days = Math.max(1, Math.min(365, parseInt(query.days, 10) || 7));
const end = isoDate(today);
const start = new Date(today.getTime() - (days - 1) * 86400000);
return { start: isoDate(start), end };
}
app.get('/api/stats', async (req, res, next) => {