aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Media/Manga/chapters.ts
blob: ff861609925e1f7ec55dddb8ba847718799163b2 (plain) (blame)
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
import { env } from "$env/dynamic/public";
import { type Media, recentMediaActivities } from "$lib/Data/AniList/media";
import { proxyRoute } from "$lib/Utility/proxy";
import settings from "$stores/settings";
import type { UserIdentity } from "../../Data/AniList/identity";
import { database } from "../../Database/IDB/chapters";

interface MangaDexChapterCount {
	chapter: number | null;
	volumeText?: string | null;
}

interface MangaDexChapterCountsResponse {
	data?: Record<string, MangaDexChapterCount>;
	pending?: number[];
	retryAfterMs?: number;
}

interface NativeChapterCount {
	chapter: number | null;
}

interface NativeChapterCountsResponse {
	data?: Record<string, NativeChapterCount>;
}

const chapterMemoryCache = new Map<number, number | null>();
const MAX_PENDING_RETRIES = 2;
const DEFAULT_PENDING_RETRY_MS = 750;

const browserChapterCacheDisabled = () =>
	env.PUBLIC_DISABLE_MANGA_BROWSER_CACHE === "true";

const parseOptionalNumber = (value: string | number | null | undefined) => {
	if (value === null || value === undefined || value === "") return null;

	const number = Number.parseFloat(String(value));

	return Number.isFinite(number) ? number : null;
};

const sleep = (milliseconds: number) =>
	new Promise((resolve) => setTimeout(resolve, milliseconds));

const readCachedChapterCount = async (
	mangaId: number,
	allowNullCache = true,
) => {
	if (chapterMemoryCache.has(mangaId)) return chapterMemoryCache.get(mangaId);

	if (browserChapterCacheDisabled()) return undefined;

	const chapter = await database.chapters.get(mangaId);

	return chapter === undefined
		? undefined
		: chapter.chapters === -1
			? allowNullCache
				? null
				: undefined
			: chapter.chapters;
};

const writeCachedChapterCount = async (
	mangaId: number,
	chapters: number | null,
	volumes: number | null = null,
) => {
	chapterMemoryCache.set(mangaId, chapters);

	if (browserChapterCacheDisabled()) return;

	await database.chapters.put({
		id: mangaId,
		chapters: chapters === null ? -1 : chapters,
		volumes,
	});
};

const getActivityChapterCount = async (
	identity: UserIdentity,
	manga: Media,
	disableGuessing: boolean,
) => {
	if (disableGuessing) {
		await writeCachedChapterCount(manga.id, null);

		return null;
	}

	const anilistData = await recentMediaActivities(
		identity,
		manga,
		settings.get().calculateGuessMethod,
	);

	await writeCachedChapterCount(manga.id, anilistData);

	return anilistData;
};

const applyResolvedChapterCount = async (
	identity: UserIdentity,
	manga: Media,
	disableGuessing: boolean,
	chapter: number,
	volumeText?: string | null,
) => {
	let resolvedChapter = chapter;

	if (
		(manga.mediaListEntry || { progress: 0 }).progress > resolvedChapter &&
		!disableGuessing
	) {
		const activityChapterCount = await recentMediaActivities(
			identity,
			manga,
			settings.get().calculateGuessMethod,
		);

		if (activityChapterCount !== null && activityChapterCount > resolvedChapter)
			resolvedChapter = activityChapterCount;
	}

	if (resolvedChapter === 0) resolvedChapter = -1;

	await writeCachedChapterCount(
		manga.id,
		resolvedChapter === -1 ? null : resolvedChapter,
		parseOptionalNumber(volumeText),
	);

	return resolvedChapter === -1 ? null : resolvedChapter;
};

