Repository navigation
feat(english): add Novellunar source #2976
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Sharique-Hassan-Malik
wants to merge
2
commits into
lnreader:master
Choose a base branch
from
Sharique-Hassan-Malik:feat/english-novellunar
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 `$<id>` 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, '<').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 `<id>:T<UTF-8 byte length in hex>,<text>` 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<string> { | ||
| 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<string, boolean> = {}; | ||
| $('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<typeof this.filters>, | ||
| ): Promise<Plugin.NovelItem[]> { | ||
| 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<Plugin.NovelItem[]> { | ||
| 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<string, boolean> = {}; | ||
| 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<Plugin.SourceNovel> { | ||
| 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<number, Plugin.ChapterItem> = {}; | ||
| 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<string> { | ||
| 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 => '<p>' + escapeHtml(p) + '</p>') | ||
| .join('\n'); | ||
| if (!html) throw createPluginError(PluginError.EmptyContent, { url }); | ||
| return html; | ||
| } | ||
|
|
||
| resolveUrl = (path: string): string => SITE + path; | ||
| } | ||
|
|
||
| export default new NovellunarPlugin(); | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.