diff --git a/plugins/english/taptotale.ts b/plugins/english/taptotale.ts new file mode 100644 index 0000000000..39e7040520 --- /dev/null +++ b/plugins/english/taptotale.ts @@ -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//` for a novel, `post/` 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(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, + ): Promise { + const sort = showLatestNovels + ? 'id:desc' + : filters?.sort?.value || 'count:desc'; + const [orderby, order] = sort.split(':'); + const { data } = await this.api( + `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 { + if (pageNo > 1) return []; + const { data } = await this.api( + 'categories?per_page=100&search=' + encodeURIComponent(searchTerm), + ); + return this.toNovels(data); + } + + async parseNovel(novelPath: string): Promise { + const categoryId = novelPath.split('/')[1]; + const { data: category } = await this.api( + 'categories/' + categoryId, + ); + const chapters: Plugin.ChapterItem[] = []; + let page = 1; + let totalPages = 1; + do { + const { data, response } = await this.api( + `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 { + const id = chapterPath.split('/').pop(); + const { data: post } = await this.api( + '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(); diff --git a/public/static/src/en/taptotale/icon.png b/public/static/src/en/taptotale/icon.png new file mode 100644 index 0000000000..7968474df2 Binary files /dev/null and b/public/static/src/en/taptotale/icon.png differ