const fetchMangaChapterCounts = async (manga: Media[]) => {
	const data: Record<string, MangaDexChapterCount> = {};
	let rateLimited = false;
	let successfulResponse = false;
	const mangaById = new Map(manga.map((entry) => [entry.id, entry]));
	let pendingManga = manga;
	let retryAfterMs = DEFAULT_PENDING_RETRY_MS;

	for (let attempt = 0; attempt <= MAX_PENDING_RETRIES; attempt += 1) {
		const nextPendingIds = new Set<number>();

		for (let index = 0; index < pendingManga.length; index += 100) {
			const chunk = pendingManga.slice(index, index + 100);
			const response = await fetch(proxyRoute("/manga/chapter-counts"), {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					manga: chunk.map((entry) => ({
						anilistId: entry.id,
						progress: entry.mediaListEntry?.progress || 0,
						status: entry.status,
						startYear: entry.startDate.year,
						nativeTitle: entry.title.native,
						englishTitle: entry.title.english,
						romajiTitle: entry.title.romaji,
					})),
				}),
			}).catch(() => null);

			if (!response) continue;

			if (!response.ok) {
				rateLimited = response.status === 429 || response.status === 503;

				continue;
			}

			const payload = (await response.json()) as MangaDexChapterCountsResponse;
			successfulResponse = true;
			retryAfterMs = payload.retryAfterMs || retryAfterMs;

			Object.assign(data, payload.data || {});

			for (const id of payload.pending || []) nextPendingIds.add(id);
		}

		if (!nextPendingIds.size || attempt === MAX_PENDING_RETRIES) break;

		pendingManga = [...nextPendingIds]
			.map((id) => mangaById.get(id))
			.filter((entry): entry is Media => entry !== undefined);

		if (!pendingManga.length) break;

		await sleep(retryAfterMs);
	}

	return { data, rateLimited: rateLimited && !successfulResponse };
};

const fetchNativeChapterCounts = async (manga: Media[]) => {
	const data: Record<string, NativeChapterCount> = {};
	const failedIds = new Set<number>();

	for (let index = 0; index < manga.length; index += 100) {
		const chunk = manga.slice(index, index + 100);
		const response = await fetch(proxyRoute("/manga/native-chapter-counts"), {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
			},
			body: JSON.stringify({
				manga: chunk.map((entry) => ({
					anilistId: entry.id,
					nativeTitle: entry.title.native,
					englishTitle: entry.title.english,
					romajiTitle: entry.title.romaji,
				})),
			}),
		}).catch(() => null);

		if (!response?.ok) {
			for (const entry of chunk) failedIds.add(entry.id);

			continue;
		}

		const payload = (await response.json()) as NativeChapterCountsResponse;

		Object.assign(data, payload.data || {});

		for (const entry of chunk)
			if (!(String(entry.id) in (payload.data || {}))) failedIds.add(entry.id);
	}

	return { data, failedIds };
};

export const hydrateChapterCounts = async (
	identity: UserIdentity,
	manga: Media[],
	disableGuessing: boolean,
): Promise<{ rateLimited: boolean }> => {
	const uniqueManga = manga.filter(
		(entry, index, array) =>
			array.findIndex((candidate) => candidate.id === entry.id) === index,
	);
	const nativeCountManga: Media[] = [];
	const unresolvedManga: Media[] = [];

	for (const entry of uniqueManga) {
		if (
			(await readCachedChapterCount(
				entry.id,
				!settings.get().calculatePreferNativeChapterCount,
			)) !== undefined
		)
			continue;

		if (entry.format === "NOVEL") {
			await getActivityChapterCount(identity, entry, disableGuessing);

			continue;
		}

		if (settings.get().calculatePreferNativeChapterCount) {
			nativeCountManga.push(entry);

			continue;
		}

		unresolvedManga.push(entry);
	}

	if (nativeCountManga.length) {
		const { data: nativeCounts, failedIds } =
			await fetchNativeChapterCounts(nativeCountManga);

		for (const entry of nativeCountManga) {
			if (failedIds.has(entry.id)) continue;

			const nativeCount = nativeCounts[String(entry.id)]?.chapter;

			if (nativeCount === null) {
				unresolvedManga.push(entry);

				continue;
			}

			if (nativeCount === undefined) continue;

			await writeCachedChapterCount(entry.id, nativeCount);
		}
	}

	if (!unresolvedManga.length) return { rateLimited: false };

	const { data, rateLimited } = await fetchMangaChapterCounts(unresolvedManga);

	for (const entry of unresolvedManga) {
		const resolved = data[String(entry.id)];

		if (resolved?.chapter !== undefined && resolved.chapter !== null) {
			await applyResolvedChapterCount(
				identity,
				entry,
				disableGuessing,
				resolved.chapter,
				resolved.volumeText,
			);

			continue;
		}

		await getActivityChapterCount(identity, entry, disableGuessing);
	}

	return { rateLimited };
};

export const chapterCount = async (
	identity: UserIdentity,
	manga: Media,
	disableGuessing: boolean,
): Promise<number | null> => {
	const cachedChapterCount = await readCachedChapterCount(manga.id);

	if (cachedChapterCount !== undefined) return cachedChapterCount;

	const { rateLimited } = await hydrateChapterCounts(
		identity,
		[manga],
		disableGuessing,
	);

	if (rateLimited) return -22;

	return (await readCachedChapterCount(manga.id)) ?? null;
};