From d32a51c8c35b14e70afd154e75c6525e555e278e Mon Sep 17 00:00:00 2001 From: Zoupers Zou <1171443643@qq.com> Date: Tue, 30 Sep 2025 11:46:20 +0800 Subject: [PATCH] fix(route/zhihu): fix zhihu posts and activities not working (#20146) --- lib/routes/zhihu/activities.ts | 12 +++-- lib/routes/zhihu/answers.ts | 8 ++- lib/routes/zhihu/posts.ts | 20 ++++--- lib/routes/zhihu/question.ts | 8 ++- lib/routes/zhihu/types.ts | 58 ++++++++++---------- lib/routes/zhihu/utils.ts | 97 ++++++++++++++++++++-------------- 6 files changed, 122 insertions(+), 81 deletions(-) diff --git a/lib/routes/zhihu/activities.ts b/lib/routes/zhihu/activities.ts index af2ce3b9e..a801031da 100644 --- a/lib/routes/zhihu/activities.ts +++ b/lib/routes/zhihu/activities.ts @@ -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 }, }); diff --git a/lib/routes/zhihu/answers.ts b/lib/routes/zhihu/answers.ts index 2ec0f9de3..b3113e74b 100644 --- a/lib/routes/zhihu/answers.ts +++ b/lib/routes/zhihu/answers.ts @@ -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, diff --git a/lib/routes/zhihu/posts.ts b/lib/routes/zhihu/posts.ts index dac4cf053..46639bb53 100644 --- a/lib/routes/zhihu/posts.ts +++ b/lib/routes/zhihu/posts.ts @@ -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(`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, }; diff --git a/lib/routes/zhihu/question.ts b/lib/routes/zhihu/question.ts index bc2c324e0..0dc56dfca 100644 --- a/lib/routes/zhihu/question.ts +++ b/lib/routes/zhihu/question.ts @@ -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, diff --git a/lib/routes/zhihu/types.ts b/lib/routes/zhihu/types.ts index d03563c53..aaf07277f 100644 --- a/lib/routes/zhihu/types.ts +++ b/lib/routes/zhihu/types.ts @@ -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 { diff --git a/lib/routes/zhihu/utils.ts b/lib/routes/zhihu/utils.ts index 443afafca..fcdecf21a 100644 --- a/lib/routes/zhihu/utils.ts +++ b/lib/routes/zhihu/utils.ts @@ -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, + }; + } };