diff --git a/plugins/english/novelscroll.ts b/plugins/english/novelscroll.ts new file mode 100644 index 0000000000..bcdb52ab0f --- /dev/null +++ b/plugins/english/novelscroll.ts @@ -0,0 +1,306 @@ +import { fetchApi } from '@libs/fetch'; +import { NovelStatus } from '@libs/novelStatus'; +import { + checkResponse, + createPluginError, + PluginError, +} from '@libs/pluginError'; +import { Plugin } from '@/types/plugin'; +import { CheerioAPI, load as parseHTML } from 'cheerio'; + +/** + * novelscroll.com is WordPress (GeneratePress) on WordPress.com hosting. + * + * - catalogue: `/genre/all/`, every novel on one page (`div.manga-item` cards + * linking to `/manga//`) + * - latest: the homepage's "Latest Releases" (`.ns-lr .ns-li`) + * - novel: `/manga//` redirects to the novel's page; `.ns-hd` holds + * title, status and cover, `.ns-sum` the synopsis, `.auto-toc` every chapter + * in reading order; premium chapters are on Patreon and not listed + * - chapter: the post's `div.entry-content` + * + * The site makes every client that names itself a browser pass a JavaScript + * check ("Checking your browser...") and serves its pages to other clients, + * so this plugin names itself in its User-Agent instead of sending the app's + * browser one. It solves no check. Its uploads answer a browser user agent + * with the check page too; the same files load through the site's Jetpack + * image CDN (i0.wp.com). + * + * Paths: `manga/` for a novel in the catalogue, the novel page's own + * slug for one that is not; the post's own path for a chapter. + */ +const SITE = 'https://novelscroll.com/'; +const VERSION = '1.0.0'; +const HEADERS = { + 'User-Agent': + 'LNReader-NovelScroll/' + + VERSION + + ' (+https://github.com/LNReader/lnreader-plugins)', + 'Accept': 'text/html', +}; +/** + * 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 NOVEL_PATH = /^(?:manga\/)?[^/?#]+$/; + +const clean = (s: unknown): string => + String(s ?? '') + .replace(/\s+/g, ' ') + .trim(); + +/** + * Title key for matching the homepage's entries to the catalogue's; the + * homepage may add a short form in brackets: "... BL Novel (MHIPBLN)". + */ +const titleKey = (s: string): string => + clean(s) + .replace(/\s*\([A-Z0-9]{2,12}\)$/, '') + .toLowerCase() + .replace(/[‘’ʼ]/g, "'") + .replace(/[^a-z0-9]+/g, ''); + +const cdn = (u: string | undefined): string | undefined => { + if (!u) return undefined; + const m = u.match( + /^https?:\/\/(?:www\.)?novelscroll\.com\/(wp-content\/uploads\/[^?#]+)/i, + ); + if (!m) return u; + let rest = m[1]; + try { + rest = decodeURI(rest); + } catch { + // keep as given + } + return 'https://i0.wp.com/novelscroll.com/' + encodeURI(rest) + '?ssl=1'; +}; + +const pathOf = (url: string | undefined): string | null => { + const m = String(url || '').match( + /^https?:\/\/(?:www\.)?novelscroll\.com\/([^#]+?)\/?(?:#.*)?$/i, + ); + return m ? m[1] : null; +}; + +const urlOf = (path: string): string => { + const p = path.replace(/^\/+|\/+$/g, ''); + return SITE + p + (p.includes('?') ? '' : '/'); +}; + +/** "02-12-2026" -> "2026-12-02" */ +const isoDate = (text: string): string | undefined => { + const m = clean(text).match(/^(\d{2})-(\d{2})-(\d{4})$/); + return m ? m[3] + '-' + m[2] + '-' + m[1] : undefined; +}; + +const styleUrl = (style: string | undefined): string | undefined => + (style || '').match(/url\((['"]?)([^'")]+)\1\)/)?.[2]; + +class NovelScrollPlugin implements Plugin.PluginBase { + id = 'novelscroll'; + name = 'NovelScroll'; + icon = 'src/en/novelscroll/icon.png'; + site = SITE; + version = VERSION; + imageRequestInit = { headers: { 'User-Agent': HEADERS['User-Agent'] } }; + + private async fetchPage(url: string): Promise { + const r = await fetchApi(url, { headers: HEADERS }); + const html = await r.text(); + if (/\s*Checking your browser/i.test(html)) { + throw createPluginError(PluginError.Captcha, { + status: r.status, + message: + 'NovelScroll answered with its "Checking your browser..." page, which only a browser can pass. Read it in WebView for now.', + url, + }); + } + checkResponse(r); + return parseHTML(html); + } + + private layoutChanged(what: string, url: string) { + return createPluginError(PluginError.InvalidResponse, { + message: `NovelScroll's ${what}: its layout changed.`, + url, + }); + } + + private async catalogue(): Promise<Plugin.NovelItem[]> { + const url = SITE + 'genre/all/'; + const $ = await this.fetchPage(url); + const novels: Plugin.NovelItem[] = []; + const seen: Record<string, boolean> = {}; + $('div.manga-item').each((_, el) => { + const link = $(el).find('h3.manga-title a').first(); + const path = pathOf(link.attr('href')); + if (!path || !/^manga\/[^/]+$/.test(path) || seen[path]) return; + seen[path] = true; + novels.push({ + name: clean(link.text()), + path, + cover: cdn($(el).find('img').first().attr('src')), + }); + }); + if (!novels.length) + throw this.layoutChanged('catalogue has no novels', url); + return novels; + } + + async popularNovels( + pageNo: number, + { showLatestNovels }: Plugin.PopularNovelsOptions, + ): Promise<Plugin.NovelItem[]> { + if (pageNo > 1) return []; // the catalogue is one page + const all = await this.catalogue(); + if (!showLatestNovels) return all; + // The homepage's "Latest Releases" link to the novel's own page, whose + // slug can differ from the catalogue's: match by title to keep one path + // per novel; a novel the catalogue lacks keeps its page's path. + const $ = await this.fetchPage(SITE); + const items = $('.ns-lr .ns-li'); + if (!items.length) { + throw this.layoutChanged('homepage has no "Latest Releases"', SITE); + } + const byTitle: Record<string, Plugin.NovelItem> = {}; + all.forEach(n => (byTitle[titleKey(n.name)] = n)); + const novels: Plugin.NovelItem[] = []; + const seen: Record<string, boolean> = {}; + items.each((_, el) => { + const link = $(el).find('a.ns-lt').first(); + const title = clean(link.text()); + let novel = byTitle[titleKey(title)]; + if (!novel) { + const path = pathOf(link.attr('href')); + if (!path || !NOVEL_PATH.test(path)) return; + novel = { + name: title, + path, + cover: cdn(styleUrl($(el).find('.ns-th').first().attr('style'))), + }; + } + if (seen[novel.path]) return; + seen[novel.path] = true; + novels.push(novel); + }); + return novels; + } + + async searchNovels( + searchTerm: string, + pageNo: number, + ): Promise<Plugin.NovelItem[]> { + // The site's own search lists chapter posts; the catalogue is one page, so + // novels are matched by title there. + if (pageNo > 1) return []; + const want = titleKey(searchTerm); + const all = await this.catalogue(); + return want ? all.filter(n => titleKey(n.name).includes(want)) : all; + } + + async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> { + const path = novelPath.replace(/^\/+|\/+$/g, ''); + if (!NOVEL_PATH.test(path)) { + throw createPluginError(PluginError.NovelNotFound, { + message: 'Not a NovelScroll novel path: ' + novelPath, + }); + } + const url = urlOf(path); + const $ = await this.fetchPage(url); + const name = clean($('.ns-hd .ns-hd-t').first().text()); + if (!name) throw createPluginError(PluginError.NovelNotFound, { url }); + + // The synopsis block also holds an old hand-made chapter list + // (paragraphs of links): keep the paragraphs without links. + const summary = $('.ns-sum .ns-sb p') + .filter((_, p) => !$(p).find('a').length) + .map((_, p) => clean($(p).text())) + .get() + .filter(Boolean); + if ($('.nsp-toc').length) { + summary.push( + "Premium (advance) chapters are on the translator's Patreon and are not listed here.", + ); + } + const toc = $('.auto-toc'); + if (!toc.length) + throw this.layoutChanged('novel page has no chapter list', url); + const chapters: Plugin.ChapterItem[] = []; + const seen: Record<string, boolean> = {}; + toc.find('a[href]').each((_, el) => { + const a = $(el); + const chapterPath = pathOf(a.attr('href')); + if (!chapterPath || seen[chapterPath]) return; + seen[chapterPath] = true; + const date = clean(a.find('span').first().text()); + chapters.push({ + name: clean(a.clone().children('span').remove().end().text()), + path: chapterPath, + releaseTime: isoDate(date), + chapterNumber: chapters.length + 1, + }); + }); + + const novel: Plugin.SourceNovel = { path, name, chapters }; + const cover = cdn(styleUrl($('.ns-hd .ns-cv').first().attr('style'))); + if (cover) novel.cover = cover; + if (summary.length) novel.summary = summary.join('\n\n'); + const status = clean($('.ns-hd .ns-bd').first().text()).toLowerCase(); + if (status.includes('ongoing')) novel.status = NovelStatus.Ongoing; + else if (status.includes('complete')) novel.status = NovelStatus.Completed; + else if (status.includes('hiatus')) novel.status = NovelStatus.OnHiatus; + else if (status.includes('drop')) novel.status = NovelStatus.Cancelled; + return novel; + } + + async parseChapter(chapterPath: string): Promise<string> { + const url = urlOf(chapterPath); + const $ = await this.fetchPage(url); + const body = $('article div.inside-article div.entry-content').first(); + if (!body.length) throw this.layoutChanged('chapter page has no text', url); + const blocks = body.children( + 'p, h1, h2, h3, h4, h5, h6, blockquote, hr, ul, ol, figure, table, pre', + ); + // Embedded documents and page-level tags can run script or reroute links. + blocks + .find( + 'script, style, noscript, ins, iframe, frame, frameset, object, embed, ' + + 'applet, svg, math, template, base, meta, link, button, form', + ) + .remove(); + blocks.find('img').each((_, img) => { + const src = $(img).attr('src'); + $(img).attr('src', cdn(src) || src || ''); + }); + blocks.add(blocks.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(blocks.text()).length < 20) { + throw createPluginError(PluginError.EmptyContent, { url }); + } + return blocks + .map((_, b) => $.html(b)) + .get() + .join('\n'); + } + + resolveUrl = (path: string): string => urlOf(path); +} + +export default new NovelScrollPlugin(); diff --git a/public/static/src/en/novelscroll/icon.png b/public/static/src/en/novelscroll/icon.png new file mode 100644 index 0000000000..2f6938e7ad Binary files /dev/null and b/public/static/src/en/novelscroll/icon.png differ