From bd099c13f7fbd89fd587df212dd28b6c1d85291d Mon Sep 17 00:00:00 2001 From: karasu Date: Mon, 22 Apr 2024 01:05:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(route):=20=E7=9F=A5=E8=AF=86=E6=98=9F?= =?UTF-8?q?=E7=90=83=20(#15320)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(route): 知识星球 * feat: add scope parameter * remove redundant variables * fix * Update lib/routes/zsxq/utils.ts Co-authored-by: Tony * fix --------- --- lib/config.ts | 6 ++ lib/routes/zsxq/group.ts | 63 +++++++++++++++ lib/routes/zsxq/namespace.ts | 6 ++ lib/routes/zsxq/types.ts | 149 +++++++++++++++++++++++++++++++++++ lib/routes/zsxq/user.ts | 58 ++++++++++++++ lib/routes/zsxq/utils.ts | 70 ++++++++++++++++ 6 files changed, 352 insertions(+) create mode 100644 lib/routes/zsxq/group.ts create mode 100644 lib/routes/zsxq/namespace.ts create mode 100644 lib/routes/zsxq/types.ts create mode 100644 lib/routes/zsxq/user.ts create mode 100644 lib/routes/zsxq/utils.ts diff --git a/lib/config.ts b/lib/config.ts index 816a68a0a..a7837ebe7 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -298,6 +298,9 @@ export type Config = { zodgame: { cookie?: string; }; + zsxq: { + accessToken?: string; + }; }; const value: Config | Record = {}; @@ -651,6 +654,9 @@ const calculateValue = () => { zodgame: { cookie: envs.ZODGAME_COOKIE, }, + zsxq: { + accessToken: envs.ZSXQ_ACCESS_TOKEN, + }, }; for (const name in _value) { diff --git a/lib/routes/zsxq/group.ts b/lib/routes/zsxq/group.ts new file mode 100644 index 000000000..6bb7d9916 --- /dev/null +++ b/lib/routes/zsxq/group.ts @@ -0,0 +1,63 @@ +import type { Data, Route } from '@/types'; +import type { Context } from 'hono'; +import { config } from '@/config'; +import ConfigNotFoundError from '@/errors/types/config-not-found'; +import type { GroupInfoResponse, TopicsResponse } from './types'; +import { customFetch, generateTopicDataItem } from './utils'; + +export const route: Route = { + name: '星球', + categories: ['social-media'], + path: '/group/:id/:scope?', + example: '/zsxq/group/88855458825252', + parameters: { + id: '星球id,从网页端url中获取', + scope: '栏目分类,默认为"all",见下表', + }, + maintainers: ['KarasuShin'], + radar: [ + { + source: ['wx.zsxq.com/dweb2/index/group/:id'], + }, + ], + features: { + requireConfig: [ + { + name: 'ZSXQ_ACCESS_TOKEN', + description: + '知识星球访问令牌,获取方式:\n1. 登录知识星球网页版\n2. 打开浏览器开发者工具,切换到 Application 面板\n3. 点击侧边栏中的Storage -> Cookies -> https://wx.zsxq.com\n4. 复制 Cookie 中的 zsxq_access_token 值', + }, + ], + }, + handler, + description: `| all | digests | by_owner | questions | tasks | + | ---- | ------ | --------- | -------- | ------ | + | 最新 | 精华 | 只看星主 | 问答 | 作业 |`, +}; + +async function handler(ctx: Context): Promise { + const groupId = ctx.req.param('id'); + const scope = ctx.req.param('scope') ?? 'all'; + const accessToken = config.zsxq.accessToken; + + if (!accessToken) { + throw new ConfigNotFoundError('该 RSS 源由于配置不正确而被禁用:令牌丢失。'); + } + + let count = Number(ctx.req.query('limit')) || 20; + if (count > 30) { + count = 30; + } + + const { group } = await customFetch(`/groups/${groupId}`); + + const { topics } = await customFetch(`/groups/${groupId}/topics?scope=${scope}&count=${count}`); + + return { + title: `知识星球 - ${group.name}`, + description: group.description, + image: group.background_url, + link: `https://wx.zsxq.com/dweb2/index/group/${groupId}`, + item: generateTopicDataItem(topics), + }; +} diff --git a/lib/routes/zsxq/namespace.ts b/lib/routes/zsxq/namespace.ts new file mode 100644 index 000000000..bca329d26 --- /dev/null +++ b/lib/routes/zsxq/namespace.ts @@ -0,0 +1,6 @@ +import type { Namespace } from '@/types'; + +export const namespace: Namespace = { + name: '知识星球', + url: 'zsxq.com', +}; diff --git a/lib/routes/zsxq/types.ts b/lib/routes/zsxq/types.ts new file mode 100644 index 000000000..5ec0851ce --- /dev/null +++ b/lib/routes/zsxq/types.ts @@ -0,0 +1,149 @@ +export interface BasicResponse { + succeeded: boolean; + resp_data: T; + code?: number; + info?: string; + error?: string; +} + +interface BasicTopic { + comments_count: number; + create_time: string; + digested: boolean; + group: { + group_id: number; + name: string; + type: string; + background_url: string; + }; + latest_likes: { + create_time: string; + owner: { + avatar_url: string; + name: string; + number: number; + user_id: number; + }; + }[]; + likes_count: number; + readers_count: number; + reading_count: number; + rewards_count: number; + topic_id: number; + type: string; + user_specific: { + liked: false; + subscribed: false; + }; + title?: string; +} + +interface TalkTopic extends BasicTopic { + type: 'talk'; + talk: { + text?: string; + images?: TopicImage[]; + }; +} + +export interface QATopic extends BasicTopic { + type: 'q&a'; + answer?: { + owner: { + avatar_url: string; + description: string; + location: string; + name: string; + user_id: number; + }; + text?: string; + images?: TopicImage[]; + }; + answered: boolean; + question: { + images?: TopicImage[]; + text?: string; + }; +} + +interface TaskTopic extends BasicTopic { + type: 'task'; + task: { + images?: TopicImage[]; + text?: string; + }; +} + +interface SolutionTopic extends BasicTopic { + type: 'solution'; + solution: { + task_id: number; + text?: string; + images?: TopicImage[]; + }; +} + +interface UserInfo { + chat: { + identifier: string; + }; + user: { + avatar_url: string; + introduction: string; + location: string; + name: string; + unique_id: string; + user_id: number; + }; + user_specific: { + followed: boolean; + }; +} + +interface GroupInfo { + group: { + admin_ids: number[]; + alive_time: string; + background_url: string; + category: { + category_id: number; + title: string; + }; + create_time: string; + description: string; + group_id: number; + guest_ids: number[]; + name: string; + }; +} + +export interface TopicImage { + image_id: number; + large: { + height: number; + width: number; + url: string; + }; + original: { + height: number; + width: number; + url: string; + size: number; + }; + thumbnail: { + height: number; + width: number; + url: string; + }; + type: string; +} + +export type Topic = TalkTopic | QATopic | TaskTopic | SolutionTopic; + +export type UserInfoResponse = BasicResponse; + +export type GroupInfoResponse = BasicResponse; + +export type TopicsResponse = BasicResponse<{ + topics: Topic[]; +}>; diff --git a/lib/routes/zsxq/user.ts b/lib/routes/zsxq/user.ts new file mode 100644 index 000000000..c728f19c9 --- /dev/null +++ b/lib/routes/zsxq/user.ts @@ -0,0 +1,58 @@ +import type { Data, Route } from '@/types'; +import type { Context } from 'hono'; +import { config } from '@/config'; +import ConfigNotFoundError from '@/errors/types/config-not-found'; +import type { TopicsResponse, UserInfoResponse } from './types'; +import { customFetch, generateTopicDataItem } from './utils'; + +export const route: Route = { + name: '用户足迹', + categories: ['social-media'], + path: '/user/:id', + example: '/zsxq/user/2414218251', + parameters: { + id: '用户id,从网页端url中获取', + }, + maintainers: ['KarasuShin'], + radar: [ + { + source: ['wx.zsxq.com/dweb2/index/footprint/:id'], + }, + ], + features: { + requireConfig: [ + { + name: 'ZSXQ_ACCESS_TOKEN', + description: + '知识星球访问令牌,获取方式:\n1. 登录知识星球网页版\n2. 打开浏览器开发者工具,切换到 Application 面板\n3. 点击侧边栏中的Storage -> Cookies -> https://wx.zsxq.com\n4. 复制 Cookie 中的 zsxq_access_token 值', + }, + ], + }, + handler, +}; + +async function handler(ctx: Context): Promise { + const uid = ctx.req.param('id'); + const accessToken = config.zsxq.accessToken; + + if (!accessToken) { + throw new ConfigNotFoundError('该 RSS 源由于配置不正确而被禁用:令牌丢失。'); + } + + let count = Number(ctx.req.query('limit')) || 20; + if (count > 30) { + count = 30; + } + + const userInfo = await customFetch(`/users/${uid}`); + + const { topics } = await customFetch(`/users/${uid}/topics/footprint?count=${count}`); + + return { + title: `知识星球 - ${userInfo.user.name}`, + description: userInfo.user.introduction, + image: userInfo.user.avatar_url, + link: `https://wx.zsxq.com/dweb2/index/footprint/${uid}`, + item: generateTopicDataItem(topics), + }; +} diff --git a/lib/routes/zsxq/utils.ts b/lib/routes/zsxq/utils.ts new file mode 100644 index 000000000..7c659a07f --- /dev/null +++ b/lib/routes/zsxq/utils.ts @@ -0,0 +1,70 @@ +import got from '@/utils/got'; +import type { TopicImage, Topic, BasicResponse } from './types'; +import { parseDate } from '@/utils/parse-date'; +import { config } from '@/config'; +import type { DataItem } from '@/types'; + +export async function customFetch>(path: string, retryCount = 0): Promise { + const apiUrl = 'https://api.zsxq.com/v2'; + + const response = await got(apiUrl + path, { + headers: { + cookie: `zsxq_access_token=${config.zsxq.accessToken};`, + }, + }); + const { succeeded, code, resp_data } = response.data as T; + if (succeeded) { + return resp_data; + } + // sometimes the request will fail with code 1059, retry will solve the problem + if (code === 1059 && retryCount < 3) { + return customFetch(path, ++retryCount); + } + throw new Error('something wrong'); +} + +function parseTopicContent(text: string = '', images: TopicImage[] = []) { + let result = text.replaceAll('\n', '
'); + result = result.replaceAll(//g, (_, p1, p2) => `${decodeURIComponent(p2)}`); + result = result.replaceAll(//g, (_, p1) => { + const title = decodeURIComponent(p1); + return `${title}`; + }); + result += images.map((image) => ``).join('
'); + return result; +} + +export function generateTopicDataItem(topics: Topic[]): DataItem[] { + return topics.map((topic) => { + let description: string | undefined; + let title = ''; + switch (topic.type) { + case 'talk': + title = topic.talk?.text?.split('\n')[0] ?? '文章'; + description = parseTopicContent(topic.talk?.text, topic.talk?.images); + break; + case 'q&a': + title = topic.question?.text?.split('\n')[0] ?? '问答'; + description = parseTopicContent(topic.question?.text, topic.question?.images); + if (topic.answered) { + description += '

'; + description += parseTopicContent(topic.answer?.text, topic.answer?.images); + } + break; + case 'task': + title = topic.task?.text?.split('\n')[0] ?? '作业'; + description = parseTopicContent(topic.task?.text, topic.task?.images); + break; + case 'solution': + title = topic.solution?.text?.split('\n')[0] ?? '写作业'; + description = parseTopicContent(topic.solution?.text, topic.solution?.images); + break; + default: + } + return { + title: topic.title ?? title, + description, + pubDate: parseDate(topic.create_time), + }; + }); +}