Skip to content

Commit 3aceeae

Browse files
authored
feat(english): add Kay's Translations source (#2867)
1 parent 9cc9f20 commit 3aceeae

2 files changed

Lines changed: 392 additions & 0 deletions

File tree

Lines changed: 392 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,392 @@
1+
import { fetchApi } from '@libs/fetch';
2+
import { Plugin } from '@/types/plugin';
3+
import { Filters, FilterTypes } from '@libs/filterInputs';
4+
import { NovelStatus } from '@libs/novelStatus';
5+
import { load as loadCheerio } from 'cheerio';
6+
import { defaultCover } from '@libs/defaultCover';
7+
8+
type TocChapter = {
9+
href: string;
10+
ts?: number;
11+
title: string;
12+
};
13+
14+
type TocData = {
15+
chapters?: TocChapter[];
16+
statusKey?: string;
17+
};
18+
19+
type SearchHit = {
20+
title: string;
21+
url: string;
22+
image?: string;
23+
};
24+
25+
/**
26+
* Kay's Translations (kaystls.site) is a custom WordPress site, so this
27+
* plugin reads the site's own pages and AJAX actions:
28+
*
29+
* - The "Browse" page lists every series through the `kay_browse_query`
30+
* admin-ajax action (20 series per page). The action needs a nonce that is
31+
* printed on the Browse page itself.
32+
* - Search uses the `kay_series_search` action behind the Browse page's live
33+
* search box. It returns every match at once.
34+
* - A series page embeds its complete chapter list as `KaySeriesTOCData`
35+
* (title, address, timestamp) and a `lockedChapters` field holding the
36+
* early-access chapters that cannot be read without signing in. Those are
37+
* left out of the chapter list.
38+
* - A chapter page holds the story text as paragraphs of the column that
39+
* starts with the chapter heading.
40+
*/
41+
class KaysTranslationsPlugin implements Plugin.PluginBase {
42+
id = 'kaystranslations';
43+
name = "Kay's Translations";
44+
icon = 'src/en/kaystranslations/icon.png';
45+
site = 'https://kaystls.site/';
46+
version = '1.0.0';
47+
48+
private ajaxUrl = 'https://kaystls.site/wp-admin/admin-ajax.php';
49+
private nonce: string | undefined;
50+
51+
async popularNovels(
52+
pageNo: number,
53+
{
54+
showLatestNovels,
55+
filters,
56+
}: Plugin.PopularNovelsOptions<typeof this.filters>,
57+
): Promise<Plugin.NovelItem[]> {
58+
const status = filters?.status?.value || 'all';
59+
const sort = showLatestNovels
60+
? 'updated_free'
61+
: filters?.sort?.value || 'popular';
62+
63+
let result = await this.browse(pageNo, status, sort, false);
64+
if (result === undefined) {
65+
// The cached nonce expired: read a fresh one and retry once.
66+
result = await this.browse(pageNo, status, sort, true);
67+
}
68+
if (result === undefined) {
69+
throw new Error("Kay's Translations: the browse request was rejected.");
70+
}
71+
72+
const $ = loadCheerio(result);
73+
const novels: Plugin.NovelItem[] = [];
74+
$('article.kay-card').each((_, el) => {
75+
const card = $(el);
76+
const link = card.find('h3.kay-card-title a').first();
77+
const path = this.toPath(link.attr('href') || '');
78+
const name = link.text().trim();
79+
if (!path || !name) return;
80+
novels.push({
81+
name,
82+
path,
83+
cover: this.imageOrDefault(card.find('img').first().attr('src')),
84+
});
85+
});
86+
return novels;
87+
}
88+
89+
async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
90+
const response = await fetchApi(this.resolveUrl(novelPath));
91+
if (!response.ok) {
92+
throw new Error(`Kay's Translations: HTTP ${response.status}.`);
93+
}
94+
const html = await response.text();
95+
const $ = loadCheerio(html);
96+
97+
const name = $('.wp-block-column h1.wp-block-heading').first().text();
98+
const novel: Plugin.SourceNovel = {
99+
path: novelPath,
100+
name: this.normalizeText(name) || this.titleFromDocument($),
101+
cover: this.imageOrDefault(
102+
$('.wp-block-cover__image-background').first().attr('src'),
103+
),
104+
chapters: [],
105+
};
106+
107+
const synopsis = this.readSynopsis($);
108+
if (synopsis) novel.summary = synopsis;
109+
110+
const toc = this.readToc(html);
111+
if (!toc || !Array.isArray(toc.chapters)) {
112+
throw new Error(
113+
`Kay's Translations: no chapter list found at ${novelPath}.`,
114+
);
115+
}
116+
novel.status = this.toStatus(toc.statusKey);
117+
118+
// Early-access chapters are listed on the page but need a sign-in.
119+
const locked = new Set(
120+
($('input.lockedChapters').attr('value') || '')
121+
.split(',')
122+
.map(href => this.toPath(href))
123+
.filter(path => path),
124+
);
125+
const chapters: Plugin.ChapterItem[] = [];
126+
toc.chapters.forEach(item => {
127+
const path = this.toPath(item.href);
128+
if (!path || locked.has(path)) return;
129+
const numbered = item.title.match(/^Chapter\s*(\d+(?:\.\d+)?)/i);
130+
chapters.push({
131+
name: this.normalizeText(item.title),
132+
path,
133+
releaseTime: item.ts
134+
? new Date(item.ts * 1000).toISOString()
135+
: undefined,
136+
chapterNumber: numbered ? Number(numbered[1]) : chapters.length + 1,
137+
});
138+
});
139+
novel.chapters = chapters;
140+
return novel;
141+
}
142+
143+
async parseChapter(chapterPath: string): Promise<string> {
144+
const response = await fetchApi(this.resolveUrl(chapterPath));
145+
if (!response.ok) {
146+
throw new Error(`Kay's Translations: HTTP ${response.status}.`);
147+
}
148+
const $ = loadCheerio(await response.text());
149+
150+
// The story text is the run of paragraphs under the chapter heading; the
151+
// next heading ("TOC | Next chapter") and the donation blocks follow it.
152+
const column = $(
153+
'.wp-block-column > h3.wp-block-heading + p.wp-block-paragraph',
154+
)
155+
.first()
156+
.parent();
157+
const parts: string[] = [];
158+
column
159+
.children()
160+
.slice(1)
161+
.each((_, el) => {
162+
if (el.tagName === 'h3') return false;
163+
const node = $(el);
164+
if (el.tagName === 'p' && node.hasClass('wp-block-paragraph')) {
165+
if (node.text().trim() || node.find('img').length) {
166+
parts.push($.html(node));
167+
}
168+
}
169+
});
170+
171+
if (parts.length === 0) {
172+
throw new Error(
173+
`Kay's Translations: no readable chapter text at ${chapterPath}. ` +
174+
'The chapter may be early access and need a sign-in on the site.',
175+
);
176+
}
177+
return parts.join('\n');
178+
}
179+
180+
async searchNovels(
181+
searchTerm: string,
182+
pageNo: number,
183+
): Promise<Plugin.NovelItem[]> {
184+
// The site's search answers with every match at once and has no pages.
185+
if (pageNo > 1) return [];
186+
const query = searchTerm.trim();
187+
if (query.length < 2) return [];
188+
189+
const response = await fetchApi(this.ajaxUrl, {
190+
method: 'POST',
191+
headers: {
192+
'Content-Type': 'application/x-www-form-urlencoded',
193+
'X-Requested-With': 'XMLHttpRequest',
194+
},
195+
body: new URLSearchParams({
196+
action: 'kay_series_search',
197+
q: query,
198+
}).toString(),
199+
});
200+
if (!response.ok) {
201+
throw new Error(`Kay's Translations: HTTP ${response.status}.`);
202+
}
203+
const hits: SearchHit[] = await response.json();
204+
if (!Array.isArray(hits)) return [];
205+
206+
const novels: Plugin.NovelItem[] = [];
207+
hits.forEach(hit => {
208+
const path = this.toPath(hit.url);
209+
if (!path || !hit.title) return;
210+
novels.push({
211+
name: this.normalizeText(hit.title),
212+
path,
213+
cover: this.imageOrDefault(hit.image),
214+
});
215+
});
216+
return novels;
217+
}
218+
219+
resolveUrl = (path: string) => this.site + path;
220+
221+
/**
222+
* Run the Browse page's `kay_browse_query` action. Resolves to the cards'
223+
* HTML, or to `undefined` when the site rejected the nonce.
224+
*/
225+
private async browse(
226+
pageNo: number,
227+
status: string,
228+
sort: string,
229+
refreshNonce: boolean,
230+
): Promise<string | undefined> {
231+
if (refreshNonce || !this.nonce) {
232+
this.nonce = await this.fetchNonce();
233+
}
234+
const response = await fetchApi(this.ajaxUrl, {
235+
method: 'POST',
236+
headers: {
237+
'Content-Type': 'application/x-www-form-urlencoded',
238+
'X-Requested-With': 'XMLHttpRequest',
239+
},
240+
body: new URLSearchParams({
241+
action: 'kay_browse_query',
242+
status,
243+
sort,
244+
page: String(pageNo),
245+
_wpnonce: this.nonce,
246+
}).toString(),
247+
});
248+
if (!response.ok) {
249+
return undefined;
250+
}
251+
const data: { html?: string; success?: boolean } = await response.json();
252+
return typeof data.html === 'string' ? data.html : undefined;
253+
}
254+
255+
private async fetchNonce(): Promise<string> {
256+
const response = await fetchApi(this.site + 'browse/');
257+
if (!response.ok) {
258+
throw new Error(`Kay's Translations: HTTP ${response.status}.`);
259+
}
260+
const $ = loadCheerio(await response.text());
261+
const nonce = $('#kay-browse-grid').attr('data-nonce');
262+
if (!nonce) {
263+
throw new Error("Kay's Translations: the browse page has no nonce.");
264+
}
265+
return nonce;
266+
}
267+
268+
/** The synopsis is the paragraphs between its heading and the TOC. */
269+
private readSynopsis($: ReturnType<typeof loadCheerio>): string {
270+
const heading = $('.wp-block-column h4.wp-block-heading')
271+
.filter((_, el) => /synopsis/i.test($(el).text()))
272+
.first();
273+
const paragraphs: string[] = [];
274+
let node = heading.next();
275+
while (node.length && !/^h\d$/.test(node.get(0)?.tagName || '')) {
276+
if (node.is('p.wp-block-paragraph')) {
277+
node.find('br').replaceWith('\n');
278+
const text = this.normalizeText(node.text());
279+
// The closing paragraph asks readers to rate the series.
280+
if (text && !/novel\s*updates/i.test(text)) paragraphs.push(text);
281+
}
282+
node = node.next();
283+
}
284+
return paragraphs.join('\n\n');
285+
}
286+
287+
/** Read the `KaySeriesTOCData = {...};` object out of the page's scripts. */
288+
private readToc(html: string): TocData | undefined {
289+
const marker = html.indexOf('KaySeriesTOCData');
290+
if (marker === -1) return undefined;
291+
const start = html.indexOf('{', html.indexOf('=', marker));
292+
if (start === -1) return undefined;
293+
294+
let depth = 0;
295+
let inString = false;
296+
for (let i = start; i < html.length; i++) {
297+
const char = html[i];
298+
if (inString) {
299+
if (char === '\\') i++;
300+
else if (char === '"') inString = false;
301+
} else if (char === '"') {
302+
inString = true;
303+
} else if (char === '{') {
304+
depth++;
305+
} else if (char === '}' && --depth === 0) {
306+
try {
307+
return JSON.parse(html.slice(start, i + 1)) as TocData;
308+
} catch {
309+
return undefined;
310+
}
311+
}
312+
}
313+
return undefined;
314+
}
315+
316+
private toStatus(key: string | undefined): string {
317+
switch (key) {
318+
case 'ongoing':
319+
return NovelStatus.Ongoing;
320+
case 'completed':
321+
return NovelStatus.Completed;
322+
case 'hiatus':
323+
return NovelStatus.OnHiatus;
324+
case 'dropped':
325+
return NovelStatus.Cancelled;
326+
default:
327+
return NovelStatus.Unknown;
328+
}
329+
}
330+
331+
private titleFromDocument($: ReturnType<typeof loadCheerio>): string {
332+
return this.normalizeText(
333+
$('title')
334+
.text()
335+
.split(/[–|-]\s*Kay/)[0],
336+
);
337+
}
338+
339+
private imageOrDefault(src: string | undefined): string {
340+
// The site fills missing covers with a shared "no-image" placeholder.
341+
if (!src || /no-image/i.test(src)) return defaultCover;
342+
return src;
343+
}
344+
345+
/** Reduce an address on this site to the path stored for novels/chapters. */
346+
private toPath(href: string): string {
347+
try {
348+
const url = new URL(href, this.site);
349+
if (url.hostname.replace(/^www\./, '') !== 'kaystls.site') return '';
350+
return url.pathname.replace(/^\/+/, '');
351+
} catch {
352+
return '';
353+
}
354+
}
355+
356+
private normalizeText(text: string): string {
357+
return text
358+
.replace(new RegExp('\\u3000', 'g'), ' ')
359+
.replace(/[ \t]+/g, ' ')
360+
.replace(/ *\n */g, '\n')
361+
.trim();
362+
}
363+
364+
filters = {
365+
status: {
366+
label: 'Status',
367+
value: 'all',
368+
options: [
369+
{ label: 'All', value: 'all' },
370+
{ label: 'Ongoing', value: 'ongoing' },
371+
{ label: 'On Hiatus', value: 'hiatus' },
372+
{ label: 'Dropped', value: 'dropped' },
373+
{ label: 'Completed', value: 'completed' },
374+
],
375+
type: FilterTypes.Picker,
376+
},
377+
sort: {
378+
label: 'Sort by',
379+
value: 'popular',
380+
options: [
381+
{ label: 'Popular', value: 'popular' },
382+
{ label: 'Updated (Free)', value: 'updated_free' },
383+
{ label: 'Updated (Premium)', value: 'updated_premium' },
384+
{ label: 'Newest', value: 'newest' },
385+
{ label: 'Oldest', value: 'oldest' },
386+
],
387+
type: FilterTypes.Picker,
388+
},
389+
} satisfies Filters;
390+
}
391+
392+
export default new KaysTranslationsPlugin();
1.75 KB
Loading

0 commit comments

Comments
 (0)