aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Data/Manga/raw.ts
blob: 64ed3de46316ea677675c50e92a557e0df8d69d1 (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
import proxy from "$lib/Utility/proxy";

interface Chapter {
	href: string;
	chapterNum: string;
	chapterDate: string;
}

const RAWKUMA_ORIGIN = "https://rawkuma.net";

const fetchDocument = async (url: string, init?: RequestInit) =>
	new DOMParser().parseFromString(
		await (await fetch(proxy(url, true), init)).text(),
		"text/html",
	);

const parseChapterNumber = (text: string | null | undefined) => {
	if (!text) return undefined;

	const match = text.match(/Chapter\s+(\d+(?:\.\d+)?)/i);

	return match ? Number.parseFloat(match[1]) : undefined;
};

export const getChapterCount = async (
	nativeTitle: string,
): Promise<number | undefined> => {
	const nonceDocument = await fetchDocument(
		`${RAWKUMA_ORIGIN}/wp-admin/admin-ajax.php?type=search_form&action=get_nonce`,
	);
	const nonce = nonceDocument
		.querySelector("input[name='search_nonce']")
		?.getAttribute("value");

	if (!nonce) return undefined;

	const searchDocument = await fetchDocument(
		`${RAWKUMA_ORIGIN}/wp-admin/admin-ajax.php?nonce=${encodeURIComponent(
			nonce,
		)}&action=search`,
		{
			method: "POST",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			},
			body: new URLSearchParams({
				query: nativeTitle,
			}),
		},
	);
	const mangaUrl = searchDocument
		.querySelector("#searchResults a[href*='/manga/']")
		?.getAttribute("href");

	if (!mangaUrl) return undefined;

	const mangaDocument = await fetchDocument(mangaUrl);
	const chapters = [...mangaDocument.querySelectorAll("a[href*='/chapter-']")]
		.map((anchor) => parseChapterNumber(anchor.textContent))
		.filter((value): value is number => value !== undefined)
		.sort((left, right) => right - left);

	return chapters[0];
};

export const getChaptersFromText = (text: string) => {
	const dom = new DOMParser()
		.parseFromString(text, "text/html")
		.querySelectorAll(".eph-num");
	const chapters: Chapter[] = [];

	dom.forEach((chapter) => {
		const href = chapter.querySelector("a")?.getAttribute("href");
		const chapterNum = chapter.querySelector(".chapternum")?.textContent;
		const chapterDate = chapter.querySelector(".chapterdate")?.textContent;

		if (href && chapterNum && chapterDate)
			chapters.push({
				href,
				chapterNum,
				chapterDate,
			});
	});

	return chapters;
};