Skip to content

Commit 259f3ac

Browse files
authored
feat(english): add Lupus-sensei Translations source (#2866)
1 parent 5809cff commit 259f3ac

2 files changed

Lines changed: 279 additions & 0 deletions

File tree

‎plugins/english/lupussensei.ts‎

Lines changed: 279 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,279 @@
1+
import { fetchApi } from '@libs/fetch';
2+
import { Plugin } from '@/types/plugin';
3+
import { load as loadCheerio } from 'cheerio';
4+
import type { AnyNode } from 'domhandler';
5+
import { defaultCover } from '@libs/defaultCover';
6+
7+
// Chapters of the oldest series live on the translator's earlier blog.
8+
const CHAPTER_HOST =
9+
/^(?:(?:www\.)?lupus-sensei\.com|isekaimynoghra\.blogspot\.com)$/i;
10+
const SITE_HOST = /^(?:www\.)?lupus-sensei\.com$/i;
11+
// Blogger post URLs look like /2021/02/slug.html.
12+
const POST_PATH = /^\/\d{4}\/\d{2}\/[^/]+\.html$/;
13+
// Entries in a chapter list that are not chapters of the novel.
14+
const NOT_CHAPTER = /^(?:spoilers?\b|synopsis$|.*\bchapters$)/i;
15+
const KEEP_ATTRIBUTES = new Set(['src', 'href', 'alt', 'width', 'height']);
16+
const CHAPTER_GROUP = /^\s*(Chapter\s+\d+)\b/i;
17+
18+
// Allows http(s) URLs and scheme-less (relative) ones; anything else, such as
19+
// `javascript:` or `data:`, is rejected.
20+
const isSafeUrl = (value: string): boolean =>
21+
/^\s*https?:/i.test(value) || !value.split(/[/?#]/)[0].includes(':');
22+
23+
type Novel = Plugin.NovelItem;
24+
25+
class LupusSenseiPlugin implements Plugin.PluginBase {
26+
id = 'lupussensei';
27+
name = 'Lupus-sensei Translations';
28+
site = 'https://www.lupus-sensei.com';
29+
icon = 'src/en/lupussensei/icon.png';
30+
version = '1.0.0';
31+
32+
private async getHtml(url: string): Promise<string> {
33+
const response = await fetchApi(url);
34+
if (!response.ok) {
35+
throw new Error(`Lupus-sensei: HTTP ${response.status} for ${url}`);
36+
}
37+
return response.text();
38+
}
39+
40+
private cleanText(text: string): string {
41+
return text.replace(/\s+/g, ' ').trim();
42+
}
43+
44+
/**
45+
* Site-relative path for the blog's own posts, an absolute URL for posts
46+
* that are hosted on the sibling blog, undefined for everything else.
47+
*/
48+
private postPath(href: string | undefined): string | undefined {
49+
if (!href) return undefined;
50+
let url: URL;
51+
try {
52+
url = new URL(href.trim(), this.site);
53+
} catch {
54+
return undefined;
55+
}
56+
if (!CHAPTER_HOST.test(url.hostname) || !POST_PATH.test(url.pathname)) {
57+
return undefined;
58+
}
59+
return SITE_HOST.test(url.hostname)
60+
? url.pathname
61+
: `https://${url.hostname}${url.pathname}`;
62+
}
63+
64+
/**
65+
* The novels are the entries of the site's "Novels" menu: a title entry
66+
* followed by that novel's "Chapter List" page.
67+
*/
68+
private async catalogue(): Promise<Novel[]> {
69+
const $ = loadCheerio(await this.getHtml(this.site));
70+
const novels: Novel[] = [];
71+
let title: string | undefined;
72+
$('#menu li a').each((_, el) => {
73+
const href = $(el).attr('href') || '';
74+
const text = this.cleanText($(el).text());
75+
if (href === '#') {
76+
title = /^_(?!_)/.test(text)
77+
? text.replace(/^_/, '').trim()
78+
: undefined;
79+
return;
80+
}
81+
if (!title || !/^__\s*chapter/i.test(text)) return;
82+
let path: string | undefined;
83+
try {
84+
const url = new URL(href, this.site);
85+
if (SITE_HOST.test(url.hostname)) path = url.pathname;
86+
} catch {
87+
// ignore malformed menu links
88+
}
89+
if (path && !novels.some(novel => novel.path === path)) {
90+
novels.push({ name: title, path, cover: defaultCover });
91+
}
92+
title = undefined;
93+
});
94+
return novels;
95+
}
96+
97+
private findCover(
98+
$: ReturnType<typeof loadCheerio>,
99+
body: ReturnType<ReturnType<typeof loadCheerio>>,
100+
): string | undefined {
101+
return body
102+
.find('img[src]')
103+
.toArray()
104+
.map(img => $(img).attr('src')!)
105+
.find(src => /^https?:\/\//.test(src));
106+
}
107+
108+
/**
109+
* The menu has no images, so covers come from the blog's label feed: one
110+
* request lists every chapter-list post with its thumbnail. Any failure
111+
* leaves the default cover.
112+
*/
113+
private async withCovers(novels: Novel[]): Promise<Novel[]> {
114+
const covers = new Map<string, string>();
115+
try {
116+
const response = await fetchApi(
117+
`${this.site}/feeds/posts/default/-/Chapterlist?alt=json&max-results=50`,
118+
);
119+
if (response.ok) {
120+
const json = await response.json();
121+
for (const entry of json?.feed?.entry || []) {
122+
const href = (entry.link || []).find(
123+
(link: { rel?: string; href?: string }) => link.rel === 'alternate',
124+
)?.href;
125+
const thumbnail = entry['media$thumbnail']?.url;
126+
if (!href || !thumbnail) continue;
127+
covers.set(
128+
new URL(href, this.site).pathname,
129+
thumbnail.replace(/\/s\d+(-w\d+-h\d+)?(-c)?\//, '/s640/'),
130+
);
131+
}
132+
}
133+
} catch {
134+
// covers are optional
135+
}
136+
return novels.map(novel => ({
137+
...novel,
138+
cover: covers.get(novel.path) || defaultCover,
139+
}));
140+
}
141+
142+
async popularNovels(pageNo: number): Promise<Plugin.NovelItem[]> {
143+
// The menu lists every series on one page.
144+
if (pageNo > 1) return [];
145+
return this.withCovers(await this.catalogue());
146+
}
147+
148+
async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
149+
const $ = loadCheerio(await this.getHtml(this.resolveUrl(novelPath)));
150+
const body = $('.post-body').first();
151+
body.find('script, style').remove();
152+
153+
const listed = await this.catalogue()
154+
.then(novels => novels.find(novel => novel.path === novelPath))
155+
.catch(() => undefined);
156+
const pageTitle = this.cleanText(
157+
$('h3.post-title, h1.post-title').first().text(),
158+
)
159+
.replace(/\s*[-–]?\s*Chapter List$/i, '')
160+
.trim();
161+
162+
const chapters: Plugin.ChapterItem[] = [];
163+
const seen = new Set<string>();
164+
let group = '';
165+
const walk = (node: AnyNode) => {
166+
if (node.type === 'text') {
167+
const match = CHAPTER_GROUP.exec(this.cleanText(node.data || ''));
168+
if (match) group = match[1];
169+
return;
170+
}
171+
if (node.type !== 'tag') return;
172+
if (node.name === 'a') {
173+
const path = this.postPath($(node).attr('href'));
174+
const name = this.cleanText($(node).text());
175+
if (!path || !name || NOT_CHAPTER.test(name) || seen.has(path)) return;
176+
seen.add(path);
177+
chapters.push({
178+
name: group && /^ep\b/i.test(name) ? `${group} - ${name}` : name,
179+
path,
180+
});
181+
return;
182+
}
183+
(node.children || []).forEach(walk);
184+
};
185+
body.contents().each((_, node) => walk(node));
186+
187+
if (!chapters.length) {
188+
throw new Error('Lupus-sensei: no chapters were found for this novel.');
189+
}
190+
191+
const cover = this.findCover($, body);
192+
193+
return {
194+
path: novelPath,
195+
name: listed?.name || pageTitle || 'Untitled',
196+
cover: cover || defaultCover,
197+
chapters,
198+
};
199+
}
200+
201+
async parseChapter(chapterPath: string): Promise<string> {
202+
const $ = loadCheerio(await this.getHtml(this.resolveUrl(chapterPath)));
203+
const body = $('.post-body').first();
204+
body
205+
.find(
206+
'script, style, noscript, iframe, object, embed, form, svg, base, meta, .adsbygoogle',
207+
)
208+
.remove();
209+
// Word-export leftovers (conditional comments) sit inside the post.
210+
body
211+
.find('*')
212+
.addBack()
213+
.contents()
214+
.filter((_, node) => node.type === 'comment')
215+
.remove();
216+
// Pasted Word markup carries megabytes of inline styling: keep only the
217+
// attributes that matter for reading.
218+
body.find('span, font').each((_, el) => {
219+
$(el).replaceWith($(el).contents());
220+
});
221+
body.find('*').each((_, el) => {
222+
if (el.type !== 'tag') return;
223+
for (const [attr, value] of Object.entries(el.attribs)) {
224+
// Links and images must stay http(s) or relative: the HTML is shown
225+
// verbatim, so `javascript:` and similar schemes must not survive.
226+
if (
227+
!KEEP_ATTRIBUTES.has(attr) ||
228+
((attr === 'href' || attr === 'src') && !isSafeUrl(value))
229+
) {
230+
$(el).removeAttr(attr);
231+
}
232+
}
233+
});
234+
body.find('p, div').each((_, el) => {
235+
const node = $(el);
236+
if (
237+
!node.find('img, hr').length &&
238+
!this.cleanText(node.text()) &&
239+
!node.find('p, div').length
240+
) {
241+
node.remove();
242+
}
243+
});
244+
245+
// Posts often open with a few blank lines.
246+
for (let first = body.contents().first(); first.length; ) {
247+
const blank =
248+
first.is('br') ||
249+
(first[0].type === 'text' && !this.cleanText(first.text()));
250+
if (!blank) break;
251+
first.remove();
252+
first = body.contents().first();
253+
}
254+
255+
const chapter = body.html()?.trim() || '';
256+
if (this.cleanText(loadCheerio(chapter).text()).length < 100) {
257+
throw new Error('Lupus-sensei: no readable chapter text found.');
258+
}
259+
return chapter;
260+
}
261+
262+
async searchNovels(
263+
searchTerm: string,
264+
pageNo: number,
265+
): Promise<Plugin.NovelItem[]> {
266+
// The blog's own search only returns individual chapter posts, so the
267+
// series are matched against the titles in the menu instead.
268+
const tokens = searchTerm.toLowerCase().split(/\s+/).filter(Boolean);
269+
if (!tokens.length || pageNo > 1) return [];
270+
const matches = (await this.catalogue()).filter(novel =>
271+
tokens.every(token => novel.name.toLowerCase().includes(token)),
272+
);
273+
return matches.length ? this.withCovers(matches) : [];
274+
}
275+
276+
resolveUrl = (path: string) => new URL(path, this.site).href;
277+
}
278+
279+
export default new LupusSenseiPlugin();
1.99 KB
Loading

0 commit comments

Comments
 (0)