Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
346 changes: 346 additions & 0 deletions plugins/english/brightnovels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,346 @@
import { fetchApi } from '@libs/fetch';
import { Filters, FilterTypes } from '@libs/filterInputs';
import {
assertNoChallenge,
checkResponse,
createPluginError,
PluginError,
} from '@libs/pluginError';
import { storage } from '@libs/storage';
import { Plugin } from '@/types/plugin';
import { load as parseHTML } from 'cheerio';

/**
* brightnovels.com is a Laravel + Inertia app: each page carries its data as
* JSON in `#app[data-page]`. A novel's chapter list comes from
* `series/<slug>/chapters` (JSON). A chapter with a price that the reader has
* not unlocked is marked 🔒.
*/
const SITE = 'https://brightnovels.com/';

type SiteNovel = {
slug: string;
title: string;
coverImage?: string;
cover?: { path?: string };
description?: string;
user?: { name?: string };
};
type SiteChapter = {
number: number;
slug?: string | number;
name?: string;
title?: string;
price?: number;
unlocked_at?: string | null;
index_at?: string;
created_at?: string;
};

const clean = (s: unknown): string =>
String(s ?? '')
.replace(/\s+/g, ' ')
.trim();

const slugOf = (path: string): string => {
const m = path.match(/series\/([^/]+)/);
return m ? m[1] : path.replace(/^\/+|\/+$/g, '').split('/')[0];
};

const coverUrl = (n: SiteNovel): string | undefined => {
if (n.coverImage) {
return n.coverImage.startsWith('/')
? SITE + n.coverImage.replace(/^\/+/, '')
: n.coverImage;
}
return n.cover?.path ? SITE + 'storage/' + n.cover.path : undefined;
};

const mapNovel = (n: SiteNovel): Plugin.NovelItem => ({
name: clean(n.title),
path: 'series/' + n.slug,
cover: coverUrl(n),
});

