Files
RSSHub/lib/routes/mangadex/user/follows.ts
T
chris zheng 62ae012cc7 feat(route/mangadex): add three new routes and modify one old route for mangadex.org (#18269)
* feat(namespace): add namespace for CJLU

* feat(route): Add route for graduate school of CJLU

为中国计量大学研究生院添加路由
支持将`教师通知`和`研究生通知`页面转化为 RSS 订阅源

* doc: modify discription of some params

修改参数描述

* fix(radar rule): modify radar rule

修改 radar 规则,以正确提供订阅源

* fix: add exception handling

增加异常处理

* chore: optimize conditional logic

优化判断逻辑

* Update lib/routes/cjlu/yjsy/index.ts

Co-authored-by: Tony <TonyRL@users.noreply.github.com>

* fix(radar rule): list all source choices

在 radar 规则中列出全部的类型
修改行尾符为 LF

* fix(example): correct example of the route

订正路由的案例

* chore: add missing namespace information

* fix(mangadex): resolve incorrect route detection

* chore: update route name and include myself as a maintainer

* feat(mangadex): add token retrieval utility base on config

* feat(mangadex): add utility to retrieve user configurations

Added a utility function `getFilteredLanguages` to retrieve filtered languages based on the current user's configuration.

* feat: add `getMangaMeta` utility to retrive metadata for a manga

* refactor: add utility to retrive chapter info for a manga

Original implementation by @vzz64 was embedded in modules.
Extracted the common logic into a standalone function for better code reusability and maintainability.

* refactor(feed util): move the fallback logic into function

Add a docstring to explain its usage

* doc(access util): add docstrings for key function

* refactor: purify result of function

Change result type from object to array by remove `total` param.

* feat(feed util): add support for alternative parameter type

- Add docstring for util functions
- Add a new combination function
- Improve code type inference

* refactor: move constants to separate files for better organization

* feat: modify the route for single manga

- **important**: add a prefix to the route for space for other routes in namespace, not compatiable to former route
- use integrated utility to retrieve details of a single manga

* refactor: move `token expire time` to constant

* docs(access): add Error docstring

* chore: make cover became thumbnail to save bandwidth and better display

* feat: add new route for user follow's list

- support reading, plan to read etc.
- add new optional param  to utility function

* fix: improve perfomance in retrieving manga's meta data

- if cover is needed, use the optional param `includes` to fetch in one request

* refactor: rearrange code

- skip some code for branch without cover needed

* docs: add description for route

* docs: add a detailed param description for route

- offer a default value for param

* feat: add a new constant

* feat: seperate util-function for better organization

- add docstring for `toQueryString`

* feat: add new utility function to fetch manga meta data in batch

* fix: use dynamic key to cache result

- otherwise it may get wrong result with diffrent types
- rearrange the code

* feat: add a new route for all user's followed mangas

* chore: add parameters' desctiption

- offer a more detailed example
- use local constant to maintance limit
- change some code's style

* style: change style in using utility function

* style: refactor query string construction for improved readability

* style: change a variable's name

* feat: add new route for sepecific mdlist feed

* fix: use correct time for pubDate

* fix: use `image` prop to display thumbnail instead of `description`

* refactor(mangadex): improve access token retrieval logic and handle refresh token errors

* refactor(mangadex): replace getMangaMeta with getMangaMetaByIds for improved efficiency

* chore: modify route's decription

* fix: remove unnecessary nullish coalescing in description assignment

* fix: update access token retrieval to use client ID and secret instead of username and password

* fix: correct spellings in definition

* chore: remove unnecessary code

* fix: dedupe ids before fetch manga metas

- add `limit` param to get the full response

* fix: remove wrong suffix

* fix: remove unnecessary code

* chore: remove unnessary code

* fix: set manga and config feed's cache to not refreshable

* fix: remove filteredLanguages option

* fix: remove filteredLanguages option

* fix: add sort operation after dedupe

* style: add trailing comma

* fix: remove common params

* fix: remove unnecessary  code

* fix: remove route's unnecessary name prefix

* fix: change TTL for hot caches

* fix: remove docs for non-exist config

* refactor: fix lint issue for better readability

* fix: ensure cover image is only set if cover filename exists

---------
2025-06-06 22:29:13 +08:00

150 lines
5.0 KiB
TypeScript

import { Route } from '@/types';
import got from '@/utils/got';
import getToken from '../_access';
import cache from '@/utils/cache';
import { config } from '@/config';
import { getMangaChapters, getMangaMetaByIds } from '../_feed';
type FollowType = 'reading' | 'plan-to-read' | 'completed' | 'on-hold' | 're-reading' | 'dropped';
type StatusType = 'reading' | 'plan_to_read' | 'completed' | 'on_hold' | 're_reading' | 'dropped';
type LabelType = 'Reading' | 'Plan to Read' | 'Completed' | 'On Hold' | 'Re-reading' | 'Dropped';
const statusMap: Record<FollowType, StatusType> = {
reading: 'reading',
'plan-to-read': 'plan_to_read',
completed: 'completed',
'on-hold': 'on_hold',
're-reading': 're_reading',
dropped: 'dropped',
};
const labelMap: Record<FollowType, LabelType> = {
reading: 'Reading',
'plan-to-read': 'Plan to Read',
completed: 'Completed',
'on-hold': 'On Hold',
're-reading': 'Re-reading',
dropped: 'Dropped',
};
export const route: Route = {
path: '/user/follow/:type?',
name: "Logged User's Followed Mangas Feed",
maintainers: ['chrisis58'],
example: '/mangadex/user/follow/reading',
description: `Fetches the feed of mangas that you follow on MangaDex whick are in the specified status.
CAUTION: With big amount of follows, it may take a long time to load or even fail.
It's recommended to use the \`/mangadex/mdlist/:listId?\` route instead for better performance, though it requires manual configuration.`,
categories: ['anime'],
parameters: {
type: {
description: 'The type of follows to fetch',
default: 'reading',
options: [
{ value: 'reading', label: 'Reading' },
{ value: 'plan-to-read', label: 'Plan to Read' },
{ value: 'completed', label: 'Completed' },
{ value: 'on-hold', label: 'On Hold' },
{ value: 're-reading', label: 'Re-reading' },
{ value: 'dropped', label: 'Dropped' },
],
},
},
radar: [
{
source: ['mangadex.org/titles/follows'],
target: '/user/follow/reading',
},
],
features: {
requireConfig: [
{
name: 'MANGADEX_USERNAME',
description: 'MangaDex Username, required when refresh-token is not set',
optional: true,
},
{
name: 'MANGADEX_PASSWORD',
description: 'MangaDex Password, required when refresh-token is not set',
optional: true,
},
{
name: 'MANGADEX_CLIENT_ID',
description: 'MangaDex Client ID',
optional: false,
},
{
name: 'MANGADEX_CLIENT_SECRET',
description: 'MangaDex Client Secret',
optional: false,
},
{
name: 'MANGADEX_REFRESH_TOKEN',
description: 'MangaDex Refresh Token, required when username and password are not set',
optional: true,
},
],
},
handler,
};
async function handler(ctx) {
const userFollowUrl = 'https://api.mangadex.org/manga/status';
const { type } = ctx.req.param();
const followType = (type || 'reading') as FollowType;
const accessToken = await getToken();
const statuses = (await cache.tryGet(
`mangadex:user-follow-${followType}`,
async () => {
const response = await got.get(userFollowUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
'User-Agent': config.trueUA,
},
});
const statuses = response?.data?.statuses;
if (!statuses) {
throw new Error('Failed to retrieve user follows from MangaDex API.');
}
return statuses;
},
config.cache.routeExpire,
false
)) as Record<string, string>;
const mangaIds = filterByValue(statuses, statusMap[followType]);
const mangaMetaMap = await getMangaMetaByIds(mangaIds);
const mangaChapters = await Promise.all(mangaIds.map((id) => getMangaChapters(id, undefined, 10)));
const mangas = mangaChapters.flatMap((chapters, index) => {
const mangaMeta = mangaMetaMap.get(mangaIds[index]);
return chapters.map((chapter) => ({
title: mangaMeta?.title ?? 'Unknown',
link: chapter.link,
pubDate: chapter.pubDate,
description: chapter.title ?? '',
image: mangaMeta?.cover ?? '',
}));
});
return {
title: `User Follows - ${labelMap[followType]} Mangas`,
link: `https://mangadex.org/titles/follows?tab=${followType}`,
description: 'Followed Mangas',
item: mangas,
};
}
const filterByValue = (record: Record<string, string>, value: string): string[] =>
Object.entries(record)
.filter(([, v]) => v === value)
.map(([k]) => k);