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

/**
* taptotale.com is WordPress where each category is a novel and each post in
* it a chapter; everything is read from the public REST API. Paths:
* `cat/<id>/<slug>` for a novel, `post/<id>` for a chapter.
*/
type Category = {
id: number;
name: string;
slug: string;
count: number;
description?: string;
};
type Post = {
id: number;
title: { rendered: string };
content?: { rendered: string };
};

const text = (html: string): string =>
parseHTML(html || '')
.root()
.text()
.replace(/\s+/g, ' ')
.trim();

/** A category's description holds the cover image and the synopsis. */
const coverOf = (html?: string): string | undefined =>
parseHTML(html || '')('img')
.first()
.attr('src') || undefined;

const summaryOf = (html?: string): string => {
const $ = parseHTML(html || '');
$('img').remove();
return $.root().text().replace(/\s+/g, ' ').trim();
};

class TapToTalePlugin implements Plugin.PluginBase {
id = 'taptotale';
name = 'TapToTale';
icon = 'src/en/taptotale/icon.png';
site = 'https://taptotale.com/';
version = '1.0.0';

// The REST API sorts categories by chapter count, name or id; the site has
// no genres or tags.
filters = {
sort: {
type: FilterTypes.Picker,
label: 'Sort',
value: 'count:desc',
options: [
{ label: 'Most chapters', value: 'count:desc' },
{ label: 'Title A-Z', value: 'name:asc' },
{ label: 'Title Z-A', value: 'name:desc' },
{ label: 'Newest added', value: 'id:desc' },
],
},
} satisfies Filters;

private async api<T>(path: string): Promise<{ data: T; response: Response }> {
const url = this.site + 'wp-json/wp/v2/' + path;
const response = await fetchApi(url);
checkResponse(response);
try {
return { data: (await response.json()) as T, response };
} catch {
throw createPluginError(PluginError.InvalidResponse, { url });
}
}

private toNovels(categories: Category[]): Plugin.NovelItem[] {
return categories
.filter(c => c.count > 0)
.map(c => ({
name: text(c.name),
path: 'cat/' + c.id + '/' + c.slug,
cover: coverOf(c.description),
}));
}

async popularNovels(
pageNo: number,
{
showLatestNovels,
filters,
}: Plugin.PopularNovelsOptions<typeof this.filters>,
): Promise<Plugin.NovelItem[]> {
const sort = showLatestNovels
? 'id:desc'
: filters?.sort?.value || 'count:desc';
const [orderby, order] = sort.split(':');
const { data } = await this.api<Category[]>(
`categories?per_page=100&orderby=${orderby}&order=${order}&page=${pageNo}`,
).catch(e => {
// Past the last page the API answers 400.
if (pageNo > 1 && e?.status === 400) return { data: [] as Category[] };
throw e;
});
return this.toNovels(data);
}

async searchNovels(
searchTerm: string,
pageNo: number,
): Promise<Plugin.NovelItem[]> {
if (pageNo > 1) return [];
const { data } = await this.api<Category[]>(
'categories?per_page=100&search=' + encodeURIComponent(searchTerm),
);
return this.toNovels(data);
}

async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
const categoryId = novelPath.split('/')[1];
const { data: category } = await this.api<Category>(
'categories/' + categoryId,
);
const chapters: Plugin.ChapterItem[] = [];
let page = 1;
let totalPages = 1;
do {
const { data, response } = await this.api<Post[]>(
`posts?categories=${categoryId}&per_page=100&order=asc&orderby=date&page=${page}&_fields=id,title`,
);
totalPages = parseInt(response.headers.get('x-wp-totalpages') || '1', 10);
for (const post of data) {
chapters.push({
name: text(post.title.rendered),
path: 'post/' + post.id,
chapterNumber: chapters.length + 1,
});
}
page++;
} while (page <= totalPages && page <= 100);

const novel: Plugin.SourceNovel = {
path: novelPath,
name: text(category.name),
chapters,
};
const cover = coverOf(category.description);
if (cover) novel.cover = cover;
const summary = summaryOf(category.description);
if (summary) novel.summary = summary;
return novel;
}

async parseChapter(chapterPath: string): Promise<string> {
const id = chapterPath.split('/').pop();
const { data: post } = await this.api<Post>(
'posts/' + id + '?_fields=title,content',
);
if (!post.content?.rendered || !text(post.content.rendered)) {
throw createPluginError(PluginError.EmptyContent, {
url: this.site + '?p=' + id,
});
}
return post.content.rendered;
}

resolveUrl = (path: string): string => {
const parts = path.split('/');
return parts[0] === 'cat'
? this.site + 'category/' + parts[2] + '/'
: this.site + '?p=' + parts[1];
};
}

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