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
310 changes: 310 additions & 0 deletions plugins/english/botitranslation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
import { fetchApi } from '@libs/fetch';
import { Filters, FilterTypes } from '@libs/filterInputs';
import { NovelStatus } from '@libs/novelStatus';
import {
checkResponse,
createPluginError,
PluginError,
} from '@libs/pluginError';
import { storage } from '@libs/storage';
import { Plugin } from '@/types/plugin';

/**
* botitranslation.com is a client-side app on the shared "StoryWave" backend.
* All data comes from its public JSON API; the `site-domain` header tells the
* multi-tenant backend which catalogue to serve. Paths: the book id for a
* novel, `<book id>/<chapter id>` for a chapter.
*/
const API = 'https://api.mystorywave.com/story-wave-backend/api/v1';
const SITE_DOMAIN = 'www.botitranslation.com';
const PAGE_SIZE = 30;
const CACHE_MS = 10 * 60 * 1000;

type ApiResponse<T> = { code?: number; message?: string; data?: T };
type Book = {
id: number;
title: string;
coverImgUrl?: string;
synopsis?: string;
authorPseudonym?: string;
genre?: number;
status?: number;
};
type Chapter = {
id: number;
title: string;
chapterOrder?: number;
publishTime?: number;
paywallStatus?: string;
paid?: boolean;
};
type Page<T> = { list?: T[]; totalPages?: number; totalCount?: number };

/**
* A chapter is locked when it is sold ("charge") and not bought; the API then
* gives only a preview of about 1000 characters. "free" and "1" chapters come
* whole.
*/
const isLocked = (c: { paywallStatus?: string; paid?: boolean }) =>
c.paywallStatus === 'charge' && !c.paid;

const HEADERS = {
'site-domain': SITE_DOMAIN,
'Accept': 'application/json',
'Referer': 'https://www.botitranslation.com/',
};

