b2caf26da3
* Moved to zustand and started refactored filters - Move from redux to zustand - Refactor Filters typings and add some helper types - Add Filters button and Picker/Switch filter options - Fixed Syosetu typings * Add rule consistent-type-definitions - Add consistent-type-definitions eslint rule to force consistent use of types instead of interfaces - Run eslint to auto-change every interface to types https://dev.to/atheodosiou/types-vs-interfaces-in-typescript-making-the-right-choice-48a4 https://www.youtube.com/watch?v=zM9UPcIyyhQ * Add other filters and refactor - Move Dialog to FiltersDialog - CheckboxFilter, TextFilter, XCheckboxFilter added - Added TripleCheckbox and TripleSwitch as tri-state checkbox/switch items using Mui stylings * TriStateCheckbox/Switch refactor - Change name of TripleSwitch and TripleCheckbox to TriState - Change slightly TriStateSwitch and StyledSwitch styles - Add option to change into TriStateSwitches via `localStorage` value `useSwitches` * Refactor code and fix issues * fix: prettier --------- Co-authored-by: nyagami <hoangquan05112002@gmail.com>
373 lines
12 KiB
TypeScript
373 lines
12 KiB
TypeScript
import { fetchApi } from '@libs/fetch';
|
|
import { Filters } from '@libs/filterInputs';
|
|
import { Plugin } from '@typings/plugin';
|
|
import { Cheerio, AnyNode, CheerioAPI, load as parseHTML } from 'cheerio';
|
|
import { defaultCover } from '@libs/defaultCover';
|
|
import { NovelStatus } from '@libs/novelStatus';
|
|
import dayjs from 'dayjs';
|
|
|
|
const includesAny = (str: string, keywords: string[]) =>
|
|
new RegExp(keywords.join('|')).test(str);
|
|
|
|
type MadaraOptions = {
|
|
useNewChapterEndpoint?: boolean;
|
|
lang?: string;
|
|
orderBy?: string;
|
|
versionIncrements?: number;
|
|
};
|
|
|
|
export type MadaraMetadata = {
|
|
id: string;
|
|
sourceSite: string;
|
|
sourceName: string;
|
|
options?: MadaraOptions;
|
|
filters?: any;
|
|
};
|
|
|
|
class MadaraPlugin implements Plugin.PluginBase {
|
|
id: string;
|
|
name: string;
|
|
icon: string;
|
|
site: string;
|
|
version: string;
|
|
options?: MadaraOptions;
|
|
filters?: Filters | undefined;
|
|
|
|
constructor(metadata: MadaraMetadata) {
|
|
this.id = metadata.id;
|
|
this.name = metadata.sourceName;
|
|
this.icon = `multisrc/madara/${metadata.id.toLowerCase()}/icon.png`;
|
|
this.site = metadata.sourceSite;
|
|
const versionIncrements = metadata.options?.versionIncrements || 0;
|
|
this.version = `1.0.${3 + versionIncrements}`;
|
|
this.options = metadata.options;
|
|
this.filters = metadata.filters;
|
|
}
|
|
|
|
translateDragontea(text: Cheerio<AnyNode>): Cheerio<AnyNode> {
|
|
if (this.id === 'dragontea') {
|
|
const $ = parseHTML(text.html() || '');
|
|
let sanitizedText = $.html() || '';
|
|
sanitizedText = sanitizedText.replace('\n', '');
|
|
sanitizedText = sanitizedText.replace(/<br\s*\/?>/g, '\n');
|
|
text.html(sanitizedText);
|
|
text.find(':not(:has(*))').each((i, el) => {
|
|
// Select only the deepest elements to avoid reversing the text twice
|
|
const $el = $(el);
|
|
const alphabet =
|
|
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
|
const reversedAlphabet =
|
|
'zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA'.split('');
|
|
const text = $el.text().normalize('NFD'); // Normalize the string to separate the accents
|
|
const reversedText = text.split('');
|
|
const reversedLetters = [...reversedText]
|
|
.map(letter => {
|
|
const baseLetter = letter.normalize('NFC');
|
|
const index = alphabet.indexOf(baseLetter);
|
|
return index !== -1
|
|
? reversedAlphabet[index] + letter.slice(baseLetter.length)
|
|
: letter;
|
|
})
|
|
.join('');
|
|
$el.html(
|
|
$el
|
|
.html()
|
|
?.replace($el.text(), reversedLetters)
|
|
.replace('\n', '<br>') || '',
|
|
);
|
|
});
|
|
}
|
|
return text;
|
|
}
|
|
|
|
getHostname(url: string): string {
|
|
url = url.split('/')[2];
|
|
const url_parts = url.split('.');
|
|
url_parts.pop(); // remove TLD
|
|
return url_parts.join('.');
|
|
}
|
|
|
|
async getCheerio(url: string, search: boolean): Promise<CheerioAPI> {
|
|
const r = await fetchApi(url);
|
|
if (!r.ok && search != true)
|
|
throw new Error(
|
|
'Could not reach site (' + r.status + ') try to open in webview.',
|
|
);
|
|
const $ = parseHTML(await r.text());
|
|
const title = $('title').text().trim();
|
|
if (
|
|
this.getHostname(url) != this.getHostname(r.url) ||
|
|
title == 'Bot Verification' ||
|
|
title == 'You are being redirected...' ||
|
|
title == 'Un instant...' ||
|
|
title == 'Just a moment...' ||
|
|
title == 'Redirecting...'
|
|
)
|
|
throw new Error('Captcha error, please open in webview');
|
|
return $;
|
|
}
|
|
|
|
parseNovels(loadedCheerio: CheerioAPI): Plugin.NovelItem[] {
|
|
const novels: Plugin.NovelItem[] = [];
|
|
|
|
loadedCheerio('.manga-title-badges').remove();
|
|
|
|
loadedCheerio('.page-item-detail, .c-tabs-item__content').each(
|
|
(index, element) => {
|
|
const novelName = loadedCheerio(element)
|
|
.find('.post-title')
|
|
.text()
|
|
.trim();
|
|
const novelUrl =
|
|
loadedCheerio(element).find('.post-title').find('a').attr('href') ||
|
|
'';
|
|
if (!novelName || !novelUrl) return;
|
|
const image = loadedCheerio(element).find('img');
|
|
const novelCover =
|
|
image.attr('data-src') ||
|
|
image.attr('src') ||
|
|
image.attr('data-lazy-srcset') ||
|
|
defaultCover;
|
|
const novel: Plugin.NovelItem = {
|
|
name: novelName,
|
|
cover: novelCover,
|
|
path: novelUrl.replace(/https?:\/\/.*?\//, '/'),
|
|
};
|
|
novels.push(novel);
|
|
},
|
|
);
|
|
|
|
return novels;
|
|
}
|
|
|
|
async popularNovels(
|
|
pageNo: number,
|
|
{
|
|
filters,
|
|
showLatestNovels,
|
|
}: Plugin.PopularNovelsOptions<typeof this.filters>,
|
|
): Promise<Plugin.NovelItem[]> {
|
|
let url = this.site + '/page/' + pageNo + '/?s=&post_type=wp-manga';
|
|
if (!filters) filters = this.filters || {};
|
|
if (showLatestNovels) url += '&m_orderby=latest';
|
|
for (const key in filters) {
|
|
if (typeof filters[key].value === 'object')
|
|
for (const value of filters[key].value as string[])
|
|
url += `&${key}=${value}`;
|
|
else if (filters[key].value) url += `&${key}=${filters[key].value}`;
|
|
}
|
|
const loadedCheerio = await this.getCheerio(url, false);
|
|
return this.parseNovels(loadedCheerio);
|
|
}
|
|
|
|
async parseNovel(novelPath: string): Promise<Plugin.SourceNovel> {
|
|
let loadedCheerio = await this.getCheerio(this.site + novelPath, false);
|
|
|
|
loadedCheerio('.manga-title-badges, #manga-title span').remove();
|
|
const novel: Plugin.SourceNovel = {
|
|
path: novelPath,
|
|
name:
|
|
loadedCheerio('.post-title h1').text().trim() ||
|
|
loadedCheerio('#manga-title h1').text(),
|
|
};
|
|
|
|
novel.cover =
|
|
loadedCheerio('.summary_image > a > img').attr('data-lazy-src') ||
|
|
loadedCheerio('.summary_image > a > img').attr('data-src') ||
|
|
loadedCheerio('.summary_image > a > img').attr('src') ||
|
|
defaultCover;
|
|
|
|
loadedCheerio('.post-content_item, .post-content').each(function () {
|
|
const detailName = loadedCheerio(this).find('h5').text().trim();
|
|
const detail = loadedCheerio(this).find('.summary-content').text().trim();
|
|
|
|
switch (detailName) {
|
|
case 'Genre(s)':
|
|
case 'Genre':
|
|
case 'Tags':
|
|
case 'Género(s)':
|
|
case 'التصنيفات':
|
|
if (novel.genres) novel.genres += ', ' + detail;
|
|
else novel.genres = detail;
|
|
break;
|
|
case 'Author(s)':
|
|
case 'Author':
|
|
case 'Autor(es)':
|
|
case 'المؤلف':
|
|
case 'المؤلف (ين)':
|
|
novel.author = detail;
|
|
break;
|
|
case 'Status':
|
|
case 'Novel':
|
|
case 'Estado':
|
|
novel.status =
|
|
detail.includes('OnGoing') || detail.includes('مستمرة')
|
|
? NovelStatus.Ongoing
|
|
: NovelStatus.Completed;
|
|
break;
|
|
}
|
|
});
|
|
|
|
loadedCheerio('div.summary__content .code-block,script,noscript').remove();
|
|
const summary =
|
|
loadedCheerio('div.summary__content') ||
|
|
loadedCheerio('#tab-manga-about') ||
|
|
loadedCheerio('.post-content_item h5:contains("Summary")').next();
|
|
novel.summary = this.translateDragontea(summary).text().trim();
|
|
const chapters: Plugin.ChapterItem[] = [];
|
|
let html = '';
|
|
|
|
if (this.options?.useNewChapterEndpoint) {
|
|
html = await fetchApi(this.site + novelPath + 'ajax/chapters/', {
|
|
method: 'POST',
|
|
}).then(res => res.text());
|
|
} else {
|
|
const novelId =
|
|
loadedCheerio('.rating-post-id').attr('value') ||
|
|
loadedCheerio('#manga-chapters-holder').attr('data-id') ||
|
|
'';
|
|
|
|
const formData = new FormData();
|
|
formData.append('action', 'manga_get_chapters');
|
|
formData.append('manga', novelId);
|
|
|
|
html = await fetchApi(this.site + 'wp-admin/admin-ajax.php', {
|
|
method: 'POST',
|
|
body: formData,
|
|
}).then(res => res.text());
|
|
}
|
|
|
|
if (html !== '0') {
|
|
loadedCheerio = parseHTML(html);
|
|
}
|
|
|
|
const totalChapters = loadedCheerio('.wp-manga-chapter').length;
|
|
loadedCheerio('.wp-manga-chapter').each((chapterIndex, element) => {
|
|
const chapterName = loadedCheerio(element).find('a').text().trim();
|
|
|
|
let releaseDate = loadedCheerio(element)
|
|
.find('span.chapter-release-date')
|
|
.text()
|
|
.trim();
|
|
|
|
if (releaseDate) {
|
|
releaseDate = this.parseData(releaseDate);
|
|
} else {
|
|
releaseDate = dayjs().format('LL');
|
|
}
|
|
|
|
const chapterUrl = loadedCheerio(element).find('a').attr('href') || '';
|
|
|
|
if (chapterUrl && chapterUrl != '#') {
|
|
chapters.push({
|
|
name: chapterName,
|
|
path: chapterUrl.replace(/https?:\/\/.*?\//, '/'),
|
|
releaseTime: releaseDate || null,
|
|
chapterNumber: totalChapters - chapterIndex,
|
|
});
|
|
}
|
|
});
|
|
|
|
novel.chapters = chapters.reverse();
|
|
return novel;
|
|
}
|
|
|
|
async parseChapter(chapterPath: string): Promise<string> {
|
|
const loadedCheerio = await this.getCheerio(this.site + chapterPath, false);
|
|
const chapterText =
|
|
loadedCheerio('.text-left') ||
|
|
loadedCheerio('.text-right') ||
|
|
loadedCheerio('.entry-content') ||
|
|
loadedCheerio('.c-blog-post > div > div:nth-child(2)');
|
|
|
|
if (this.id === 'riwyat') {
|
|
chapterText.find('span[style*="opacity: 0; position: fixed;"]').remove();
|
|
}
|
|
chapterText.find('div.text-right').attr('style', 'text-align: right;');
|
|
return this.translateDragontea(chapterText).html() || '';
|
|
}
|
|
|
|
async searchNovels(
|
|
searchTerm: string,
|
|
pageNo?: number | undefined,
|
|
): Promise<Plugin.NovelItem[]> {
|
|
const url =
|
|
this.site +
|
|
'/page/' +
|
|
pageNo +
|
|
'/?s=' +
|
|
searchTerm +
|
|
'&post_type=wp-manga';
|
|
const loadedCheerio = await this.getCheerio(url, true);
|
|
return this.parseNovels(loadedCheerio);
|
|
}
|
|
|
|
parseData = (date: string) => {
|
|
let dayJSDate = dayjs(); // today
|
|
const timeAgo = date.match(/\d+/)?.[0] || '';
|
|
const timeAgoInt = parseInt(timeAgo, 10);
|
|
|
|
if (!timeAgo) return date; // there is no number!
|
|
|
|
if (includesAny(date, ['detik', 'segundo', 'second', 'วินาที'])) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'second'); // go back N seconds
|
|
} else if (
|
|
includesAny(date, [
|
|
'menit',
|
|
'dakika',
|
|
'min',
|
|
'minute',
|
|
'minuto',
|
|
'นาที',
|
|
'دقائق',
|
|
])
|
|
) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'minute'); // go back N minute
|
|
} else if (
|
|
includesAny(date, [
|
|
'jam',
|
|
'saat',
|
|
'heure',
|
|
'hora',
|
|
'hour',
|
|
'ชั่วโมง',
|
|
'giờ',
|
|
'ore',
|
|
'ساعة',
|
|
'小时',
|
|
])
|
|
) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'hours'); // go back N hours
|
|
} else if (
|
|
includesAny(date, [
|
|
'hari',
|
|
'gün',
|
|
'jour',
|
|
'día',
|
|
'dia',
|
|
'day',
|
|
'วัน',
|
|
'ngày',
|
|
'giorni',
|
|
'أيام',
|
|
'天',
|
|
])
|
|
) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'days'); // go back N days
|
|
} else if (includesAny(date, ['week', 'semana'])) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'week'); // go back N a week
|
|
} else if (includesAny(date, ['month', 'mes'])) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'month'); // go back N months
|
|
} else if (includesAny(date, ['year', 'año'])) {
|
|
dayJSDate = dayJSDate.subtract(timeAgoInt, 'year'); // go back N years
|
|
} else {
|
|
if (dayjs(date).format('LL') !== 'Invalid Date') {
|
|
return dayjs(date).format('LL');
|
|
}
|
|
return date;
|
|
}
|
|
|
|
return dayJSDate.format('LL');
|
|
};
|
|
}
|