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
|
import stringSimilarity from "string-similarity";
import { get } from "svelte/store";
import type { Media } from "$lib/Data/AniList/media";
import settings from "$stores/settings";
import { season } from "../season";
import type { AiringEntry, AiringSchedule, AirType } from "./animeSchedule";
const SEVEN_DAYS_SECONDS = 7 * 24 * 60 * 60;
const STALE_AIRING_GRACE_SECONDS = 5 * 60;
const MAX_EPISODE_SHIFT_WINDOW_SECONDS = 8 * 24 * 60 * 60;
const MAX_INJECT_CACHE_ENTRIES = 10_000;
const FUZZY_MIN_SCORE = 0.82;
// Strip season/part markers and punctuation so canonical romaji/english titles
// from AniList and AnimeSchedule normalise to the same key. NFKC folds fullwidth
// characters down to ASCII first.
const normalizeLatin = (title: string): string =>
(title || "")
.normalize("NFKC")
.toLowerCase()
.replace(/\b(season|s|part|cour)\s*(\d+)\b/g, " $2 ")
.replace(/\b(season|s|part|cour)\b/g, " ")
.replace(/[^a-z0-9\s]/g, " ")
.trim()
.split(/\s+/)
.join(" ");
// Native titles are CJK (Japanese, Chinese, Korean); collapse whitespace but
// keep every glyph. NFKC reconciles fullwidth and halfwidth digits (農家2 vs 農家2).
const normalizeNative = (title: string): string =>
(title || "").normalize("NFKC").replace(/\s+/g, "").toLowerCase();
interface ScheduleIndex {
byNative: Map<string, AiringEntry>;
byLatin: Map<string, AiringEntry>;
entries: AiringEntry[];
}
const indexSet = (
index: Map<string, AiringEntry>,
key: string,
entry: AiringEntry,
) => {
if (key && !index.has(key)) index.set(key, entry);
};
const buildScheduleIndex = (entries: AiringEntry[]): ScheduleIndex => {
const byNative = new Map<string, AiringEntry>();
const byLatin = new Map<string, AiringEntry>();
for (const entry of entries) {
indexSet(byNative, normalizeNative(entry.native), entry);
indexSet(byLatin, normalizeLatin(entry.romaji), entry);
indexSet(byLatin, normalizeLatin(entry.english), entry);
indexSet(byLatin, normalizeLatin(entry.title), entry);
}
return { byNative, byLatin, entries };
};
const indexCache = new WeakMap<
AiringSchedule,
Partial<Record<AirType, ScheduleIndex>>
>();
const getScheduleIndex = (
schedule: AiringSchedule,
source: AirType,
): ScheduleIndex => {
let perSource = indexCache.get(schedule);
if (!perSource) {
perSource = {};
indexCache.set(schedule, perSource);
}
const cached = perSource[source];
if (cached) return cached;
const built = buildScheduleIndex(schedule[source]);
perSource[source] = built;
return built;
};
const fuzzyMatch = (
index: ScheduleIndex,
searchTitles: string[],
): AiringEntry | null => {
let bestEntry: AiringEntry | null = null;
let bestScore = 0;
for (const searchTitle of searchTitles) {
const normalized = normalizeLatin(searchTitle);
if (!normalized) continue;
for (const entry of index.entries) {
const score = stringSimilarity.compareTwoStrings(
normalized,
normalizeLatin(entry.english || entry.romaji || entry.title),
);
if (score > bestScore) {
bestScore = score;
bestEntry = entry;
}
}
}
return bestScore >= FUZZY_MIN_SCORE ? bestEntry : null;
};
// Join an AniList show to its AnimeSchedule release. The native title is a
// near-perfect key; romaji/english cover the rest, with a fuzzy fallback.
const findScheduleEntry = (
schedule: AiringSchedule,
source: AirType,
anime: Media,
): AiringEntry | null => {
const index = getScheduleIndex(schedule, source);
const nativeMatch = index.byNative.get(normalizeNative(anime.title.native));
if (nativeMatch) return nativeMatch;
const latinTitles = [
anime.title.romaji,
anime.title.english,
...anime.synonyms,
];
for (const title of latinTitles) {
const match = index.byLatin.get(normalizeLatin(title));
if (match) return match;
}
return fuzzyMatch(index, latinTitles.filter(Boolean));
};
// Resolve the next future release time for a matched entry. AnimeSchedule gives
// the current week's episode; a delay window or a weekly cadence rolls a past
// release forward to the next occurrence. This must never return a past time —
// a stuck-in-the-past airingAt produces a negative countdown and a tight
// refresh loop (see scheduleAiringRefresh).
const nextReleaseTime = (
entry: AiringEntry,
nowEpochSeconds: number,
): number => {
if (entry.delayedUntil && entry.delayedUntil > nowEpochSeconds)
return entry.delayedUntil;
const base = entry.airingAt;
if (!base) return 0;
if (base > nowEpochSeconds) return base;
const weeksElapsed = Math.ceil((nowEpochSeconds - base) / SEVEN_DAYS_SECONDS);
return base + weeksElapsed * SEVEN_DAYS_SECONDS;
};
const injectAiringTimeCache = new Map<string, Media>();
const setBoundedCacheValue = (key: string, value: Media) => {
if (injectAiringTimeCache.size >= MAX_INJECT_CACHE_ENTRIES)
injectAiringTimeCache.clear();
injectAiringTimeCache.set(key, value);
};
const animeTitleFingerprint = (anime: Media) =>
[
anime.title.romaji,
anime.title.english,
anime.title.native,
...anime.synonyms,
]
.filter(Boolean)
.join("|");
const buildInjectAiringTimeCacheKey = (
anime: Media,
scheduleVersion: string,
source: string,
) =>
[
anime.id,
anime.status,
anime.mediaListEntry?.status || "",
anime.mediaListEntry?.progress || 0,
anime.mediaListEntry?.updatedAt || 0,
anime.nextAiringEpisode?.episode || 0,
anime.nextAiringEpisode?.airingAt || 0,
source,
scheduleVersion,
animeTitleFingerprint(anime),
].join(":");
const cloneInjectedMedia = (media: Media): Media =>
({
...media,
mediaListEntry: media.mediaListEntry
? {
...media.mediaListEntry,
startedAt: { ...media.mediaListEntry.startedAt },
completedAt: { ...media.mediaListEntry.completedAt },
customLists: { ...media.mediaListEntry.customLists },
}
: undefined,
nextAiringEpisode: media.nextAiringEpisode
? { ...media.nextAiringEpisode }
: undefined,
}) as Media;
// Override a show's countdown with its subbed or dubbed release time while
// preserving the native broadcast time and episode for due classification.
export const injectAiringTime = (
anime: Media,
schedule: AiringSchedule | null,
) => {
if (season() !== anime.season) return anime;
const source = get(settings).countdownSource;
const useSchedule = source !== "native" && schedule !== null;
const scheduleVersion = useSchedule
? String((schedule as AiringSchedule).generatedAt)
: "native-only";
const cacheKey = buildInjectAiringTimeCacheKey(
anime,
scheduleVersion,
source,
);
const cached = injectAiringTimeCache.get(cacheKey);
if (cached) return cloneInjectedMedia(cached);
const airingAt = anime.nextAiringEpisode?.airingAt;
const now = new Date();
const nativeTime = new Date(airingAt ? airingAt * 1000 : 0);
let time = new Date(airingAt ? airingAt * 1000 : 0);
let nextEpisode = anime.nextAiringEpisode?.episode || 0;
let nativeEpisode = nextEpisode;
// Prefer the selected track, then fall back: dub → sub → native. Sub never
// falls back to dub. Native is the initial value of `time`.
if (useSchedule && (anime.nextAiringEpisode?.episode || 0) > 1) {
const fallbackOrder: AirType[] =
source === "dub" ? ["dub", "sub"] : ["sub"];
for (const candidateSource of fallbackOrder) {
const entry = findScheduleEntry(
schedule as AiringSchedule,
candidateSource,
anime,
);
if (!entry) continue;
const releaseTime = nextReleaseTime(entry, Date.now() / 1000);
if (releaseTime) {
time = new Date(releaseTime * 1000);
break;
}
}
}
const nowEpochSeconds = Date.now() / 1000;
const nativeAheadSeconds =
nativeTime.getTime() / 1000 - time.getTime() / 1000;
if (
nativeAheadSeconds > 0 &&
nativeAheadSeconds <= MAX_EPISODE_SHIFT_WINDOW_SECONDS &&
nativeTime.getTime() / 1000 > nowEpochSeconds + STALE_AIRING_GRACE_SECONDS
) {
nextEpisode -= 1;
nativeEpisode = nextEpisode;
}
if (nativeTime.getTime() - now.getTime() > SEVEN_DAYS_SECONDS * 1000) {
const beforeTime = time;
time = new Date(nativeTime.getTime());
time.setHours(beforeTime.getHours());
time.setMinutes(beforeTime.getMinutes());
}
const injected = {
...anime,
nextAiringEpisode: {
episode: nextEpisode,
airingAt: time.getTime() / 1000,
nativeAiringAt: nativeTime.getTime() / 1000,
nativeEpisode,
},
} as Media;
const cachedValue = cloneInjectedMedia(injected);
setBoundedCacheValue(cacheKey, cachedValue);
return cloneInjectedMedia(cachedValue);
};
export const clearInjectAiringTimeCache = () => injectAiringTimeCache.clear();
const normalizeTitle = (title: string | null) =>
(title || "")
.toLowerCase()
.replace(/\b(s|season|part|cour)\s*\d+/g, "")
.replace(/[\W_]+/g, " ")
.trim();
const findClosestMediaCache = new Map<string, Media | null>();
// Reverse lookup used by the schedule page: pick the AniList show that best
// matches a given release title.
export const findClosestMedia = (media: Media[], matchFor: string) => {
if (!matchFor) return null;
const cached = findClosestMediaCache.get(matchFor);
if (cached !== undefined) return cached;
const normalizedMatchFor = normalizeTitle(matchFor);
const matchForWords = normalizedMatchFor.split(" ");
let bestFitMedia: Media | null = null;
let bestDistance = -Infinity;
for (const mediaItem of media) {
const titles = [
mediaItem.title.romaji,
mediaItem.title.english,
...mediaItem.synonyms,
].filter(Boolean);
if (
titles.some(
(title) =>
title.toLowerCase().includes("special") ||
title.toLowerCase().includes("ova"),
)
)
continue;
const normalizedTitles = titles.map(normalizeTitle);
for (const normalizedTitle of normalizedTitles) {
const distance = stringSimilarity.compareTwoStrings(
normalizedMatchFor,
normalizedTitle,
);
if (distance <= bestDistance) continue;
const wordMatch =
matchForWords.every((word) =>
normalizedTitles.some((t) => t.includes(word)),
) || normalizedTitles.some((t) => t.includes(normalizedMatchFor));
if (wordMatch) {
bestDistance = distance;
bestFitMedia = mediaItem;
if (distance === 1) break;
}
}
if (bestDistance === 1) break;
}
findClosestMediaCache.set(matchFor, bestFitMedia);
return bestFitMedia as Media | null;
};
|