Skip to content

Commit 2fbac72

Browse files
authored
feat(portuguese): add Anime Center BR source (#2883)
1 parent 7bf1157 commit 2fbac72

2 files changed

Lines changed: 341 additions & 0 deletions

File tree

Lines changed: 341 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,341 @@
1+
import { fetchApi } from '@libs/fetch';
2+
import { Plugin } from '@/types/plugin';
3+
import { load as loadCheerio } from 'cheerio';
4+
import { defaultCover } from '@libs/defaultCover';
5+
import { NovelStatus } from '@libs/novelStatus';
6+
7+
const SITE_HOST = /^(?:www\.)?animecenterbr\.com$/i;
8+
// The A-Z index is one long page: it is split into pages of this size.
9+
const PAGE_SIZE = 24;
10+
// Index entries are followed by "(Finalizado)" when the translation is over.
11+
const FINISHED = /\(\s*finalizado\s*\)/i;
12+
// "Light Novel – Português (PT-BR)" and similar suffixes of the post titles.
13+
const TITLE_SUFFIX =
14+
/\s+[–—-]\s+(?:(?:light |web )?novel\s+[–—-]\s+)?portugu[eê]s.*$/i;
15+
const VOLUME = /^\s*(?:volume|vol\.?)\s*(\d+(?:[.,]\d+)?)/i;
16+
const CHAPTER_NUMBER = /^\s*cap[ií]tulos?\s+(\d+(?:[.,]\d+)?)/i;
17+
// Slugs of novel pages (the chapter lists link to other novels as well).
18+
const NOVEL_PAGE_SLUG =
19+
/(?:^|-)(?:portugues-pt-br|pt-br-portugues|light-novel-pt-br|light-novel-portugues)$/;
20+
const SUPPORT_NOTICE = /^\s*apoie o site/i;
21+
const SINOPSE = /^\s*(?:sinopse|sobre)\s*:\s*/i;
22+
const REST_LATEST =
23+
'/wp-json/wp/v2/posts?categories=26&orderby=date&order=desc&_embed=wp:featuredmedia&_fields=link,title,_embedded';
24+
25+
type RestPost = {
26+
link: string;
27+
title?: { rendered?: string };
28+
_embedded?: { 'wp:featuredmedia'?: { source_url?: string }[] };
29+
};
30+
31+
type IndexNovel = Plugin.NovelItem & { finished: boolean };
32+
33+
class AnimeCenterBR implements Plugin.PluginBase {
34+
id = 'animecenterbr';
35+
name = 'Anime Center BR';
36+
site = 'https://animecenterbr.com';
37+
icon = 'src/pt-br/animecenterbr/icon.png';
38+
version = '1.0.0';
39+
40+
private async request(url: string) {
41+
const response = await fetchApi(url);
42+
if (!response.ok) {
43+
throw Object.assign(
44+
new Error(`Anime Center BR: HTTP ${response.status}.`),
45+
{ status: response.status },
46+
);
47+
}
48+
return response;
49+
}
50+
51+
private cleanText(text: string): string {
52+
return text.replace(/\s+/g, ' ').trim();
53+
}
54+
55+
/**
56+
* Converts a link into a site-relative path (`/slug/`). Returns undefined for
57+
* other sites, the home page, anchors and non-content areas of the site.
58+
*/
59+
private sitePath(href: string | undefined): string | undefined {
60+
if (!href) return undefined;
61+
let url: URL;
62+
try {
63+
url = new URL(href, this.site);
64+
} catch {
65+
return undefined;
66+
}
67+
if (!SITE_HOST.test(url.hostname)) return undefined;
68+
const segments = url.pathname.split('/').filter(Boolean);
69+
if (
70+
segments.length !== 1 ||
71+
/^(?:category|tag|page|wp-)/.test(segments[0])
72+
) {
73+
return undefined;
74+
}
75+
return `/${segments[0]}/`;
76+
}
77+
78+
/**
79+
* The "LIGHT NOVELS" page is the site's catalogue: an A-Z index with one
80+
* list per initial letter.
81+
*/
82+
private async catalogue(): Promise<IndexNovel[]> {
83+
const $ = loadCheerio(
84+
await (await this.request(`${this.site}/light-novels-2/`)).text(),
85+
);
86+
const novels: IndexNovel[] = [];
87+
const seen = new Set<string>();
88+
$('h1')
89+
.filter((_, el) => /^(?:0-9|[A-Z])$/i.test($(el).text().trim()))
90+
.next('ul')
91+
.children('li')
92+
.each((_, item) => {
93+
const link = $(item).find('a[href]').first();
94+
const path = this.sitePath(link.attr('href'));
95+
const name = this.cleanText(link.text());
96+
if (!path || !name || seen.has(path)) return;
97+
seen.add(path);
98+
novels.push({
99+
name,
100+
path,
101+
cover: defaultCover,
102+
finished: FINISHED.test($(item).text()),
103+
});
104+
});
105+
return novels;
106+
}
107+
108+
private page(novels: IndexNovel[], pageNo: number): Plugin.NovelItem[] {
109+
const from = (Math.max(pageNo, 1) - 1) * PAGE_SIZE;
110+
return novels
111+
.slice(from, from + PAGE_SIZE)
112+
.map(({ name, path, cover }) => ({ name, path, cover }));
113+
}
114+
115+
/** Novels in the "Light Novels" category, most recently added first. */
116+
private async latestNovels(pageNo: number): Promise<Plugin.NovelItem[]> {
117+
const response = await fetchApi(
118+
`${this.site}${REST_LATEST}&per_page=${PAGE_SIZE}&page=${pageNo}`,
119+
);
120+
// WordPress answers a page past the last one with HTTP 400.
121+
if (response.status === 400 || response.status === 404) return [];
122+
if (!response.ok) {
123+
throw new Error(`Anime Center BR: HTTP ${response.status}.`);
124+
}
125+
const posts: RestPost[] = await response.json();
126+
const novels: Plugin.NovelItem[] = [];
127+
for (const post of posts) {
128+
const path = this.sitePath(post.link);
129+
const name = this.cleanText(
130+
loadCheerio(post.title?.rendered || '')
131+
.text()
132+
.replace(TITLE_SUFFIX, ''),
133+
);
134+
if (!path || !name) continue;
135+
novels.push({
136+
name,
137+
path,
138+
cover:
139+
post._embedded?.['wp:featuredmedia']?.[0]?.source_url || defaultCover,
140+
});
141+
}
142+
return novels;
143+
}
144+
145+
async popularNovels(
146+
pageNo: number,
147+
{ showLatestNovels }: Plugin.PopularNovelsOptions,
148+
): Promise<Plugin.NovelItem[]> {
149+
// The site has no popularity ranking: browsing is its A-Z catalogue.
150+
if (showLatestNovels) return this.latestNovels(pageNo);
151+
return this.page(await this.catalogue(), pageNo);
152+
}
153+
154+
async searchNovels(
155+
searchTerm: string,
156+
pageNo: number,
157+
): Promise<Plugin.NovelItem[]> {
158+
// The site's own search only finds individual chapter posts, so series are
159+
// matched against the titles of the catalogue instead.
160+
const tokens = searchTerm.toLowerCase().split(/\s+/).filter(Boolean);
161+
if (!tokens.length) return [];
162+
const novels = await this.catalogue();
163+
return this.page(
164+
novels.filter(novel => {
165+
const name = novel.name.toLowerCase();
166+
return tokens.every(token => name.includes(token));
167+
}),
168+
pageNo,
169+
);
170+
}
171+
172+
/**
173+
* Returns the part of the page that belongs to the post itself: everything
174+
* before the share buttons (what follows is related posts and comments).
175+
*/
176+
private postBody($: ReturnType<typeof loadCheerio>) {
177+
const article = $('article.single').first();
178+
const body = article.length ? article : $('article').first();
179+
const share = body.find('.post-share').first();
180+
share.nextAll().remove();
181+
share.remove();
182+
body.find('script, style, noscript, iframe, ins, form').remove();
183+
return body;
184+
}
185+
186+
private async coverIfReachable(src: string | undefined): Promise<string> {
187+
// Most of the older uploads of the site were deleted: only use the
188+
// picture when it can still be loaded.
189+
if (!src || src.startsWith('data:')) return defaultCover;
190+
try {
191+
const url = new URL(src, this.site).href;
192+
const response = await fetchApi(url, { method: 'HEAD' });
193+
return response.ok ? url : defaultCover;
194+
} catch {
195+
return defaultCover;
196+
}
197+
}
198+
199+
private status(label: string | undefined, finished?: boolean): string {
200+
const text = (label || '').toLowerCase();
201+
if (/finaliz|complet/.test(text)) return NovelStatus.Completed;
202+
if (/andamento|lançamento|ativo/.test(text)) return NovelStatus.Ongoing;
203+
if (/hiato|pausad/.test(text)) return NovelStatus.OnHiatus;
204+
if (/cancel|abandon|dropad/.test(text)) return NovelStatus.Cancelled;
205+
return finished ? NovelStatus.Completed : NovelStatus.Unknown;
206+
}
207+
208+
async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
209+
const $ = loadCheerio(
210+
await (await this.request(this.resolveUrl(novelPath))).text(),
211+
);
212+
const body = this.postBody($);
213+
const selfPath = this.sitePath(novelPath) || novelPath;
214+
215+
const name =
216+
this.cleanText($('h1.title').first().text()).replace(TITLE_SUFFIX, '') ||
217+
this.cleanText(body.find('h2, h3').first().text()) ||
218+
'Untitled';
219+
// The catalogue tells which links are other novels and which are finished.
220+
const catalogue = await this.catalogue().catch(() => [] as IndexNovel[]);
221+
const listed = catalogue.find(novel => novel.path === selfPath);
222+
const otherNovels = new Set(catalogue.map(novel => novel.path));
223+
224+
const details: Record<string, string> = {};
225+
body.find('li').each((_, item) => {
226+
const label = this.cleanText($(item).children('strong').first().text());
227+
if (!label || !label.endsWith(':')) return;
228+
const value = this.cleanText(
229+
$(item).text().replace($(item).children('strong').first().text(), ''),
230+
);
231+
if (value) details[label.slice(0, -1).toLowerCase()] = value;
232+
});
233+
const genres = (details['gêneros'] || details['gênero'] || '')
234+
.replace(/\.$/, '')
235+
.trim();
236+
237+
// The chapter links come in lists, grouped under "Volume N" lines.
238+
const chapters: Plugin.ChapterItem[] = [];
239+
const seen = new Set<string>([selfPath]);
240+
let volume = '';
241+
let hasVolumes = false;
242+
body.children().each((_, el) => {
243+
const block = $(el);
244+
const links = block.is('a') ? block : block.find('a[href]');
245+
if (!links.length) {
246+
const text = this.cleanText(block.text());
247+
const match = text.length < 250 ? VOLUME.exec(text) : null;
248+
if (match) {
249+
volume = `Volume ${match[1]}`;
250+
hasVolumes = true;
251+
}
252+
return;
253+
}
254+
links.each((_, link) => {
255+
const path = this.sitePath($(link).attr('href'));
256+
const text = this.cleanText($(link).text());
257+
if (!path || !text || seen.has(path)) return;
258+
if (otherNovels.has(path) || NOVEL_PAGE_SLUG.test(path.slice(1, -1))) {
259+
return;
260+
}
261+
seen.add(path);
262+
const number = CHAPTER_NUMBER.exec(text)?.[1];
263+
chapters.push({
264+
name: volume && !VOLUME.test(text) ? `${volume} – ${text}` : text,
265+
path,
266+
chapterNumber: number ? Number(number.replace(',', '.')) : undefined,
267+
});
268+
});
269+
});
270+
if (hasVolumes) {
271+
// Chapter numbers restart in every volume: keep the site's order.
272+
chapters.forEach(chapter => delete chapter.chapterNumber);
273+
}
274+
if (!chapters.length) {
275+
throw new Error(
276+
'Anime Center BR: no chapters are hosted on the site for this novel (it only links to downloads).',
277+
);
278+
}
279+
280+
// The synopsis starts at the "Sinopse:" line and runs over the plain
281+
// paragraphs that follow it.
282+
const paragraphs: string[] = [];
283+
let inSynopsis = false;
284+
for (const el of body.children().toArray()) {
285+
const block = $(el);
286+
const text = this.cleanText(block.text());
287+
if (!inSynopsis) {
288+
if (block.is('p') && SINOPSE.test(text)) {
289+
inSynopsis = true;
290+
paragraphs.push(text.replace(SINOPSE, ''));
291+
}
292+
continue;
293+
}
294+
if (
295+
!block.is('p') ||
296+
!text ||
297+
SUPPORT_NOTICE.test(text) ||
298+
block.find('a[href], img').length
299+
) {
300+
break;
301+
}
302+
paragraphs.push(text);
303+
}
304+
305+
return {
306+
path: novelPath,
307+
name,
308+
cover: await this.coverIfReachable(body.find('img[src]').attr('src')),
309+
author: details['autor'],
310+
genres: genres || undefined,
311+
status: this.status(details['status'], listed?.finished),
312+
summary: paragraphs.filter(Boolean).join('\n\n') || undefined,
313+
chapters,
314+
};
315+
}
316+
317+
async parseChapter(chapterPath: string): Promise<string> {
318+
const $ = loadCheerio(
319+
await (await this.request(this.resolveUrl(chapterPath))).text(),
320+
);
321+
const body = this.postBody($);
322+
body
323+
.find('.adsbygoogle, [id^="denakop-ad"], nav, .post-navigation')
324+
.remove();
325+
// Ad slots leave empty wrappers behind.
326+
body.find('div').each((_, el) => {
327+
if (!$(el).text().trim() && !$(el).find('img').length) $(el).remove();
328+
});
329+
330+
const chapter = body.html()?.trim() || '';
331+
// The illustration pages of a volume have pictures and almost no text.
332+
if (this.cleanText(body.text()).length < 100 && !body.find('img').length) {
333+
throw new Error('Anime Center BR: no readable chapter text found.');
334+
}
335+
return chapter;
336+
}
337+
338+
resolveUrl = (path: string) => new URL(path, this.site).href;
339+
}
340+
341+
export default new AnimeCenterBR();
3.41 KB
Loading

0 commit comments

Comments
 (0)