diff --git a/plugins/english/novellunar.ts b/plugins/english/novellunar.ts new file mode 100644 index 0000000000..220a688f30 --- /dev/null +++ b/plugins/english/novellunar.ts @@ -0,0 +1,319 @@ +import { fetchApi } from '@libs/fetch'; +import { Filters, FilterTypes } from '@libs/filterInputs'; +import { + assertNoChallenge, + checkResponse, + createPluginError, + PluginError, +} from '@libs/pluginError'; +import { Plugin } from '@/types/plugin'; +import { load as parseHTML } from 'cheerio'; + +/** + * novellunar.com is a Next.js app behind a Cloudflare check (pass it once in + * WebView). Lists are the `/ranking` and `/latest` pages (one page each); + * search filters the catalogue the `/search` page embeds. A novel's chapter + * list and a chapter's text come from the chapter page's server-component + * stream (`self.__next_f.push([1,"..."])`): the list as `"chapters":[...]`, + * the text as `"content"` (inline, or a `$` reference to a text row). + */ +const SITE = 'https://novellunar.com/'; +const IMG = 'https://img.novellunar.com/'; + +type ListedNovel = { slug?: string; title?: string; coverImage?: string }; +type ListedChapter = { + chapterNumber?: number; + number?: number; + title?: string; + createdAt?: string; +}; + +const clean = (s: unknown): string => + String(s ?? '') + .replace(/\s+/g, ' ') + .trim(); + +const escapeHtml = (s: string): string => + s.replace(/&/g, '&').replace(//g, '>'); + +const slugOf = (path: string): string => { + const m = path.match(/novel\/([^/]+)/); + return m ? m[1] : path.replace(/^\/+|\/+$/g, ''); +}; + +/** The page's server-component stream, as one string. */ +function rscStream(html: string): string { + const re = /__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)/g; + let out = ''; + let m: RegExpExecArray | null; + while ((m = re.exec(html)) !== null) { + try { + out += JSON.parse('"' + m[1] + '"') as string; + } catch { + out += m[1]; + } + } + return out; +} + +/** The JSON array after the first `"key":` in the stream, or null. */ +function jsonArray(stream: string, key: string): unknown[] | null { + const marker = '"' + key + '":['; + const start = stream.indexOf(marker); + if (start === -1) return null; + let j = start + marker.length - 1; + let depth = 0; + let inString = false; + let escaped = false; + for (; j < stream.length; j++) { + const c = stream[j]; + if (escaped) { + escaped = false; + continue; + } + if (c === '\\') { + escaped = true; + continue; + } + if (c === '"') { + inString = !inString; + continue; + } + if (inString) continue; + if (c === '[') depth++; + else if (c === ']' && --depth === 0) { + j++; + break; + } + } + try { + const value = JSON.parse(stream.substring(start + marker.length - 1, j)); + return Array.isArray(value) ? value : null; + } catch { + return null; + } +} + +/** A text row `:T,` of the stream. */ +function textRow(stream: string, id: string): string | null { + const m = new RegExp('(?:^|[\\n}\\]"])' + id + ':T([0-9a-fA-F]+),').exec( + stream, + ); + if (!m) return null; + const need = parseInt(m[1], 16); + const start = m.index + m[0].length; + let bytes = 0; + let i = start; + for (; i < stream.length && bytes < need; i++) { + const c = stream.charCodeAt(i); + if (c < 0x80) bytes += 1; + else if (c < 0x800) bytes += 2; + else if (c >= 0xd800 && c <= 0xdbff) { + bytes += 4; + i++; + } else bytes += 3; + } + return stream.substring(start, i); +} + +function chapterText(stream: string): string { + const ref = stream.match(/"content":"\$(\w+)"/); + if (ref) { + const text = textRow(stream, ref[1]); + if (text) return text; + } + const m = stream.match(/"content":"((?:[^"\\]|\\.)*)","contentLength"/); + if (m) { + try { + return JSON.parse('"' + m[1] + '"') as string; + } catch { + return ''; + } + } + return ''; +} + +class NovellunarPlugin implements Plugin.PluginBase { + id = 'novellunar'; + name = 'Novellunar'; + icon = 'src/en/novellunar/icon.png'; + site = SITE; + version = '1.0.0'; + + filters = { + sort: { + type: FilterTypes.Picker, + label: 'Sort', + value: 'ranking', + options: [ + { label: 'Ranking', value: 'ranking' }, + { label: 'Latest', value: 'latest' }, + ], + }, + } satisfies Filters; + + private async fetchHtml(url: string): Promise { + const r = await fetchApi(url); + checkResponse(r); + const html = await r.text(); + assertNoChallenge(html, url, r.url); + return html; + } + + private toPath(href: string | undefined): string | null { + if (!href) return null; + const url = /^https?:/.test(href) ? href : SITE + href.replace(/^\/+/, ''); + if (!url.startsWith(SITE)) return null; + return url + .slice(SITE.length) + .replace(/#.*$/, '') + .replace(/(^\/+|\/+$)/g, ''); + } + + private cards(html: string): Plugin.NovelItem[] { + const $ = parseHTML(html); + const novels: Plugin.NovelItem[] = []; + const seen: Record = {}; + $('a[href^="/novel/"]').each((_, el) => { + const a = $(el); + const path = this.toPath(a.attr('href')); + if (!path || seen[path] || path.split('/').length !== 2) return; + const img = a.find('img').first(); + const name = clean( + img.attr('alt') || a.attr('title') || a.text(), + ).replace(/\s+Novel$/i, ''); + if (!name) return; + seen[path] = true; + const src = img.attr('src') || img.attr('data-src'); + novels.push({ + name, + path, + cover: src + ? /^https?:/.test(src) + ? src + : SITE + src.replace(/^\/+/, '') + : IMG + slugOf(path) + '.webp', + }); + }); + return novels; + } + + async popularNovels( + pageNo: number, + { + showLatestNovels, + filters, + }: Plugin.PopularNovelsOptions, + ): Promise { + if (pageNo !== 1) return []; // each list is one page + const list = showLatestNovels + ? 'latest' + : filters?.sort?.value || 'ranking'; + return this.cards(await this.fetchHtml(SITE + list)); + } + + async searchNovels( + searchTerm: string, + pageNo: number, + ): Promise { + if (pageNo > 1) return []; + const term = clean(searchTerm).toLowerCase(); + // /search embeds the catalogue as "novelLinks"; the other pages add the + // novels shown there. + const urls = [ + SITE + 'search?q=' + encodeURIComponent(searchTerm), + SITE, + SITE + 'ranking', + SITE + 'latest', + ]; + const pages = await Promise.all(urls.map(u => this.fetchHtml(u))); + const found: Plugin.NovelItem[] = []; + const seen: Record = {}; + const add = (n: Plugin.NovelItem) => { + if (!seen[n.path]) { + seen[n.path] = true; + found.push(n); + } + }; + for (const n of (jsonArray(rscStream(pages[0]), 'novelLinks') || + []) as ListedNovel[]) { + if (n && n.slug && n.title) { + add({ + name: clean(n.title), + path: 'novel/' + n.slug, + cover: n.coverImage || IMG + n.slug + '.webp', + }); + } + } + pages.forEach(html => this.cards(html).forEach(add)); + return found.filter(n => n.name.toLowerCase().includes(term)); + } + + async parseNovel(novelPath: string): Promise { + const slug = slugOf(novelPath); + const $ = parseHTML(await this.fetchHtml(SITE + novelPath)); + const name = clean( + $('meta[property="og:title"]').attr('content') || $('h1').first().text(), + ).replace(/\s+Novel$/i, ''); + if (!name) { + throw createPluginError(PluginError.NovelNotFound, { + url: SITE + novelPath, + }); + } + + // The chapter page carries the whole chapter list. + const listUrl = SITE + 'novel/' + slug + '/chapter/1'; + const raw = jsonArray(rscStream(await this.fetchHtml(listUrl)), 'chapters'); + if (!raw) { + throw createPluginError(PluginError.InvalidResponse, { + message: "Novellunar's chapter page has no chapter list.", + url: listUrl, + }); + } + const byNumber: Record = {}; + for (const c of raw as ListedChapter[]) { + const n = c.chapterNumber ?? c.number; + if (n === undefined || n === null) continue; + byNumber[n] = { + name: clean(c.title) || 'Chapter ' + n, + path: 'novel/' + slug + '/chapter/' + n, + chapterNumber: n, + releaseTime: c.createdAt ? c.createdAt.slice(0, 10) : undefined, + }; + } + const chapters = Object.keys(byNumber) + .map(k => byNumber[Number(k)]) + .sort((a, b) => (a.chapterNumber || 0) - (b.chapterNumber || 0)); + + const novel: Plugin.SourceNovel = { + path: novelPath, + name, + cover: + $('meta[property="og:image"]').attr('content') || IMG + slug + '.webp', + chapters, + }; + const summary = clean( + $('meta[name="description"]').attr('content'), + ).replace(/^Read\s+'.*?'\s+Novel Online for Free[,.]?\s*/i, ''); + if (summary) novel.summary = summary; + return novel; + } + + async parseChapter(chapterPath: string): Promise { + const url = SITE + chapterPath; + const text = chapterText(rscStream(await this.fetchHtml(url))); + let paragraphs = text.split(/\n{2,}/); + if (paragraphs.length < 2) paragraphs = text.split(/\n/); + const html = paragraphs + .map(clean) + .filter(p => p.length) + .map(p => '

' + escapeHtml(p) + '

') + .join('\n'); + if (!html) throw createPluginError(PluginError.EmptyContent, { url }); + return html; + } + + resolveUrl = (path: string): string => SITE + path; +} + +export default new NovellunarPlugin(); diff --git a/public/static/src/en/novellunar/icon.png b/public/static/src/en/novellunar/icon.png new file mode 100644 index 0000000000..5d451a6c49 Binary files /dev/null and b/public/static/src/en/novellunar/icon.png differ