Files
lnreader-plugins/plugins/russian/authortoday.broken.ts
T
nyagami e602df44c8 Full TS for Plugins (#538)
* remove lang, descrription in plugin script

* remove languages import

* Update README.md

* fix: missing lang

* clean: remove description

* feat(Add Sources) (#15)

* add many sources

* add showToast

* feat(Add Source): (#16)

* add source

* remove descriptions

* Early Novel & Fast Novel (#1)

* some more plugin

* plugin

* try something new

* yes

* try yes

* genres is plural

* fastnovel full fix

* testings

* early check

* earlynovel fixed

* showToast check

* earlynovel done

* fastnovel fixe

* again

* showToasts again

* fix for fastnovel

* done

* for pr

* Update freenovelupdates.js

* MTL Reader and MTL Novel (#2)

* first

* test

* wops

* mtlreaders

* ok

* for PR

* Nitro Scans and Novel Hold (#3)

* start feature

* more feature

* something

* eslint

* yes

* maybe

* wa

* asdasd

* amazing

* change it up

* for pr

* WPmangastream and Novelfull (#4) (#17)

* source generation

* fix json parse error

* update plguins

* delete fetchApi, nobleMTL (.js)

* delete showToast.js

* Typescript Support (#18)

* Initial TS Config

* Initial TS Config

* Fix most errors

* Fix test webserver

* Fix webserver isPlugin not working

* Fix typos

* Add check if plugins have all the fields

* Move exports.protected to the bottom of the plugin

* Change username, reponame and branchname

* Fix no exports error

* Fix type

* Fix typo in tsc_fix

* Remove const from exports to not re-define consts

* Readd const becuause exports may not exist.

* Fix plugins to work in-app

* Fix NobleMTL

* Remove fix_ts.ts

* Change template.ts

* delete cheerio_space

* move api into ./testweb

* remove js dir

* remove js dir (again)

* remove ./js (again)

* init multisrc generator (test)

* remove module.exports in libs

* madara generator

* update template

* rename generator, TS for hako

* fix icon url for madara

* fix icon for madara (again)

* update Readme, nodemon

* export default for all libs

* fix madara novelurl

* update: pluginId, name, filename for madara

* feat: check same id error

* update: precommit, fix: require.default

* Revert "update: precommit, fix: require.default"

This reverts commit c642c5c72241f13eccfe417210c22272c4739ffa.

* Port all plugins to ts (#19)

- fix cheerio
- remove export default
- fix spelling

* update template

* add multisrc noveltl, update generator param, fix web search

* fix undefined id for Snailulitka

* add rulate multisrc, fix max length textarea

* add readwn multisrc

* delete: erolate and rulate are in multisrc

* Change broken extension and show error on commit for those files (#20)

* Change to .broken.ts and show error on commit for those files

* remove novelStatus

* fix: wrong id in github action

* remove mangastream multisrc

* update icon for readwn multisrc

---------

Co-authored-by: K1ngfish3r <trulyihu@gmail.com>
Co-authored-by: Marcin Majewski <skilletssgames@gmail.com>
2023-08-17 08:49:45 +05:30

342 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import cheerio from "cheerio";
import dayjs from "dayjs";
import { fetchApi } from "@libs/fetch";
import { NovelStatus } from "@libs/novelStatus";
import { FilterInputs } from "@libs/filterInputs";
import { Chapter, Novel, Plugin } from "@typings/plugin";
import { defaultCover } from "@libs/defaultCover";
export const id = "AT";
export const name = "Автор Тудей";
export const site = "https://author.today";
export const version = "1.0.0";
export const icon = "src/ru/authortoday/icon.png";
const baseUrl = site;
const apiUrl = "https://api.author.today/";
const token = "Bearer guest";
export const popularNovels: Plugin.popularNovels = async function (
page,
{ showLatestNovels, filters }
) {
let url = apiUrl + "v1/catalog/search?page=" + page;
if (filters?.genre) {
url += "&genre=" + filters.genre;
}
url +=
"&sorting=" +
(showLatestNovels ? "recent" : filters?.sort || "popular");
url += "&form=" + (filters?.form || "any");
url += "&state=" + (filters?.state || "any");
url += "&series=" + (filters?.series || "any");
url += "&access=" + (filters?.access || "any");
url += "&promo=" + (filters?.promo || "hide");
const result = await fetchApi(url, {
headers: {
Authorization: token,
},
});
const json = await result.json();
if (json?.code === "NotFound") {
return [];
}
let novels: Novel.Item[] = [];
json.searchResults.forEach((novel) =>
novels.push({
name: novel.title,
cover: novel?.coverUrl
? "https://cm.author.today/content/" + novel.coverUrl
: defaultCover,
url: baseUrl + "/work/" + novel.id,
})
);
return novels;
};
export const parseNovelAndChapters: Plugin.parseNovelAndChapters =
async function (novelUrl) {
const workID = novelUrl.split("/")[4];
let result = await fetchApi(`${apiUrl}v1/work/${workID}/details`, {
headers: {
Authorization: token,
},
});
let json = await result.json();
let novel: Novel.instance = {
url: novelUrl,
name: json.title,
cover: json?.coverUrl ? json.coverUrl.split("?")[0] : defaultCover,
author:
json?.originalAuthor ||
json?.authorFIO ||
json?.coAuthorFIO ||
json?.secondCoAuthorFIO ||
json?.translator ||
"",
genres: json?.tags?.join(", "),
status: json?.isFinished
? NovelStatus.Completed
: NovelStatus.Ongoing,
};
novel.summary = "";
novel.summary += json?.annotation ? json.annotation + "\n" : "";
novel.summary += json?.authorNotes
? "Примечания автора:\n" + json.authorNotes
: "";
// all chapters
result = await fetchApi(`${apiUrl}v1/work/${workID}/content`, {
headers: {
Authorization: token,
},
});
json = await result.json();
let chapters: Chapter.Item[] = [];
json?.forEach((chapter, index) => {
if (chapter?.isAvailable && !chapter?.isDraft) {
chapters.push({
name: chapter?.title || `Глава ${index + 1}`,
releaseTime: dayjs(
chapter?.publishTime || chapter.lastModificationTime
).format("LLL"),
url: `${apiUrl}v1/work/${workID}/chapter/${chapter.id}/text`,
});
}
});
novel.chapters = chapters;
return novel;
};
export const parseChapter: Plugin.parseChapter = async function (chapterUrl) {
const result = await fetchApi(chapterUrl, {
headers: {
Authorization: token,
},
});
const json = await result.json();
if (json?.code) {
return json.code + "\n" + json?.message;
}
let key = json.key.split("").reverse().join("") + "@_@";
let text = "";
for (let i = 0; i < json.text.length; i++) {
text += String.fromCharCode(
json.text.charCodeAt(i) ^ key.charCodeAt(Math.floor(i % key.length))
);
}
const loadedCheerio = cheerio.load(text);
loadedCheerio("img").each(function () {
if (!loadedCheerio(this).attr("src")?.startsWith("http")) {
const src = loadedCheerio(this).attr("src");
loadedCheerio(this).attr("src", baseUrl + src);
}
});
const chapterText = loadedCheerio.html();
return chapterText;
};
export const searchNovels: Plugin.searchNovels = async function (searchTerm) {
const url = `${baseUrl}/search?category=works&q=${searchTerm}`;
const result = await fetchApi(url, {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0",
referer: baseUrl,
});
const body = await result.text();
const loadedCheerio = cheerio.load(body);
let novels: Novel.Item[] = [];
loadedCheerio("div.book-row").each(function () {
const name = loadedCheerio(this)
.find('div[class="book-title"] a')
.text()
.trim();
let cover = loadedCheerio(this).find("img").attr("src");
const url =
baseUrl +
"/work/" +
loadedCheerio(this)
.find('div[class="book-title"] a')
.attr("href")
?.split("/")[2];
if (cover) {
cover = cover.split("?")[0];
} else {
cover = defaultCover;
}
novels.push({ name, cover, url });
});
return novels;
};
export const filters = [
{
key: "sort",
label: "Сортировка",
values: [
{ label: "По популярности", value: "popular" },
{ label: "По количеству лайков", value: "likes" },
{ label: "По комментариям", value: "comments" },
{ label: "По новизне", value: "recent" },
{ label: "По просмотрам", value: "views" },
{ label: "Набирающие популярность", value: "trending" },
],
inputType: FilterInputs.Picker,
},
{
key: "genre",
label: "Жанры",
values: [
{ label: "Альтернативная история", value: "sf-history" },
{ label: "Антиутопия", value: "dystopia" },
{ label: "Бизнес-литература", value: "biznes-literatura" },
{ label: "Боевая фантастика", value: "sf-action" },
{ label: "Боевик", value: "action" },
{ label: "Боевое фэнтези", value: "fantasy-action" },
{ label: "Бояръ-Аниме", value: "boyar-anime" },
{ label: "Героическая фантастика", value: "sf-heroic" },
{ label: "Героическое фэнтези", value: "heroic-fantasy" },
{ label: "Городское фэнтези", value: "urban-fantasy" },
{ label: "Детектив", value: "detective" },
{ label: "Детская литература", value: "detskaya-literatura" },
{ label: "Документальная проза", value: "non-fiction" },
{ label: "Историческая проза", value: "historical-fiction" },
{
label: "Исторические приключения",
value: "historical-adventure",
},
{ label: "Исторический детектив", value: "historical-mystery" },
{
label: "Исторический любовный роман",
value: "historical-romance",
},
{ label: "Историческое фэнтези", value: "historical-fantasy" },
{ label: "Киберпанк", value: "cyberpunk" },
{ label: "Короткий любовный роман", value: "short-romance" },
{ label: "Космическая фантастика", value: "sf-space" },
{ label: "ЛитРПГ", value: "litrpg" },
{ label: "Любовное фэнтези", value: "love-fantasy" },
{ label: "Любовные романы", value: "romance" },
{ label: "Мистика", value: "paranormal" },
{ label: "Назад в СССР", value: "back-to-ussr" },
{ label: "Научная фантастика", value: "science-fiction" },
{ label: "Подростковая проза", value: "teen-prose" },
{ label: "Политический роман", value: "political-fiction" },
{ label: "Попаданцы", value: "popadantsy" },
{ label: "Попаданцы в космос", value: "popadantsy-v-kosmos" },
{
label: "Попаданцы в магические миры",
value: "popadantsy-v-magicheskie-miry",
},
{ label: "Попаданцы во времени", value: "popadantsy-vo-vremeni" },
{ label: "Постапокалипсис", value: "postapocalyptic" },
{ label: "Поэзия", value: "poetry" },
{ label: "Приключения", value: "adventure" },
{ label: "Публицистика", value: "publicism" },
{ label: "Развитие личности", value: "razvitie-lichnosti" },
{ label: "Разное", value: "other" },
{ label: "РеалРПГ", value: "realrpg" },
{ label: "Романтическая эротика", value: "romantic-erotika" },
{ label: "Сказка", value: "fairy-tale" },
{ label: "Современная проза", value: "modern-prose" },
{
label: "Современный любовный роман",
value: "contemporary-romance",
},
{ label: "Социальная фантастика", value: "sf-social" },
{ label: "Стимпанк", value: "steampunk" },
{ label: "Темное фэнтези", value: "dark-fantasy" },
{ label: "Триллер", value: "thriller" },
{ label: "Ужасы", value: "horror" },
{ label: "Фантастика", value: "sci-fi" },
{
label: "Фантастический детектив",
value: "detective-science-fiction",
},
{ label: "Фанфик", value: "fanfiction" },
{ label: "Фэнтези", value: "fantasy" },
{ label: "Шпионский детектив", value: "spy-mystery" },
{ label: "Эпическое фэнтези", value: "epic-fantasy" },
{ label: "Эротика", value: "erotica" },
{ label: "Эротическая фантастика", value: "sf-erotika" },
{ label: "Эротический фанфик", value: "fanfiction-erotika" },
{ label: "Эротическое фэнтези", value: "fantasy-erotika" },
{ label: "Юмор", value: "humor" },
{ label: "Юмористическая фантастика", value: "sf-humor" },
{ label: "Юмористическое фэнтези", value: "ironical-fantasy" },
],
inputType: FilterInputs.Picker,
},
{
key: "form",
label: "Форма произведения",
values: [
{ label: "Любой", value: "any" },
{ label: "Перевод", value: "translation" },
{ label: "Повесть", value: "tale" },
{ label: "Рассказ", value: "story" },
{ label: "Роман", value: "novel" },
{ label: "Сборник поэзии", value: "poetry" },
{ label: "Сборник рассказов", value: "story-book" },
],
inputType: FilterInputs.Picker,
},
{
key: "state",
label: "Статус произведения",
values: [
{ label: "Любой статус", value: "any" },
{ label: "В процессе", value: "in-progress" },
{ label: "Завершено", value: "finished" },
],
inputType: FilterInputs.Picker,
},
{
key: "series",
label: "Статус цикла",
values: [
{ label: "Не важно", value: "any" },
{ label: "Вне цикла", value: "out" },
{ label: "Цикл завершен", value: "finished" },
{ label: "Цикл не завершен", value: "unfinished" },
],
inputType: FilterInputs.Picker,
},
{
key: "access",
label: "Тип доступа",
values: [
{ label: "Любой", value: "any" },
{ label: "Платный", value: "paid" },
{ label: "Бесплатный", value: "free" },
],
inputType: FilterInputs.Picker,
},
{
key: "promo",
label: "Промо-фрагмент",
values: [
{ label: "Скрывать", value: "hide" },
{ label: "Показывать", value: "show" },
],
inputType: FilterInputs.Picker,
},
];