dsh-ustc-campus 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,7 +24,7 @@
24
24
  - **第二课堂(青春科大)**:可查报名中/已结束/已报名的活动(含报名人数/人数上限与剩余名额)、活动详情与现场签到要求、德智体美劳各模块学时与志愿签到记录,也可在对话中确认报名或取消常规活动(需额外填表的项目会引导至官网操作)。
25
25
  - **西区与高新园区图书馆研讨室**:支持西区图书馆与高新园区图书馆交流体验中心(`hs.lib.ustc.edu.cn`),可查询空间分类、开放时段、预约规则与实时占用情况,并按人数、时段与用途在对话中确认预约、取消及查看本人预约记录。
26
26
  - **校园班车**:覆盖校园班车(东/西/南/北)、高新园区(东/西/先研院/高新)、太湖路园区(东/太湖路)以及中区就近站点换乘建议,返回工作日与节假日时刻。
27
- - **公开资讯与也西书架**:整合新闻网、学校公告、教务处、学工、团委、图书馆与 LUG 动态,支持关键词筛选、排序与收藏为本地日程;也西书架支持按课号或课程名检索公开资料索引与原始出处链接。
27
+ - **公开资讯与也西书架**:整合 25 个科大官方公开资讯源(新闻网、科研进展、校级公告、教务/交流、学工、团委、图书馆与讲座、LUG 活动与新闻、网信/保卫/校医院/财务以及少院/AI/网安/计院/信院等学院通知);已登录学校账号时自动把青春科大「报名中二课活动」融合进推荐流,并支持按「活动 / 通知」筛选、接自定义 RSS / 静态 JSON 订阅源、本机个性化推荐排序(课表冷启动、浏览收藏反馈学习、跨源去重与多样性打散)及收藏为本地日程;也西书架支持按课号或课程名检索公开资料索引与原始出处链接。
28
28
 
29
29
  ## 功能与实测状态
30
30
 
@@ -44,7 +44,7 @@
44
44
  | **高新图书馆(只读)** | 静默登录、分类与房间占用、预约规则摘要、本人记录 | **已实测通过** | 已在并发查询下验证通过 |
45
45
  | **高新图书馆(预约/取消)** | 按房号对话确认预约与取消 | **仅离线测试** | 尚未用真实账号实际下单或取消 |
46
46
  | **校园班车** | 校园(东/西/南/北)、高新、太湖路班次与中区换乘 | **已实网核对** | 已实网解析校方官方时刻表核对 |
47
- | **公开资讯与也西书架** | 9 个官方资讯源检索、收藏活动、也西书架资料索引 | **已实网通过** | 全部公开源与桌面端检索收藏均验证通过 |
47
+ | **公开资讯与也西书架** | 25 个官方资讯源检索、个性化推荐与反馈、收藏活动、也西书架资料索引 | **已实网通过** | 全部 25 个公开源已实网验证,本地推荐算法通过单元测试与离线评测;桌面端检索收藏验证通过 |
48
48
  | **桌面端校园页 UI** | 侧栏界面与多宿主兼容 | **部分复测** | 主界面加载与对话工具已在 DeepSeek Harness 验证;词元工坊桌面端近期未复测 |
49
49
 
50
50
  ## 不做、受限与暂缓的功能
@@ -59,6 +59,7 @@
59
59
  | **受限 / 仅引导官网** | 需额外填表/传附件的二课活动、高新图书馆平面图选座与团队审核房间 | 交互或审批附件超出对话能力,附官方链接引导至网页办理 |
60
60
  | **受限 / 仅引导官网** | 国金院班车时刻 | 校方移动端班车时刻表未提供该线路 |
61
61
  | **受限 / 仅引导官网** | 自动完成学校二次验证(MFA) | 安全边界限制,遇验证时弹出官方页面由本人完成 |
62
+ | **受限 / 暂不内置** | 微信公众号文章直接抓取 | 微信公众平台为封闭系统,无免登录公开列表接口,本机临时抓取不可行;若由维护方搭服务器集中抓取又会引入强服务器依赖,且在 VPS 上长期挂个人微信号存在风控与账号安全顾虑。现优先融合青春科大二课活动池与校内官网,同时开放自定义 RSS / 外部静态 JSON 订阅入口供有自建源的同学自行接入 |
62
63
  | **当前暂缓** | 图书馆藏检索、我的图书馆借阅到期日查询与续借 | 官方入口已定位,后续按需接入 |
