koishi-plugin-anime-schedule 1.1.1 → 1.1.3
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/lib/config.js +1 -1
- package/lib/constants.d.ts +20 -2
- package/lib/constants.js +29 -3
- package/lib/data/anilist-match.js +5 -1
- package/lib/handlers.js +17 -9
- package/lib/render/image.js +1 -1
- package/lib/services/airing.d.ts +8 -0
- package/lib/services/airing.js +22 -5
- package/lib/services/digest.d.ts +20 -1
- package/lib/services/digest.js +98 -17
- package/lib/services/info.js +9 -3
- package/lib/services/localizer.d.ts +31 -5
- package/lib/services/localizer.js +104 -20
- package/lib/services/scheduler.js +10 -4
- package/lib/utils/index.d.ts +1 -1
- package/lib/utils/index.js +15 -6
- package/package.json +2 -2
- package/readme.md +1 -1
package/lib/config.js
CHANGED
|
@@ -117,7 +117,7 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
117
117
|
.default('localized'),
|
|
118
118
|
scoreTtlHours: koishi_1.Schema.number()
|
|
119
119
|
.min(1).step(1)
|
|
120
|
-
.description('
|
|
120
|
+
.description('评分多久后台补取一次(小时),到期不阻塞构建')
|
|
121
121
|
.default(constants_1.DEFAULT_SCORE_TTL_HOURS),
|
|
122
122
|
cacheTtlDays: koishi_1.Schema.number()
|
|
123
123
|
.min(1).step(1)
|
package/lib/constants.d.ts
CHANGED
|
@@ -36,8 +36,13 @@ export declare const BANGUMI_DATA_FALLBACK_URLS: string[];
|
|
|
36
36
|
export declare const BANGUMI_DATA_FILE = "bangumi-data.json";
|
|
37
37
|
/** bangumi-data 回退缓存的目录(相对于 ctx.baseDir),与本地化缓存放在一起 */
|
|
38
38
|
export declare const DATA_DIR: string[];
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/**
|
|
40
|
+
* 插件版本与主页,请求 Bangumi 时用于自报身份。
|
|
41
|
+
*
|
|
42
|
+
* 版本号从 `package.json` 读:单独维护一份字面量必然会在发版时漏更新(它曾停在 1.0.0),
|
|
43
|
+
* 而 `package.json` 一定随包发布,读它不会失效。
|
|
44
|
+
*/
|
|
45
|
+
export declare const PLUGIN_VERSION: string;
|
|
41
46
|
export declare const PLUGIN_HOMEPAGE = "https://github.com/YuzuharaYuka/koishi-plugin-anime-schedule";
|
|
42
47
|
/**
|
|
43
48
|
* 请求 Bangumi 时使用的 User-Agent。
|
|
@@ -75,6 +80,9 @@ export declare const LOCALIZE_CACHE_FILE = "localize-cache.json";
|
|
|
75
80
|
*
|
|
76
81
|
* 比标题封面的 cacheTtlDays 短得多:新番开播头几周评分天天在变,样本量从个位数
|
|
77
82
|
* 涨到几百,用 30 天缓存会一直显示「只有十几个人投票」时的噪声值。
|
|
83
|
+
*
|
|
84
|
+
* 到期只触发后台补取(`Localizer.kickScoreRefresh()`),不阻塞构建:评分是一张表的
|
|
85
|
+
* 附属信息,为它把整张表推迟十几秒不划算。
|
|
78
86
|
*/
|
|
79
87
|
export declare const DEFAULT_SCORE_TTL_HOURS = 24;
|
|
80
88
|
/**
|
|
@@ -151,6 +159,16 @@ export declare const MAX_SUPERSAMPLE = 5;
|
|
|
151
159
|
*/
|
|
152
160
|
export declare const DAILY_OFFSET_MIN = -7;
|
|
153
161
|
export declare const DAILY_OFFSET_MAX = 7;
|
|
162
|
+
/**
|
|
163
|
+
* 构建结果的复用窗口(毫秒)。
|
|
164
|
+
*
|
|
165
|
+
* 推送遍历频道时每个群都调一次构建,指令层也常被连着问同一张表。这些调用的差别只有
|
|
166
|
+
* 「已订阅」标记,其余部分(场次推算、AniList 状态、Bangumi 详情、封面地址)完全相同,
|
|
167
|
+
* 因此一份结果在窗口内可以重复用,订阅标记事后再按频道注入。
|
|
168
|
+
*/
|
|
169
|
+
export declare const BUILD_CACHE_TTL_MS: number;
|
|
170
|
+
/** 构建结果同时留存几份(日/深夜/周/季 × 少量偏移),超出丢最早的一份 */
|
|
171
|
+
export declare const BUILD_CACHE_MAX_ENTRIES = 16;
|
|
154
172
|
/** 注册到 canvas 的字体族名,与 config.render.fontFamily 的默认值保持一致 */
|
|
155
173
|
export declare const DEFAULT_FONT_FAMILY = "Anime Schedule Sans";
|
|
156
174
|
/**
|
package/lib/constants.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LOG_MESSAGES = exports.RESPONSES = exports.MESSAGES = exports.IMAGE_THEME = exports.IMAGE_LAYOUT = exports.DEFAULT_FONT_FAMILY = exports.DAILY_OFFSET_MAX = exports.DAILY_OFFSET_MIN = exports.MAX_SUPERSAMPLE = exports.DEFAULT_SUPERSAMPLE = exports.DEFAULT_JPEG_QUALITY = exports.BOLD_FONT_CANDIDATES = exports.FONT_CANDIDATES = exports.COVER_MEMORY_MAX_BYTES = exports.COVER_CACHE_MAX_FILES = exports.COVER_CACHE_TTL_MS = exports.COVER_CACHE_DIR = exports.COVER_MAX_BYTES = exports.COVER_TIMEOUT_MS = exports.COVER_CONCURRENCY = exports.LOCALIZE_TIMEOUT_SECONDS = exports.LOCALIZE_CONCURRENCY = exports.EPISODE_QUERY_LIMIT = exports.LOCALIZE_CACHE_MAX_ENTRIES = exports.LOCALIZE_CACHE_VERSION = exports.MIN_SCORE_VOTES = exports.DEFAULT_SCORE_TTL_HOURS = exports.LOCALIZE_CACHE_FILE = exports.LATE_NIGHT_END_HOUR = exports.IMAGE_LIST_TWO_COLUMN_AT = exports.IMAGE_MAX_CARDS = exports.DIGEST_LABELS = exports.PLUGIN_HOMEPAGE = exports.PLUGIN_VERSION = exports.DATA_DIR = exports.BANGUMI_DATA_FILE = exports.BANGUMI_DATA_FALLBACK_URLS = exports.ANILIST_COOLDOWN_MS = exports.ANILIST_MIN_INTERVAL_MS = exports.ANILIST_BATCH_SIZE = exports.ANILIST_API_URL = exports.BANGUMI_API_HOST = exports.PLUGIN_NAME = void 0;
|
|
3
|
+
exports.LOG_MESSAGES = exports.RESPONSES = exports.MESSAGES = exports.IMAGE_THEME = exports.IMAGE_LAYOUT = exports.DEFAULT_FONT_FAMILY = exports.BUILD_CACHE_MAX_ENTRIES = exports.BUILD_CACHE_TTL_MS = exports.DAILY_OFFSET_MAX = exports.DAILY_OFFSET_MIN = exports.MAX_SUPERSAMPLE = exports.DEFAULT_SUPERSAMPLE = exports.DEFAULT_JPEG_QUALITY = exports.BOLD_FONT_CANDIDATES = exports.FONT_CANDIDATES = exports.COVER_MEMORY_MAX_BYTES = exports.COVER_CACHE_MAX_FILES = exports.COVER_CACHE_TTL_MS = exports.COVER_CACHE_DIR = exports.COVER_MAX_BYTES = exports.COVER_TIMEOUT_MS = exports.COVER_CONCURRENCY = exports.LOCALIZE_TIMEOUT_SECONDS = exports.LOCALIZE_CONCURRENCY = exports.EPISODE_QUERY_LIMIT = exports.LOCALIZE_CACHE_MAX_ENTRIES = exports.LOCALIZE_CACHE_VERSION = exports.MIN_SCORE_VOTES = exports.DEFAULT_SCORE_TTL_HOURS = exports.LOCALIZE_CACHE_FILE = exports.LATE_NIGHT_END_HOUR = exports.IMAGE_LIST_TWO_COLUMN_AT = exports.IMAGE_MAX_CARDS = exports.DIGEST_LABELS = exports.PLUGIN_HOMEPAGE = exports.PLUGIN_VERSION = exports.DATA_DIR = exports.BANGUMI_DATA_FILE = exports.BANGUMI_DATA_FALLBACK_URLS = exports.ANILIST_COOLDOWN_MS = exports.ANILIST_MIN_INTERVAL_MS = exports.ANILIST_BATCH_SIZE = exports.ANILIST_API_URL = exports.BANGUMI_API_HOST = exports.PLUGIN_NAME = void 0;
|
|
4
4
|
exports.buildUserAgent = buildUserAgent;
|
|
5
5
|
exports.getMessages = getMessages;
|
|
6
6
|
/** 插件名,同时作为日志前缀与 User-Agent 主体 */
|
|
@@ -44,8 +44,21 @@ exports.BANGUMI_DATA_FALLBACK_URLS = [
|
|
|
44
44
|
exports.BANGUMI_DATA_FILE = 'bangumi-data.json';
|
|
45
45
|
/** bangumi-data 回退缓存的目录(相对于 ctx.baseDir),与本地化缓存放在一起 */
|
|
46
46
|
exports.DATA_DIR = ['data', 'anime-schedule'];
|
|
47
|
-
/**
|
|
48
|
-
|
|
47
|
+
/**
|
|
48
|
+
* 插件版本与主页,请求 Bangumi 时用于自报身份。
|
|
49
|
+
*
|
|
50
|
+
* 版本号从 `package.json` 读:单独维护一份字面量必然会在发版时漏更新(它曾停在 1.0.0),
|
|
51
|
+
* 而 `package.json` 一定随包发布,读它不会失效。
|
|
52
|
+
*/
|
|
53
|
+
exports.PLUGIN_VERSION = (() => {
|
|
54
|
+
try {
|
|
55
|
+
const pkg = require('../package.json');
|
|
56
|
+
return pkg.version ?? '0.0.0';
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return '0.0.0';
|
|
60
|
+
}
|
|
61
|
+
})();
|
|
49
62
|
exports.PLUGIN_HOMEPAGE = 'https://github.com/YuzuharaYuka/koishi-plugin-anime-schedule';
|
|
50
63
|
/**
|
|
51
64
|
* 请求 Bangumi 时使用的 User-Agent。
|
|
@@ -91,6 +104,9 @@ exports.LOCALIZE_CACHE_FILE = 'localize-cache.json';
|
|
|
91
104
|
*
|
|
92
105
|
* 比标题封面的 cacheTtlDays 短得多:新番开播头几周评分天天在变,样本量从个位数
|
|
93
106
|
* 涨到几百,用 30 天缓存会一直显示「只有十几个人投票」时的噪声值。
|
|
107
|
+
*
|
|
108
|
+
* 到期只触发后台补取(`Localizer.kickScoreRefresh()`),不阻塞构建:评分是一张表的
|
|
109
|
+
* 附属信息,为它把整张表推迟十几秒不划算。
|
|
94
110
|
*/
|
|
95
111
|
exports.DEFAULT_SCORE_TTL_HOURS = 24;
|
|
96
112
|
/**
|
|
@@ -188,6 +204,16 @@ exports.MAX_SUPERSAMPLE = 5;
|
|
|
188
204
|
*/
|
|
189
205
|
exports.DAILY_OFFSET_MIN = -7;
|
|
190
206
|
exports.DAILY_OFFSET_MAX = 7;
|
|
207
|
+
/**
|
|
208
|
+
* 构建结果的复用窗口(毫秒)。
|
|
209
|
+
*
|
|
210
|
+
* 推送遍历频道时每个群都调一次构建,指令层也常被连着问同一张表。这些调用的差别只有
|
|
211
|
+
* 「已订阅」标记,其余部分(场次推算、AniList 状态、Bangumi 详情、封面地址)完全相同,
|
|
212
|
+
* 因此一份结果在窗口内可以重复用,订阅标记事后再按频道注入。
|
|
213
|
+
*/
|
|
214
|
+
exports.BUILD_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
215
|
+
/** 构建结果同时留存几份(日/深夜/周/季 × 少量偏移),超出丢最早的一份 */
|
|
216
|
+
exports.BUILD_CACHE_MAX_ENTRIES = 16;
|
|
191
217
|
/** 注册到 canvas 的字体族名,与 config.render.fontFamily 的默认值保持一致 */
|
|
192
218
|
exports.DEFAULT_FONT_FAMILY = 'Anime Schedule Sans';
|
|
193
219
|
/**
|
|
@@ -59,7 +59,11 @@ function matchByTitle(target, candidates) {
|
|
|
59
59
|
continue;
|
|
60
60
|
const startMs = startMsOf(candidate);
|
|
61
61
|
const dayGap = startMs !== null && beginMs !== null ? Math.abs(startMs - beginMs) / DAY : null;
|
|
62
|
-
|
|
62
|
+
// 标题相等只说明是同一部作品,不能排除同名续作;首播日期缺失时无法校验,直接放弃,
|
|
63
|
+
// 否则「第 2 期」这类同名条目会被错配到前一季。
|
|
64
|
+
if (dayGap === null)
|
|
65
|
+
continue;
|
|
66
|
+
if (dayGap > exports.MAX_DAY_GAP)
|
|
63
67
|
continue;
|
|
64
68
|
const nodes = (candidate.airingSchedule?.nodes ?? []).filter((node) => typeof node.airingAt === 'number');
|
|
65
69
|
const first = nodes.length
|
package/lib/handlers.js
CHANGED
|
@@ -92,6 +92,8 @@ function platformOf(session) {
|
|
|
92
92
|
/** 构建一次推送内容并回复当前会话 */
|
|
93
93
|
async function replyDigest(deps, session, digest) {
|
|
94
94
|
const { config, renderer, logger } = deps;
|
|
95
|
+
// 内容已经拿到手,评分过期的条目趁出图这段时间在后台补,不占用这次指令的等待
|
|
96
|
+
deps.digest.localizer.kickScoreRefresh();
|
|
95
97
|
if (!digest.groups.length) {
|
|
96
98
|
await session.send([digest.header, digest.summary].filter(Boolean).join('\n'));
|
|
97
99
|
return;
|
|
@@ -378,13 +380,9 @@ async function commandSubList(deps, session) {
|
|
|
378
380
|
const upcoming = await digest.upcomingAirings(tids, 31);
|
|
379
381
|
// `upcomingAirings` 会滤掉已播完的作品,故单独查询一次用于标注「已播完」
|
|
380
382
|
const finished = new Set(await digest.finishedSubscriptionTids(tids));
|
|
381
|
-
const names =
|
|
383
|
+
const names = await digest.resolveSubscriptionNames(tids);
|
|
382
384
|
const nextOf = new Map();
|
|
383
385
|
const todayOf = new Map();
|
|
384
|
-
for (const row of rows) {
|
|
385
|
-
const resolved = await digest.resolveSubscriptionName(row.tid);
|
|
386
|
-
names.set(row.tid, resolved ?? row.title ?? row.tid);
|
|
387
|
-
}
|
|
388
386
|
for (const item of upcoming) {
|
|
389
387
|
if (!nextOf.has(item.tid))
|
|
390
388
|
nextOf.set(item.tid, item);
|
|
@@ -506,7 +504,8 @@ async function commandSubClear(deps, session) {
|
|
|
506
504
|
/** 查询订阅作品未来若干天的播出计划 */
|
|
507
505
|
async function commandNext(deps, session, daysText) {
|
|
508
506
|
const { config, digest } = deps;
|
|
509
|
-
const
|
|
507
|
+
const parsed = Number.parseInt(daysText ?? '7', 10);
|
|
508
|
+
const days = (0, utils_1.clamp)(Number.isFinite(parsed) ? parsed : 7, 1, 31);
|
|
510
509
|
try {
|
|
511
510
|
const rows = await digest.listSubscriptions(platformOf(session), channelOf(session));
|
|
512
511
|
if (!rows.length)
|
|
@@ -543,7 +542,7 @@ function commandOff(deps, session, kindText) {
|
|
|
543
542
|
return togglePush(deps, session, kindText, false);
|
|
544
543
|
}
|
|
545
544
|
async function togglePush(deps, session, kindText, enabled) {
|
|
546
|
-
const { config, digest } = deps;
|
|
545
|
+
const { ctx, config, digest } = deps;
|
|
547
546
|
if (!session.guildId)
|
|
548
547
|
return constants_1.RESPONSES.needGuild;
|
|
549
548
|
const raw = (kindText ?? '').trim().toLowerCase();
|
|
@@ -567,6 +566,13 @@ async function togglePush(deps, session, kindText, enabled) {
|
|
|
567
566
|
enabled: true,
|
|
568
567
|
});
|
|
569
568
|
}
|
|
569
|
+
else if (existing.botId !== session.selfId || existing.guildId !== session.guildId) {
|
|
570
|
+
// 机器人换号或频道迁移后,开播提醒要能找到当前机器人;顺手刷新归属信息
|
|
571
|
+
await ctx.database.set('anime_channel', {
|
|
572
|
+
platform: platformOf(session),
|
|
573
|
+
channelId: channelOf(session),
|
|
574
|
+
}, { botId: session.selfId, guildId: session.guildId });
|
|
575
|
+
}
|
|
570
576
|
await digest.setKinds(platformOf(session), channelOf(session), kind === 'daily' ? { dailyEnabled: enabled }
|
|
571
577
|
: kind === 'night' ? { nightEnabled: enabled }
|
|
572
578
|
: kind === 'weekly' ? { weeklyEnabled: enabled }
|
|
@@ -590,11 +596,13 @@ async function commandStatus(deps, session) {
|
|
|
590
596
|
try {
|
|
591
597
|
const channel = await digest.getChannel(platformOf(session), channelOf(session));
|
|
592
598
|
const subscriptions = await digest.listSubscriptions(platformOf(session), channelOf(session));
|
|
599
|
+
const dayStart = (0, time_1.getDayStartMs)((0, time_1.today)(digest.timeZone), digest.timeZone);
|
|
600
|
+
// 只取今天的记录;以前是全量取回再在内存里过滤,推送记录攒久后会越来越慢
|
|
593
601
|
const dispatches = await ctx.database.get('anime_dispatch', {
|
|
594
602
|
platform: platformOf(session),
|
|
595
603
|
channelId: channelOf(session),
|
|
604
|
+
dispatchedAt: { $gte: dayStart, $lt: dayStart + 86400000 },
|
|
596
605
|
});
|
|
597
|
-
const dayStart = (0, time_1.getDayStartMs)((0, time_1.today)(digest.timeZone), digest.timeZone);
|
|
598
606
|
const formatText = config.output.format === 'image'
|
|
599
607
|
? `图片 (${config.output.layout === 'list' ? '卡片列表' : '时间表'})`
|
|
600
608
|
: `纯文本${config.output.useForward ? ' (合并转发)' : ''}`;
|
|
@@ -609,7 +617,7 @@ async function commandStatus(deps, session) {
|
|
|
609
617
|
`订阅番剧: ${subscriptions.length} 部${config.subscription.maxPerChannel > 0 ? ` (上限 ${config.subscription.maxPerChannel})` : ''}`,
|
|
610
618
|
`开播提醒: ${config.push.updateReminderEnabled ? `开,提前 ${config.push.updateLookaheadMinutes} 分钟` : '关'}`,
|
|
611
619
|
// 按记录时间统计:`sub`(开播提醒)的去重键里带的是时刻而不是日期,不能靠键判断
|
|
612
|
-
`今日推送记录: ${dispatches.
|
|
620
|
+
`今日推送记录: ${dispatches.length} 条`,
|
|
613
621
|
].join('\n');
|
|
614
622
|
}
|
|
615
623
|
catch (error) {
|
package/lib/render/image.js
CHANGED
|
@@ -80,7 +80,7 @@ class Renderer {
|
|
|
80
80
|
const started = Date.now();
|
|
81
81
|
const canvas = await this.draw(payload);
|
|
82
82
|
const encoded = await canvas.encode('jpeg', this.config.render.jpegQuality);
|
|
83
|
-
this.logger.debug('[render] %s
|
|
83
|
+
this.logger.debug('[render] %s 出图完成(%dms),尺寸 %dx%d(超采样 %dx),%d bytes(jpeg q=%d)', payload.kind, Date.now() - started, canvas.width, canvas.height, this.scale, encoded.length, this.config.render.jpegQuality);
|
|
84
84
|
releaseSurface(canvas);
|
|
85
85
|
return encoded;
|
|
86
86
|
}
|
package/lib/services/airing.d.ts
CHANGED
|
@@ -44,6 +44,14 @@ export declare class AiringStatusService {
|
|
|
44
44
|
/** 无需预热(缓存只在内存里),保留此方法让调用方写法统一 */
|
|
45
45
|
ensure(): Promise<void>;
|
|
46
46
|
private isFresh;
|
|
47
|
+
/**
|
|
48
|
+
* 标题缓存键。
|
|
49
|
+
*
|
|
50
|
+
* 不能只用折叠标题:`normalizeTitle` 会删掉「第 2 期」这类季别,不同季的同名作品
|
|
51
|
+
* 会命中同一个 ID。把开播日期(取 `beginMs`,缺失时用 `broadcastMs`)按天拼进去,
|
|
52
|
+
* 同名但不同季/不同年的作品就能区分开。
|
|
53
|
+
*/
|
|
54
|
+
private titleKey;
|
|
47
55
|
/**
|
|
48
56
|
* 按标题给缺失 `aniList` ID 的条目补一个 ID:补上就用 AniList 的逐話時刻排期,搜不到返回
|
|
49
57
|
* null 让调用方退回周期推算。结果(含「搜不到」)在进程内缓存。
|
package/lib/services/airing.js
CHANGED
|
@@ -79,8 +79,22 @@ class AiringStatusService {
|
|
|
79
79
|
ensure() {
|
|
80
80
|
return Promise.resolve();
|
|
81
81
|
}
|
|
82
|
-
isFresh(entry, ttlDays) {
|
|
83
|
-
return
|
|
82
|
+
isFresh(entry, ttlDays, now = Date.now()) {
|
|
83
|
+
return now - entry.cachedAt < Math.max(0, ttlDays) * 24 * 60 * 60 * 1000;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 标题缓存键。
|
|
87
|
+
*
|
|
88
|
+
* 不能只用折叠标题:`normalizeTitle` 会删掉「第 2 期」这类季别,不同季的同名作品
|
|
89
|
+
* 会命中同一个 ID。把开播日期(取 `beginMs`,缺失时用 `broadcastMs`)按天拼进去,
|
|
90
|
+
* 同名但不同季/不同年的作品就能区分开。
|
|
91
|
+
*/
|
|
92
|
+
titleKey(target) {
|
|
93
|
+
const title = (0, anilist_match_1.normalizeTitle)(target.title);
|
|
94
|
+
if (!title)
|
|
95
|
+
return '';
|
|
96
|
+
const anchor = target.beginMs ?? target.broadcastMs ?? null;
|
|
97
|
+
return anchor === null ? title : `${title}@${Math.floor(anchor / 86400000)}`;
|
|
84
98
|
}
|
|
85
99
|
/**
|
|
86
100
|
* 按标题给缺失 `aniList` ID 的条目补一个 ID:补上就用 AniList 的逐話時刻排期,搜不到返回
|
|
@@ -88,7 +102,7 @@ class AiringStatusService {
|
|
|
88
102
|
* 校验交给 `matchByTitle`:标题相等 + 首播日期相近,缺一不可。
|
|
89
103
|
*/
|
|
90
104
|
async resolveByTitle(target) {
|
|
91
|
-
const key =
|
|
105
|
+
const key = this.titleKey(target);
|
|
92
106
|
if (!key)
|
|
93
107
|
return null;
|
|
94
108
|
const cached = this.idByTitle.get(key);
|
|
@@ -123,7 +137,10 @@ class AiringStatusService {
|
|
|
123
137
|
return payload?.data?.Page?.media ?? [];
|
|
124
138
|
}
|
|
125
139
|
catch (error) {
|
|
126
|
-
|
|
140
|
+
// 只有「成功响应但没有候选」才是 [];网络/解析失败必须返回 null,
|
|
141
|
+
// 否则会被 resolveByTitle 当成「确定搜不到」永久写入 idByTitle。
|
|
142
|
+
this.handleRequestError(error);
|
|
143
|
+
return null;
|
|
127
144
|
}
|
|
128
145
|
}
|
|
129
146
|
/**
|
|
@@ -147,7 +164,7 @@ class AiringStatusService {
|
|
|
147
164
|
}
|
|
148
165
|
// 过期条目先返回旧值,避免一次请求失败就没有数据可用
|
|
149
166
|
result.set(id, cached);
|
|
150
|
-
if (!this.isFresh(cached, ttlDays))
|
|
167
|
+
if (!this.isFresh(cached, ttlDays, now))
|
|
151
168
|
wanted.push(id);
|
|
152
169
|
}
|
|
153
170
|
if (!wanted.length)
|
package/lib/services/digest.d.ts
CHANGED
|
@@ -16,6 +16,10 @@ export declare class DigestService {
|
|
|
16
16
|
/** AniList 播出状态查询;未注入时退化为「按 Bangumi 逐集档期判断」 */
|
|
17
17
|
private airing?;
|
|
18
18
|
readonly localizer: Localizer;
|
|
19
|
+
/** 已构建结果的短缓存,见 `shared()` */
|
|
20
|
+
private readonly recentBuilds;
|
|
21
|
+
/** 同一份内容正被构建时,后来的调用直接等它,不重复构建 */
|
|
22
|
+
private readonly pendingBuilds;
|
|
19
23
|
constructor(ctx: Context, config: Config, logger: Logger, index: BangumiDataIndex, http: HttpClient,
|
|
20
24
|
/** AniList 播出状态查询;未注入时退化为「按 Bangumi 逐集档期判断」 */
|
|
21
25
|
airing?: AiringStatusService | undefined);
|
|
@@ -172,6 +176,14 @@ export declare class DigestService {
|
|
|
172
176
|
/** 每种表的分组方式 */
|
|
173
177
|
private groupOf;
|
|
174
178
|
private emptyTextOf;
|
|
179
|
+
/**
|
|
180
|
+
* 取共享构建结果,再把本频道的订阅标记补上。
|
|
181
|
+
*
|
|
182
|
+
* @param key 只由「内容口径」决定:表种、偏移、以及 `now` 落在哪一天/哪一季。同一个键在
|
|
183
|
+
* `BUILD_CACHE_TTL_MS` 内只构建一次。
|
|
184
|
+
*/
|
|
185
|
+
private shared;
|
|
186
|
+
private rememberBuild;
|
|
175
187
|
/**
|
|
176
188
|
* 每日更新表,`offset` 为相对今天的日期偏移(-1 表示前一天)。
|
|
177
189
|
*
|
|
@@ -205,7 +217,12 @@ export declare class DigestService {
|
|
|
205
217
|
* 主动指定的),但已播完的必须滤掉:周期规则无限重复,旧季番照样能推算出「第 287 集」。
|
|
206
218
|
*/
|
|
207
219
|
upcomingAirings(tids: string[], days: number, now?: number): Promise<DigestItem[]>;
|
|
208
|
-
/**
|
|
220
|
+
/**
|
|
221
|
+
* 按类型构建,供调度器与指令共用。
|
|
222
|
+
*
|
|
223
|
+
* 除订阅排期外都走 `shared()`:同一份内容在窗口内只构建一次,逐群推送与重复指令只多付
|
|
224
|
+
* 一次注入「已订阅」标记的工夫。
|
|
225
|
+
*/
|
|
209
226
|
build(kind: DigestKind, platform: string, channelId: string, now?: number): Promise<Digest>;
|
|
210
227
|
/**
|
|
211
228
|
* 收尾:套上上限、算统计行、拼出最终 `Digest`。`now` 必须由调用方传入而**不能取
|
|
@@ -263,6 +280,8 @@ export declare class DigestService {
|
|
|
263
280
|
* @param limit 返回条数上限,`<= 0` 表示不限制
|
|
264
281
|
*/
|
|
265
282
|
search(keyword: string, limit?: number): Promise<DigestItem[]>;
|
|
283
|
+
/** 按条目 ID 批量解析作品名;订阅列表一次取完,避免逐条串行请求 */
|
|
284
|
+
resolveSubscriptionNames(tids: string[]): Promise<Map<string, string | null>>;
|
|
266
285
|
/** 按条目 ID 解析作品名;同时接受 `253104` 与 `bgm:253104` 两种写法 */
|
|
267
286
|
resolveSubscriptionName(tid: string): Promise<string | null>;
|
|
268
287
|
}
|
package/lib/services/digest.js
CHANGED
|
@@ -66,6 +66,21 @@ const EMPTY_SETS = new Set();
|
|
|
66
66
|
function defaultTidOf(entry) {
|
|
67
67
|
return entry.bangumiId === null ? null : `bgm:${entry.bangumiId}`;
|
|
68
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* 把共享构建结果里的「已订阅」标记换成调用方频道的集合。
|
|
71
|
+
*
|
|
72
|
+
* 共享结果按空集合构建,因此条目上的标记全是 `false`,这里只需给命中的条目翻一个布尔值,
|
|
73
|
+
* 不必重排、重算摘要——那些都只跟条目内容有关。
|
|
74
|
+
*/
|
|
75
|
+
function withSubscribed(digest, subscribed) {
|
|
76
|
+
if (!subscribed.size || !digest.groups.length)
|
|
77
|
+
return digest;
|
|
78
|
+
const groups = digest.groups.map((group) => ({
|
|
79
|
+
...group,
|
|
80
|
+
items: group.items.map((item) => (subscribed.has(item.tid) ? { ...item, subscribed: true } : item)),
|
|
81
|
+
}));
|
|
82
|
+
return { ...digest, groups };
|
|
83
|
+
}
|
|
69
84
|
/**
|
|
70
85
|
* 推送内容构建服务。
|
|
71
86
|
* 播出时刻与集数全部由 bangumi-data 的周期规则推算,构建过程不产生番组表请求。
|
|
@@ -76,6 +91,10 @@ class DigestService {
|
|
|
76
91
|
index;
|
|
77
92
|
airing;
|
|
78
93
|
localizer;
|
|
94
|
+
/** 已构建结果的短缓存,见 `shared()` */
|
|
95
|
+
recentBuilds = new Map();
|
|
96
|
+
/** 同一份内容正被构建时,后来的调用直接等它,不重复构建 */
|
|
97
|
+
pendingBuilds = new Map();
|
|
79
98
|
constructor(ctx, config, logger, index, http,
|
|
80
99
|
/** AniList 播出状态查询;未注入时退化为「按 Bangumi 逐集档期判断」 */
|
|
81
100
|
airing) {
|
|
@@ -844,6 +863,38 @@ class DigestService {
|
|
|
844
863
|
return this.messages.emptyWeekly;
|
|
845
864
|
return this.messages.emptyDaily;
|
|
846
865
|
}
|
|
866
|
+
/**
|
|
867
|
+
* 取共享构建结果,再把本频道的订阅标记补上。
|
|
868
|
+
*
|
|
869
|
+
* @param key 只由「内容口径」决定:表种、偏移、以及 `now` 落在哪一天/哪一季。同一个键在
|
|
870
|
+
* `BUILD_CACHE_TTL_MS` 内只构建一次。
|
|
871
|
+
*/
|
|
872
|
+
async shared(key, create, subscribed) {
|
|
873
|
+
const hit = this.recentBuilds.get(key);
|
|
874
|
+
if (hit && Date.now() - hit.at < constants_1.BUILD_CACHE_TTL_MS)
|
|
875
|
+
return withSubscribed(hit.digest, subscribed);
|
|
876
|
+
let pending = this.pendingBuilds.get(key);
|
|
877
|
+
if (!pending) {
|
|
878
|
+
pending = create()
|
|
879
|
+
.then((digest) => {
|
|
880
|
+
this.rememberBuild(key, digest);
|
|
881
|
+
return digest;
|
|
882
|
+
})
|
|
883
|
+
.finally(() => this.pendingBuilds.delete(key));
|
|
884
|
+
this.pendingBuilds.set(key, pending);
|
|
885
|
+
}
|
|
886
|
+
return withSubscribed(await pending, subscribed);
|
|
887
|
+
}
|
|
888
|
+
rememberBuild(key, digest) {
|
|
889
|
+
// 先删后加:同一个键再构建一次时把它挪到队尾,淘汰的永远是最久没用过的那份
|
|
890
|
+
this.recentBuilds.delete(key);
|
|
891
|
+
this.recentBuilds.set(key, { at: Date.now(), digest });
|
|
892
|
+
for (const oldest of this.recentBuilds.keys()) {
|
|
893
|
+
if (this.recentBuilds.size <= constants_1.BUILD_CACHE_MAX_ENTRIES)
|
|
894
|
+
break;
|
|
895
|
+
this.recentBuilds.delete(oldest);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
847
898
|
/**
|
|
848
899
|
* 每日更新表,`offset` 为相对今天的日期偏移(-1 表示前一天)。
|
|
849
900
|
*
|
|
@@ -852,17 +903,20 @@ class DigestService {
|
|
|
852
903
|
async buildDaily(offset = this.config.push.dailyOffsetDays, subscribed = EMPTY_SETS, now = Date.now()) {
|
|
853
904
|
// 与配置项 `.min()/.max()` 共用同一对边界,避免「配置页能填、这里又被夹一次」
|
|
854
905
|
const days = (0, utils_1.clamp)(offset, constants_1.DAILY_OFFSET_MIN, constants_1.DAILY_OFFSET_MAX);
|
|
855
|
-
|
|
906
|
+
const key = `daily|${days}|${(0, time_1.today)(this.timeZone, now)}`;
|
|
907
|
+
const create = () => this.buildAirings('daily', EMPTY_SETS, now, (at) => {
|
|
856
908
|
const startMs = (0, time_1.getDayStartMs)((0, time_1.addDays)((0, time_1.today)(this.timeZone, at), days, this.timeZone), this.timeZone);
|
|
857
909
|
return { fromMs: startMs, toMs: startMs + 86400000 - 1, now: startMs };
|
|
858
910
|
});
|
|
911
|
+
return this.shared(key, create, subscribed);
|
|
859
912
|
}
|
|
860
913
|
/**
|
|
861
914
|
* 深夜档更新表:覆盖「今晚 21:00 之后」与「次日 6:00 之前」两段。凌晨场次按实际播出时刻
|
|
862
915
|
* 展示,因此熬夜追更时一眼就能看到现在之后还有什么可看。
|
|
863
916
|
*/
|
|
864
917
|
async buildNight(subscribed = EMPTY_SETS, now = Date.now()) {
|
|
865
|
-
|
|
918
|
+
const key = `night|${(0, time_1.today)(this.timeZone, now)}`;
|
|
919
|
+
const create = () => this.buildAirings('night', EMPTY_SETS, now, (at) => {
|
|
866
920
|
const date = (0, time_1.today)(this.timeZone, at);
|
|
867
921
|
const eveningStartMs = (0, time_1.getDayStartMs)(date, this.timeZone) + EVENING_START_HOUR * 3600000;
|
|
868
922
|
const tomorrowStartMs = (0, time_1.getDayStartMs)((0, time_1.addDays)(date, 1, this.timeZone), this.timeZone);
|
|
@@ -873,16 +927,19 @@ class DigestService {
|
|
|
873
927
|
now: eveningStartMs,
|
|
874
928
|
};
|
|
875
929
|
});
|
|
930
|
+
return this.shared(key, create, subscribed);
|
|
876
931
|
}
|
|
877
932
|
/** 本周更新表,覆盖今天起七天,每部作品只占一条 */
|
|
878
933
|
async buildWeekly(subscribed = EMPTY_SETS, now = Date.now()) {
|
|
879
|
-
|
|
934
|
+
const key = `weekly|${(0, time_1.today)(this.timeZone, now)}`;
|
|
935
|
+
const create = () => this.buildAirings('weekly', EMPTY_SETS, now, (at) => {
|
|
880
936
|
const start = (0, time_1.today)(this.timeZone, at);
|
|
881
937
|
const startMs = (0, time_1.getDayStartMs)(start, this.timeZone);
|
|
882
938
|
// 七天整:到「第 8 天 0 点」为止
|
|
883
939
|
const endMs = (0, time_1.getDayStartMs)((0, time_1.addDays)(start, 7, this.timeZone), this.timeZone);
|
|
884
940
|
return { fromMs: startMs, toMs: endMs - 1, onePerTitle: true, now: startMs };
|
|
885
941
|
});
|
|
942
|
+
return this.shared(key, create, subscribed);
|
|
886
943
|
}
|
|
887
944
|
/**
|
|
888
945
|
* 本季(或指定季度)的新番概览:收录该季首播的全部 TV / WEB 动画,不剔除已播完的作品,
|
|
@@ -893,7 +950,9 @@ class DigestService {
|
|
|
893
950
|
async buildSeason(seasonOffset = 0, subscribed = EMPTY_SETS, now = Date.now()) {
|
|
894
951
|
await this.prepare();
|
|
895
952
|
const { year, startMonth } = this.resolveSeason(seasonOffset, now);
|
|
896
|
-
|
|
953
|
+
// 同一季的内容与「今天」无关,键里不必带日期
|
|
954
|
+
const key = `season|${year}|${startMonth}`;
|
|
955
|
+
return this.shared(key, () => this.buildSeasonOf(year, startMonth, EMPTY_SETS, now), subscribed);
|
|
897
956
|
}
|
|
898
957
|
/** 由「相对当前季度的偏移」算出目标季度 */
|
|
899
958
|
resolveSeason(offset, now) {
|
|
@@ -1016,7 +1075,12 @@ class DigestService {
|
|
|
1016
1075
|
(0, utils_1.debugLog)('[digest] 订阅排期: %d 条订阅 → 未来 %d 天内 %d 场', tids.length, days, items.length);
|
|
1017
1076
|
return items.sort((a, b) => a.atMs - b.atMs);
|
|
1018
1077
|
}
|
|
1019
|
-
/**
|
|
1078
|
+
/**
|
|
1079
|
+
* 按类型构建,供调度器与指令共用。
|
|
1080
|
+
*
|
|
1081
|
+
* 除订阅排期外都走 `shared()`:同一份内容在窗口内只构建一次,逐群推送与重复指令只多付
|
|
1082
|
+
* 一次注入「已订阅」标记的工夫。
|
|
1083
|
+
*/
|
|
1020
1084
|
async build(kind, platform, channelId, now = Date.now()) {
|
|
1021
1085
|
const subscribed = await this.subscribedKeys(platform, channelId);
|
|
1022
1086
|
if (kind === 'daily')
|
|
@@ -1024,7 +1088,7 @@ class DigestService {
|
|
|
1024
1088
|
if (kind === 'night')
|
|
1025
1089
|
return this.buildNight(subscribed, now);
|
|
1026
1090
|
if (kind === 'weekly')
|
|
1027
|
-
return this.buildWeekly(subscribed);
|
|
1091
|
+
return this.buildWeekly(subscribed, now);
|
|
1028
1092
|
if (kind === 'season')
|
|
1029
1093
|
return this.buildSeason(0, subscribed, now);
|
|
1030
1094
|
return this.buildSubscription(platform, channelId, now);
|
|
@@ -1264,19 +1328,36 @@ class DigestService {
|
|
|
1264
1328
|
return this.toItem(candidate, entry.bangumiId !== null ? subjects.get(entry.bangumiId) : undefined);
|
|
1265
1329
|
});
|
|
1266
1330
|
}
|
|
1331
|
+
/** 按条目 ID 批量解析作品名;订阅列表一次取完,避免逐条串行请求 */
|
|
1332
|
+
async resolveSubscriptionNames(tids) {
|
|
1333
|
+
await this.prepare();
|
|
1334
|
+
const result = new Map();
|
|
1335
|
+
const entries = new Map();
|
|
1336
|
+
const idByTid = new Map();
|
|
1337
|
+
for (const tid of new Set(tids)) {
|
|
1338
|
+
const matched = BGM_TID_RE.exec(tid) ?? BGM_ID_RE.exec(tid);
|
|
1339
|
+
if (!matched) {
|
|
1340
|
+
result.set(tid, null);
|
|
1341
|
+
continue;
|
|
1342
|
+
}
|
|
1343
|
+
const id = Number(matched[1]);
|
|
1344
|
+
const entry = this.index.bySubjectId(id);
|
|
1345
|
+
if (!entry) {
|
|
1346
|
+
result.set(tid, null);
|
|
1347
|
+
continue;
|
|
1348
|
+
}
|
|
1349
|
+
entries.set(tid, entry);
|
|
1350
|
+
idByTid.set(tid, id);
|
|
1351
|
+
}
|
|
1352
|
+
const subjects = await this.localizer.localizeByIds([...new Set(idByTid.values())], false);
|
|
1353
|
+
for (const [tid, entry] of entries) {
|
|
1354
|
+
result.set(tid, this.toItem({ entry, atMs: this.nextAirMs(entry, Date.now()), episode: 1 }, subjects.get(idByTid.get(tid))).name);
|
|
1355
|
+
}
|
|
1356
|
+
return result;
|
|
1357
|
+
}
|
|
1267
1358
|
/** 按条目 ID 解析作品名;同时接受 `253104` 与 `bgm:253104` 两种写法 */
|
|
1268
1359
|
async resolveSubscriptionName(tid) {
|
|
1269
|
-
await this.
|
|
1270
|
-
const matched = BGM_TID_RE.exec(tid) ?? BGM_ID_RE.exec(tid);
|
|
1271
|
-
if (!matched)
|
|
1272
|
-
return null;
|
|
1273
|
-
const id = Number(matched[1]);
|
|
1274
|
-
const entry = this.index.bySubjectId(id);
|
|
1275
|
-
if (!entry)
|
|
1276
|
-
return null;
|
|
1277
|
-
// 只是为了拿一个展示用的名字,不需要逐集档期
|
|
1278
|
-
const subjects = await this.localizer.localizeByIds([id]);
|
|
1279
|
-
return this.toItem({ entry, atMs: this.nextAirMs(entry, Date.now()), episode: 1 }, subjects.get(id)).name;
|
|
1360
|
+
return (await this.resolveSubscriptionNames([tid])).get(tid) ?? null;
|
|
1280
1361
|
}
|
|
1281
1362
|
}
|
|
1282
1363
|
exports.DigestService = DigestService;
|
package/lib/services/info.js
CHANGED
|
@@ -398,10 +398,16 @@ exports.InfoService = InfoService;
|
|
|
398
398
|
function flattenSummary(summary) {
|
|
399
399
|
if (!summary)
|
|
400
400
|
return '';
|
|
401
|
-
|
|
401
|
+
const lines = summary
|
|
402
402
|
.replace(/\r\n?/g, '\n')
|
|
403
403
|
.split('\n')
|
|
404
404
|
.map((line) => line.trim())
|
|
405
|
-
.filter(Boolean)
|
|
406
|
-
|
|
405
|
+
.filter(Boolean);
|
|
406
|
+
// 中文/日文换行处不需要空格;英文单词在源文本里被折行时则需要补一个,
|
|
407
|
+
// 否则「the story」会被拼成「thestory」。
|
|
408
|
+
return lines.reduce((text, line) => {
|
|
409
|
+
if (!text)
|
|
410
|
+
return line;
|
|
411
|
+
return `${text}${/[!-~]$/.test(text) && /^[A-Za-z0-9]/.test(line) ? ' ' : ''}${line}`;
|
|
412
|
+
}, '');
|
|
407
413
|
}
|
|
@@ -45,25 +45,42 @@ export declare class Localizer {
|
|
|
45
45
|
private loadPromise;
|
|
46
46
|
private dirty;
|
|
47
47
|
private flushTimer;
|
|
48
|
+
/** 正在进行的写盘;并发调用共享同一个 Promise,避免两个 tmp 文件互相覆盖 */
|
|
49
|
+
private flushing;
|
|
50
|
+
/** 上一次写盘是否失败:失败后不立即重排定时器,避免磁盘故障时每 3 秒刷一条警告 */
|
|
51
|
+
private writeFailed;
|
|
52
|
+
/** 本次构建里评分过期、等出图之后在后台补取的条目 */
|
|
53
|
+
private readonly pendingScores;
|
|
54
|
+
private refreshingScores;
|
|
48
55
|
constructor(ctx: Context, config: Config, logger: Logger, http: HttpClient);
|
|
49
56
|
/** 是否使用中文名与评分展示(详情本身始终获取,用于判断是否已播完) */
|
|
50
57
|
get enabled(): boolean;
|
|
51
58
|
/** 确保磁盘缓存已读取(重复调用只读一次) */
|
|
52
59
|
ensure(): Promise<void>;
|
|
53
60
|
load(): Promise<void>;
|
|
54
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* 把缓存写回磁盘。
|
|
63
|
+
*
|
|
64
|
+
* 同一时刻只允许一个写盘:`save()` 与 3 秒防抖可能同时触发,两个写操作会争用同一个
|
|
65
|
+
* `.tmp` 文件。`dirty` 只在写入成功后才保持 `false`;失败时重新置位,等下一次
|
|
66
|
+
* `scheduleFlush()` 或 `save()` 再试,避免一次磁盘抖动就让本次更新永久丢失。
|
|
67
|
+
*/
|
|
55
68
|
private flush;
|
|
69
|
+
private writeCache;
|
|
56
70
|
/** 延迟合并写入,避免每次命中都落盘 */
|
|
57
71
|
private scheduleFlush;
|
|
58
72
|
/** 主动落盘,插件卸载与调度结束后调用 */
|
|
59
73
|
save(): Promise<void>;
|
|
60
74
|
/**
|
|
61
|
-
*
|
|
62
|
-
* 新番开播头几周天天在变(`scoreTtlHours`)。
|
|
75
|
+
* 标题、封面与首末集日期是否还能用。这几项基本不变,只受 `cacheTtlDays` 管。
|
|
63
76
|
*
|
|
64
|
-
*
|
|
77
|
+
* 评分不在其中:它只在开播头几周天天变,而重取一次评分要走整条
|
|
78
|
+
* `GET /v0/subjects/{id}` 请求。让评分过期去卡构建,等于为了一个数字把整张表推迟十几秒,
|
|
79
|
+
* 因此过期评分先照旧展示,构建结束后再由 `kickScoreRefresh()` 在后台补。
|
|
65
80
|
*/
|
|
66
|
-
private
|
|
81
|
+
private isDisplayFresh;
|
|
82
|
+
/** 评分是否该重取;「条目不存在」的占位记录没有评分,不参与 */
|
|
83
|
+
private needsScoreRefresh;
|
|
67
84
|
/**
|
|
68
85
|
* 批量取回条目详情,返回「条目 ID → 详情」。未命中的条目不会出现在结果里,调用方按
|
|
69
86
|
* 「取不到就退化为日文原名」处理。
|
|
@@ -73,6 +90,15 @@ export declare class Localizer {
|
|
|
73
90
|
* `hasEpisodeTimes: false`,日后真有需要时会自动补取。
|
|
74
91
|
*/
|
|
75
92
|
localizeByIds(ids: number[], wantEpisodeTimes?: boolean): Promise<Map<number, LocalizeCacheEntry>>;
|
|
93
|
+
/**
|
|
94
|
+
* 把这次用到的、评分过期的条目在后台重取一遍。出图之后再调,让用户先看到内容。
|
|
95
|
+
*
|
|
96
|
+
* 不写在 `localizeByIds` 里自动跑,是因为快照与预览脚本要的结果必须只取决于本地缓存:
|
|
97
|
+
* 后台刷新会让同一份缓存在不同时刻构建出不同的评分。
|
|
98
|
+
*/
|
|
99
|
+
kickScoreRefresh(): void;
|
|
100
|
+
/** 只补评分相关字段;逐集档期是另一笔请求,不在这里重取 */
|
|
101
|
+
private refreshScores;
|
|
76
102
|
/** 按条目 ID 取单个条目详情;条目不存在(404)或请求失败时返回 null */
|
|
77
103
|
private fetchSubject;
|
|
78
104
|
/**
|
|
@@ -60,6 +60,13 @@ class Localizer {
|
|
|
60
60
|
loadPromise = null;
|
|
61
61
|
dirty = false;
|
|
62
62
|
flushTimer = null;
|
|
63
|
+
/** 正在进行的写盘;并发调用共享同一个 Promise,避免两个 tmp 文件互相覆盖 */
|
|
64
|
+
flushing = null;
|
|
65
|
+
/** 上一次写盘是否失败:失败后不立即重排定时器,避免磁盘故障时每 3 秒刷一条警告 */
|
|
66
|
+
writeFailed = false;
|
|
67
|
+
/** 本次构建里评分过期、等出图之后在后台补取的条目 */
|
|
68
|
+
pendingScores = new Set();
|
|
69
|
+
refreshingScores = false;
|
|
63
70
|
constructor(ctx, config, logger, http) {
|
|
64
71
|
this.ctx = ctx;
|
|
65
72
|
this.config = config;
|
|
@@ -112,10 +119,27 @@ class Localizer {
|
|
|
112
119
|
})();
|
|
113
120
|
return this.loadPromise;
|
|
114
121
|
}
|
|
115
|
-
/**
|
|
116
|
-
|
|
122
|
+
/**
|
|
123
|
+
* 把缓存写回磁盘。
|
|
124
|
+
*
|
|
125
|
+
* 同一时刻只允许一个写盘:`save()` 与 3 秒防抖可能同时触发,两个写操作会争用同一个
|
|
126
|
+
* `.tmp` 文件。`dirty` 只在写入成功后才保持 `false`;失败时重新置位,等下一次
|
|
127
|
+
* `scheduleFlush()` 或 `save()` 再试,避免一次磁盘抖动就让本次更新永久丢失。
|
|
128
|
+
*/
|
|
129
|
+
flush() {
|
|
130
|
+
if (this.flushing)
|
|
131
|
+
return this.flushing;
|
|
117
132
|
if (!this.dirty)
|
|
118
|
-
return;
|
|
133
|
+
return Promise.resolve();
|
|
134
|
+
this.flushing = this.writeCache().finally(() => {
|
|
135
|
+
this.flushing = null;
|
|
136
|
+
// 写盘快照之后又有新条目:补一次合并写盘;失败时不自动重排,等下一次 save/schedule
|
|
137
|
+
if (this.dirty && !this.writeFailed)
|
|
138
|
+
this.scheduleFlush();
|
|
139
|
+
});
|
|
140
|
+
return this.flushing;
|
|
141
|
+
}
|
|
142
|
+
async writeCache() {
|
|
119
143
|
this.dirty = false;
|
|
120
144
|
if (this.memory.size > constants_1.LOCALIZE_CACHE_MAX_ENTRIES) {
|
|
121
145
|
const sorted = [...this.memory.entries()].sort((a, b) => a[1].cachedAt - b[1].cachedAt);
|
|
@@ -131,8 +155,12 @@ class Localizer {
|
|
|
131
155
|
await fs_1.promises.mkdir((0, path_1.dirname)(this.cachePath), { recursive: true });
|
|
132
156
|
await fs_1.promises.writeFile(temp, JSON.stringify(payload), 'utf8');
|
|
133
157
|
await fs_1.promises.rename(temp, this.cachePath);
|
|
158
|
+
this.writeFailed = false;
|
|
134
159
|
}
|
|
135
160
|
catch (error) {
|
|
161
|
+
// 写入期间可能又有新条目进来;失败后也保持 dirty,交给下一次写盘重试
|
|
162
|
+
this.dirty = true;
|
|
163
|
+
this.writeFailed = true;
|
|
136
164
|
this.logger.warn('[localize] 写入本地化缓存失败:', error);
|
|
137
165
|
await fs_1.promises.rm(temp, { force: true }).catch(() => undefined);
|
|
138
166
|
}
|
|
@@ -154,27 +182,26 @@ class Localizer {
|
|
|
154
182
|
this.flushTimer = null;
|
|
155
183
|
}
|
|
156
184
|
await this.flush();
|
|
185
|
+
// 写盘期间又产生了新条目:等当前写盘结束后再补一次
|
|
186
|
+
if (this.dirty && !this.flushing)
|
|
187
|
+
await this.flush();
|
|
157
188
|
}
|
|
158
189
|
/**
|
|
159
|
-
*
|
|
160
|
-
* 新番开播头几周天天在变(`scoreTtlHours`)。
|
|
190
|
+
* 标题、封面与首末集日期是否还能用。这几项基本不变,只受 `cacheTtlDays` 管。
|
|
161
191
|
*
|
|
162
|
-
*
|
|
192
|
+
* 评分不在其中:它只在开播头几周天天变,而重取一次评分要走整条
|
|
193
|
+
* `GET /v0/subjects/{id}` 请求。让评分过期去卡构建,等于为了一个数字把整张表推迟十几秒,
|
|
194
|
+
* 因此过期评分先照旧展示,构建结束后再由 `kickScoreRefresh()` 在后台补。
|
|
163
195
|
*/
|
|
164
|
-
|
|
165
|
-
if (entry.missing) {
|
|
166
|
-
// 「不存在」也是有效结果:同一季内不必反复去问一个不会出现的条目
|
|
167
|
-
return Date.now() - entry.cachedAt < this.config.localize.cacheTtlDays * 24 * 60 * 60 * 1000;
|
|
168
|
-
}
|
|
169
|
-
// 取过条目详情、却没取逐集档期,而这次需要档期 → 必须重取。旧版缓存没有 hasEpisodeTimes 字段,按「取过」处理。
|
|
170
|
-
if (wantEpisodeTimes && entry.hasEpisodeTimes === false)
|
|
171
|
-
return false;
|
|
172
|
-
// 评分单独算保质期:到期就重取详情,重取时仍按调用方的需要决定要不要连档期一起取
|
|
173
|
-
const scoreAt = entry.scoreCachedAt ?? entry.cachedAt;
|
|
174
|
-
if (Date.now() - scoreAt >= this.config.localize.scoreTtlHours * 60 * 60 * 1000)
|
|
175
|
-
return false;
|
|
196
|
+
isDisplayFresh(entry) {
|
|
176
197
|
return Date.now() - entry.cachedAt < this.config.localize.cacheTtlDays * 24 * 60 * 60 * 1000;
|
|
177
198
|
}
|
|
199
|
+
/** 评分是否该重取;「条目不存在」的占位记录没有评分,不参与 */
|
|
200
|
+
needsScoreRefresh(entry) {
|
|
201
|
+
if (entry.missing)
|
|
202
|
+
return false;
|
|
203
|
+
return Date.now() - (entry.scoreCachedAt ?? entry.cachedAt) >= this.config.localize.scoreTtlHours * 60 * 60 * 1000;
|
|
204
|
+
}
|
|
178
205
|
/**
|
|
179
206
|
* 批量取回条目详情,返回「条目 ID → 详情」。未命中的条目不会出现在结果里,调用方按
|
|
180
207
|
* 「取不到就退化为日文原名」处理。
|
|
@@ -203,7 +230,12 @@ class Localizer {
|
|
|
203
230
|
}
|
|
204
231
|
// 过期条目也先返回,避免一次请求失败就让整张表掉封面
|
|
205
232
|
result.set(id, cached);
|
|
206
|
-
if (
|
|
233
|
+
if (this.needsScoreRefresh(cached))
|
|
234
|
+
this.pendingScores.add(id);
|
|
235
|
+
// 只有展示数据过期、或这次要档期而缓存里没有档期时才阻塞构建。
|
|
236
|
+
// 404 占位记录带 `hasEpisodeTimes:false`,但它的 TTL 内不该反复重试,由 isDisplayFresh 决定。
|
|
237
|
+
if (!this.isDisplayFresh(cached)
|
|
238
|
+
|| (wantEpisodeTimes && !cached.missing && cached.hasEpisodeTimes === false)) {
|
|
207
239
|
wanted.push(id);
|
|
208
240
|
previous.set(id, cached);
|
|
209
241
|
}
|
|
@@ -217,7 +249,7 @@ class Localizer {
|
|
|
217
249
|
//
|
|
218
250
|
// 已经取过档期的条目**不重复取**——评分每天刷新,而档期是另一笔请求,跟着一起重发
|
|
219
251
|
// 会让请求量凭空翻倍。只有「没取过」或「这次确实缺它」才补。
|
|
220
|
-
const needsTimes = wantEpisodeTimes && !(stale && stale.hasEpisodeTimes
|
|
252
|
+
const needsTimes = wantEpisodeTimes && !(stale && stale.hasEpisodeTimes === true);
|
|
221
253
|
const subject = await this.fetchSubject(id);
|
|
222
254
|
const times = needsTimes && subject && resolveEpisodeTotal(subject)
|
|
223
255
|
? await this.fetchEpisodeTimes(id)
|
|
@@ -261,6 +293,58 @@ class Localizer {
|
|
|
261
293
|
}
|
|
262
294
|
return result;
|
|
263
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* 把这次用到的、评分过期的条目在后台重取一遍。出图之后再调,让用户先看到内容。
|
|
298
|
+
*
|
|
299
|
+
* 不写在 `localizeByIds` 里自动跑,是因为快照与预览脚本要的结果必须只取决于本地缓存:
|
|
300
|
+
* 后台刷新会让同一份缓存在不同时刻构建出不同的评分。
|
|
301
|
+
*/
|
|
302
|
+
kickScoreRefresh() {
|
|
303
|
+
if (this.refreshingScores || !this.pendingScores.size)
|
|
304
|
+
return;
|
|
305
|
+
const ids = [...this.pendingScores];
|
|
306
|
+
this.pendingScores.clear();
|
|
307
|
+
this.refreshingScores = true;
|
|
308
|
+
void this.refreshScores(ids).finally(() => {
|
|
309
|
+
this.refreshingScores = false;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
/** 只补评分相关字段;逐集档期是另一笔请求,不在这里重取 */
|
|
313
|
+
async refreshScores(ids) {
|
|
314
|
+
const started = Date.now();
|
|
315
|
+
let ok = 0;
|
|
316
|
+
await (0, utils_1.mapLimit)(ids, constants_1.LOCALIZE_CONCURRENCY, async (id) => {
|
|
317
|
+
const stale = this.memory.get(id);
|
|
318
|
+
// 排队期间可能已被别的构建刷新过
|
|
319
|
+
if (!stale || !this.needsScoreRefresh(stale))
|
|
320
|
+
return;
|
|
321
|
+
const subject = await this.fetchSubject(id);
|
|
322
|
+
if (!subject)
|
|
323
|
+
return;
|
|
324
|
+
// fetchSubject 是 await 点:期间 `localizeByIds` 可能刚写入更完整的档期字段。
|
|
325
|
+
// 这里必须基于「最新的一份」合并,不能拿请求前的快照整体覆盖。
|
|
326
|
+
const current = this.memory.get(id);
|
|
327
|
+
if (!current || current.missing || !this.needsScoreRefresh(current))
|
|
328
|
+
return;
|
|
329
|
+
ok++;
|
|
330
|
+
this.memory.set(id, {
|
|
331
|
+
...current,
|
|
332
|
+
title: subject.name_cn?.trim() || subject.name,
|
|
333
|
+
coverUrl: subject.images?.large ?? subject.images?.common ?? '',
|
|
334
|
+
score: computeScore(subject.rating),
|
|
335
|
+
ratingTotal: typeof subject.rating?.total === 'number' ? subject.rating.total : null,
|
|
336
|
+
totalEpisodes: resolveEpisodeTotal(subject),
|
|
337
|
+
hasEpisodeTimes: current.hasEpisodeTimes,
|
|
338
|
+
firstAirMs: current.firstAirMs,
|
|
339
|
+
lastAirMs: current.lastAirMs,
|
|
340
|
+
cachedAt: Date.now(),
|
|
341
|
+
scoreCachedAt: Date.now(),
|
|
342
|
+
});
|
|
343
|
+
this.scheduleFlush();
|
|
344
|
+
});
|
|
345
|
+
if (ok)
|
|
346
|
+
(0, utils_1.debugLog)('[localize] 后台补评分: %d 部(%dms)', ok, Date.now() - started);
|
|
347
|
+
}
|
|
264
348
|
/** 按条目 ID 取单个条目详情;条目不存在(404)或请求失败时返回 null */
|
|
265
349
|
async fetchSubject(id) {
|
|
266
350
|
const url = `${constants_1.BANGUMI_API_HOST}/v0/subjects/${id}`;
|
|
@@ -63,7 +63,8 @@ class Scheduler {
|
|
|
63
63
|
try {
|
|
64
64
|
const due = this.dueKinds(now);
|
|
65
65
|
const reminder = this.config.push.updateReminderEnabled && this.reminderDue(now);
|
|
66
|
-
//
|
|
66
|
+
// 没有到期的推送就不碰数据库:清理与落盘只在真正有推送/提醒的轮次里跑。
|
|
67
|
+
// 提醒默认每 10 分钟轮询一次,因此缓存落盘与过期记录清理也随之变成约 10 分钟一次。
|
|
67
68
|
if (!due.length && !reminder)
|
|
68
69
|
return;
|
|
69
70
|
for (const kind of due)
|
|
@@ -163,8 +164,9 @@ class Scheduler {
|
|
|
163
164
|
const key = (0, dispatch_1.digestKey)(kind, date);
|
|
164
165
|
for (const channel of channels) {
|
|
165
166
|
try {
|
|
166
|
-
//
|
|
167
|
-
//
|
|
167
|
+
// 逐群构建,但除订阅标记外的部分由 `DigestService.shared()` 复用:订阅集合按
|
|
168
|
+
// `platform:channelId` 算,「已订阅」气泡不能跨群复用,否则除第一个群以外都会
|
|
169
|
+
// 显示第一个群的订阅标记
|
|
168
170
|
const current = await this.digest.build(kind, channel.platform, channel.channelId, now);
|
|
169
171
|
if (!current.groups.length) {
|
|
170
172
|
result.skipped++;
|
|
@@ -185,6 +187,8 @@ class Scheduler {
|
|
|
185
187
|
this.logger.warn('[push] 向 %s:%s 发送 %s 失败:', channel.platform, channel.channelId, constants_1.DIGEST_LABELS[kind], error);
|
|
186
188
|
}
|
|
187
189
|
}
|
|
190
|
+
// 推送内容已经发完,评分过期的条目在后台补,不拖慢这一轮推送
|
|
191
|
+
this.digest.localizer.kickScoreRefresh();
|
|
188
192
|
if (result.sent === 0 && result.failed === 0) {
|
|
189
193
|
this.logger.info('[push] %s: 本次没有符合条件的作品,未发送任何消息', constants_1.DIGEST_LABELS[kind]);
|
|
190
194
|
return result;
|
|
@@ -197,7 +201,9 @@ class Scheduler {
|
|
|
197
201
|
: kind === 'night' ? 'nightEnabled'
|
|
198
202
|
: kind === 'weekly' ? 'weeklyEnabled'
|
|
199
203
|
: 'seasonEnabled';
|
|
200
|
-
|
|
204
|
+
const rows = await this.ctx.database.get('anime_channel', { [field]: true });
|
|
205
|
+
// `enabled` 是后加的字段,老数据的 null 不能被当成「已关闭」;显式 false 才跳过。
|
|
206
|
+
return rows.filter((row) => row.enabled !== false);
|
|
201
207
|
}
|
|
202
208
|
/**
|
|
203
209
|
* 订阅作品的开播提醒。场次由周期规则推算,与定时列表推送面向不同时间点,也不受频道的列表
|
package/lib/utils/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { Logger } from 'koishi';
|
|
|
7
7
|
* 不展开就只能看到「fetch failed」,无法判断是 DNS、连接超时还是被重置。
|
|
8
8
|
*/
|
|
9
9
|
export declare function errorMessage(error: unknown): string;
|
|
10
|
-
/** 读取 HTTP 错误的状态码,取不到时返回 null */
|
|
10
|
+
/** 读取 HTTP 错误的状态码,取不到时返回 null。兼容 `response.status`、直接 `status` 与 `cause` 链 */
|
|
11
11
|
export declare function errorStatus(error: unknown): number | null;
|
|
12
12
|
/**
|
|
13
13
|
* 这个错误是不是「超时」(包括 undici 的连接超时与响应超时)。
|
package/lib/utils/index.js
CHANGED
|
@@ -57,13 +57,22 @@ function errorName(error) {
|
|
|
57
57
|
return String(error.name ?? '');
|
|
58
58
|
return '';
|
|
59
59
|
}
|
|
60
|
-
/** 读取 HTTP 错误的状态码,取不到时返回 null */
|
|
60
|
+
/** 读取 HTTP 错误的状态码,取不到时返回 null。兼容 `response.status`、直接 `status` 与 `cause` 链 */
|
|
61
61
|
function errorStatus(error) {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
let current = error;
|
|
63
|
+
for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {
|
|
64
|
+
if (!current || typeof current !== 'object')
|
|
65
|
+
break;
|
|
66
|
+
const direct = current.status;
|
|
67
|
+
if (typeof direct === 'number')
|
|
68
|
+
return direct;
|
|
69
|
+
const response = current.response;
|
|
70
|
+
const status = response?.status;
|
|
71
|
+
if (typeof status === 'number')
|
|
72
|
+
return status;
|
|
73
|
+
current = current.cause;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
67
76
|
}
|
|
68
77
|
/**
|
|
69
78
|
* 这个错误是不是「超时」(包括 undici 的连接超时与响应超时)。
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "koishi-plugin-anime-schedule",
|
|
3
3
|
"description": "番剧时间表与订阅提醒:提供日 / 周 / 季三表,支持定时推送、指定订阅、搜索和详情展示",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.3",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"@napi-rs/canvas": "^1.0.10",
|
|
41
|
-
"bangumi-data": "^0.3.
|
|
41
|
+
"bangumi-data": "^0.3.234"
|
|
42
42
|
},
|
|
43
43
|
"koishi": {
|
|
44
44
|
"description": {
|
package/readme.md
CHANGED
|
@@ -60,7 +60,7 @@ npm i koishi-plugin-anime-schedule
|
|
|
60
60
|
| `output.infoKeywordLimit` | `20` | `anime.info` 按关键词最多出几部,`0` 不限制 |
|
|
61
61
|
| `output.showScore` | `true` | 显示评分,评价不足 10 人时隐藏 |
|
|
62
62
|
| `localize.titleStyle` | `localized` | `localized` 仅中文 / `both` 中文(日文原名)/ `original` 仅日文原名 |
|
|
63
|
-
| `localize.scoreTtlHours` | `24` |
|
|
63
|
+
| `localize.scoreTtlHours` | `24` | 评分与评价人数的后台刷新间隔,到期不阻塞出图 |
|
|
64
64
|
| `render.jpegQuality` | `100` | 图片编码质量,调低可减小体积 |
|
|
65
65
|
| `render.supersample` | `3` | 超采样倍数,提升小字与封面清晰度;`1` 最省体积 |
|
|
66
66
|
| `advanced.debug` | `false` | 输出调试日志 |
|