diff --git a/plugins/english/weebsread.ts b/plugins/english/weebsread.ts new file mode 100644 index 0000000000..4e8a49c0e8 --- /dev/null +++ b/plugins/english/weebsread.ts @@ -0,0 +1,405 @@ +import { fetchApi } from '@libs/fetch'; +import { Filters, FilterTypes } from '@libs/filterInputs'; +import { NovelStatus } from '@libs/novelStatus'; +import { + checkResponse, + createPluginError, + PluginError, +} from '@libs/pluginError'; +import { Plugin } from '@/types/plugin'; +import { load as parseHTML } from 'cheerio'; + +/** + * www.weebsread.com is a Blogger blog. Its labels carry the structure: + * "novel" marks a novel's page, "chapter" a chapter, every novel has a label + * of its own shared by its page and chapters, and "featured", "completed" and + * "dropped" mark novels. Lists come from Blogger's JSON feeds (at most 150 + * entries per request, paged by start-index): + * + * - novels: `/feeds/posts/summary/-/novel` + * - one novel: `/feeds/posts/default/` (details are in the post HTML) + * - chapters: `/feeds/posts/summary/-/chapter/` + * - chapter: the post page, text in `#chapterContent` + * + * Paths are the post's own path, e.g. `2026/10/.html`. + */ +const SITE = 'https://www.weebsread.com/'; +const PER_REQUEST = 150; +const MAX_PAGES = 40; + +/** + * True for attribute values that would run script when the reader follows + * or loads them. Browsers ignore control characters and spaces inside a URL + * scheme (`java script:`), so those are dropped first; the parser has + * already decoded entities. + */ +function isUnsafeUrl(value: string): boolean { + // eslint-disable-next-line no-control-regex + const url = value.replace(/[\u0000- \u007f]/g, '').toLowerCase(); + return ( + url.startsWith('javascript:') || + url.startsWith('vbscript:') || + (url.startsWith('data:') && !url.startsWith('data:image/')) + ); +} +const STRUCTURE: Record = { + novel: true, + chapter: true, + featured: true, + completed: true, + dropped: true, +}; + +type FeedText = { $t: string }; +type FeedEntry = { + id: FeedText; + title: FeedText; + published?: FeedText; + content?: FeedText; + link?: { rel: string; href: string }[]; + category?: { term: string }[]; + media$thumbnail?: { url: string }; +}; +type Feed = { + feed?: { entry?: FeedEntry[]; openSearch$totalResults?: FeedText }; + entry?: FeedEntry; +}; + +const clean = (s: unknown): string => + String(s ?? '') + .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '') + .replace(/\s+/g, ' ') + .trim(); + +const titleKey = (s: string): string => + clean(s) + .toLowerCase() + .replace(/[\u2018\u2019\u02bc]/g, "'") + .replace(/[^a-z0-9]+/g, ''); + +const pathOf = (url: string | undefined): string | null => + String(url || '').match( + /^https?:\/\/(?:www\.)?weebsread\.com\/([^?#]+?)\/?(?:[?#].*)?$/i, + )?.[1] || null; + +const entryPath = (e: FeedEntry): string | null => + pathOf((e.link || []).find(l => l.rel === 'alternate')?.href); + +const labelsOf = (e: FeedEntry): string[] => + (e.category || []).map(c => c.term); + +/** Feed thumbnails are 72px crops; ask Blogger's image server for 400px. */ +const coverOf = (e: FeedEntry): string | undefined => + e.media$thumbnail?.url + .replace(/\/s\d+(-c)?\//, '/s400/') + .replace(/=s\d+(-c)?$/, '=s400'); + +class WeebsReadPlugin implements Plugin.PluginBase { + id = 'weebsread'; + name = 'WeebsRead'; + icon = 'src/en/weebsread/icon.png'; + site = SITE; + version = '1.0.0'; + + // The blog's own labels for novels. + filters = { + label: { + type: FilterTypes.Picker, + label: 'Show', + value: '', + options: [ + { label: 'All novels', value: '' }, + { label: 'Featured', value: 'featured' }, + { label: 'Translation completed', value: 'completed' }, + { label: 'Translation dropped', value: 'dropped' }, + ], + }, + } satisfies Filters; + + private async json(url: string): Promise { + const r = await fetchApi(url, { headers: { Accept: 'application/json' } }); + checkResponse(r); + try { + return (await r.json()) as Feed; + } catch { + throw createPluginError(PluginError.InvalidResponse, { url }); + } + } + + /** + * Every entry of a feed, newest first, following its 150-entry pages. + * Fails rather than return part of a feed: a chapter list that lost its + * older entries would otherwise look complete. + */ + private async allEntries(base: string): Promise { + let entries: FeedEntry[] = []; + for (let i = 0; i < MAX_PAGES; i++) { + const url = + base + + (base.includes('?') ? '&' : '?') + + 'alt=json&orderby=published&max-results=' + + PER_REQUEST + + '&start-index=' + + (1 + entries.length); + const d = await this.json(url); + const total = parseInt(d.feed?.openSearch$totalResults?.$t ?? '', 10); + if (!d.feed || isNaN(total)) { + throw createPluginError(PluginError.InvalidResponse, { + message: "WeebsRead's feed gives no entry total.", + url, + }); + } + const got = d.feed.entry || []; + entries = entries.concat(got); + if (entries.length >= total) return entries; + if (!got.length) { + throw createPluginError(PluginError.InvalidResponse, { + message: `WeebsRead's feed stopped at ${entries.length} of ${total} entries.`, + url, + }); + } + } + throw createPluginError(PluginError.InvalidResponse, { + message: `WeebsRead's feed has more than ${MAX_PAGES * PER_REQUEST} entries.`, + url: base, + }); + } + + private async novelEntries(): Promise { + const entries = await this.allEntries(SITE + 'feeds/posts/summary/-/novel'); + if (!entries.length) { + throw createPluginError(PluginError.InvalidResponse, { + message: 'WeebsRead\'s feed lists no novels (label "novel").', + url: SITE, + }); + } + return entries; + } + + private toNovels(entries: FeedEntry[]): Plugin.NovelItem[] { + const novels: Plugin.NovelItem[] = []; + for (const e of entries) { + const path = entryPath(e); + if (path) + novels.push({ name: clean(e.title.$t), path, cover: coverOf(e) }); + } + return novels; + } + + async popularNovels( + pageNo: number, + { + showLatestNovels, + filters, + }: Plugin.PopularNovelsOptions, + ): Promise { + if (pageNo > 1) return []; // every novel comes on the first page + const label = filters?.label?.value; + let entries = await this.novelEntries(); + if (label) entries = entries.filter(e => labelsOf(e).includes(label)); + if (showLatestNovels) { + // Novels in the order of their newest chapter among the latest 150. + const recent = await this.json( + SITE + + 'feeds/posts/summary/-/chapter?alt=json&orderby=published&max-results=' + + PER_REQUEST, + ); + const rank: Record = {}; + (recent.feed?.entry || []).forEach((c, i) => + labelsOf(c).forEach(l => { + if (!STRUCTURE[l] && rank[l] === undefined) rank[l] = i; + }), + ); + const at = (e: FeedEntry) => + Math.min( + Infinity, + ...labelsOf(e) + .map(l => rank[l]) + .filter(x => x !== undefined), + ); + entries = entries + .map((e, i) => ({ e, r: at(e), i })) + .sort((a, b) => a.r - b.r || a.i - b.i) + .map(x => x.e); + } + return this.toNovels(entries); + } + + async searchNovels( + searchTerm: string, + pageNo: number, + ): Promise { + if (pageNo > 1) return []; + const want = titleKey(searchTerm); + return this.toNovels(await this.novelEntries()).filter( + n => !want || titleKey(n.name).includes(want), + ); + } + + async parseNovel(novelPath: string): Promise { + const path = novelPath.replace(/^\/+|\/+$/g, ''); + const entry = (await this.novelEntries()).find(e => entryPath(e) === path); + if (!entry) { + throw createPluginError(PluginError.NovelNotFound, { url: SITE + path }); + } + const labels = labelsOf(entry); + const own = labels.filter(l => !STRUCTURE[l]); + if (own.length !== 1) { + throw createPluginError(PluginError.InvalidResponse, { + message: `WeebsRead's novel "${clean(entry.title.$t)}" has ${own.length} labels of its own (${own.join(', ')}); its chapters are found by exactly one.`, + url: SITE + path, + }); + } + const postId = entry.id.$t.match(/post-(\d+)$/)?.[1]; + const full = postId + ? (await this.json(SITE + 'feeds/posts/default/' + postId + '?alt=json')) + .entry + : undefined; + const $ = parseHTML(full?.content?.$t || ''); + let status = ''; + $('span').each((_, el) => { + if (!status && clean($(el).text()) === 'Status:') { + status = clean($(el).next('span').text()); + } + }); + let synopsis = $('#synopsis p') + .map((_, p) => clean($(p).text())) + .get() + .filter(Boolean); + if (!synopsis.length) { + synopsis = $('.screen-reader-only p') + .map((_, p) => clean($(p).text())) + .get() + .filter(Boolean); + } + if (labels.includes('dropped')) { + synopsis.push('WeebsRead marks this translation as dropped.'); + } else if (labels.includes('completed')) { + synopsis.push('WeebsRead marks this translation as completed.'); + } + const author = clean( + $('p') + .filter((_, p) => /^By\b/.test(clean($(p).text()))) + .first() + .find('span') + .first() + .text(), + ); + const name = clean(entry.title.$t); + const prefix = new RegExp( + '^' + + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + + '\\s*[-\u2013\u2014:]\\s*', + 'i', + ); + + const seen: Record = {}; + const posted = ( + await this.allEntries( + SITE + 'feeds/posts/summary/-/chapter/' + encodeURIComponent(own[0]), + ) + ) + .map(c => { + const title = clean(c.title.$t); + const num = title.match(/chapter\s*([0-9]+(?:\.[0-9]+)?)/i)?.[1]; + return { + name: title.replace(prefix, '') || title, + path: entryPath(c) || '', + releaseTime: c.published?.$t, + chapterNumber: num ? parseFloat(num) : undefined, + }; + }) + .filter(c => { + if (!c.path || seen[c.path]) return false; + seen[c.path] = true; + return true; + }) + .sort((a, b) => + String(a.releaseTime).localeCompare(String(b.releaseTime)), + ); + // Reading order is by chapter number (batch uploads post chapters out of + // order); a chapter without a number (prologue, side story) stays after + // the numbered chapter posted before it. + let last = 0; + const chapters: Plugin.ChapterItem[] = posted + .map((c, i) => { + if (c.chapterNumber !== undefined) last = c.chapterNumber; + return { + c, + key: c.chapterNumber ?? last, + numbered: c.chapterNumber !== undefined ? 0 : 1, + i, + }; + }) + .sort((a, b) => a.key - b.key || a.numbered - b.numbered || a.i - b.i) + .map(x => x.c); + + const novel: Plugin.SourceNovel = { path, name, chapters }; + const cover = + $('img[alt="Novel Cover"]').first().attr('src') || coverOf(entry); + if (cover) novel.cover = cover; + if (synopsis.length) novel.summary = synopsis.join('\n\n'); + if (author) novel.author = author; + const s = status.toLowerCase(); + if (s.includes('ongoing')) novel.status = NovelStatus.Ongoing; + else if (s.includes('complete')) novel.status = NovelStatus.Completed; + else if (s.includes('hiatus')) novel.status = NovelStatus.OnHiatus; + else if (labels.includes('dropped')) novel.status = NovelStatus.Cancelled; + const genres = $('.genre-tag') + .map((_, g) => clean($(g).text())) + .get(); + if (genres.length) novel.genres = genres.join(', '); + return novel; + } + + async parseChapter(chapterPath: string): Promise { + const url = SITE + chapterPath.replace(/^\/+/, ''); + const r = await fetchApi(url, { headers: { Accept: 'text/html' } }); + checkResponse(r, { notFoundCode: PluginError.ChapterNotFound }); + const $ = parseHTML(await r.text()); + const content = $('#chapterContent').first(); + if (!content.length) { + throw createPluginError(PluginError.InvalidResponse, { + message: "WeebsRead's chapter page has no #chapterContent block.", + url, + }); + } + // Embedded documents and page-level tags can run script or reroute links. + content + .find( + 'script, style, noscript, ins, iframe, frame, frameset, object, embed, ' + + 'applet, svg, math, template, base, meta, link, button, form', + ) + .remove(); + content.find('*').each((_, el) => { + for (const attr of Object.keys(el.attribs)) { + if (/^on/i.test(attr) || isUnsafeUrl(el.attribs[attr])) { + $(el).removeAttr(attr); + } + } + }); + if (clean(content.text()).length < 20) { + throw createPluginError(PluginError.EmptyContent, { url }); + } + if (content.find('p').length) return content.html() || ''; + // Lines separated by
, with zero-width spaces on the blank ones. + return String(content.html() || '') + .split(//i) + .map(line => + line + .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '') + .replace(/ /g, ' ') + .trim(), + ) + .filter(line => { + const l = parseHTML(line).root(); + return clean(l.text()) || l.find('img[src]').length; + }) + .map(line => '

' + line + '

') + .join('\n'); + } + + resolveUrl = (path: string): string => SITE + path.replace(/^\/+/, ''); +} + +export default new WeebsReadPlugin(); diff --git a/public/static/src/en/weebsread/icon.png b/public/static/src/en/weebsread/icon.png new file mode 100644 index 0000000000..6654961c8b Binary files /dev/null and b/public/static/src/en/weebsread/icon.png differ