fix(route/zhihu): fix zhihu posts and activities not working (#20146)

This commit is contained in:
Zoupers Zou
2025-09-30 11:46:20 +08:00
committed by GitHub
parent fe416a017a
commit d32a51c8c3
6 changed files with 122 additions and 81 deletions
+9 -3
View File
@@ -11,7 +11,13 @@ export const route: Route = {
example: '/zhihu/people/activities/diygod',
parameters: { id: '作者 id,可在用户主页 URL 中找到' },
features: {
requireConfig: false,
requireConfig: [
{
name: 'ZHIHU_COOKIES',
description: '',
optional: true,
},
],
requirePuppeteer: false,
antiCrawler: true,
supportBT: false,
@@ -32,7 +38,7 @@ async function handler(ctx) {
const id = ctx.req.param('id');
// second: get real data from zhihu
const apiPath = `/api/v3/moments/${id}/activities?limit=7&desktop=true`;
const apiPath = `/api/v3/moments/${id}/activities?limit=5&desktop=true&ws_qiangzhisafe=0`;
const signedHeader = await getSignedHeader(`https://www.zhihu.com/people/${id}`, apiPath);
@@ -40,7 +46,7 @@ async function handler(ctx) {
headers: {
...header,
...signedHeader,
Referer: `https://www.zhihu.com/people/${id}/activities`,
Referer: `https://www.zhihu.com/people/${id}`,
// Authorization: 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20', // hard-coded in js
},
});
+7 -1
View File
@@ -9,7 +9,13 @@ export const route: Route = {
example: '/zhihu/people/answers/diygod',
parameters: { id: '作者 id,可在用户主页 URL 中找到' },
features: {
requireConfig: false,
requireConfig: [
{
name: 'ZHIHU_COOKIES',
description: '',
optional: true,
},
],
requirePuppeteer: false,
antiCrawler: true,
supportBT: false,
+14 -6
View File
@@ -1,4 +1,5 @@
import { Route } from '@/types';
import { load } from 'cheerio';
import ofetch from '@/utils/ofetch';
import cache from '@/utils/cache';
import { header, getSignedHeader, processImage } from './utils';
@@ -11,7 +12,13 @@ export const route: Route = {
example: '/zhihu/posts/people/frederchen',
parameters: { usertype: '作者 id,可在用户主页 URL 中找到', id: '用户类型usertype,参考用户主页的URL。目前有两种,见下表' },
features: {
requireConfig: false,
requireConfig: [
{
name: 'ZHIHU_COOKIES',
description: '',
optional: true,
},
],
requirePuppeteer: false,
antiCrawler: true,
supportBT: false,
@@ -36,17 +43,18 @@ async function handler(ctx) {
const usertype = ctx.req.param('usertype');
const userProfile = await cache.tryGet(`zhihu:posts:profile:${id}`, async () => {
const userAPIPath = `/api/v4/${usertype === 'people' ? 'members' : 'org'}/${id}?${new URLSearchParams({
include: 'allow_message,is_followed,is_following,is_org,is_blocking,employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics',
})}`;
const userAPIPath = `/${usertype === 'people' ? 'people' : 'org'}/${id}`;
return await ofetch<Profile>(`https://www.zhihu.com${userAPIPath}`, {
const result = await ofetch(`https://www.zhihu.com${userAPIPath}`, {
headers: {
...header,
...(await getSignedHeader(`https://www.zhihu.com/${usertype}/${id}/`, userAPIPath)),
Referer: `https://www.zhihu.com/${usertype}/${id}/`,
},
});
const $ = load(result);
const data = JSON.parse($('#js-initialData').text());
return data?.initialState?.entities?.users[id] as Profile;
});
const apiPath = `/api/v4/${usertype === 'people' ? 'members' : 'org'}/${id}/articles?${new URLSearchParams({
@@ -80,7 +88,7 @@ async function handler(ctx) {
title: `${userProfile.name} 的知乎文章`,
link: `https://www.zhihu.com/${usertype}/${id}/posts`,
description: userProfile.headline,
image: userProfile.avatar_url.split('?')[0],
image: userProfile.avatarUrl.split('?')[0],
// banner: userData?.coverUrl?.split('?')[0],
item: items,
};
+7 -1
View File
@@ -9,7 +9,13 @@ export const route: Route = {
example: '/zhihu/question/59895982',
parameters: { questionId: '问题 id', sortBy: '排序方式:`default`, `created`, `updated`。默认为 `default`' },
features: {
requireConfig: false,
requireConfig: [
{
name: 'ZHIHU_COOKIES',
description: '',
optional: true,
},
],
requirePuppeteer: false,
antiCrawler: true,
supportBT: false,
+29 -29
View File
@@ -2,45 +2,45 @@ export interface Profile {
id: string;
url_token: string;
name: string;
use_default_avatar: boolean;
avatar_url: string;
avatar_url_template: string;
is_org: boolean;
useDefaultAvatar: boolean;
avatarUrl: string;
avatarUrlTemplate: string;
isOrg: boolean;
type: string;
url: string;
user_type: string;
userType: string;
headline: string;
headline_render: string;
headlineRender: string;
gender: number;
is_advertiser: boolean;
ip_info: string;
vip_info: {
is_vip: boolean;
vip_type: number;
rename_days: string;
entrance_v2: null;
rename_frequency: number;
rename_await_days: number;
isAdvertiser: boolean;
ipInfo: string;
vipInfo: {
isVip: boolean;
vipType: number;
renameDays: string;
entranceV2: null;
renameFrequency: number;
renameAwaitDays: number;
};
badge: any[];
badge_v2: {
badgeV2: {
title: string;
merged_badges: any[];
detail_badges: any[];
mergedBadges: any[];
detailBadges: any[];
icon: string;
night_icon: string;
nightIcon: string;
};
allow_message: boolean;
is_following: boolean;
is_followed: boolean;
is_blocking: boolean;
follower_count: number;
answer_count: number;
articles_count: number;
available_medals_count: number;
allowMessage: boolean;
isFollowing: boolean;
isFollowed: boolean;
isBlocking: boolean;
followerCount: number;
answerCount: number;
articlesCount: number;
availableMedalsCount: number;
employments: any[];
is_realname: boolean;
has_applying_column: boolean;
isRealname: boolean;
hasApplyingColumn: boolean;
}
interface Article {
+56 -41
View File
@@ -64,51 +64,66 @@ export const getCookieValueByKey = (key: string) =>
?.slice(key.length + 1) || '';
export const getSignedHeader = async (url: string, apiPath: string) => {
// Because the API of zhihu.com has changed, we must use the value of `d_c0` (extracted from cookies) to calculate
// `x-zse-96`. So first get `d_c0`, then get the actual data of a ZhiHu question. In this way, we don't need to
// require users to set the cookie in environmental variables anymore.
if (config?.zhihu?.cookies) {
const dc0 = getCookieValueByKey('d_c0');
// fisrt: get cookie(dc_0) from zhihu.com
const { dc0, zseCk } = await cache.tryGet('zhihu:cookies:d_c0', async () => {
if (getCookieValueByKey('d_c0') && getCookieValueByKey('__zse_ck')) {
return { dc0: getCookieValueByKey('d_c0'), zseCk: getCookieValueByKey('__zse_ck') };
}
const response1 = await ofetch.raw('https://static.zhihu.com/zse-ck/v3.js');
const script = await response1._data.text();
const zseCk = script.match(/__g\.ck\|\|"([\w+/=\\]*?)",_=/)?.[1];
const response2 = zseCk
? await ofetch.raw(url, {
headers: {
cookie: `${response1.headers
.getSetCookie()
.map((s) => s.split(';')[0])
.join('; ')}; __zse_ck=${zseCk}`,
},
})
: null;
const xzse93 = '101_3_3.0';
const f = `${xzse93}+${apiPath}+${dc0}`;
const xzse96 = '2.0_' + g_encrypt(md5(f));
return {
cookie: config.zhihu.cookies,
'x-zse-96': xzse96,
'x-app-za': 'OS=Web',
'x-zse-93': xzse93,
};
} else {
// NOTICE: this method is out of date.
// Because the API of zhihu.com has changed, we must use the value of `d_c0` (extracted from cookies) to calculate
// `x-zse-96`. So first get `d_c0`, then get the actual data of a ZhiHu question. In this way, we don't need to
// require users to set the cookie in environmental variables anymore.
const dc0 =
(response2 || response1).headers
.getSetCookie()
.find((s) => s.startsWith('d_c0='))
?.split(';')[0]
.trim()
.slice('d_c0='.length) || '';
// fisrt: get cookie(dc_0) from zhihu.com
const { dc0, zseCk } = await cache.tryGet('zhihu:cookies:d_c0', async () => {
if (getCookieValueByKey('d_c0') && getCookieValueByKey('__zse_ck')) {
return { dc0: getCookieValueByKey('d_c0'), zseCk: getCookieValueByKey('__zse_ck') };
}
const response1 = await ofetch.raw('https://static.zhihu.com/zse-ck/v3.js');
const script = await response1._data.text();
const zseCk = script.match(/__g\.ck\|\|"([\w+/=\\]*?)",_=/)?.[1];
const response2 = zseCk
? await ofetch.raw(url, {
headers: {
cookie: `${response1.headers
.getSetCookie()
.map((s) => s.split(';')[0])
.join('; ')}; __zse_ck=${zseCk}`,
},
})
: null;
return { dc0, zseCk };
});
const dc0 =
(response2 || response1).headers
.getSetCookie()
.find((s) => s.startsWith('d_c0='))
?.split(';')[0]
.trim()
.slice('d_c0='.length) || '';
// calculate x-zse-96, refer to https://github.com/srx-2000/spider_collection/issues/18
const xzse93 = '101_3_3.0';
const f = `${xzse93}+${apiPath}+${dc0}`;
const xzse96 = '2.0_' + g_encrypt(md5(f));
return { dc0, zseCk };
});
const zc0 = getCookieValueByKey('z_c0');
// calculate x-zse-96, refer to https://github.com/srx-2000/spider_collection/issues/18
const xzse93 = '101_3_3.0';
const f = `${xzse93}+${apiPath}+${dc0}`;
const xzse96 = '2.0_' + g_encrypt(md5(f));
return {
cookie: `__zse_ck=${zseCk}; d_c0=${dc0}${zc0 ? `;z_c0=${zc0}` : ''}`,
'x-zse-96': xzse96,
'x-app-za': 'OS=Web',
'x-zse-93': xzse93,
};
const zc0 = getCookieValueByKey('z_c0');
return {
cookie: `__zse_ck=${zseCk}; d_c0=${dc0}${zc0 ? `;z_c0=${zc0}` : ''}`,
'x-zse-96': xzse96,
'x-app-za': 'OS=Web',
'x-zse-93': xzse93,
};
}
};