class BotiTranslationPlugin implements Plugin.PluginBase {
id = 'botitranslation';
name = 'Boti Translation';
icon = 'src/en/botitranslation/icon.png';
site = 'https://www.botitranslation.com/';
version = '1.0.0';

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

// Sorts are the site's own ranking lists; genre ids and names as the API
// reports them; status 1 = ongoing, 2 = completed.
filters = {
sort: {
type: FilterTypes.Picker,
label: 'Sort',
value: 'MostPopularLocal',
options: [
{ label: 'Most popular', value: 'MostPopularLocal' },
{ label: 'Popular translations', value: 'TranslationMostPopularLocal' },
{ label: 'Most words', value: 'MostWordCountLocal' },
{ label: 'Recently updated', value: 'LastUpdatedLocal' },
],
},
status: {
type: FilterTypes.Picker,
label: 'Status',
value: '',
options: [
{ label: 'All', value: '' },
{ label: 'Ongoing', value: '1' },
{ label: 'Completed', value: '2' },
],
},
genre: {
type: FilterTypes.CheckboxGroup,
label: 'Genres (any of)',
value: [],
options: [
{ label: 'Fantasy', value: '1' },
{ label: 'Sci-fi', value: '2' },
{ label: 'Sports', value: '3' },
{ label: 'Urban', value: '4' },
{ label: 'Eastern Fantasy', value: '5' },
{ label: 'Horror&Thriller', value: '6' },
{ label: 'Video Game', value: '7' },
{ label: 'History', value: '8' },
{ label: 'War', value: '9' },
{ label: 'Urban Romance', value: '10' },
{ label: 'Fantasy Romance', value: '11' },
{ label: 'Historical Romance', value: '12' },
{ label: 'Teen', value: '13' },
{ label: 'LGBT+', value: '14' },
],
},
} satisfies Filters;

private catalogue: Record<string, { at: number; list: Book[] }> = {};

private async api<T>(
path: string,
params?: Record<string, string | number>,
init?: { method: string; body: string },
): Promise<T> {
let url = API + path;
if (params) {
url +=
'?' +
Object.keys(params)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
.join('&');
}
const r = await fetchApi(url, {
headers: init
? { ...HEADERS, 'Content-Type': 'application/json' }
: HEADERS,
...init,
});
checkResponse(r);
let json: ApiResponse<T>;
try {
json = (await r.json()) as ApiResponse<T>;
} catch {
throw createPluginError(PluginError.InvalidResponse, { url });
}
if (json.code !== 0 || json.data === undefined || json.data === null) {
throw createPluginError(PluginError.InvalidResponse, {
message:
'Boti Translation: ' +
(json.message || 'no data') +
' (' +
path +
')',
url,
});
}
return json.data;
}

private mapBook(b: Book): Plugin.NovelItem {
const novel: Plugin.NovelItem = { name: b.title, path: String(b.id) };
if (b.coverImgUrl) novel.cover = b.coverImgUrl;
return novel;
}

/** One page of a ranking list (the same request the site's home page makes). */
private rankList(name: string, page: number, size: number) {
return this.api<Page<Book>>('/content/books/custom/' + name, undefined, {
method: 'POST',
body: JSON.stringify({
conditionJson: '{}',
pageNumber: page,
pageSize: size,
}),
});
}

/**
* The ranking lists ignore genre and status, so those filters run here over
* the whole list of the chosen order, fetched once and kept ten minutes.
*/
private async wholeList(name: string): Promise<Book[]> {
const hit = this.catalogue[name];
if (hit && Date.now() - hit.at < CACHE_MS) return hit.list;
const first = await this.rankList(name, 1, 2000);
let list = first.list || [];
for (
let page = 2;
list.length < (first.totalCount || 0) && page <= 20;
page++
) {
list = list.concat((await this.rankList(name, page, 2000)).list || []);
}
this.catalogue[name] = { at: Date.now(), list };
return list;
}

async popularNovels(
pageNo: number,
{
showLatestNovels,
filters,
}: Plugin.PopularNovelsOptions<typeof this.filters>,
): Promise<Plugin.NovelItem[]> {
const sort = showLatestNovels
? 'LastUpdatedLocal'
: filters?.sort?.value || 'MostPopularLocal';
const genres = filters?.genre?.value || [];
const status = filters?.status?.value || '';
if (!genres.length && !status) {
const page = await this.rankList(sort, pageNo, PAGE_SIZE);
return (page.list || []).map(b => this.mapBook(b));
}
const hits = (await this.wholeList(sort)).filter(
b =>
(!genres.length || genres.includes(String(b.genre))) &&
(!status || String(b.status) === status),
);
return hits
.slice((pageNo - 1) * PAGE_SIZE, pageNo * PAGE_SIZE)
.map(b => this.mapBook(b));
}

async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
const id = novelPath.replace(/[^0-9]/g, '');
const book = await this.api<Book>('/content/books/' + id);
const hideLocked = storage.get('hideLocked');

// The API pages the list, newest first.
const chapters: Plugin.ChapterItem[] = [];
let pageNumber = 1;
let totalPages = 1;
do {
const page = await this.api<Page<Chapter>>('/content/chapters/page', {
bookId: id,
pageNumber,
pageSize: 100,
});
totalPages = page.totalPages || 1;
for (const c of page.list || []) {
const locked = isLocked(c);
if (locked && hideLocked) continue;
chapters.push({
name: (locked ? '🔒 ' : '') + c.title,
path: id + '/' + c.id,
chapterNumber: c.chapterOrder,
releaseTime: c.publishTime
? new Date(c.publishTime).toISOString().slice(0, 10)
: undefined,
});
}
pageNumber++;
} while (pageNumber <= totalPages && pageNumber <= 500);
chapters.sort((a, b) => (a.chapterNumber || 0) - (b.chapterNumber || 0));

const novel: Plugin.SourceNovel = {
path: novelPath,
name: book.title,
chapters,
};
if (book.coverImgUrl) novel.cover = book.coverImgUrl;
if (book.synopsis) novel.summary = book.synopsis.replace(/\r/g, '');
if (book.authorPseudonym) novel.author = book.authorPseudonym;
if (book.status === 1) novel.status = NovelStatus.Ongoing;
else if (book.status === 2) novel.status = NovelStatus.Completed;
return novel;
}

async parseChapter(chapterPath: string): Promise<string> {
const id = (chapterPath.split('/').pop() || '').replace(/[^0-9]/g, '');
const chapter = await this.api<{
content?: string;
paywallStatus?: string;
paid?: boolean;
}>('/content/chapters/' + id);
if (!chapter.content || isLocked(chapter)) {
// A paid chapter the reader has not unlocked comes without content.
throw createPluginError(PluginError.AuthRequired, {
message:
'This chapter is locked on Boti Translation. Unlock it on the site to read it.',
url: this.site + 'viewer/' + id,
});
}
return chapter.content;
}

async searchNovels(
searchTerm: string,
pageNo: number,
): Promise<Plugin.NovelItem[]> {
// The parameter is `keyWord`; a lowercase `keyword` is ignored and the
// full list comes back.
const page = await this.api<Page<Book>>('/content/books/search', {
keyWord: searchTerm,
pageNumber: pageNo,
pageSize: PAGE_SIZE,
});
return (page.list || []).map(b => this.mapBook(b));
}

resolveUrl = (path: string, isNovel?: boolean): string => {
const parts = path.split('/');
return isNovel
? this.site + 'story/' + parts[0]
: this.site + 'viewer/' + parts[parts.length - 1];
};
}

export default new BotiTranslationPlugin();
Binary file added public/static/src/en/botitranslation/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