63
64
  | **当前暂缓** | 停调课独立通知、培养方案/毕业学分缺口、学籍变更 | 暂未接入 |
64
65
  | **当前暂缓** | 在读证明/电子证明/学位证明下载与申请 | 官方入口已定位,暂缓 |
package/package.json CHANGED
@@ -1,17 +1,45 @@
1
1
  {
2
2
  "name": "dsh-ustc-campus",
3
- "version": "0.2.14",
3
+ "version": "0.2.15",
4
4
  "description": "非官方科大校园工作台:在 DeepSeek Harness 中查询课表、作业、二课、图书馆与校园班车",
5
5
  "homepage": "https://github.com/TwinJades/dsh-ustc-campus#readme",
6
- "bugs": { "url": "https://github.com/TwinJades/dsh-ustc-campus/issues" },
7
- "repository": { "type": "git", "url": "git+https://github.com/TwinJades/dsh-ustc-campus.git" },
6
+ "bugs": {
7
+ "url": "https://github.com/TwinJades/dsh-ustc-campus/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/TwinJades/dsh-ustc-campus.git"
12
+ },
8
13
  "type": "module",
9
- "engines": { "node": ">=22.13.0", "dsh": ">=0.2.2-rc.2 <0.3.0" },
10
- "exports": { ".": "./src/host.mjs", "./tools": "./src/tools.mjs", "./mcp-host": "./src/mcp-host.mjs", "./client": "./dist/client.js", "./package.json": "./package.json" },
11
- "files": ["cordis.patch.yml", "src/*.mjs", "dist/client.js", "demo/demo.ics", "third_party/"],
14
+ "engines": {
15
+ "node": ">=22.13.0",
16
+ "dsh": ">=0.2.2-rc.2 <0.3.0"
17
+ },
18
+ "exports": {
19
+ ".": "./src/host.mjs",
20
+ "./tools": "./src/tools.mjs",
21
+ "./mcp-host": "./src/mcp-host.mjs",
22
+ "./client": "./dist/client.js",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "cordis.patch.yml",
27
+ "src/*.mjs",
28
+ "dist/client.js",
29
+ "demo/demo.ics",
30
+ "third_party/"
31
+ ],
12
32
  "dsh": {
13
- "bundle": { "patch": "./cordis.patch.yml" },
14
- "client": { "platform": "web", "inject": ["@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-sidebar"] }
33
+ "bundle": {
34
+ "patch": "./cordis.patch.yml"
35
+ },
36
+ "client": {
37
+ "platform": "web",
38
+ "inject": [
39
+ "@deepseek-ai/dsh-client-ui-layout",
40
+ "@deepseek-ai/dsh-client-ui-sidebar"
41
+ ]
42
+ }
15
43
  },
16
44
  "scripts": {
17
45
  "build": "node scripts/build.mjs",
@@ -19,6 +47,14 @@
19
47
  "test:campus": "node --test test/*.test.mjs",
20
48
  "smoke:upstreams": "node scripts/upstreams.mjs"
21
49
  },
22
- "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", "cheerio": "1.1.2", "ical.js": "2.2.1", "playwright-core": "1.65.1", "zod": "4.6.7" },
23
- "devDependencies": { "esbuild": "0.25.12" }
50
+ "dependencies": {
51
+ "@modelcontextprotocol/sdk": "1.32.2",
52
+ "cheerio": "1.1.2",
53
+ "ical.js": "2.2.1",
54
+ "playwright-core": "1.65.1",
55
+ "zod": "4.6.7"
56
+ },
57
+ "devDependencies": {
58
+ "esbuild": "0.25.12"
59
+ }
24
60
  }
