fix(route/jandan): use official APIs in section logics

This commit is contained in:
pseudoyu
2025-04-17 11:27:32 +08:00
parent bb5bef5e9b
commit 53d6e9ab74
3 changed files with 386 additions and 56 deletions
+36 -12
View File
@@ -1,24 +1,47 @@
import { Route } from '@/types';
import { Route, DataItem } from '@/types';
import cache from '@/utils/cache';
import got from '@/utils/got';
import { ofetch } from 'ofetch';
import { load } from 'cheerio';
import parser from '@/utils/rss-parser';
export const route: Route = {
path: '/',
name: 'Unknown',
maintainers: ['nczitzk', 'bigfei'],
example: '/jandan',
name: 'Feed',
maintainers: ['nczitzk', 'bigfei', 'pseudoyu'],
parameters: {},
features: {
requireConfig: false,
requirePuppeteer: false,
antiCrawler: false,
supportBT: false,
supportPodcast: false,
supportScihub: false,
},
radar: [
{
source: ['i.jandan.net'],
target: '/jandan',
},
],
handler,
};
async function handler() {
async function handler(): Promise<{
title: string;
link: string;
item: DataItem[];
}> {
const rootUrl = 'http://i.jandan.net';
const feed = await parser.parseURL(`${rootUrl}/feed/`);
const items = await Promise.all(
feed.items.map((item) =>
cache.tryGet(item.link, async () => {
const response = await got(item.link);
const $ = load(response.data);
cache.tryGet(item.link || '', async () => {
if (!item.link) {
return undefined as unknown as DataItem;
}
const response = await ofetch(item.link);
const $ = load(response);
$('.wechat-hide').prev().nextAll().remove();
$('img').replaceWith((i, e) => {
const src = $(e).attr('src');
@@ -26,9 +49,9 @@ async function handler() {
const newSrc = src?.replace(/https?:\/\/(\w+)\.moyu\.im/, 'https://$1.sinaimg.cn');
return `<img src="${newSrc}" alt="${alt}">`;
});
const single = {
title: item.title,
description: $('.entry').html(),
const single: DataItem = {
title: item.title || '',
description: $('.entry').html() || '',
pubDate: item.pubDate,
link: item.link,
author: item['dc:creator'],
@@ -37,7 +60,8 @@ async function handler() {
return single;
})
)
);
).then((items) => items.filter((item): item is DataItem => item !== undefined));
return {
title: '煎蛋',
link: rootUrl,
+102 -44
View File
@@ -1,59 +1,117 @@
import { Route } from '@/types';
import got from '@/utils/got';
import { load } from 'cheerio';
import { parseDate } from '@/utils/parse-date';
import { Route, DataItem } from '@/types';
import { handleTopSection, handleForumSection, handleCommentSection } from './utils';
export const route: Route = {
path: '/:category',
name: 'Unknown',
maintainers: [],
path: '/:category/:type?',
example: '/jandan/top',
name: 'Section',
maintainers: ['nczitzk', 'pseudoyu'],
parameters: {
category: {
description: '板块',
options: [
{
label: '热榜',
value: 'top',
},
{
label: '问答',
value: 'qa',
},
{
label: '树洞',
value: 'treehole',
},
{
label: '随手拍',
value: 'ooxx',
},
{
label: '无聊图',
value: 'pic',
},
{
label: '鱼塘',
value: 'bbs',
},
],
},
type: {
description: '热榜类型,仅当 category 选择 `top` 时有效',
default: '4hr',
options: [
{
label: '4小时热门',
value: '4hr',
},
{
label: '3天内无聊图',
value: 'pic3days',
},
{
label: '7天内无聊图',
value: 'pic7days',
},
],
},
},
features: {
requireConfig: false,
requirePuppeteer: false,
antiCrawler: false,
supportBT: false,
supportPodcast: false,
supportScihub: false,
},
radar: [
{
source: ['i.jandan.net/:category'],
target: '/jandan/:category?',
},
],
handler,
};
async function handler(ctx) {
const category = ctx.req.param('category') ?? 'top';
async function handler(ctx): Promise<{
title: string;
link: string;
item: DataItem[];
}> {
let category = ctx.req.param('category') ?? 'top';
category = category.replace(/#.*$/, '');
const type = ctx.req.param('type') ?? '4hr';
const rootUrl = 'http://i.jandan.net';
const currentUrl = `${rootUrl}/${category}`;
const response = await got({
method: 'get',
url: currentUrl,
});
let result: { title: string; items: DataItem[] };
const $ = load(response.data);
const items = $('ol.commentlist li')
.not('.row')
.slice(0, ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit')) : 50)
.toArray()
.map((item) => {
item = $(item);
item.find('.commenttext img, .tucao-report').remove();
item.find('.commenttext .view_img_link').each(function () {
const url = new URL($(this).attr('href'), rootUrl);
url.protocol = 'https:';
url.host = url.host.replace('moyu.im', 'sinaimg.cn');
$(this).replaceWith(`<img src="${url}">`);
});
const author = item.find('b').first().text();
const description = item.find('.commenttext');
return {
author,
description: description.html(),
title: `${author}: ${description.text()}`,
pubDate: parseDate(item.find('.time').text()),
link: `${rootUrl}/t/${item.attr('id').split('-').pop()}`,
};
});
try {
if (category === 'top') {
result = await handleTopSection(rootUrl, type);
} else if (category === 'bbs') {
result = await handleForumSection(rootUrl);
} else {
result = await handleCommentSection(rootUrl, category);
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
result = {
title: `煎蛋 - ${category}`,
items: [
{
title: `抓取出错: ${category}`,
description: `抓取 ${category} 分区时出现错误: ${errorMessage}`,
link: currentUrl,
pubDate: new Date(),
},
],
};
}
return {
title: `${$('title').text()} - 煎蛋`,
title: result.title,
link: currentUrl,
item: items,
item: result.items,
};
}
+248
View File
@@ -0,0 +1,248 @@
import { DataItem } from '@/types';
import { ofetch } from 'ofetch';
import { load } from 'cheerio';
import { parseDate } from '@/utils/parse-date';
export const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36';
/**
* Extract page ID from script tags in HTML
*/
export const extractPageId = async (url: string, referer: string): Promise<string> => {
const response = await ofetch(url, {
headers: {
'User-Agent': USER_AGENT,
Referer: referer,
Accept: 'application/json, text/plain, */*',
},
});
const $ = load(response);
let pageId = '';
$('script').each((_, script) => {
const content = $(script).html() || '';
const match = content.match(/PAGE\s*=\s*{\s*id\s*:\s*(\d+)\s*}/);
if (match) {
pageId = match[1];
}
});
return pageId;
};
/**
* Handle the top section (热榜)
*/
export const handleTopSection = async (rootUrl: string, type: string): Promise<{ title: string; items: DataItem[] }> => {
const apiUrl = `${rootUrl}/api/top/${type}`;
const response = await ofetch(apiUrl, {
headers: {
'User-Agent': USER_AGENT,
Referer: rootUrl,
Accept: 'application/json, text/plain, */*',
},
});
let title = '热榜';
switch (type) {
case 'pic3days':
title += ' - 3天内无聊图';
break;
case 'pic7days':
title += ' - 7天内无聊图';
break;
default:
title += ' - 4小时热门';
break;
}
if (response.code === 0 && response.data && Array.isArray(response.data)) {
const items = response.data.map((item) => {
const content = item.content.replaceAll(/img src="(.*?)"/g, (match, src) => match.replace(src, src.replace(/^https?:\/\/(\w+)\.moyu\.im/, 'https://$1.sinaimg.cn')));
return {
author: item.author,
title: `${item.author}: ${content.replaceAll(/<[^>]+>/g, '')}`,
description: content,
pubDate: parseDate(item.date),
link: `${rootUrl}/t/${item.id}`,
} as DataItem;
});
return { title, items };
}
return {
title,
items: [
{
title: `获取失败: ${title}`,
description: '未能获取热榜数据',
link: `${rootUrl}/top`,
pubDate: new Date(),
},
],
};
};
/**
* Handle the forum/bbs section (鱼塘)
*/
export const handleForumSection = async (rootUrl: string): Promise<{ title: string; items: DataItem[] }> => {
const title = '煎蛋 - 鱼塘';
const currentUrl = `${rootUrl}/bbs`;
try {
const forumId = await extractPageId(currentUrl, rootUrl);
if (!forumId) {
return {
title,
items: [
{
title: `获取失败: ${title}`,
description: '无法获取论坛ID',
link: currentUrl,
pubDate: new Date(),
},
],
};
}
const apiUrl = `${rootUrl}/api/forum/posts/${forumId}?page=1`;
const forumData = await ofetch(apiUrl, {
headers: {
'User-Agent': USER_AGENT,
Referer: currentUrl,
Accept: 'application/json, text/plain, */*',
},
});
if (forumData.code === 0 && forumData.data && forumData.data.list && Array.isArray(forumData.data.list)) {
const items = forumData.data.list.map((post) => {
const content = post.content.replaceAll(/img src="(.*?)"/g, (match, src) => match.replace(src, src.replace(/^https?:\/\/(\w+)\.moyu\.im/, 'https://$1.sinaimg.cn')));
return {
author: post.author_name,
title: post.title || `${post.author_name}发表了新主题`,
description: content,
pubDate: parseDate(post.update_time || post.create_time),
link: `${rootUrl}/bbs#/topic/${post.post_id}`,
category: post.reply_count > 0 ? [`${post.reply_count}条回复`] : undefined,
} as DataItem;
});
return { title, items };
}
return {
title,
items: [
{
title: `获取失败: ${title}`,
description: '未能获取鱼塘数据',
link: currentUrl,
pubDate: new Date(),
},
],
};
} catch (error) {
return {
title,
items: [
{
title: `解析错误: 鱼塘`,
description: `解析鱼塘页面时出错: ${error instanceof Error ? error.message : String(error)}`,
link: currentUrl,
pubDate: new Date(),
},
],
};
}
};
/**
* Handle other sections (问答, 树洞, 随手拍, 无聊图)
*/
export const handleCommentSection = async (rootUrl: string, category: string): Promise<{ title: string; items: DataItem[] }> => {
const currentUrl = `${rootUrl}/${category}`;
try {
const pageId = await extractPageId(currentUrl, rootUrl);
const response = await ofetch(currentUrl, {
headers: {
'User-Agent': USER_AGENT,
Referer: rootUrl,
Accept: 'application/json, text/plain, */*',
},
});
const $ = load(response);
const title = String($('title').text().trim()) || `煎蛋 - ${category}`;
if (!pageId) {
return {
title,
items: [
{
title: `无法解析: ${title}`,
description: '无法从页面中获取到帖子ID,可能网站结构已变更',
link: currentUrl,
pubDate: new Date(),
},
],
};
}
const apiUrl = `${rootUrl}/api/comment/post/${pageId}?order=desc&page=1`;
const commentsData = await ofetch(apiUrl, {
headers: {
'User-Agent': USER_AGENT,
Referer: currentUrl,
Accept: 'application/json, text/plain, */*',
},
});
if (commentsData.code === 0 && commentsData.data && commentsData.data.list && Array.isArray(commentsData.data.list)) {
const items = commentsData.data.list.map((comment) => {
const content = comment.content.replaceAll(/img src="(.*?)"/g, (match, src) => match.replace(src, src.replace(/^https?:\/\/(\w+)\.moyu\.im/, 'https://$1.sinaimg.cn')));
return {
author: comment.author,
title: `${comment.author}: ${content.replaceAll(/<[^>]+>/g, '')}`,
description: content,
pubDate: parseDate(comment.date_gmt || comment.date),
link: `${rootUrl}/t/${comment.id}`,
} as DataItem;
});
return { title, items };
}
return {
title,
items: [
{
title: `暂无内容: ${title || category}`,
description: '没有获取到内容,可能需要更新解析规则',
link: currentUrl,
pubDate: new Date(),
},
],
};
} catch {
return {
title: `煎蛋 - ${category}`,
items: [
{
title: `解析错误: ${category}`,
description: '解析页面时出错',
link: currentUrl,
pubDate: new Date(),
},
],
};
}
};