Files
RSSHub/lib/routes/zhihu/posts.ts
T
Tony b7f8ff4632 fix(route): zhihu posts (#15618)
* chore: split zhihu header signing

* fix(route): zhihu posts
2024-05-18 00:35:59 +08:00

83 lines
3.0 KiB
TypeScript

import { Route } from '@/types';
import ofetch from '@/utils/ofetch';
import { header, getSignedHeader, processImage } from './utils';
import { load } from 'cheerio';
import { parseDate } from '@/utils/parse-date';
export const route: Route = {
path: '/posts/:usertype/:id',
categories: ['social-media'],
example: '/zhihu/posts/people/frederchen',
parameters: { usertype: '作者 id,可在用户主页 URL 中找到', id: '用户类型usertype,参考用户主页的URL。目前有两种,见下表' },
features: {
requireConfig: false,
requirePuppeteer: false,
antiCrawler: true,
supportBT: false,
supportPodcast: false,
supportScihub: false,
},
radar: [
{
source: ['www.zhihu.com/:usertype/:id/posts'],
},
],
name: '用户文章',
maintainers: ['whtsky', 'Colin-XKL'],
handler,
description: `| 普通用户 | 机构用户 |
| -------- | -------- |
| people | org |`,
};
async function handler(ctx) {
const id = ctx.req.param('id');
const usertype = ctx.req.param('usertype');
const data = await ofetch(`https://www.zhihu.com/${usertype}/${id}/posts`, {
headers: {
...header,
Referer: `https://www.zhihu.com/${usertype}/${id}/`,
},
});
const $ = load(data);
const initialData = JSON.parse($('#js-initialData').text());
const userData = initialData?.initialState?.entities?.users?.[id];
const apiPath = `/api/v4/${usertype === 'people' ? 'members' : 'org'}/${id}/articles?${new URLSearchParams({
include:
'data[*].comment_count,suggest_edit,is_normal,thumbnail_extra_info,thumbnail,can_comment,comment_permission,admin_closed_comment,content,voteup_count,created,updated,upvoted_followees,voting,review_info,reaction_instruction,is_labeled,label_info;data[*].vessay_info;data[*].author.badge[?(type=best_answerer)].topics;data[*].author.vip_info;',
offset: '0',
limit: '20',
sort_by: 'created',
})}`;
const signedHeader = await getSignedHeader(`https://www.zhihu.com/${usertype}/${id}/posts`, apiPath);
const articleResponse = await ofetch(`https://www.zhihu.com${apiPath}`, {
headers: {
...header,
...signedHeader,
Referer: `https://www.zhihu.com/${usertype}/${id}/posts`,
},
});
const items = articleResponse.data.map((item) => ({
title: item.title,
description: processImage(item.content),
link: `https://zhuanlan.zhihu.com/p/${item.id}`,
pubDate: parseDate(item.created, 'X'),
updated: parseDate(item.updated, 'X'),
author: item.author.name,
}));
return {
title: `${userData?.name} 的知乎文章`,
link: `https://www.zhihu.com/${usertype}/${id}/posts`,
description: userData?.headline,
image: userData?.avatarUrlTemplate?.split('?')[0],
banner: userData?.coverUrl?.split('?')[0],
item: items,
};
}