From b7f8ff4632b1591b5f8e08f98fa4ff467704ed22 Mon Sep 17 00:00:00 2001 From: Tony Date: Sat, 18 May 2024 00:35:59 +0800 Subject: [PATCH] fix(route): zhihu posts (#15618) * chore: split zhihu header signing * fix(route): zhihu posts --- lib/routes/zhihu/activities.ts | 48 ++--------- lib/routes/zhihu/answers.ts | 6 +- lib/routes/zhihu/collection.ts | 8 +- lib/routes/zhihu/daily-section.ts | 6 +- lib/routes/zhihu/daily.ts | 6 +- lib/routes/zhihu/hotlist.ts | 6 +- lib/routes/zhihu/posts.ts | 68 +++++++-------- lib/routes/zhihu/question.ts | 54 +++--------- lib/routes/zhihu/timeline.ts | 4 +- lib/routes/zhihu/topic.ts | 36 ++------ lib/routes/zhihu/utils.ts | 133 +++++++++++++++++++----------- lib/routes/zhihu/zhuanlan.ts | 8 +- 12 files changed, 172 insertions(+), 211 deletions(-) diff --git a/lib/routes/zhihu/activities.ts b/lib/routes/zhihu/activities.ts index 8e760bd3c..73823c6d7 100644 --- a/lib/routes/zhihu/activities.ts +++ b/lib/routes/zhihu/activities.ts @@ -1,11 +1,7 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; import got from '@/utils/got'; -import ofetch from '@/utils/ofetch'; -import utils from './utils'; +import { header, processImage, getSignedHeader } from './utils'; import { parseDate } from '@/utils/parse-date'; -import g_encrypt from './execlib/x-zse-96-v3'; -import md5 from '@/utils/md5'; export const route: Route = { path: '/people/activities/:id', @@ -33,43 +29,17 @@ export const route: Route = { async function handler(ctx) { const id = ctx.req.param('id'); - // 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. - - // fisrt: get cookie(dc_0) from zhihu.com - const cookie_mes = await cache.tryGet('zhihu:cookies:d_c0', async () => { - const response = await ofetch.raw(`https://www.zhihu.com/people/${id}`, { - headers: { - ...utils.header, - }, - }); - - const cookie_org = response.headers.get('set-cookie'); - const cookie = cookie_org?.toString(); - const match = cookie?.match(/d_c0=(\S+?)(?:;|$)/); - const cookie_mes = match && match[1]; - if (!cookie_mes) { - throw new Error('Failed to extract `d_c0` from cookies'); - } - return cookie_mes; - }); - const cookie = `d_c0=${cookie_mes}`; - // second: get real data from zhihu const apiPath = `/api/v3/moments/${id}/activities?limit=7&desktop=true`; - // calculate x-zse-96, refer to https://github.com/srx-2000/spider_collection/issues/18 - const f = `101_3_3.0+${apiPath}+${cookie_mes}`; - const xzse96 = '2.0_' + g_encrypt(md5(f)); - const _header = { cookie, 'x-zse-96': xzse96, 'x-app-za': 'OS=Web', 'x-zse-93': '101_3_3.0' }; + const signedHeader = await getSignedHeader(`https://www.zhihu.com/people/${id}`, apiPath); const response = await got(`https://www.zhihu.com${apiPath}`, { headers: { - ...utils.header, - ..._header, + ...header, + ...signedHeader, Referer: `https://www.zhihu.com/people/${id}/activities`, - Authorization: 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20', // hard-coded in js + // Authorization: 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20', // hard-coded in js }, }); @@ -85,7 +55,7 @@ async function handler(ctx) { let title; let description; let url; - const images = []; + const images: string[] = []; let text = ''; let link = ''; let author = ''; @@ -94,13 +64,13 @@ async function handler(ctx) { case 'answer': title = detail.question.title; author = detail.author.name; - description = utils.ProcessImage(detail.content); + description = processImage(detail.content); url = `https://www.zhihu.com/question/${detail.question.id}/answer/${detail.id}`; break; case 'article': title = detail.title; author = detail.author.name; - description = utils.ProcessImage(detail.content); + description = processImage(detail.content); url = `https://zhuanlan.zhihu.com/p/${detail.id}`; break; case 'pin': @@ -142,7 +112,7 @@ async function handler(ctx) { case 'question': title = detail.title; author = detail.author.name; - description = utils.ProcessImage(detail.detail); + description = processImage(detail.detail); url = `https://www.zhihu.com/question/${detail.id}`; break; case 'collection': diff --git a/lib/routes/zhihu/answers.ts b/lib/routes/zhihu/answers.ts index 6dd7f44b4..e065bff2a 100644 --- a/lib/routes/zhihu/answers.ts +++ b/lib/routes/zhihu/answers.ts @@ -1,7 +1,7 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; import got from '@/utils/got'; -import utils from './utils'; +import { header, processImage } from './utils'; import { parseDate } from '@/utils/parse-date'; export const route: Route = { @@ -51,7 +51,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com${apiPath}`, headers: { - ...utils.header, + ...header, Referer: `https://www.zhihu.com/people/${id}`, }, }); @@ -71,7 +71,7 @@ async function handler(ctx) { url: `https://api.zhihu.com/appview/api/v4/answers/${item.id}?include=content&is_appview=true`, headers, }); - description = utils.ProcessImage(detail.data.content); + description = processImage(detail.data.content); } catch { description = `${title}`; } diff --git a/lib/routes/zhihu/collection.ts b/lib/routes/zhihu/collection.ts index 1844031e1..43489c3ba 100644 --- a/lib/routes/zhihu/collection.ts +++ b/lib/routes/zhihu/collection.ts @@ -2,7 +2,7 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; import got from '@/utils/got'; import { load } from 'cheerio'; -import utils from './utils'; +import { header } from './utils'; import { generateData } from './pin/utils'; import { parseDate } from '@/utils/parse-date'; @@ -38,7 +38,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com/api/v4/collections/${id}/items?offset=0&limit=20`, headers: { - ...utils.header, + ...header, Referer: `https://www.zhihu.com/collection/${id}`, }, }); @@ -56,7 +56,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com/api/v4/collections/${id}/items?offset=${offset}&limit=20`, headers: { - ...utils.header, + ...header, Referer: `https://www.zhihu.com/collection/${id}`, }, }); @@ -72,7 +72,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com/collection/${id}`, headers: { - ...utils.header, + ...header, Referer: `https://www.zhihu.com/collection/${id}`, }, }); diff --git a/lib/routes/zhihu/daily-section.ts b/lib/routes/zhihu/daily-section.ts index d594717f7..7ca1cf6ea 100644 --- a/lib/routes/zhihu/daily-section.ts +++ b/lib/routes/zhihu/daily-section.ts @@ -1,7 +1,7 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; import got from '@/utils/got'; -import utils from './utils'; +import { header, processImage } from './utils'; import { parseDate } from '@/utils/parse-date'; // 参考:https://github.com/izzyleung/ZhihuDailyPurify/wiki/%E7%9F%A5%E4%B9%8E%E6%97%A5%E6%8A%A5-API-%E5%88%86%E6%9E%90 @@ -38,7 +38,7 @@ async function handler(ctx) { method: 'get', url: `https://news-at.zhihu.com/api/7/section/${sectionId}`, headers: { - ...utils.header, + ...header, Referer: `https://news-at.zhihu.com/api/7/section/${sectionId}`, }, }); @@ -61,7 +61,7 @@ async function handler(ctx) { Referer: url, }, }); - item.description = utils.ProcessImage(storyDetail.data.body.replaceAll(/
([\S\s]*?)<\/div>/g, '$1').replaceAll(/<\/?h2.*?>/g, '')); + item.description = processImage(storyDetail.data.body.replaceAll(/
([\S\s]*?)<\/div>/g, '$1').replaceAll(/<\/?h2.*?>/g, '')); return item; }); diff --git a/lib/routes/zhihu/daily.ts b/lib/routes/zhihu/daily.ts index 5125087ea..342664357 100644 --- a/lib/routes/zhihu/daily.ts +++ b/lib/routes/zhihu/daily.ts @@ -1,7 +1,7 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; import got from '@/utils/got'; -import utils from './utils'; +import { header, processImage } from './utils'; import { parseDate } from '@/utils/parse-date'; // 参考:https://github.com/izzyleung/ZhihuDailyPurify/wiki/%E7%9F%A5%E4%B9%8E%E6%97%A5%E6%8A%A5-API-%E5%88%86%E6%9E%90 @@ -58,7 +58,7 @@ async function handler() { method: 'get', url: `${api}/latest`, headers: { - ...utils.header, + ...header, Referer: `${api}/latest`, Host: address, }, @@ -89,7 +89,7 @@ async function handler() { }, // host: address, }); - return utils.ProcessImage(storyDetail.data.body.replaceAll(/
([\S\s]*?)<\/div>/g, '$1').replaceAll(/<\/?h2.*?>/g, '')); + return processImage(storyDetail.data.body.replaceAll(/
([\S\s]*?)<\/div>/g, '$1').replaceAll(/<\/?h2.*?>/g, '')); }); item.description = description; return item; diff --git a/lib/routes/zhihu/hotlist.ts b/lib/routes/zhihu/hotlist.ts index a227637c4..9183cfeb5 100644 --- a/lib/routes/zhihu/hotlist.ts +++ b/lib/routes/zhihu/hotlist.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; import got from '@/utils/got'; -import utils from './utils'; +import { processImage } from './utils'; import { parseDate } from '@/utils/parse-date'; export const route: Route = { @@ -44,7 +44,7 @@ async function handler() { case 'answer': return { title: item.target.question.title, - description: `${item.target.author.name}的回答

${utils.ProcessImage(item.target.content)}`, + description: `${item.target.author.name}的回答

${processImage(item.target.content)}`, author: item.target.author.name, pubDate: parseDate(item.target.updated_time * 1000), guid: item.target.id.toString(), @@ -53,7 +53,7 @@ async function handler() { case 'article': return { title: item.target.title, - description: `${item.target.author.name}的文章

${utils.ProcessImage(item.target.content)}`, + description: `${item.target.author.name}的文章

${processImage(item.target.content)}`, author: item.target.author.name, pubDate: parseDate(item.updated * 1000), guid: item.target.id.toString(), diff --git a/lib/routes/zhihu/posts.ts b/lib/routes/zhihu/posts.ts index 8fff51e45..29d971ef4 100644 --- a/lib/routes/zhihu/posts.ts +++ b/lib/routes/zhihu/posts.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; -import got from '@/utils/got'; -import utils from './utils'; +import ofetch from '@/utils/ofetch'; +import { header, getSignedHeader, processImage } from './utils'; import { load } from 'cheerio'; import { parseDate } from '@/utils/parse-date'; @@ -34,47 +34,49 @@ async function handler(ctx) { const id = ctx.req.param('id'); const usertype = ctx.req.param('usertype'); - const { data } = await got(`https://www.zhihu.com/${usertype}/${id}/posts`, { + const data = await ofetch(`https://www.zhihu.com/${usertype}/${id}/posts`, { headers: { - ...utils.header, + ...header, Referer: `https://www.zhihu.com/${usertype}/${id}/`, }, }); const $ = load(data); - const jsondata = $('#js-initialData'); - const authorname = $('.ProfileHeader-name') - .contents() - .filter((_index, element) => element.type === 'text') - .text(); - const authordescription = $('.ProfileHeader-headline').text(); + const initialData = JSON.parse($('#js-initialData').text()); + const userData = initialData?.initialState?.entities?.users?.[id]; - const parsed = JSON.parse(jsondata.html()); - const articlesdata = parsed.initialState.entities.articles; + 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 list = Object.keys(articlesdata).map((key) => { - const $ = load(articlesdata[key].content, null, false); - $('noscript').remove(); - $('img').each((_, item) => { - if (item.attribs['data-actualsrc'] || item.attribs['data-original']) { - item.attribs['data-actualsrc'] = item.attribs['data-actualsrc'] ? item.attribs['data-actualsrc'].split('?source')[0] : null; - item.attribs['data-original'] = item.attribs['data-original'] ? item.attribs['data-original'].split('?source')[0] : null; - item.attribs.src = item.attribs['data-original'] || item.attribs['data-actualsrc']; - delete item.attribs['data-actualsrc']; - delete item.attribs['data-original']; - } - }); - return { - title: articlesdata[key].title, - description: $.html(), - link: articlesdata[key].url, - pubDate: parseDate(articlesdata[key].created, 'X'), - }; + 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: `${authorname} 的知乎文章`, + title: `${userData?.name} 的知乎文章`, link: `https://www.zhihu.com/${usertype}/${id}/posts`, - description: authordescription, - item: list, + description: userData?.headline, + image: userData?.avatarUrlTemplate?.split('?')[0], + banner: userData?.coverUrl?.split('?')[0], + item: items, }; } diff --git a/lib/routes/zhihu/question.ts b/lib/routes/zhihu/question.ts index e95f0d984..bc2c324e0 100644 --- a/lib/routes/zhihu/question.ts +++ b/lib/routes/zhihu/question.ts @@ -1,9 +1,6 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; import got from '@/utils/got'; -import utils from './utils'; -import md5 from '@/utils/md5'; -import g_encrypt from './execlib/x-zse-96-v3'; +import { header, processImage, getSignedHeader } from './utils'; import { parseDate } from '@/utils/parse-date'; export const route: Route = { @@ -35,50 +32,25 @@ async function handler(ctx) { questionId, sortBy = 'default', // default,created,updated } = ctx.req.param(); - // 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. - - // fisrt: get cookie(dc_0) from zhihu.com - const cookie_mes = await cache.tryGet('zhihu:cookies:d_c0', async () => { - const response = await got({ - method: 'get', - url: `https://www.zhihu.com/question/${questionId}`, - headers: { - ...utils.header, - }, - }); - - const cookie_org = response.headers['set-cookie']; - const cookie = cookie_org.toString(); - const match = cookie.match(/d_c0=(\S+?)(?:;|$)/); - const cookie_mes = match && match[1]; - if (!cookie_mes) { - throw new Error('Failed to extract `d_c0` from cookies'); - } - return cookie_mes; - }); - const cookie = `d_c0=${cookie_mes}`; // second: get real data from zhihu - const limit = 20; - const include = - 'data%5B*%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cattachment%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Cis_labeled%2Cpaid_info%2Cpaid_info_content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_recognized%3Bdata%5B*%5D.mark_infos%5B*%5D.url%3Bdata%5B*%5D.author.follower_count%2Cbadge%5B*%5D.topics%3Bdata%5B*%5D.settings.table_of_content.enabled&offset=0'; const rootUrl = 'https://www.zhihu.com'; - const apiPath = `/api/v4/questions/${questionId}/answers?include=${include}&limit=${limit}&sort_by=${sortBy}&platform=desktop`; - const url = rootUrl + apiPath; + const apiPath = `/api/v4/questions/${questionId}/answers?${new URLSearchParams({ + include: + 'data[*].is_normal,admin_closed_comment,reward_info,is_collapsed,annotation_action,annotation_detail,collapse_reason,is_sticky,collapsed_by,suggest_edit,comment_count,can_comment,content,editable_content,attachment,voteup_count,reshipment_settings,comment_permission,created_time,updated_time,review_info,relevant_info,question,excerpt,is_labeled,paid_info,paid_info_content,relationship.is_authorized,is_author,voting,is_thanked,is_nothelp,is_recognized;data[*].mark_infos[*].url;data[*].author.follower_count,badge[*].topics;data[*].settings.table_of_content.enabled&offset=0', + limit: '20', + sort_by: sortBy, + platform: 'desktop', + })}`; - // calculate x-zse-96, refer to https://github.com/srx-2000/spider_collection/issues/18 - const f = `101_3_3.0+${apiPath}+${cookie_mes}`; - const xzse96 = '2.0_' + g_encrypt(md5(f)); - const _header = { cookie, 'x-zse-96': xzse96, 'x-app-za': 'OS=Web', 'x-zse-93': '101_3_3.0' }; + const signedHeader = await getSignedHeader(`https://www.zhihu.com/question/${questionId}`, apiPath); const response = await got({ method: 'get', - url, + url: rootUrl + apiPath, headers: { - ...utils.header, - ..._header, + ...header, + ...signedHeader, Referer: `https://www.zhihu.com/question/${questionId}`, // Authorization: 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20', // previously hard-coded in js, outdated }, @@ -91,7 +63,7 @@ async function handler(ctx) { link: `https://www.zhihu.com/question/${questionId}`, item: listRes.map((item) => { const title = `${item.author.name}的回答:${item.excerpt}`; - const description = `${item.author.name}的回答

${utils.ProcessImage(item.content)}`; + const description = `${item.author.name}的回答

${processImage(item.content)}`; return { title, diff --git a/lib/routes/zhihu/timeline.ts b/lib/routes/zhihu/timeline.ts index cdd7f28a4..e174ee9ea 100644 --- a/lib/routes/zhihu/timeline.ts +++ b/lib/routes/zhihu/timeline.ts @@ -1,7 +1,7 @@ import { Route } from '@/types'; import got from '@/utils/got'; import { config } from '@/config'; -import utils from './utils'; +import { processImage } from './utils'; import { parseDate } from '@/utils/parse-date'; import ConfigNotFoundError from '@/errors/types/config-not-found'; @@ -106,7 +106,7 @@ async function handler(ctx) { const link = buildLink(e); return { title: `${e.action_text_tpl.replace('{}', buildActors(e))}: ${getOne([e.target.title, e.target.question ? e.target.question.title : ''])}`, - description: utils.ProcessImage(`
${getOne([e.target.content_html, getContent(e.target.content), e.target.detail, e.target.excerpt, ''])}
`), + description: processImage(`
${getOne([e.target.content_html, getContent(e.target.content), e.target.detail, e.target.excerpt, ''])}
`), pubDate: parseDate(e.updated_time * 1000), link, author: e.target.author ? e.target.author.name : '', diff --git a/lib/routes/zhihu/topic.ts b/lib/routes/zhihu/topic.ts index e181dd33a..190b1e4df 100644 --- a/lib/routes/zhihu/topic.ts +++ b/lib/routes/zhihu/topic.ts @@ -1,10 +1,8 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; import got from '@/utils/got'; -import utils from './utils'; +import { header, processImage, getSignedHeader } from './utils'; import { parseDate } from '@/utils/parse-date'; -import g_encrypt from './execlib/x-zse-96-v3'; -import md5 from '@/utils/md5'; export const route: Route = { path: '/topic/:topicId/:isTop?', @@ -34,22 +32,6 @@ async function handler(ctx) { const { topicId, isTop = false } = ctx.req.param(); const link = `https://www.zhihu.com/topic/${topicId}/${isTop ? 'top-answers' : 'newest'}`; - const cookieDc0 = await cache.tryGet('zhihu:cookies:d_c0', async () => { - const { headers } = await got(link, { - headers: { - ...utils.header, - }, - }); - const cookie = headers['set-cookie'].toString(); - const match = cookie.match(/d_c0=(\S+?)(?:;|$)/); - const cookieMatched = match?.[1]; - if (!cookieMatched) { - throw new Error('Failed to extract `d_c0` from cookies'); - } - return cookieMatched; - }); - const cookie = `d_c0=${cookieDc0}`; - const topicMeta = await cache.tryGet(`zhihu:topic:${topicId}`, async () => { const { data: response } = await got(`https://www.zhihu.com/api/v4/topics/${topicId}/intro`, { searchParams: { @@ -60,15 +42,12 @@ async function handler(ctx) { }); const apiPath = `/api/v5.1/topics/${topicId}/feeds/${isTop ? 'top_activity' : 'timeline_activity'}`; - const xzse93 = '101_3_3.0'; - const f = `${xzse93}+${apiPath}+${cookieDc0}`; - const xzse96 = '2.0_' + g_encrypt(md5(f)); - const _header = { cookie, 'x-zse-96': xzse96, 'x-zse-93': xzse93 }; + const signedHeader = await getSignedHeader(link, apiPath); const { data: response } = await got(`https://www.zhihu.com${apiPath}`, { headers: { - ...utils.header, - ..._header, + ...header, + ...signedHeader, Referer: link, }, }); @@ -78,13 +57,13 @@ async function handler(ctx) { let title = ''; let description = ''; let link = ''; - let pubDate = ''; + let pubDate: Date; let author = ''; switch (type) { case 'answer': title = `${item.question.title}-${item.author.name}的回答:${item.excerpt}`; - description = `${item.question.title}
${item.author.name}的回答
${utils.ProcessImage(item.content)}`; + description = `${item.question.title}
${item.author.name}的回答
${processImage(item.content)}`; link = `https://www.zhihu.com/question/${item.question.id}/answer/${item.id}`; pubDate = parseDate(item.updated_time * 1000); author = item.author.name; @@ -99,7 +78,7 @@ async function handler(ctx) { case 'article': title = item.title; - description = utils.ProcessImage(item.content); + description = processImage(item.content); link = item.url; pubDate = parseDate(item.created * 1000); break; @@ -116,6 +95,7 @@ async function handler(ctx) { default: description = '未知类型,请点击链接提交issue'; + pubDate = parseDate(Date.now()); } return { diff --git a/lib/routes/zhihu/utils.ts b/lib/routes/zhihu/utils.ts index 217bb9ebb..d5705c83c 100644 --- a/lib/routes/zhihu/utils.ts +++ b/lib/routes/zhihu/utils.ts @@ -1,51 +1,88 @@ import { load } from 'cheerio'; +import cache from '@/utils/cache'; +import ofetch from '@/utils/ofetch'; +import g_encrypt from './execlib/x-zse-96-v3'; +import md5 from '@/utils/md5'; -export default { - header: { - 'x-api-version': '3.0.91', - }, - ProcessImage(content) { - const $ = load(content, null, false); - - $('noscript').remove(); - - $('a[data-draft-type="mcn-link-card"]').remove(); - - $('a').each((_, elem) => { - const href = $(elem).attr('href'); - if (href?.startsWith('https://link.zhihu.com/?target=')) { - const url = new URL(href); - const target = url.searchParams.get('target') || ''; - try { - $(elem).attr('href', decodeURIComponent(target)); - } catch { - // sometimes the target is not a valid url - } - } - }); - - $('img.content_image, img.origin_image, img.content-image, img.data-actualsrc, figure>img').each((i, e) => { - if (e.attribs['data-actualsrc']) { - $(e).attr({ - src: e.attribs['data-actualsrc'].replace('_b.jpg', '_1440w.jpg'), - width: null, - height: null, - }); - } else if (e.attribs['data-original']) { - $(e).attr({ - src: e.attribs['data-original'].replace('_r.jpg', '_1440w.jpg'), - width: null, - height: null, - }); - } else { - $(e).attr({ - src: e.attribs.src.replace('_b.jpg', '_1440w.jpg'), - width: null, - height: null, - }); - } - }); - - return $.html(); - }, +export const header = { + 'x-api-version': '3.0.91', +}; + +const fixImageUrl = (url: string) => url.split('?')[0].replace('_b.jpg', '.jpg').replace('_r.jpg', '.jpg').replace('_720w.jpg', '.jpg'); + +export const processImage = (content: string) => { + const $ = load(content, null, false); + + $('noscript, a[data-draft-type="mcn-link-card"]').remove(); + + $('a').each((_, elem) => { + const href = $(elem).attr('href'); + if (href?.startsWith('http://link.zhihu.com/?target=') || href?.startsWith('https://link.zhihu.com/?target=')) { + const url = new URL(href); + const target = url.searchParams.get('target') || ''; + try { + $(elem).attr('href', decodeURIComponent(target)); + } catch { + // sometimes the target is not a valid url + } + } + }); + + $('img.content_image, img.origin_image, img.content-image, img.data-actualsrc, figure>img').each((i, e) => { + if (e.attribs['data-actualsrc']) { + $(e).attr({ + src: fixImageUrl(e.attribs['data-actualsrc']), + width: null, + height: null, + }); + $(e).removeAttr('data-actualsrc'); + } else if (e.attribs['data-original']) { + $(e).attr({ + src: fixImageUrl(e.attribs['data-original']), + width: null, + height: null, + }); + $(e).removeAttr('data-original'); + } else { + $(e).attr({ + src: fixImageUrl(e.attribs.src), + width: null, + height: null, + }); + } + }); + + return $.html(); +}; + +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. + + // fisrt: get cookie(dc_0) from zhihu.com + const dc0 = await cache.tryGet('zhihu:cookies:d_c0', async () => { + const response = await ofetch.raw(url); + + const dc0 = response.headers + .getSetCookie() + .find((s) => s.startsWith('d_c0=')) + ?.split(';')[0]; + if (!dc0) { + throw new Error('Failed to extract `d_c0` from cookies'); + } + + return dc0; + }); + + // 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: `d_c0=${dc0}`, + 'x-zse-96': xzse96, + 'x-app-za': 'OS=Web', + 'x-zse-93': xzse93, + }; }; diff --git a/lib/routes/zhihu/zhuanlan.ts b/lib/routes/zhihu/zhuanlan.ts index 95bebd91a..ea0595318 100644 --- a/lib/routes/zhihu/zhuanlan.ts +++ b/lib/routes/zhihu/zhuanlan.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; import got from '@/utils/got'; -import utils from './utils'; +import { header } from './utils'; import { load } from 'cheerio'; import { parseDate } from '@/utils/parse-date'; @@ -34,7 +34,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com/api/v4/columns/${id}/items`, headers: { - ...utils.header, + ...header, Referer: `https://zhuanlan.zhihu.com/${id}`, }, }); @@ -43,7 +43,7 @@ async function handler(ctx) { method: 'get', url: `https://www.zhihu.com/api/v4/columns/${id}/pinned-items`, headers: { - ...utils.header, + ...header, Referer: `https://zhuanlan.zhihu.com/${id}`, }, }); @@ -73,7 +73,7 @@ async function handler(ctx) { let title = ''; let link = ''; let author = ''; - let pubDate = ''; + let pubDate: Date; switch (item.type) { case 'answer':