@@ -0,0 +1,516 @@
1
+ import { isIP } from 'node:net';
2
+ import { load } from 'cheerio';
3
+
4
+ import {
5
+ errorText,
6
+ safeHttpUrl,
7
+ sanitizeText,
8
+ shanghaiEpoch
9
+ } from './public-fetch.mjs';
10
+
11
+ const STORE_KEY = 'custom-feeds';
12
+ const STORE_VERSION = 1;
13
+ const STALE_MS = 6 * 60 * 60 * 1000;
14
+ const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000;
15
+ const FETCH_TIMEOUT_MS = 10_000;
16
+ const MAX_SUBSCRIPTIONS = 15;
17
+ const MAX_ITEMS_PER_SOURCE = 100;
18
+ const MAX_BODY_BYTES = 1024 * 1024;
19
+ const MAX_REDIRECTS = 4;
20
+ const REFRESH_CONCURRENCY = 4;
21
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
22
+
23
+ export class CustomFeedError extends Error {}
24
+
25
+ function isPrivateOrBlockedHost(hostname) {
26
+ const host = String(hostname ?? '').toLowerCase().replace(/^\[|\]$/g, '');
27
+ if (!host) return true;
28
+ if (
29
+ host === 'localhost' ||
30
+ host.endsWith('.localhost') ||
31
+ host.endsWith('.local') ||
32
+ host.endsWith('.internal') ||
33
+ host.endsWith('.lan') ||
34
+ host.endsWith('.home') ||
35
+ host.endsWith('.arpa')
36
+ ) {
37
+ return true;
38
+ }
39
+ if (isIP(host) !== 0) return true;
40
+ return false;
41
+ }
42
+
43
+ /** Validate a user-configured RSS/Atom/JSON subscription URL (HTTPS public host only). */
44
+ export function validateCustomFeedUrl(rawUrl) {
45
+ if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
46
+ throw new CustomFeedError('请提供订阅地址(https:// 开头)。');
47
+ }
48
+ const trimmed = rawUrl.trim();
49
+ if (trimmed.length > 500 || /[\u0000-\u001f\u007f]/.test(trimmed)) {
50
+ throw new CustomFeedError('订阅地址格式无效。');
51
+ }
52
+ let parsed;
53
+ try {
54
+ parsed = new URL(trimmed);
55
+ } catch {
56
+ throw new CustomFeedError('订阅地址不是有效的网址。');
57
+ }
58
+ if (parsed.protocol !== 'https:') {
59
+ throw new CustomFeedError('自定义订阅仅支持 https:// 安全连接。');
60
+ }
61
+ if (parsed.username || parsed.password) {
62
+ throw new CustomFeedError('订阅地址不能包含账号或密码。');
63
+ }
64
+ if (isPrivateOrBlockedHost(parsed.hostname)) {
65
+ throw new CustomFeedError('不允许订阅本机或内网地址。');
66
+ }
67
+ return parsed.href;
68
+ }
69
+
70
+ function hashId(value) {
71
+ let hash = 0x811c9dc5;
72
+ const text = String(value);
73
+ for (let i = 0; i < text.length; i += 1) {
74
+ hash ^= text.charCodeAt(i);
75
+ hash = Math.imul(hash, 0x01000193);
76
+ }
77
+ return (hash >>> 0).toString(36);
78
+ }
79
+
80
+ function shanghaiDateFromEpoch(epochMs) {
81
+ if (!Number.isFinite(epochMs)) return null;
82
+ const d = new Date(epochMs + 8 * 60 * 60 * 1000);
83
+ const y = d.getUTCFullYear();
84
+ const m = String(d.getUTCMonth() + 1).padStart(2, '0');
85
+ const day = String(d.getUTCDate()).padStart(2, '0');
86
+ if (y < 1970 || y > 2100) return null;
87
+ return `${y}-${m}-${day}`;
88
+ }
89
+
90
+ function parseDateValue(raw) {
91
+ if (raw == null) return null;
92
+ if (Number.isFinite(raw)) {
93
+ const date = shanghaiDateFromEpoch(raw);
94
+ return date ? { date, epoch: raw } : null;
95
+ }
96
+ const text = sanitizeText(String(raw), 100);
97
+ if (!text) return null;
98
+
99
+ const ymd = text.match(/(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?/);
100
+ if (ymd) {
101
+ const epoch = shanghaiEpoch(Number(ymd[1]), Number(ymd[2]), Number(ymd[3]));
102
+ if (epoch != null) {
103
+ return {
104
+ date: `${ymd[1]}-${String(ymd[2]).padStart(2, '0')}-${String(ymd[3]).padStart(2, '0')}`,
105
+ epoch
106
+ };
107
+ }
108
+ }
109
+
110
+ const parsed = Date.parse(text);
111
+ if (Number.isFinite(parsed)) {
112
+ const date = shanghaiDateFromEpoch(parsed);
113
+ if (date) return { date, epoch: parsed };
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function safeItemLink(raw, origin) {
119
+ const href = safeHttpUrl(raw, origin);
120
+ if (!href) return null;
121
+ try {
122
+ const host = new URL(href).hostname;
123
+ if (isPrivateOrBlockedHost(host)) return null;
124
+ } catch {
125
+ return null;
126
+ }
127
+ return href;
128
+ }
129
+
130
+ function resolveIntent(rawIntent, defaultIntent) {
131
+ if (rawIntent === 'activity' || rawIntent === 'notice') return rawIntent;
132
+ if (defaultIntent === 'activity' || defaultIntent === 'notice') return defaultIntent;
133
+ return undefined;
134
+ }
135
+
136
+ /** Parse RSS 2.0, Atom XML, or static JSON feed content into normalized campus feed items. */
137
+ export function parseCustomFeedContent(body, subscription, nowMs = Date.now()) {
138
+ const rawText = typeof body === 'string' ? body : JSON.stringify(body ?? '');
139
+ const trimmed = rawText.trim();
140
+ if (!trimmed) throw new Error('订阅返回内容为空');
141
+
142
+ const sourceOrigin = new URL(subscription.url).origin;
143
+ const format = subscription.format === 'json' || subscription.format === 'xml'
144
+ ? subscription.format
145
+ : (trimmed.startsWith('{') || trimmed.startsWith('[') ? 'json' : 'xml');
146
+
147
+ const items = [];
148
+ const seen = new Set();
149
+
150
+ if (format === 'json') {
151
+ let parsed;
152
+ try {
153
+ parsed = JSON.parse(trimmed);
154
+ } catch {
155
+ throw new Error('JSON 订阅内容解析失败');
156
+ }
157
+ const list = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.items) ? parsed.items : null);
158
+ if (!list) throw new Error('JSON 订阅缺少 items 数组');
159
+
160
+ for (const entry of list.slice(0, MAX_ITEMS_PER_SOURCE)) {
161
+ if (!entry || typeof entry !== 'object') continue;
162
+ const title = sanitizeText(String(entry.title ?? ''), 500);
163
+ if (!title) continue;
164
+ const url = entry.url ? safeItemLink(String(entry.url), sourceOrigin) : (entry.link ? safeItemLink(String(entry.link), sourceOrigin) : null);
165
+ const start = Number.isFinite(entry.start) ? entry.start : null;
166
+ const end = Number.isFinite(entry.end) && entry.end >= (start ?? 0) ? entry.end : null;
167
+ const dateParsed = parseDateValue(entry.date ?? entry.publishedAt ?? start);
168
+ const date = dateParsed?.date ?? shanghaiDateFromEpoch(nowMs);
169
+ const idBase = sanitizeText(String(entry.id ?? ''), 120) || hashId(`${url ?? ''}|${date ?? ''}|${title}`);
170
+ const id = `${subscription.id}:${idBase}`.slice(0, 200);
171
+ if (seen.has(id)) continue;
172
+ seen.add(id);
173
+
174
+ const intent = resolveIntent(entry.intent, subscription.defaultIntent);
175
+ items.push({
176
+ id,
177
+ source: subscription.id,
178
+ category: subscription.category || 'activity',
179
+ ...(intent ? { intent } : {}),
180
+ ...(entry.requiresRegistration === true ? { requiresRegistration: true } : {}),
181
+ title,
182
+ url,
183
+ date,
184
+ time: entry.time ? sanitizeText(String(entry.time), 40) : null,
185
+ location: entry.location ? sanitizeText(String(entry.location), 300) : null,
186
+ start,
187
+ end,
188
+ secondClassroom: entry.secondClassroom === true,
189
+ ...(entry.organizer ? { organizer: sanitizeText(String(entry.organizer), 120) } : {}),
190
+ reason: '',
191
+ past: false
192
+ });
193
+ }
194
+ return items;
195
+ }
196
+
197
+ // XML mode (RSS 2.0 <item> or Atom <entry>)
198
+ const $ = load(trimmed, { xmlMode: true });
199
+ const rssItems = $('item').toArray();
200
+ const atomEntries = rssItems.length === 0 ? $('entry').toArray() : [];
201
+ const nodes = rssItems.length > 0 ? rssItems : atomEntries;
202
+ if (nodes.length === 0 && !/<(?:rss|feed|channel)\b/i.test(trimmed)) {
203
+ throw new Error('无法识别的 RSS / Atom 订阅格式');
204
+ }
205
+
206
+ for (const node of nodes.slice(0, MAX_ITEMS_PER_SOURCE)) {
207
+ const el = $(node);
208
+ const title = sanitizeText(el.children('title').first().text(), 500);
209
+ if (!title) continue;
210
+
211
+ let rawLink = sanitizeText(el.children('link').first().text(), 500);
212
+ if (!rawLink) {
213
+ const linkAttr = el.children('link[rel="alternate"]').first().attr('href')
214
+ || el.children('link[href]').first().attr('href');
215
+ rawLink = linkAttr ? linkAttr.trim() : '';
216
+ }
217
+ const url = rawLink ? safeItemLink(rawLink, sourceOrigin) : null;
218
+
219
+ const rawDate = el.children('pubDate, published, updated, dc\\:date, date').first().text();
220
+ const dateParsed = parseDateValue(rawDate);
221
+ const date = dateParsed?.date ?? shanghaiDateFromEpoch(nowMs);
222
+
223
+ const guid = sanitizeText(el.children('guid, id').first().text(), 140);
224
+ const key = guid ? hashId(guid) : hashId(`${url ?? ''}|${date ?? ''}|${title}`);
225
+ const id = `${subscription.id}:${key}`.slice(0, 200);
226
+ if (seen.has(id)) continue;
227
+ seen.add(id);
228
+
229
+ const intent = resolveIntent(undefined, subscription.defaultIntent);
230
+ items.push({
231
+ id,
232
+ source: subscription.id,
233
+ category: subscription.category || 'activity',
234
+ ...(intent ? { intent } : {}),
235
+ title,
236
+ url,
237
+ date,
238
+ time: null,
239
+ location: null,
240
+ start: null,
241
+ end: null,
242
+ secondClassroom: false,
243
+ reason: '',
244
+ past: false
245
+ });
246
+ }
247
+ return items;
248
+ }
249
+
250
+ async function fetchSafeCustomBody(startUrl, fetchImpl, signal) {
251
+ let currentUrl = validateCustomFeedUrl(startUrl);
252
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
253
+ const timeoutSignal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
254
+ const combined = signal && typeof AbortSignal.any === 'function'
255
+ ? AbortSignal.any([timeoutSignal, signal])
256
+ : timeoutSignal;
257
+
258
+ const response = await fetchImpl(currentUrl, {
259
+ redirect: 'manual',
260
+ signal: combined,
261
+ headers: {
262
+ accept: 'application/rss+xml, application/atom+xml, application/xml, application/json, text/xml;q=0.9, */*;q=0.5',
263
+ 'user-agent': 'dsh-ustc-campus/0.2'
264
+ }
265
+ });
266
+
267
+ if (REDIRECT_STATUSES.has(response.status)) {
268
+ const loc = response.headers?.get?.('location');
269
+ if (!loc) throw new Error('订阅重定向缺少目标地址');
270
+ currentUrl = validateCustomFeedUrl(new URL(loc, currentUrl).href);
271
+ continue;
272
+ }
273
+
274
+ if (!response.ok) {
275
+ throw new Error(`订阅返回状态 ${response.status}`);
276
+ }
277
+
278
+ const text = await response.text();
279
+ if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > MAX_BODY_BYTES) {
280
+ throw new Error('订阅内容超过 1 MiB 限制');
281
+ }
282
+ return text;
283
+ }
284
+ throw new Error('订阅重定向次数过多');
285
+ }
286
+
287
+ function emptyStore() {
288
+ return { version: STORE_VERSION, subscriptions: {} };
289
+ }
290
+
291
+ function loadStore(read) {
292
+ const out = emptyStore();
293
+ let raw;
294
+ try {
295
+ raw = read(STORE_KEY);
296
+ } catch {
297
+ return out;
298
+ }
299
+ if (!raw || typeof raw !== 'object' || !raw.subscriptions || typeof raw.subscriptions !== 'object') {
300
+ return out;
301
+ }
302
+ for (const [id, entry] of Object.entries(raw.subscriptions).slice(0, MAX_SUBSCRIPTIONS)) {
303
+ if (!entry || typeof entry !== 'object') continue;
304
+ try {
305
+ const url = validateCustomFeedUrl(entry.url);
306
+ const label = sanitizeText(String(entry.label ?? ''), 80);
307
+ if (!id || !label) continue;
308
+ out.subscriptions[id] = {
309
+ id,
310
+ label,
311
+ url,
312
+ format: ['auto', 'xml', 'json'].includes(entry.format) ? entry.format : 'auto',
313
+ defaultIntent: ['auto', 'activity', 'notice'].includes(entry.defaultIntent) ? entry.defaultIntent : 'auto',
314
+ category: sanitizeText(String(entry.category ?? 'activity'), 32) || 'activity',
315
+ items: Array.isArray(entry.items) ? entry.items.slice(0, MAX_ITEMS_PER_SOURCE) : [],
316
+ fetchedAt: Number.isFinite(entry.fetchedAt) ? entry.fetchedAt : null,
317
+ error: typeof entry.error === 'string' ? sanitizeText(entry.error, 200) : null
318
+ };
319
+ } catch {
320
+ /* drop corrupted invalid entry */
321
+ }
322
+ }
323
+ return out;
324
+ }
325
+
326
+ function memoryStore() {
327
+ const map = new Map();
328
+ return {
329
+ read: (k) => map.get(k),
330
+ write: (k, v) => map.set(k, v)
331
+ };
332
+ }
333
+
334
+ /** Manage user-configured custom RSS / Atom / static JSON feed subscriptions. */
335
+ export function createCustomFeeds(options = {}) {
336
+ const fallback = memoryStore();
337
+ const read = typeof options.read === 'function' ? options.read : fallback.read;
338
+ const write = typeof options.write === 'function' ? options.write : fallback.write;
339
+ const fetchImpl = options.fetch ?? globalThis.fetch;
340
+ const now = typeof options.now === 'function' ? options.now : Date.now;
341
+
342
+ const store = loadStore(read);
343
+ let refreshing = null;
344
+ let lastAttempt = 0;
345
+ let closed = false;
346
+ let controller = null;
347
+
348
+ function persist() {
349
+ try {
350
+ write(STORE_KEY, store);
351
+ } catch {
352
+ /* best effort persistence */
353
+ }
354
+ }
355
+
356
+ function list() {
357
+ return Object.values(store.subscriptions).map((sub) => ({
358
+ id: sub.id,
359
+ label: sub.label,
360
+ url: sub.url,
361
+ format: sub.format,
362
+ defaultIntent: sub.defaultIntent,
363
+ category: sub.category,
364
+ itemCount: sub.items.length,
365
+ fetchedAt: sub.fetchedAt,
366
+ error: sub.error
367
+ }));
368
+ }
369
+
370
+ function add({ label, url, format = 'auto', defaultIntent = 'auto', category = 'activity' } = {}) {
371
+ const cleanUrl = validateCustomFeedUrl(url);
372
+ const cleanLabel = sanitizeText(String(label ?? ''), 80);
373
+ if (!cleanLabel) throw new CustomFeedError('请提供订阅名称(label)。');
374
+ const cleanFormat = ['auto', 'xml', 'json'].includes(format) ? format : 'auto';
375
+ const cleanIntent = ['auto', 'activity', 'notice'].includes(defaultIntent) ? defaultIntent : 'auto';
376
+ const cleanCat = sanitizeText(String(category ?? 'activity'), 32) || 'activity';
377
+
378
+ const duplicate = Object.values(store.subscriptions).find((s) => s.url === cleanUrl);
379
+ if (duplicate) {
380
+ return { status: 'already_exists', subscription: list().find((s) => s.id === duplicate.id) };
381
+ }
382
+ if (Object.keys(store.subscriptions).length >= MAX_SUBSCRIPTIONS) {
383
+ throw new CustomFeedError(`最多只能添加 ${MAX_SUBSCRIPTIONS} 个自定义订阅源。`);
384
+ }
385
+
386
+ const id = `custom:${hashId(cleanUrl)}`;
387
+ store.subscriptions[id] = {
388
+ id,
389
+ label: cleanLabel,
390
+ url: cleanUrl,
391
+ format: cleanFormat,
392
+ defaultIntent: cleanIntent,
393
+ category: cleanCat,
394
+ items: [],
395
+ fetchedAt: null,
396
+ error: null
397
+ };
398
+ persist();
399
+ return { status: 'added', subscription: list().find((s) => s.id === id) };
400
+ }
401
+
402
+ function remove({ id } = {}) {
403
+ const cleanId = sanitizeText(String(id ?? ''), 100);
404
+ if (!cleanId || !Object.hasOwn(store.subscriptions, cleanId)) {
405
+ throw new CustomFeedError('找不到该自定义订阅源。');
406
+ }
407
+ const removed = store.subscriptions[cleanId];
408
+ delete store.subscriptions[cleanId];
409
+ persist();
410
+ return { status: 'removed', id: cleanId, label: removed.label };
411
+ }
412
+
413
+ function getSourceStatuses() {
414
+ return Object.values(store.subscriptions).map((sub) => ({
415
+ id: sub.id,
416
+ label: sub.label,
417
+ category: sub.category,
418
+ fetchedAt: sub.fetchedAt ?? null,
419
+ error: sub.error ?? null
420
+ }));
421
+ }
422
+
423
+ function getItems() {
424
+ return Object.values(store.subscriptions).flatMap((sub) => sub.items);
425
+ }
426
+
427
+ function getItemById(id) {
428
+ for (const sub of Object.values(store.subscriptions)) {
429
+ const found = sub.items.find((x) => x.id === id);
430
+ if (found) return found;
431
+ }
432
+ return null;
433
+ }
434
+
435
+ function getSourceMeta(id) {
436
+ const sub = store.subscriptions[id];
437
+ if (!sub) return null;
438
+ return {
439
+ id: sub.id,
440
+ label: sub.label,
441
+ category: sub.category,
442
+ kind: sub.defaultIntent === 'activity' ? 'event' : 'news'
443
+ };
444
+ }
445
+
446
+ async function refresh({ force = false } = {}) {
447
+ const subs = Object.values(store.subscriptions);
448
+ if (closed || subs.length === 0) return { sources: getSourceStatuses() };
449
+ if (refreshing) return refreshing;
450
+
451
+ const nowMs = now();
452
+ const staleSubs = force
453
+ ? subs
454
+ : subs.filter((s) => !Number.isFinite(s.fetchedAt) || Boolean(s.error) || nowMs - s.fetchedAt >= STALE_MS);
455
+ if (staleSubs.length === 0) return { sources: getSourceStatuses() };
456
+ if (!force && lastAttempt > 0 && nowMs - lastAttempt < RETRY_AFTER_FAILURE_MS) {
457
+ return { sources: getSourceStatuses() };
458
+ }
459
+
460
+ lastAttempt = nowMs;
461
+ controller = new AbortController();
462
+ const signal = controller.signal;
463
+
464
+ refreshing = (async () => {
465
+ let nextIdx = 0;
466
+ async function worker() {
467
+ while (nextIdx < staleSubs.length && !closed) {
468
+ const sub = staleSubs[nextIdx];
469
+ nextIdx += 1;
470
+ try {
471
+ const body = await fetchSafeCustomBody(sub.url, fetchImpl, signal);
472
+ const items = parseCustomFeedContent(body, sub, now());
473
+ sub.items = items;
474
+ sub.fetchedAt = now();
475
+ sub.error = null;
476
+ } catch (error) {
477
+ sub.error = errorText(error, '订阅暂时不可用');
478
+ }
479
+ }
480
+ }
481
+ await Promise.all(
482
+ Array.from({ length: Math.min(REFRESH_CONCURRENCY, staleSubs.length) }, () => worker())
483
+ );
484
+ if (!closed) persist();
485
+ return { sources: getSourceStatuses() };
486
+ })().finally(() => {
487
+ refreshing = null;
488
+ controller = null;
489
+ });
490
+
491
+ return refreshing;
492
+ }
493
+
494
+ function close() {
495
+ closed = true;
496
+ try {
497
+ controller?.abort();
498
+ } catch {
499
+ /* ignore */
500
+ }
501
+ controller = null;
502
+ refreshing = null;
503
+ }
504
+
505
+ return {
506
+ list,
507
+ add,
508
+ remove,
509
+ refresh,
510
+ getItems,
511
+ getSourceStatuses,
512
+ getItemById,
513
+ getSourceMeta,
514
+ close
515
+ };
516
+ }