/**
* Tag names to the site's slugs: lowercase, "/" and apostrophes dropped,
* other runs of non-alphanumerics to "-" (matches every tag on the site).
*/
const tagSlugs = (text: string): string[] =>
text
.split(',')
.map(t =>
t
.toLowerCase()
.replace(/['’/]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, ''),
)
.filter(Boolean);

class BrightNovelsPlugin implements Plugin.PluginBase {
id = 'brightnovels';
name = 'Bright Novels';
icon = 'src/en/brightnovels/icon.png';
site = SITE;
version = '1.0.0';

pluginSettings = {
hideLocked: {
value: false,
label: 'Hide locked chapters',
type: 'Switch',
},
};

// What the site's /series page accepts: sort trending|updated|title (with
// order=asc|desc), nothing = newest; status; genres and tags as
// comma-separated slugs (any of). The site has hundreds of tags, so they are
// typed by name.
filters = {
sort: {
type: FilterTypes.Picker,
label: 'Sort',
value: 'trending',
options: [
{ label: 'Trending', value: 'trending' },
{ label: 'Newest', value: '' },
{ label: 'Recently updated', value: 'updated' },
{ label: 'Title A-Z', value: 'title:asc' },
{ label: 'Title Z-A', value: 'title:desc' },
],
},
status: {
type: FilterTypes.Picker,
label: 'Status',
value: '',
options: [
{ label: 'All', value: '' },
{ label: 'Ongoing', value: 'ongoing' },
{ label: 'Completed', value: 'completed' },
{ label: 'Hiatus', value: 'hiatus' },
],
},
genres: {
type: FilterTypes.CheckboxGroup,
label: 'Genres (any of)',
value: [],
options: [
{ label: 'Action', value: 'action' },
{ label: 'Adult', value: 'adult' },
{ label: 'Adventure', value: 'adventure' },
{ label: 'Comedy', value: 'comedy' },
{ label: 'Drama', value: 'drama' },
{ label: 'Ecchi', value: 'ecchi' },
{ label: 'Fantasy', value: 'fantasy' },
{ label: 'Gender Bender', value: 'gender-bender' },
{ label: 'Harem', value: 'harem' },
{ label: 'Historical', value: 'historical' },
{ label: 'Horror', value: 'horror' },
{ label: 'Josei', value: 'josei' },
{ label: 'Martial Arts', value: 'martial-arts' },
{ label: 'Mature', value: 'mature' },
{ label: 'Mecha', value: 'mecha' },
{ label: 'Mystery', value: 'mystery' },
{ label: 'Psychological', value: 'psychological' },
{ label: 'Romance', value: 'romance' },
{ label: 'School Life', value: 'school-life' },
{ label: 'Sci-fi', value: 'sci-fi' },
{ label: 'Seinen', value: 'seinen' },
{ label: 'Shoujo', value: 'shoujo' },
{ label: 'Shoujo Ai', value: 'shoujo-ai' },
{ label: 'Shounen', value: 'shounen' },
{ label: 'Shounen Ai', value: 'shounen-ai' },
{ label: 'Slice of Life', value: 'slice-of-life' },
{ label: 'Smut', value: 'smut' },
{ label: 'Sports', value: 'sports' },
{ label: 'Supernatural', value: 'supernatural' },
{ label: 'Tragedy', value: 'tragedy' },
{ label: 'Wuxia', value: 'wuxia' },
{ label: 'Xianxia', value: 'xianxia' },
{ label: 'Xuanhuan', value: 'xuanhuan' },
{ label: 'Yaoi', value: 'yaoi' },
{ label: 'Yuri', value: 'yuri' },
],
},
tags: {
type: FilterTypes.TextInput,
label: 'Tags (names, comma-separated, any of)',
value: '',
},
} satisfies Filters;

private async fetchText(url: string, accept?: string): Promise<string> {
const r = await fetchApi(
url,
accept
? {
headers: { 'Accept': accept, 'X-Requested-With': 'XMLHttpRequest' },
}
: undefined,
);
checkResponse(r);
const text = await r.text();
if (!accept) assertNoChallenge(text, url, r.url);
return text;
}

private async fetchJson<T>(url: string): Promise<T> {
const text = await this.fetchText(url, 'application/json');
try {
return JSON.parse(text) as T;
} catch {
throw createPluginError(PluginError.InvalidResponse, { url });
}
}

/** The Inertia page props of a page, from `#app[data-page]`. */
private async pageProps(url: string): Promise<Record<string, unknown>> {
const $ = parseHTML(await this.fetchText(url));
const raw =
$('#app').attr('data-page') || $('[data-page]').attr('data-page');
try {
const props = raw ? JSON.parse(raw).props : undefined;
if (props && typeof props === 'object') return props;
} catch {
// reported below
}
throw createPluginError(PluginError.InvalidResponse, {
message: 'Bright Novels: no page data (the layout may have changed).',
url,
});
}

async popularNovels(
pageNo: number,
{
showLatestNovels,
filters,
}: Plugin.PopularNovelsOptions<typeof this.filters>,
): Promise<Plugin.NovelItem[]> {
const sort = showLatestNovels ? 'updated' : filters?.sort?.value ?? '';
const query = ['page=' + pageNo];
if (sort) {
const [by, order] = sort.split(':');
query.push('sort=' + by);
if (order) query.push('order=' + order);
}
if (filters?.status?.value) {
query.push('status=' + encodeURIComponent(filters.status.value));
}
const genres = filters?.genres?.value || [];
if (genres.length) {
query.push('genres=' + genres.map(encodeURIComponent).join(','));
}
const tags = tagSlugs(filters?.tags?.value || '');
if (tags.length) {
query.push('tags=' + tags.map(encodeURIComponent).join(','));
}
const url = SITE + 'series?' + query.join('&');
const props = await this.pageProps(url);
const list = (props.seriesList as { data?: SiteNovel[] } | undefined)?.data;
if (!Array.isArray(list)) {
throw createPluginError(PluginError.InvalidResponse, {
message: 'Bright Novels returned no series list.',
url,
});
}
return list.map(mapNovel);
}

async searchNovels(
searchTerm: string,
pageNo: number,
): Promise<Plugin.NovelItem[]> {
if (pageNo > 1) return []; // the site's search has one page
const url = SITE + 'api/search?query=' + encodeURIComponent(searchTerm);
const res = await this.fetchJson<{ data?: { series?: SiteNovel[] } }>(url);
const series = res.data?.series;
if (!Array.isArray(series)) {
throw createPluginError(PluginError.InvalidResponse, {
message: 'Bright Novels returned no search results list.',
url,
});
}
return series.map(mapNovel);
}

async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
const path = 'series/' + slugOf(novelPath);
const props = await this.pageProps(SITE + path);
const series = props.series as SiteNovel | undefined;
if (!series || !series.title) {
throw createPluginError(PluginError.NovelNotFound, { url: SITE + path });
}
const listUrl = SITE + path + '/chapters';
const list = await this.fetchJson<{ chapters?: SiteChapter[] }>(listUrl);
let raw: SiteChapter[];
if (Array.isArray(list.chapters)) raw = list.chapters;
else if (Array.isArray(props.allChapters)) {
raw = props.allChapters as SiteChapter[];
} else {
throw createPluginError(PluginError.InvalidResponse, {
message: 'Bright Novels returned no chapter list.',
url: listUrl,
});
}
const hideLocked = storage.get('hideLocked');
const chapters: Plugin.ChapterItem[] = [];
for (const c of raw) {
const locked = (c.price || 0) > 0 && !c.unlocked_at;
if (locked && hideLocked) continue;
chapters.push({
name:
(locked ? '🔒 ' : '') +
(clean(c.name) || clean(c.title) || 'Chapter ' + c.number),
path: path + '/' + (c.slug ?? c.number),
chapterNumber: c.number,
releaseTime:
(c.index_at || c.created_at || '').slice(0, 10) || undefined,
});
}
chapters.sort((a, b) => (a.chapterNumber || 0) - (b.chapterNumber || 0));

const novel: Plugin.SourceNovel = {
path,
name: clean(series.title),
chapters,
};
const cover = coverUrl(series);
if (cover) novel.cover = cover;
if (series.description) {
novel.summary = clean(
parseHTML('<x>' + series.description + '</x>').text(),
);
}
if (series.user?.name) novel.author = clean(series.user.name);
return novel;
}

async parseChapter(chapterPath: string): Promise<string> {
const url = SITE + chapterPath;
const props = await this.pageProps(url);
const chapter = (props.chapter || {}) as {
content?: string;
is_premium?: boolean;
};
if (
props.isUnlocked === false ||
(!chapter.content && chapter.is_premium)
) {
throw createPluginError(PluginError.AuthRequired, {
message:
'This chapter is locked on Bright Novels. Unlock it on the site to read it.',
url,
});
}
if (!chapter.content) {
throw createPluginError(PluginError.EmptyContent, { url });
}
return chapter.content;
}

resolveUrl = (path: string): string => SITE + path;
}

export default new BrightNovelsPlugin();
Binary file added public/static/src/en/brightnovels/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading