Skip to content

Commit 6898325

Browse files
authored
feat(spanish): add Novel Translations source (#2889)
1 parent 69a9617 commit 6898325

2 files changed

Lines changed: 308 additions & 0 deletions

File tree

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
import { load as parseHTML } from 'cheerio';
2+
import { fetchApi } from '@libs/fetch';
3+
import { Plugin } from '@/types/plugin';
4+
import { defaultCover } from '@libs/defaultCover';
5+
import { NovelStatus } from '@libs/novelStatus';
6+
7+
const BASE = 'https://noveltranslations18.blogspot.com';
8+
const SERIES_URL = `${BASE}/search/label/Series?max-results=150`;
9+
const SERIES_FEED_URL = `${BASE}/feeds/posts/default/-/Series?alt=json&max-results=150`;
10+
const FEED_PAGE_SIZE = 150;
11+
const MAX_FEED_PAGES = 10;
12+
13+
const STATUS: Record<string, string> = {
14+
ongoing: NovelStatus.Ongoing,
15+
completed: NovelStatus.Completed,
16+
hiatus: NovelStatus.OnHiatus,
17+
cancelled: NovelStatus.Cancelled,
18+
dropped: NovelStatus.Cancelled,
19+
};
20+
21+
const normalize = (text: string) =>
22+
text
23+
.toLowerCase()
24+
.replace(/[áàä]/g, 'a')
25+
.replace(/[éèë]/g, 'e')
26+
.replace(/[íìï]/g, 'i')
27+
.replace(/[óòö]/g, 'o')
28+
.replace(/[úùü]/g, 'u')
29+
.replace(/ñ/g, 'n')
30+
.replace(/[^a-z0-9]+/g, '');
31+
32+
const toPath = (url: string) => url.replace(/^https?:\/\/[^/]+/, '');
33+
34+
// Batch posts such as "Capitulo 1 a 25" only embed a Google Drive file.
35+
const isBatchPost = (title: string) => /\d+\s+a\s+\d+/i.test(title);
36+
37+
// "Capítulo 12", "Capitulo 12.5" or "Chapter 12"; volume labels have no
38+
// single chapter number.
39+
const chapterNumberOf = (title: string) => {
40+
const match =
41+
/cap(?:[ií]tulo|\.)?\s*(\d+(?:\.\d+)?)|chapter\s*(\d+(?:\.\d+)?)/i.exec(
42+
title,
43+
);
44+
return match ? Number(match[1] || match[2]) : undefined;
45+
};
46+
47+
type Series = { name: string; path: string; cover?: string; body?: string };
48+
type FeedEntry = {
49+
title: { $t: string };
50+
content?: { $t: string };
51+
published: { $t: string };
52+
link: { rel: string; href: string }[];
53+
media$thumbnail?: { url: string };
54+
};
55+
56+
class NovelTranslations18Plugin implements Plugin.PluginBase {
57+
id = 'noveltranslations18';
58+
name = 'Novel Translations';
59+
icon = 'src/es/noveltranslations18/icon.png';
60+
site = `${BASE}/`;
61+
version = '1.0.0';
62+
filters = undefined;
63+
64+
private seriesCache?: Promise<Series[]>;
65+
66+
// Blogger answers bursts with 429/503: wait once, then retry exactly once.
67+
private async request(url: string) {
68+
const response = await fetchApi(url);
69+
if (response.status !== 429 && response.status !== 503) return response;
70+
const retryAfter = Number(response.headers.get('Retry-After'));
71+
const seconds = retryAfter > 0 ? Math.min(retryAfter, 10) : 2;
72+
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
73+
return fetchApi(url);
74+
}
75+
76+
private async getHtml(url: string) {
77+
const response = await this.request(url);
78+
if (!response.ok) {
79+
throw new Error(`No se pudo acceder al sitio (${response.status}).`);
80+
}
81+
return parseHTML(await response.text());
82+
}
83+
84+
private async getSeriesFromFeed() {
85+
const response = await this.request(SERIES_FEED_URL);
86+
if (!response.ok) throw new Error(`Feed (${response.status}).`);
87+
const entries: FeedEntry[] = (await response.json())?.feed?.entry || [];
88+
const series: Series[] = [];
89+
entries.forEach(entry => {
90+
const link = entry.link.find(item => item.rel === 'alternate');
91+
const name = entry.title.$t.trim();
92+
if (!link || !name) return;
93+
series.push({
94+
name,
95+
path: toPath(link.href),
96+
cover: entry.media$thumbnail?.url.replace('/s72-c/', '/s400/'),
97+
body: entry.content?.$t,
98+
});
99+
});
100+
if (series.length === 0) throw new Error('Feed vacío.');
101+
return series;
102+
}
103+
104+
private async getSeriesFromHtml() {
105+
const $ = await this.getHtml(SERIES_URL);
106+
const series: Series[] = [];
107+
$('a.clamp').each((_, el) => {
108+
const link = $(el);
109+
const href = link.attr('href');
110+
const name = link.text().trim();
111+
if (!href || !name) return;
112+
const cover = link.parent().find('img').first().attr('src');
113+
series.push({ name, path: toPath(href), cover });
114+
});
115+
return series;
116+
}
117+
118+
// The whole catalogue is the "Series" label: read its feed, falling back to
119+
// the label page.
120+
private getSeries() {
121+
if (!this.seriesCache) {
122+
this.seriesCache = this.getSeriesFromFeed()
123+
.catch(() => this.getSeriesFromHtml())
124+
.catch(error => {
125+
// Let the next call retry instead of caching a failed request.
126+
this.seriesCache = undefined;
127+
throw error;
128+
});
129+
}
130+
return this.seriesCache;
131+
}
132+
133+
private toItems(series: Series[]): Plugin.NovelItem[] {
134+
return series.map(item => ({
135+
name: item.name,
136+
path: item.path,
137+
cover: item.cover || defaultCover,
138+
}));
139+
}
140+
141+
async popularNovels(pageNo: number): Promise<Plugin.NovelItem[]> {
142+
if (pageNo > 1) return [];
143+
return this.toItems(await this.getSeries());
144+
}
145+
146+
// Some novels have no chapter index in their page (the site fills it in with
147+
// a script from the label feed), so the same feed is read here.
148+
private async getFeedChapters(label: string, novelPath: string) {
149+
const chapters: Plugin.ChapterItem[] = [];
150+
for (let page = 0; page < MAX_FEED_PAGES; page++) {
151+
const start = page * FEED_PAGE_SIZE + 1;
152+
const response = await this.request(
153+
`${BASE}/feeds/posts/default/-/${encodeURIComponent(label)}?alt=json&start-index=${start}&max-results=${FEED_PAGE_SIZE}`,
154+
);
155+
if (!response.ok) {
156+
throw new Error(
157+
`No se pudieron cargar los capítulos (${response.status}).`,
158+
);
159+
}
160+
const entries: FeedEntry[] = (await response.json())?.feed?.entry || [];
161+
entries.forEach(entry => {
162+
const link = entry.link.find(item => item.rel === 'alternate');
163+
if (!link) return;
164+
const path = toPath(link.href);
165+
if (path === novelPath) return;
166+
const name = parseHTML(`<p>${entry.title.$t}</p>`).text().trim();
167+
if (isBatchPost(name)) return;
168+
chapters.push({
169+
name,
170+
path,
171+
releaseTime: entry.published.$t,
172+
chapterNumber: chapterNumberOf(name),
173+
});
174+
});
175+
if (entries.length < FEED_PAGE_SIZE) break;
176+
}
177+
return chapters.reverse();
178+
}
179+
180+
async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
181+
const response = await this.request(BASE + novelPath);
182+
let body: string;
183+
let fallbackCover: string | undefined;
184+
if (response.ok) {
185+
body = await response.text();
186+
} else {
187+
// Blogger may throttle novel pages; the series feed carries the same
188+
// post content (synopsis and chapter index).
189+
const entry = (await this.getSeries().catch(() => [])).find(
190+
item => item.path === novelPath && item.body,
191+
);
192+
if (!entry) {
193+
throw new Error(`No se pudo acceder a la novela (${response.status}).`);
194+
}
195+
body = `<h1>${entry.name}</h1>${entry.body}`;
196+
fallbackCover = entry.cover;
197+
}
198+
const $ = parseHTML(body);
199+
200+
const novel: Plugin.SourceNovel = {
201+
path: novelPath,
202+
name: $('h1').first().text().trim() || 'Untitled',
203+
cover:
204+
$('meta[property="og:image"]').attr('content') ||
205+
fallbackCover ||
206+
defaultCover,
207+
};
208+
209+
const summary = $('#synopsis').text().trim();
210+
if (summary) novel.summary = summary;
211+
212+
const author = $('#extra-info .y6x11p')
213+
.filter((_, el) => /^(author|autor)\b/i.test($(el).text().trim()))
214+
.find('.dt')
215+
.text()
216+
.trim();
217+
if (author && author !== 'None') novel.author = author;
218+
219+
const genres = $('a.label[rel="tag"]')
220+
.map((_, el) => $(el).text().trim())
221+
.get()
222+
.filter(Boolean)
223+
.join(', ');
224+
if (genres) novel.genres = genres;
225+
226+
const status = $('aside .y6x11p')
227+
.filter((_, el) => /^estado/i.test($(el).text().trim()))
228+
.find('a')
229+
.text()
230+
.trim()
231+
.toLowerCase();
232+
novel.status = STATUS[status] || NovelStatus.Unknown;
233+
234+
const chapters: Plugin.ChapterItem[] = [];
235+
$('#download .index-list a').each((_, el) => {
236+
const link = $(el);
237+
const href = link.attr('href') || '';
238+
// Download links (Google Drive, ...) are not readable chapters.
239+
if (href.indexOf(BASE) !== 0) return;
240+
const name = link.text().replace(/\s+/g, ' ').trim();
241+
if (!name || isBatchPost(name)) return;
242+
chapters.push({
243+
name,
244+
path: toPath(href),
245+
chapterNumber: chapterNumberOf(name),
246+
});
247+
});
248+
// The index lists the newest chapter first.
249+
chapters.reverse();
250+
251+
if (chapters.length === 0) {
252+
const label = /clwd\.run\('((?:[^'\\]|\\.)*)'\)/.exec(body);
253+
if (label) {
254+
novel.chapters = await this.getFeedChapters(
255+
label[1].replace(/\\'/g, "'"),
256+
novelPath,
257+
);
258+
return novel;
259+
}
260+
}
261+
262+
novel.chapters = chapters;
263+
return novel;
264+
}
265+
266+
async parseChapter(chapterPath: string): Promise<string> {
267+
// Blogger throttles post pages but not the feed, which carries the same
268+
// post body.
269+
const response = await this.request(
270+
`${BASE}/feeds/posts/default?alt=json&path=${encodeURIComponent(chapterPath)}`,
271+
);
272+
if (!response.ok) {
273+
throw new Error(`No se pudo acceder al sitio (${response.status}).`);
274+
}
275+
const entry: FeedEntry | undefined = (await response.json())?.feed
276+
?.entry?.[0];
277+
if (!entry?.content) throw new Error('Capítulo no encontrado.');
278+
const $ = parseHTML(`<div class="check-box">${entry.content.$t}</div>`);
279+
const content = $('.check-box').first();
280+
content.find('script, style, ins, iframe').remove();
281+
// Text pasted from Google Docs carries inline styles and spacer breaks.
282+
content.find('[style]').removeAttr('style');
283+
content.find('br').remove();
284+
content.find('p').each((_, el) => {
285+
const paragraph = $(el);
286+
if (!paragraph.text().trim() && !paragraph.find('img').length) {
287+
paragraph.remove();
288+
}
289+
});
290+
return content.html() || '';
291+
}
292+
293+
async searchNovels(
294+
searchTerm: string,
295+
pageNo: number,
296+
): Promise<Plugin.NovelItem[]> {
297+
// The site's search also matches chapter posts, so the catalogue is
298+
// filtered by title instead.
299+
if (pageNo > 1) return [];
300+
const term = normalize(searchTerm);
301+
const series = await this.getSeries();
302+
return this.toItems(
303+
series.filter(item => normalize(item.name).indexOf(term) >= 0),
304+
);
305+
}
306+
}
307+
308+
export default new NovelTranslations18Plugin();
7.33 KB
Loading

0 commit comments

Comments
 (0)