-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathserver.js
More file actions
3512 lines (3271 loc) · 133 KB
/
Copy pathserver.js
File metadata and controls
3512 lines (3271 loc) · 133 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 { fork } = require('child_process');
const compression = require('compression');
const fetcher = require('./lib/fetcher');
const deepseek = require('./lib/deepseek');
const { requestAiConfig } = require('./lib/request-ai-config');
const store = require('./lib/store');
const app = express();
app.disable('x-powered-by');
const PORT = process.env.PORT || 8080;
const HOST = process.env.HOST || '0.0.0.0';
const MINUTE_MS = 60 * 1000;
const HOUR_MS = 60 * MINUTE_MS;
const DAILY_REFRESH_HOUR_SHANGHAI = 8;
const STARTUP_REFRESH_DELAY_MS = parseInt(process.env.STARTUP_REFRESH_DELAY_MS || '30000', 10);
const SOURCE_INTERACTION_REFRESH_COOLDOWN_MS = parseInt(process.env.SOURCE_INTERACTION_REFRESH_COOLDOWN_MS || `${5 * MINUTE_MS}`, 10);
const FRESHNESS_SWEEP_INTERVAL_MS = parseInt(process.env.FRESHNESS_SWEEP_INTERVAL_MS || `${5 * MINUTE_MS}`, 10);
const FRESHNESS_STARTUP_DELAY_MS = parseInt(process.env.FRESHNESS_STARTUP_DELAY_MS || `${2 * MINUTE_MS}`, 10);
const FRESHNESS_SWEEP_BATCH_SIZE = parseInt(process.env.FRESHNESS_SWEEP_BATCH_SIZE || '3', 10);
const FRESHNESS_SWEEP_MAX_COST = parseInt(process.env.FRESHNESS_SWEEP_MAX_COST || '6', 10);
const NEWS_REFRESH_INTERVAL_MS = parseInt(process.env.NEWS_REFRESH_INTERVAL_MS || `${30 * MINUTE_MS}`, 10);
const ARTICLE_REFRESH_INTERVAL_MS = parseInt(process.env.ARTICLE_REFRESH_INTERVAL_MS || `${2 * HOUR_MS}`, 10);
const PODCAST_REFRESH_INTERVAL_MS = parseInt(process.env.PODCAST_REFRESH_INTERVAL_MS || `${6 * HOUR_MS}`, 10);
const TITLE_TRANSLATION_LIMIT = parseInt(process.env.TITLE_TRANSLATION_LIMIT || '80', 10);
const AUTO_REWRITE_SOURCE_IDS = new Set(String(process.env.AUTO_REWRITE_SOURCE_IDS || '')
.split(',')
.map(id => id.trim())
.filter(Boolean));
const SESSION_COOKIE = 'qm_session';
const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;
const INDEX_PATH = path.join(__dirname, 'public', 'index.html');
const DOMPURIFY_PATH = require.resolve('dompurify/dist/purify.min.js');
const DOMPURIFY_VERSION = JSON.parse(fs.readFileSync(
path.join(path.dirname(require.resolve('dompurify')), '..', 'package.json'),
'utf8',
)).version;
const REFRESH_WORKER_PATH = path.join(__dirname, 'scripts', 'refresh-worker.js');
const DEFAULT_TITLE = 'QMReader · RSS 阅读器';
const DEFAULT_DESCRIPTION = '围绕 RSS 文章沉淀中文翻译、乔木风格重写、人工点评和文章对话的公开阅读站。';
const HTML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
const UMAMI_WEBSITE_ID = String(process.env.UMAMI_WEBSITE_ID || '').trim();
const UMAMI_SRC = String(process.env.UMAMI_SRC || 'https://umami.qiaomu.ai/script.js').trim();
const ARTICLE_SHORT_ID_LENGTH = 12;
const ASSET_DIRECTORY_META = {
translation: {
label: '中文翻译',
description: 'QMReader 已沉淀中文双语对照翻译的公开 RSS 文章目录。',
},
rewrite: {
label: '乔木风格重写',
description: 'QMReader 已沉淀乔木风格中文重写的公开 RSS 文章目录。',
},
comments: {
label: '人工点评',
description: 'QMReader 已沉淀人工点评的公开 RSS 文章目录。',
},
annotations: {
label: '划线点评',
description: 'QMReader 已沉淀文章划线点评和段落讨论的公开 RSS 文章目录。',
},
chat: {
label: '文章对话',
description: 'QMReader 已沉淀公开 AI 文章对话的 RSS 文章目录。',
},
};
app.set('trust proxy', 1);
app.use(compression());
app.use(express.json({ limit: '2mb' }));
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
const unsafe = !['GET', 'HEAD', 'OPTIONS'].includes(req.method);
if (!unsafe) return next();
if (String(req.get('sec-fetch-site') || '').toLowerCase() === 'cross-site') {
return res.status(403).json({ error: '拒绝跨站操作' });
}
const origin = String(req.get('origin') || '').trim();
if (!origin) return next();
try {
if (new URL(origin).host !== req.get('host')) return res.status(403).json({ error: '拒绝跨站操作' });
} catch {
return res.status(403).json({ error: '请求来源无效' });
}
return next();
});
app.use((req, res, next) => {
try {
req.user = store.getUserBySessionToken(cookieValue(req, SESSION_COOKIE));
} catch (error) {
console.warn('Session lookup skipped:', error.message || error);
req.user = null;
}
next();
});
let refreshing = false;
let refreshProgress = { done: 0, total: 0 };
let refreshWorker = null;
let refreshJob = null;
let refreshLast = null;
let aiWorker = null;
let aiJob = null;
let aiLast = null;
const aiQueuedSourceIds = new Set();
let autoRewriteRunning = false;
let autoRewriteLast = null;
const sourceInteractionRefreshAt = new Map();
const faviconCache = new Map();
const faviconInFlight = new Map();
const FAVICON_MAX_BYTES = 256 * 1024;
const FAVICON_CACHE_MAX_ENTRIES = 512;
const FAVICON_TOTAL_TIMEOUT_MS = 6000;
const FAVICON_MAX_INFLIGHT = 64;
const RATE_LIMIT_MAX_BUCKETS = 2048;
function createRateLimiter({ windowMs, max, message, key: keyForRequest = null }) {
const buckets = new Map();
return (req, res, next) => {
const now = Date.now();
const key = String(
typeof keyForRequest === 'function'
? keyForRequest(req)
: (req.ip || req.socket.remoteAddress || 'unknown')
);
let bucket = buckets.get(key);
if (!bucket || now - bucket.startedAt >= windowMs) {
if (!bucket && buckets.size >= RATE_LIMIT_MAX_BUCKETS) {
buckets.delete(buckets.keys().next().value);
}
bucket = { startedAt: now, count: 0 };
buckets.set(key, bucket);
}
bucket.count += 1;
if (bucket.count <= max) return next();
const retryAfter = Math.max(1, Math.ceil((bucket.startedAt + windowMs - now) / 1000));
res.setHeader('Retry-After', String(retryAfter));
return res.status(429).json({ error: message || '请求过于频繁,请稍后再试' });
};
}
const submitLinkRateLimit = createRateLimiter({
windowMs: 60 * 60 * 1000,
max: 6,
message: '每小时最多收录 6 个链接,请稍后再试',
key: req => `user:${req.user && req.user.id || 'anonymous'}`,
});
const submitLinkDailyRateLimit = createRateLimiter({
windowMs: 24 * 60 * 60 * 1000,
max: 20,
message: '每天最多收录 20 个链接,请明天再试',
key: req => `user:${req.user && req.user.id || 'anonymous'}`,
});
const registerRateLimit = createRateLimiter({
windowMs: 60 * 60 * 1000,
max: 5,
message: '该网络注册账号过于频繁,请稍后再试',
});
const loginRateLimit = createRateLimiter({
windowMs: 15 * 60 * 1000,
max: 30,
message: '登录尝试过于频繁,请稍后再试',
});
const originalFetchRateLimit = createRateLimiter({
windowMs: 10 * 60 * 1000,
max: 20,
message: '原文抓取过于频繁,请稍后再试',
});
const faviconRateLimit = createRateLimiter({
windowMs: 10 * 60 * 1000,
max: 240,
message: '图标请求过于频繁,请稍后再试',
});
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, char => HTML_ESCAPES[char]);
}
function safeJsonForHtml(value) {
const escapes = {
'<': '\\u003c',
'>': '\\u003e',
'&': '\\u0026',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
};
return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, char => escapes[char]);
}
function normalizeFaviconTarget(value) {
try {
const parsed = new URL(String(value || '').trim());
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
return parsed.origin;
} catch {
return null;
}
}
function fallbackFaviconPng() {
return Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64');
}
function faviconCandidates(target, size) {
const encoded = encodeURIComponent(target);
return [
`https://www.google.com/s2/favicons?domain_url=${encoded}&sz=${size}`,
`${target}/favicon.ico`,
`${target}/apple-touch-icon.png`,
`${target}/apple-touch-icon-precomposed.png`,
];
}
async function fetchFaviconCandidate(url, deadline) {
try {
const result = await fetcher.fetchPublicBuffer(url, {
deadline,
maxBytes: FAVICON_MAX_BYTES,
maxRedirects: 4,
headers: { 'User-Agent': 'QMReader favicon proxy/1.0' },
});
if (result.status < 200 || result.status >= 300) return null;
const type = fetcher.safeRasterMimeType(result.buffer);
return type ? { buffer: result.buffer, type } : null;
} catch {
return null;
}
}
function cacheFavicon(cacheKey, value) {
faviconCache.delete(cacheKey);
faviconCache.set(cacheKey, value);
while (faviconCache.size > FAVICON_CACHE_MAX_ENTRIES) {
faviconCache.delete(faviconCache.keys().next().value);
}
}
function sendFavicon(res, value) {
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('Content-Security-Policy', 'sandbox');
res.setHeader('X-Content-Type-Options', 'nosniff');
return res.type(value.type).send(value.buffer);
}
async function loadFavicon(target, size) {
const fallback = { buffer: fallbackFaviconPng(), type: 'image/png' };
const deadline = Date.now() + FAVICON_TOTAL_TIMEOUT_MS;
let safeTarget;
try {
safeTarget = new URL(await fetcher.assertPublicHttpUrl(target, { deadline })).origin;
} catch {
return fallback;
}
for (const url of faviconCandidates(safeTarget, size)) {
if (Date.now() >= deadline) break;
const result = await fetchFaviconCandidate(url, deadline);
if (result) return result;
}
return fallback;
}
function jsonLdScript(value) {
if (!value) return '';
return `<script type="application/ld+json">${safeJsonForHtml(value)}</script>`;
}
function clipText(value, max = 180) {
const text = String(value || '')
.replace(/!\[[^\]]*]\([^)]*\)/g, ' ')
.replace(/\[([^\]]+)]\([^)]*\)/g, '$1')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/[#>*_`~]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (text.length <= max) return text;
return `${text.slice(0, max - 1).trim()}…`;
}
function slugifyForUrl(value, fallback = 'article') {
const slug = String(value || '')
.normalize('NFKC')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/&/g, ' and ')
.replace(/['’"“”‘]/g, '')
.replace(/[^\p{Letter}\p{Number}]+/gu, '-')
.replace(/^-+|-+$/g, '')
.replace(/-{2,}/g, '-')
.slice(0, 80)
.replace(/-+$/g, '');
return slug || fallback;
}
function entrySlug(entry) {
const fallback = slugifyForUrl(entry && entry.id, 'article');
return slugifyForUrl(entry && (entry.titleZh || entry.title || entry.id), fallback);
}
function entryShortId(entryOrId) {
const id = typeof entryOrId === 'string' ? entryOrId : entryOrId && entryOrId.id;
return String(id || '').trim().slice(0, ARTICLE_SHORT_ID_LENGTH);
}
function encodePathSegment(value) {
return encodeURIComponent(String(value || '').trim());
}
function entryArticleLocator(entry) {
const shortId = entryShortId(entry);
return `${entrySlug(entry)}--${shortId}`;
}
function decodePathSegment(value) {
try {
return decodeURIComponent(value).trim();
} catch {
return String(value || '').trim();
}
}
function splitArticleLocator(locator) {
const value = String(locator || '').trim();
const marker = value.lastIndexOf('--');
if (marker <= 0) return null;
const slug = value.slice(0, marker).replace(/^-+|-+$/g, '');
const shortId = value.slice(marker + 2).trim();
if (!slug || shortId.length < 6) return null;
return { slug, shortId };
}
function translationBlockText(pair) {
if (!pair) return '';
return String(pair.target || '').trim() || clipText(pair.targetHtml || '', 240);
}
function publicUrl(req, target = req.originalUrl || '/') {
const host = req.get('host') || 'rss.qiaomu.ai';
const proto = req.protocol || (req.get('x-forwarded-proto') || 'https').split(',')[0];
return `${proto}://${host}${target}`;
}
function absolutePublicUrl(req, value) {
if (!value) return '';
try {
return new URL(value, publicUrl(req, '/')).href;
} catch {
return '';
}
}
function normalizeAssetDirectoryType(value) {
return ASSET_DIRECTORY_META[value] ? value : '';
}
function requestAssetDirectoryType(req) {
const queryType = normalizeAssetDirectoryType(String(req.query.asset || ''));
if (queryType) return queryType;
const match = String(req.path || '').match(/^\/assets\/([^/.]+)\/?$/);
return normalizeAssetDirectoryType(match ? match[1] : '');
}
function requestAssetSort(req) {
return String(req.query.sort || '') === 'helpful' ? 'helpful' : 'latest';
}
function isAssetDirectoryRequest(req) {
if (String(req.query.view || '') === 'assets') return true;
return /^\/assets(?:\/[^/.]+)?\/?$/.test(String(req.path || ''));
}
function isContributorDirectoryRequest(req) {
return /^\/contributors\/?$/.test(String(req.path || ''));
}
function contributorIdFromRequest(req) {
const match = String(req.path || '').match(/^\/contributors\/([^/?#]+)\/?$/);
if (!match) return '';
try {
return decodeURIComponent(match[1]).trim();
} catch {
return String(match[1] || '').trim();
}
}
function articleRouteFromRequest(req) {
const match = String(req.path || '').match(/^\/articles\/(.+?)\/?$/);
if (!match) return null;
const segments = String(match[1] || '').split('/').filter(Boolean).map(decodePathSegment);
const first = segments[0] || '';
if (!first) return null;
const locator = splitArticleLocator(first);
if (locator) {
const focus = normalizeAssetDirectoryType(segments[1] || '');
return {
id: locator.shortId,
shortId: locator.shortId,
slug: locator.slug,
focus,
itemId: focus ? (segments[2] || '') : '',
legacy: false,
};
}
const id = first;
const raw = segments.slice(1);
let focus = '';
let itemId = '';
const firstAssetIndex = raw.findIndex(value => normalizeAssetDirectoryType(value));
let slug = raw[0] || '';
if (firstAssetIndex >= 0) {
focus = normalizeAssetDirectoryType(raw[firstAssetIndex]);
slug = raw.slice(0, firstAssetIndex).filter(Boolean).join('-');
itemId = raw[firstAssetIndex + 1] || '';
}
return { id, shortId: '', slug, focus, itemId, legacy: true };
}
function entryForArticleRoute(route, viewer = null) {
if (!route || !route.id) return null;
return route.shortId
? fetcher.getEntryByIdPrefix(route.shortId, viewer)
: fetcher.getEntryById(route.id, viewer);
}
function entryByIdOrPrefix(id, viewer = null) {
const clean = String(id || '').trim();
if (!clean) return null;
return fetcher.getEntryById(clean, viewer) || fetcher.getEntryByIdPrefix(clean, viewer);
}
function articleCanonicalPathForRoute(entry, route, { includeHash = false } = {}) {
if (!entry) return '/';
return entryPublicPath(entry, route && route.focus, route && route.itemId, { includeHash });
}
function normalizePathForCompare(value) {
const path = String(value || '').replace(/\/+$/, '');
return path || '/';
}
function requestAssetItemId(req, focus = '') {
const assetFocus = normalizeAssetDirectoryType(focus);
const articleRoute = articleRouteFromRequest(req);
if (articleRoute && articleRoute.focus === assetFocus && articleRoute.itemId) return articleRoute.itemId;
if (assetFocus === 'translation' || assetFocus === 'rewrite') return String(req.query.assetId || '').trim();
if (assetFocus === 'comments') return String(req.query.comment || '').trim();
if (assetFocus === 'annotations') return String(req.query.annotation || '').trim();
if (assetFocus === 'chat') return String(req.query.chat || '').trim();
return '';
}
function requestAssetFocus(req) {
const articleRoute = articleRouteFromRequest(req);
if (articleRoute && articleRoute.focus) return articleRoute.focus;
if (String(req.query.comment || '').trim()) return 'comments';
if (String(req.query.annotation || '').trim()) return 'annotations';
if (String(req.query.chat || '').trim()) return 'chat';
const focus = normalizeAssetDirectoryType(String(req.query.focus || ''));
if (focus) return focus;
const tab = String(req.query.tab || '');
if (tab === 'translation') return 'translation';
if (tab === 'rewrite') return 'rewrite';
return '';
}
function assetDirectoryMeta(req) {
if (!isAssetDirectoryRequest(req)) return null;
const type = requestAssetDirectoryType(req);
const sort = requestAssetSort(req);
const sortPrefix = sort === 'helpful' ? '有用 · ' : '';
const sortDescription = sort === 'helpful' ? '按读者“有用”反馈优先浏览。' : '';
const q = clipText(String(req.query.q || '').trim(), 48);
const stats = assetDirectoryStats(type, q);
const searchSuffix = stats.summary || '';
const latestSuffix = stats.latestText || '';
if (!type) {
if (q) {
return {
title: `${sortPrefix}公开资产搜索:${q} · QMReader`,
description: `搜索“${q}”相关的公开资产,包含中文翻译、乔木风格重写、划线点评、人工点评和文章对话。${sortDescription}${searchSuffix}`,
};
}
return {
title: stats.assetCount ? `${sortPrefix}公开资产(${stats.assetCount} 条) · QMReader` : `${sortPrefix}公开资产 · QMReader`,
description: stats.assetCount
? `QMReader 已沉淀 ${stats.assetCount} 条公开资产,覆盖 ${stats.entryCount} 篇文章,包括中文翻译、乔木风格重写、划线点评、人工点评和文章对话。${sortDescription}${latestSuffix}`
: DEFAULT_DESCRIPTION,
};
}
const meta = ASSET_DIRECTORY_META[type];
if (q) {
return {
title: `${sortPrefix}${meta.label}资产搜索:${q} · QMReader`,
description: `搜索“${q}”相关的${meta.label}资产。${sortDescription}${searchSuffix}`,
};
}
return {
title: stats.assetCount ? `${sortPrefix}${meta.label}资产(${stats.assetCount} 条) · QMReader` : `${sortPrefix}${meta.label}资产 · QMReader`,
description: stats.assetCount
? `QMReader 已沉淀 ${stats.assetCount} 条${meta.label}资产,覆盖 ${stats.entryCount} 篇文章,可通过网页或 RSS 浏览。${sortDescription}${latestSuffix}`
: meta.description,
};
}
function normalizeContributorSort(sort = '') {
return ['helpful', 'assets'].includes(String(sort || '').trim()) ? String(sort || '').trim() : 'latest';
}
function contributorDirectoryMeta(req = null) {
const sort = normalizeContributorSort(req && req.query && req.query.sort);
const contributors = store.getContributors({ limit: 200, sort });
const totalAssets = contributors.reduce((sum, contributor) => sum + Number(contributor.assetCount || 0), 0);
const totalHelpful = contributors.reduce((sum, contributor) => sum + Number(contributor.helpfulCount || 0), 0);
const latestAt = contributors.reduce((latest, contributor) => Math.max(latest, Number(contributor.latestAt) || 0), 0);
const helpfulSuffix = totalHelpful ? `获得 ${totalHelpful} 次有用反馈。` : '';
const sortTitle = sort === 'helpful' ? '有用贡献榜' : sort === 'assets' ? '高产贡献榜' : '公开贡献榜';
const sortDescription = sort === 'helpful'
? '当前按读者有用反馈排序。'
: sort === 'assets'
? '当前按公开资产数量排序。'
: '';
return {
contributors,
title: contributors.length ? `${sortTitle}(${contributors.length} 人) · QMReader` : `${sortTitle} · QMReader`,
description: contributors.length
? `QMReader 有 ${contributors.length} 位用户沉淀了 ${totalAssets} 条公开翻译、重写、划线点评、点评和文章对话。${helpfulSuffix}${sortDescription}${latestAt ? `最新更新 ${formatShanghaiMinute(latestAt)}。` : ''}`
: '浏览在 QMReader 沉淀过公开翻译、重写、划线点评、点评和文章对话的贡献榜。',
latestAt,
};
}
function contributorPageMeta(req) {
return contributorPageMetaForId(contributorIdFromRequest(req), {
type: normalizeAssetDirectoryType(String(req.query.type || req.query.asset || '')),
sort: String(req.query.sort || '') === 'helpful' ? 'helpful' : 'latest',
});
}
function contributorPageMetaForId(id, { type = '', sort = 'latest' } = {}) {
if (!id) return null;
const assetType = normalizeAssetDirectoryType(type);
const assetSort = sort === 'helpful' ? 'helpful' : 'latest';
const contributor = store.getContributor(id);
if (!contributor) return null;
const translations = store.getUserTranslations(id, { limit: 200 });
const rewrites = store.getUserRewrites(id, { limit: 200 });
const comments = store.getUserComments(id, { limit: 200 });
const annotations = store.getUserAnnotations(id, { limit: 200 });
const messages = store.getUserChatMessages(id, { limit: 200 });
const translationCount = translations.length;
const rewriteCount = rewrites.length;
const commentCount = comments.length;
const annotationCount = annotations.length;
const chatCount = messages.length;
const assetCount = translationCount + rewriteCount + annotationCount + commentCount + chatCount;
const typeCounts = { translation: translationCount, rewrite: rewriteCount, annotations: annotationCount, comments: commentCount, chat: chatCount };
const visibleAssetCount = assetType ? typeCounts[assetType] || 0 : assetCount;
const latestAt = Math.max(
translations.reduce((latest, item) => Math.max(latest, Number(item.updatedAt || item.createdAt) || 0), 0),
rewrites.reduce((latest, item) => Math.max(latest, Number(item.updatedAt || item.createdAt) || 0), 0),
annotations.reduce((latest, annotation) => Math.max(latest, Number(annotation.updatedAt || annotation.createdAt) || 0), 0),
comments.reduce((latest, comment) => Math.max(latest, Number(comment.updatedAt || comment.createdAt) || 0), 0),
messages.reduce((latest, message) => Math.max(latest, Number(message.createdAt) || 0), 0),
);
const typeLatestAt = assetType === 'translation'
? translations.reduce((latest, item) => Math.max(latest, Number(item.updatedAt || item.createdAt) || 0), 0)
: assetType === 'rewrite'
? rewrites.reduce((latest, item) => Math.max(latest, Number(item.updatedAt || item.createdAt) || 0), 0)
: assetType === 'annotations'
? annotations.reduce((latest, annotation) => Math.max(latest, Number(annotation.updatedAt || annotation.createdAt) || 0), 0)
: assetType === 'comments'
? comments.reduce((latest, comment) => Math.max(latest, Number(comment.updatedAt || comment.createdAt) || 0), 0)
: assetType === 'chat'
? messages.reduce((latest, message) => Math.max(latest, Number(message.createdAt) || 0), 0)
: latestAt;
const displayName = clipText(contributor.displayName || '读者', 48);
const typeMeta = assetType ? ASSET_DIRECTORY_META[assetType] : null;
const sortPrefix = assetSort === 'helpful' ? '有用 · ' : '';
const helpfulSentence = Number(contributor.helpfulCount || 0)
? `获得 ${Number(contributor.helpfulCount || 0)} 次有用反馈。`
: '';
const sortSentence = assetSort === 'helpful' ? '当前按读者有用反馈优先浏览。' : '';
const title = typeMeta
? `${sortPrefix}${displayName} 的${typeMeta.label}(${visibleAssetCount} 条) · QMReader`
: `${sortPrefix}${displayName} 的公开资产(${assetCount} 条) · QMReader`;
const description = typeMeta
? `${displayName} 在 QMReader 沉淀了 ${visibleAssetCount} 条${typeMeta.label}资产。${helpfulSentence}${sortSentence}${typeLatestAt ? `最新更新 ${formatShanghaiMinute(typeLatestAt)}。` : ''}`
: assetCount
? `${displayName} 在 QMReader 沉淀了 ${assetCount} 条公开资产,包括 ${translationCount} 条中文翻译、${rewriteCount} 条乔木风格重写、${annotationCount} 条划线点评、${commentCount} 条人工点评和 ${chatCount} 条文章对话。${helpfulSentence}${sortSentence}${latestAt ? `最新更新 ${formatShanghaiMinute(latestAt)}。` : ''}`
: `${displayName} 的 QMReader 个人主页。`;
return {
contributor: { ...contributor, displayName },
translations,
rewrites,
annotations,
comments,
messages,
translationCount,
rewriteCount,
annotationCount,
commentCount,
chatCount,
assetCount,
visibleAssetCount,
assetType,
assetSort,
latestAt: typeLatestAt || latestAt,
title,
description,
};
}
function assetDirectoryStats(type = '', q = '') {
const assetType = normalizeAssetDirectoryType(type);
const query = normalizeSearchText(q);
const entries = fetcher.getEntries({ limit: 1000 })
.filter(entry => entry && entry.id && hasPublicAssets(entry))
.filter(entry => !assetType || hasPublicAssetType(entry, assetType))
.filter(entry => !query || normalizeSearchText(entryDirectorySearchText(entry)).includes(query));
let assetCount = 0;
let latestAt = 0;
for (const entry of entries) {
assetCount += entryAssetCount(entry, assetType);
latestAt = Math.max(latestAt, entryAssetTypeTimestamp(entry, assetType));
}
const latestText = latestAt ? `最新更新 ${formatShanghaiMinute(latestAt)}。` : '';
const summary = assetCount ? `${assetCount} 条 · ${entries.length} 篇文章。${latestText}` : '';
return {
assetCount,
entryCount: entries.length,
latestAt,
latestText,
summary,
entries,
};
}
function entryAssetCount(entry, type = '') {
const assets = entry && entry.assets ? entry.assets : {};
if (type === 'translation') return aiAssetCount(assets, 'translation');
if (type === 'rewrite') return aiAssetCount(assets, 'rewrite');
if (type === 'comments') return Number(assets.comments) || 0;
if (type === 'annotations') return Number(assets.annotations) || 0;
if (type === 'chat') return Number(assets.chatMessages) || 0;
return Object.keys(ASSET_DIRECTORY_META).reduce((sum, itemType) => sum + entryAssetCount(entry, itemType), 0);
}
function aiAssetCount(assets, type) {
const count = Number(assets && assets[`${type}Count`]) || 0;
if (count) return count;
const items = assets && assets.items && Array.isArray(assets.items[type]) ? assets.items[type] : [];
if (items.length) return items.length;
return assets && assets[type] ? 1 : 0;
}
function entryDirectorySearchText(entry) {
const assets = entry && entry.assets ? entry.assets : {};
const parts = [entry.title, entry.titleZh, entry.summary, entry.summaryZh];
for (const preview of Object.values(assets.previews || {})) {
parts.push(preview.type, preview.author, preview.title, preview.model, preview.role, preview.text);
}
for (const items of Object.values(assets.items || {})) {
for (const item of items || []) parts.push(item.type, item.author, item.title, item.model, item.role, item.text);
}
return parts.filter(Boolean).join(' ');
}
function normalizeSearchText(value) {
return String(value || '').toLowerCase().replace(/\s+/g, ' ').trim();
}
function formatShanghaiMinute(timestamp) {
const t = Number(timestamp) || 0;
if (!t) return '';
try {
return new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(new Date(t));
} catch {
return '';
}
}
function socialMetaTags(req, entry) {
const directoryMeta = entry ? null : assetDirectoryMeta(req);
const contributorPage = !entry && !directoryMeta ? contributorPageMeta(req) : null;
const contributorMeta = !entry && !directoryMeta && !contributorPage && isContributorDirectoryRequest(req) ? contributorDirectoryMeta(req) : null;
const focus = entry ? requestAssetFocus(req) : '';
const title = entry
? entryShareTitle(entry, focus, req)
: (directoryMeta?.title || contributorPage?.title || contributorMeta?.title || DEFAULT_TITLE);
const description = entry
? entryShareDescription(entry, focus, req)
: clipText(directoryMeta?.description || contributorPage?.description || contributorMeta?.description || DEFAULT_DESCRIPTION);
const modifiedTime = entry
? entryShareModifiedTime(entry, focus, req)
: timestampIso(directoryMeta?.latestAt || contributorPage?.latestAt || contributorMeta?.latestAt);
const url = canonicalUrlForRequest(req, entry, focus);
const image = entry ? absolutePublicUrl(req, entry.image) : '';
const tags = [
`<meta name="description" content="${escapeHtml(description)}" />`,
shouldNoindexRequest(req, entry) ? `<meta name="robots" content="noindex,follow" />` : '',
`<link rel="canonical" href="${escapeHtml(url)}" />`,
`<meta property="og:site_name" content="QMReader" />`,
`<meta property="og:type" content="${entry ? 'article' : contributorPage ? 'profile' : 'website'}" />`,
`<meta property="og:title" content="${escapeHtml(title)}" />`,
`<meta property="og:description" content="${escapeHtml(description)}" />`,
`<meta property="og:url" content="${escapeHtml(url)}" />`,
`<meta name="twitter:card" content="${image ? 'summary_large_image' : 'summary'}" />`,
`<meta name="twitter:title" content="${escapeHtml(title)}" />`,
`<meta name="twitter:description" content="${escapeHtml(description)}" />`,
].filter(Boolean);
if (image) {
tags.push(`<meta property="og:image" content="${escapeHtml(image)}" />`);
tags.push(`<meta name="twitter:image" content="${escapeHtml(image)}" />`);
}
if (entry && entry.published) {
tags.push(`<meta property="article:published_time" content="${escapeHtml(entry.published)}" />`);
}
if (modifiedTime) {
if (entry) tags.push(`<meta property="article:modified_time" content="${escapeHtml(modifiedTime)}" />`);
tags.push(`<meta property="og:updated_time" content="${escapeHtml(modifiedTime)}" />`);
}
const structuredData = shareStructuredData(req, {
entry,
focus,
directoryMeta,
contributorPage,
title,
description,
modifiedTime,
image,
url,
});
if (structuredData) tags.push(jsonLdScript(structuredData));
return { title, tags: tags.join('\n ') };
}
function canonicalUrlForRequest(req, entry, focus = '') {
if (entry) {
const assetFocus = normalizeAssetDirectoryType(focus);
const itemId = requestAssetItemId(req, assetFocus);
if (assetFocus && itemId) {
return entryAssetItemUrl(req, entry, assetFocus, { id: itemId }, { includeHash: false });
}
return entryPublicUrl(req, entry, assetFocus);
}
if (isAssetDirectoryRequest(req)) return assetDirectoryUrl(req, requestAssetDirectoryType(req), requestAssetSort(req));
const contributorId = contributorIdFromRequest(req);
if (contributorId) return contributorPageUrl(req, contributorId);
if (isContributorDirectoryRequest(req)) {
const sort = normalizeContributorSort(req && req.query && req.query.sort);
const query = sort === 'latest' ? '' : `?sort=${encodeURIComponent(sort)}`;
return publicUrl(req, `/contributors${query}`);
}
return publicUrl(req, '/');
}
function shouldNoindexRequest(req, entry) {
if (String(req.query.q || '').trim()) return true;
if (entry && !hasPublicAssets(entry)) return true;
return false;
}
function shareStructuredData(req, { entry, focus, directoryMeta, contributorPage, title, description, modifiedTime, image, url }) {
if (entry) return entryStructuredData(req, entry, { focus, title, description, modifiedTime, image, url });
if (directoryMeta) return assetDirectoryStructuredData(req, directoryMeta, { title, description, url });
if (contributorPage) return contributorPageStructuredData(req, contributorPage, { title, description, url });
return {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: 'QMReader',
url,
description,
};
}
function contributorAssetStructuredItems(req, contributorPage) {
const translationItems = (contributorPage.translations || []).map(item => ({
type: 'translation',
id: item.id,
text: item.contentSnippet || item.summaryZh || '',
at: item.updatedAt || item.createdAt,
helpfulCount: Number(item.helpfulCount) || 0,
entry: item.entry,
}));
const rewriteItems = (contributorPage.rewrites || []).map(item => ({
type: 'rewrite',
id: item.id,
text: item.bodySnippet || '',
at: item.updatedAt || item.createdAt,
helpfulCount: Number(item.helpfulCount) || 0,
entry: item.entry,
}));
const commentItems = (contributorPage.comments || []).map(comment => ({
type: 'comments',
id: comment.id,
text: comment.bodySnippet || comment.body || '',
at: comment.updatedAt || comment.createdAt,
helpfulCount: Number(comment.helpfulCount) || 0,
entry: comment.entry,
}));
const annotationItems = (contributorPage.annotations || []).map(annotation => ({
type: 'annotations',
id: annotation.id,
text: `${annotation.quote || annotation.quoteSnippet || ''}\n${annotation.bodySnippet || annotation.body || ''}`,
at: annotation.updatedAt || annotation.createdAt,
helpfulCount: Number(annotation.helpfulCount) || 0,
entry: annotation.entry,
}));
const chatItems = (contributorPage.messages || []).map(message => ({
type: 'chat',
id: message.id,
text: message.contentSnippet || message.content || '',
at: message.createdAt,
helpfulCount: Number(message.helpfulCount) || 0,
entry: message.entry,
}));
return [...translationItems, ...rewriteItems, ...annotationItems, ...commentItems, ...chatItems]
.filter(item => item.entry && item.entry.id)
.filter(item => !contributorPage.assetType || item.type === contributorPage.assetType)
.sort((a, b) => {
if (contributorPage.assetSort === 'helpful') {
const helpfulDelta = Number(b.helpfulCount || 0) - Number(a.helpfulCount || 0);
if (helpfulDelta) return helpfulDelta;
}
return (Number(b.at) || 0) - (Number(a.at) || 0);
})
.slice(0, 10)
.map((item, index) => {
const label = ASSET_DIRECTORY_META[item.type]?.label || (item.type === 'chat' ? '文章对话' : '人工点评');
return {
'@type': 'ListItem',
position: index + 1,
url: entryAssetItemUrl(req, { id: item.entry.id }, item.type, item, { includeHash: false }),
name: `${label}:${clipText(item.entry.titleZh || item.entry.title || '文章', 90)}`,
description: clipText(item.text, 180),
dateModified: timestampIso(item.at) || undefined,
};
});
}
function contributorPageStructuredData(req, contributorPage, { title, description, url }) {
return {
'@context': 'https://schema.org',
'@type': 'ProfilePage',
name: title.replace(/\s·\sQMReader$/, ''),
description,
url,
isPartOf: siteStructuredData(req),
dateModified: timestampIso(contributorPage.latestAt) || undefined,
mainEntity: {
'@type': 'Person',
name: contributorPage.contributor.displayName || '读者',
identifier: contributorPage.contributor.id,
url,
},
hasPart: {
'@type': 'ItemList',
name: contributorPage.assetType ? `${ASSET_DIRECTORY_META[contributorPage.assetType].label}资产` : '公开资产',
numberOfItems: typeof contributorPage.visibleAssetCount === 'number'
? contributorPage.visibleAssetCount
: contributorPage.assetCount || 0,
itemListElement: contributorAssetStructuredItems(req, contributorPage),
},
};
}
function siteStructuredData(req) {
return {
'@type': 'WebSite',
name: 'QMReader',
url: publicUrl(req, '/'),
};
}
function assetDirectoryStructuredData(req, directoryMeta, { title, description, url }) {
const type = requestAssetDirectoryType(req);
const stats = directoryMeta.stats || assetDirectoryStats(type, String(req.query.q || '').trim());
const label = type ? `${ASSET_DIRECTORY_META[type].label}资产` : '公开资产';
const items = (stats.entries || [])
.flatMap(entry => {
const assets = entry.assets || {};
const previews = assets.previews || {};
const types = type ? [type] : publicAssetTypes(entry);
return types
.filter(itemType => hasPublicAssetType(entry, itemType))
.flatMap(itemType => assetFeedPreviews(entry, itemType, previews).map(preview => ({
entry,
type: itemType,
preview,
at: Number(preview.at) || entryAssetTypeTimestamp(entry, itemType),
})));
})
.sort((a, b) => Number(b.at || 0) - Number(a.at || 0))
.slice(0, 10);
return {
'@context': 'https://schema.org',
'@type': 'CollectionPage',
name: title.replace(/\s·\sQMReader$/, ''),
description,
url,
isPartOf: siteStructuredData(req),
dateModified: timestampIso(stats.latestAt) || undefined,
mainEntity: {
'@type': 'ItemList',
name: label,
numberOfItems: stats.assetCount || 0,
itemListElement: items.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
url: entryAssetItemUrl(req, item.entry, item.type, item.preview, { includeHash: false }),
name: assetFeedTitle(item.entry, item.type, item.preview),
description: clipText(item.preview && item.preview.text, 180),
dateModified: timestampIso(item.at) || entryAssetTypeLastModified(item.entry, item.type) || entryLastModified(item.entry) || undefined,
})),
},
};
}
function entryStructuredData(req, entry, { focus, title, description, modifiedTime, image, url }) {
const article = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: clipText(entry.titleZh || entry.title || title, 120),
alternativeHeadline: entry.titleZh && entry.title ? clipText(entry.title, 120) : undefined,
description,
url,
mainEntityOfPage: url,
datePublished: entry.published || undefined,
dateModified: modifiedTime || entryLastModified(entry) || entry.published || undefined,
image: image || undefined,
author: structuredAuthor(entry.author || sourceNameForEntry(entry) || 'QMReader'),
publisher: {
'@type': 'Organization',
name: 'QMReader',
url: publicUrl(req, '/'),
},
inLanguage: entry.titleZh || entry.summaryZh ? 'zh-CN' : undefined,
};
const part = entryAssetStructuredPart(req, entry, focus);
if (part) article.hasPart = part;
return article;
}
function entryAssetStructuredPart(req, entry, focus) {
const type = normalizeAssetDirectoryType(focus);
if (!type) return null;
const exactPreview = exactAssetPreview(entry, type, req);
const preview = exactPreview || entry.assets?.previews?.[type];
if (!preview || !preview.text) return null;
const itemUrl = entryAssetItemUrl(req, entry, type, preview);
const itemIdUrl = entryAssetItemUrl(req, entry, type, preview, { includeHash: false });
const base = {
'@id': `${itemIdUrl}#structured`,
name: assetShareIdentity(type, preview) || ASSET_DIRECTORY_META[type]?.label || '公开资产',
text: clipText(preview.text, 500),
url: itemUrl,
dateCreated: timestampIso(preview.at) || undefined,
dateModified: timestampIso(preview.at) || undefined,
author: structuredAuthor(preview.author || preview.model || 'QMReader'),
isPartOf: entryPublicUrl(req, entry),
};
if (type === 'comments' || type === 'annotations') return { '@type': 'Comment', ...base };
if (type === 'chat') {
const schemaType = preview.role === 'user' ? 'Question' : preview.role === 'assistant' ? 'Answer' : 'CreativeWork';
return { '@type': schemaType, ...base };
}
return {
'@type': 'CreativeWork',
...base,
about: ASSET_DIRECTORY_META[type]?.label || '公开资产',
};
}
function structuredAuthor(name) {
const text = clipText(name || 'QMReader', 80);
const isOrg = /ai|deepseek|openai|anthropic|claude|gemini|gpt|qmreader/i.test(text);
return {
'@type': isOrg ? 'Organization' : 'Person',
name: text,
};
}
function sourceNameForEntry(entry) {
const source = fetcher.getSourceById(entry && entry.sourceId);
return source ? source.name : '';
}