From f19a725157ff7ea4c0bdd04f7708ff387b2926d8 Mon Sep 17 00:00:00 2001 From: Tony Date: Wed, 30 Apr 2025 04:16:32 +0800 Subject: [PATCH] refactor: fix all no array reduce (#18973) * refactor: no-array-reduce cleanup * refactor: keep * refactor: nhk * refactor: rattibha * fix: cctv * fix: jiemian * refactor: juejin * refactor: kpopping * refactor: yoasobi-music * refactor: mycard520 * refactor: newrank * refactor: sse * refactor: zhihu * feat!: remove trending https://github.com/huqi-pr/trending-in-one is archived and no longer being updated. https://github.com/huqi-pr/trending-in-one/commit/2ef4cd236fcccb908be7907d5ac9aab6f1f4a188 * refactor: sspai * refactor: sysu * refactor: nikkei * refactor: utils * refactor: mydrivers * refactor: scmp * refactor: gov/moa * refactor: bloomberg * refactor: manhuagui * refactor: twitter --- lib/routes/36kr/hot-list.ts | 10 +- lib/routes/ally/rail.ts | 38 +-- lib/routes/bloomberg/utils.ts | 8 +- lib/routes/cctv/utils/news.ts | 6 +- lib/routes/cyzone/util.ts | 18 +- lib/routes/foresightnews/util.ts | 18 +- lib/routes/gcores/radio.ts | 10 +- lib/routes/gov/moa/zdscxx.ts | 22 +- lib/routes/iguoguo/index.ts | 112 ++++----- lib/routes/jiemian/account.ts | 16 ++ lib/routes/jiemian/common.ts | 101 ++++++++ lib/routes/jiemian/list.ts | 14 -- lib/routes/jiemian/lists.ts | 197 +++++++-------- lib/routes/jiemian/special.ts | 12 + lib/routes/jiemian/video.ts | 19 ++ lib/routes/jiemian/vip.ts | 20 ++ lib/routes/jike/utils.ts | 1 - lib/routes/juejin/pins.ts | 10 +- lib/routes/keep/templates/user.art | 18 +- lib/routes/keep/user.ts | 66 +++-- lib/routes/kpopping/kpics.ts | 17 +- lib/routes/manhuagui/comic.ts | 61 +++-- lib/routes/mycard520/news.ts | 11 +- lib/routes/mydrivers/cid.ts | 198 ++++++++++++++- lib/routes/mydrivers/index.ts | 52 +++- lib/routes/mydrivers/rank.ts | 5 +- lib/routes/mydrivers/util.ts | 23 +- lib/routes/newrank/utils.ts | 12 +- lib/routes/nhk/news-web-easy.ts | 35 ++- lib/routes/nikkei/cn/index.ts | 9 +- lib/routes/rattibha/templates/description.art | 12 + lib/routes/rattibha/user.ts | 57 +++-- lib/routes/scmp/index.ts | 25 +- lib/routes/sse/convert.ts | 16 +- lib/routes/sse/disclosure.ts | 14 +- lib/routes/sspai/series.ts | 44 ++-- lib/routes/sysu/ygafz.ts | 36 +-- lib/routes/trending/all-trending.ts | 226 ------------------ lib/routes/trending/namespace.ts | 7 - lib/routes/trending/templates/content.art | 25 -- lib/routes/twitter/utils.ts | 17 +- lib/routes/yoasobi-music/media.ts | 9 +- lib/routes/zhihu/pin/utils.ts | 10 +- lib/utils/camelcase-keys.ts | 7 +- 44 files changed, 878 insertions(+), 766 deletions(-) create mode 100644 lib/routes/jiemian/account.ts create mode 100644 lib/routes/jiemian/common.ts delete mode 100644 lib/routes/jiemian/list.ts create mode 100644 lib/routes/jiemian/special.ts create mode 100644 lib/routes/jiemian/video.ts create mode 100644 lib/routes/jiemian/vip.ts create mode 100644 lib/routes/rattibha/templates/description.art delete mode 100644 lib/routes/trending/all-trending.ts delete mode 100644 lib/routes/trending/namespace.ts delete mode 100644 lib/routes/trending/templates/content.art diff --git a/lib/routes/36kr/hot-list.ts b/lib/routes/36kr/hot-list.ts index 85c537670..cf39f4834 100644 --- a/lib/routes/36kr/hot-list.ts +++ b/lib/routes/36kr/hot-list.ts @@ -52,6 +52,15 @@ export const route: Route = { | 24 | renqi | zonghe | shoucang |`, }; +const getProperty = (object, key) => { + let result = object; + const keys = key.split('.'); + for (const k of keys) { + result = result && result[k]; + } + return result; +}; + async function handler(ctx) { const category = ctx.req.param('category') ?? '24'; @@ -66,7 +75,6 @@ async function handler(ctx) { url: currentUrl, }); - const getProperty = (object, key) => key.split('.').reduce((o, k) => o && o[k], object); const data = getProperty(JSON.parse(response.data.match(/window.initialState=({.*})/)[1]), categories[category].key); let items = data diff --git a/lib/routes/ally/rail.ts b/lib/routes/ally/rail.ts index 8927ab8f4..1680fe69a 100644 --- a/lib/routes/ally/rail.ts +++ b/lib/routes/ally/rail.ts @@ -1,4 +1,4 @@ -import { Route } from '@/types'; +import { DataItem, Route } from '@/types'; import cache from '@/utils/cache'; import { load } from 'cheerio'; import got from '@/utils/got'; @@ -8,7 +8,7 @@ import timezone from '@/utils/timezone'; export const route: Route = { path: '/rail/:category?/:topic?', categories: ['new-media'], - example: '/ally/rail/hyzix/chengguijiaotong/', + example: '/ally/rail/hyzix/chengguijiaotong', parameters: { category: '分类,可在 URL 中找到;略去则抓取首页', topic: '话题,可在 URL 中找到;并非所有页面均有此字段' }, features: { requireConfig: false, @@ -40,26 +40,28 @@ async function handler(ctx) { const response = await got.get(pageUrl); const $ = load(response.data); - let title = $('.container .regsiter a') // what a typo... - .get() - .slice(1) // drop "首页" - .reduce((prev, curr) => (prev ? `${prev} - ${$(curr).text()}` : $(curr).text()), ''); + let title = ''; + const titleLinks = $('.container .regsiter a').toArray().slice(1); // what a typo... drop "首页" + for (const link of titleLinks) { + const linkText = $(link).text(); + title = title ? `${title} - ${linkText}` : linkText; + } title = title || (category && topic ? `${category} - ${topic}` : category) || '首页'; let links = [ // list page: http://rail.ally.net.cn/html/lujuzixun/ - $('.left .hynewsO h2 a').get(), + $('.left .hynewsO h2 a').toArray(), // multi-sub-topic page: http://rail.ally.net.cn/html/hyzix/ - $('.left .list_content_c').find('.new_hy_focus_con_tit a, .new_hy_list_name a').get(), + $('.left .list_content_c').find('.new_hy_focus_con_tit a, .new_hy_list_name a').toArray(), // multi-sub-topic page 2: http://rail.ally.net.cn/html/foster/ - $('.left').find('.nnewslistpic a, .nnewslistinfo dd a').get(), + $('.left').find('.nnewslistpic a, .nnewslistinfo dd a').toArray(), // data list page: http://rail.ally.net.cn/html/tongjigongbao/ - $('.left .list_con .datacountTit a').get(), + $('.left .list_con .datacountTit a').toArray(), // home page: http://rail.ally.net.cn - $('.container_left').find('dd a, h1 a, ul.slideshow li a').get(), + $('.container_left').find('dd a, h1 a, ul.slideshow li a').toArray(), ].flat(); if (!links.length) { // try aggressively sniffing links, e.g. http://rail.ally.net.cn/html/InviteTen/ - links = $('.left a, .container_left a').get(); + links = $('.left a, .container_left a').toArray(); } let items = links @@ -77,10 +79,14 @@ async function handler(ctx) { pubDate: timezone(parseDate(`${urlMatch[1]}${urlMatch[2]}`), 8), }; }) - .filter(Boolean) - .reduce((prev, curr) => (prev.length && prev.at(-1).link === curr.link ? prev : [...prev, curr]), []) - .sort((a, b) => b.pubDate - a.pubDate) - .slice(0, ctx.req.query('limit') || 20); + .filter(Boolean); + const uniqueItems: DataItem[] = []; + for (const item of items) { + if (!uniqueItems.some((uniqueItem) => uniqueItem.link === item?.link)) { + uniqueItems.push(item!); + } + } + items = uniqueItems.sort((a, b) => b.pubDate - a.pubDate).slice(0, ctx.req.query('limit') || 20); items = await Promise.all( items.map((item) => diff --git a/lib/routes/bloomberg/utils.ts b/lib/routes/bloomberg/utils.ts index 7736a6703..924e16083 100644 --- a/lib/routes/bloomberg/utils.ts +++ b/lib/routes/bloomberg/utils.ts @@ -197,10 +197,10 @@ const parseVideoPage = async (res, api, item) => { const parsePhotoEssaysPage = async (res, api, item) => { const $ = load(res.data.html); - const article_json = $(api.sel) - .toArray() - .map((e) => JSON.parse($(e).html())) - .reduce((pv, cv) => ({ ...pv, ...cv }), {}); + const article_json = {}; + for (const e of $(api.sel).toArray()) { + Object.assign(article_json, JSON.parse($(e).html())); + } const rss_item = { title: article_json.headline || item.title, link: article_json.canonical || item.link, diff --git a/lib/routes/cctv/utils/news.ts b/lib/routes/cctv/utils/news.ts index 69cbc4079..8e6c8a0c1 100644 --- a/lib/routes/cctv/utils/news.ts +++ b/lib/routes/cctv/utils/news.ts @@ -70,14 +70,14 @@ const getNews = async (category) => { break; case 'PHO': - description = data.photo_album_list.reduce((description, { photo_url, photo_name, photo_brief }) => { + description = ''; + for (const { photo_url, photo_name, photo_brief } of data.photo_album_list) { description += `
${photo_name}
${photo_brief}
`; - return description; - }, ''); + } author = data.source; break; diff --git a/lib/routes/cyzone/util.ts b/lib/routes/cyzone/util.ts index dd2d45797..b399c6303 100644 --- a/lib/routes/cyzone/util.ts +++ b/lib/routes/cyzone/util.ts @@ -43,19 +43,17 @@ const getInfo = (url, tryGet) => * @param {...Object} searchParams - The search parameter objects. * @returns {Promise} - The processed item array. */ -const processItems = async (apiUrl, limit, tryGet, ...searchParams) => { +const processItems = async (apiUrl, limit, tryGet, ...params) => { // Merge search parameters - searchParams = { - ...searchParams.reduce( - (result, object) => ({ - ...result, - ...object, - }), - {} - ), - + let searchParams = { size: limit, }; + for (const param of params) { + searchParams = { + ...searchParams, + ...param, + }; + } const { data: response } = await got(apiUrl, { searchParams, diff --git a/lib/routes/foresightnews/util.ts b/lib/routes/foresightnews/util.ts index 24884e67b..2f0c70856 100644 --- a/lib/routes/foresightnews/util.ts +++ b/lib/routes/foresightnews/util.ts @@ -23,18 +23,16 @@ const imgRootUrl = 'https://img.foresightnews.pro'; const icon = new URL('foresight.ico', rootUrl).href; const image = new URL('vertical_logo.png', imgRootUrl).href; -const processItems = async (apiUrl, limit, ...searchParams) => { - searchParams = { - ...searchParams.reduce( - (result, object) => ({ - ...result, - ...object, - }), - {} - ), - +const processItems = async (apiUrl, limit, ...parameters) => { + let searchParams = { size: limit, }; + for (const param of parameters) { + searchParams = { + ...searchParams, + ...param, + }; + } const info = { column: '', diff --git a/lib/routes/gcores/radio.ts b/lib/routes/gcores/radio.ts index 7d43de030..60af99cd2 100644 --- a/lib/routes/gcores/radio.ts +++ b/lib/routes/gcores/radio.ts @@ -44,17 +44,17 @@ async function handler(ctx) { const api = getApi(category); api.searchParams.set('include', 'media'); - api.searchParams.set('page[limit]', limit); + api.searchParams.set('page[limit]', limit.toString()); api.searchParams.set('sort', '-published-at'); api.searchParams.set('filter[list-all]', '0'); api.searchParams.set('filter[is-require-privilege]', '0'); api.searchParams.set('fields[radios]', 'title,cover,published-at,duration,content,media'); const { data, included } = await get(api); - const audios = included.reduce((result, media) => { - result[media.id] = media.attributes.audio; - return result; - }, {}); + const audios = {}; + for (const media of included) { + audios[media.id] = media.attributes.audio; + } const item = data.map((radio) => { const { id, attributes, relationships } = radio; diff --git a/lib/routes/gov/moa/zdscxx.ts b/lib/routes/gov/moa/zdscxx.ts index 8cec8e4d8..4a5aafb10 100644 --- a/lib/routes/gov/moa/zdscxx.ts +++ b/lib/routes/gov/moa/zdscxx.ts @@ -17,7 +17,7 @@ export const handler = async (ctx) => { const currentUrl = new URL('nyb/pc/messageList.jsp', rootUrl).href; const frameUrl = new URL('iframe/top_sj/', rootFrameUrl).href; - let filterForm = {}; + const filterForm = {}; if (category) { const apiFilterUrl = new URL('nyb/getMessageFilters', rootUrl).href; @@ -29,17 +29,19 @@ export const handler = async (ctx) => { }, }); - const filters = filterResponse.result.reduce((filters, f) => { + const filters: Record = {}; + for (const f of filterResponse.result) { filters[f.name.trim()] = f.data.map((d) => d.name.trim()); - return filters; - }, {}); + } - filterForm = category.split(/\//).reduce((form, c) => { - for (const key of Object.keys(filters).filter((key) => filters[key].includes(c))) { - form[key] = c; + const categories = category.split(/\//); + for (const c of categories) { + for (const key of Object.keys(filters)) { + if (filters[key].includes(c)) { + filterForm[key] = c; + } } - return form; - }, {}); + } } const { data: response } = await got.post(apiUrl, { @@ -108,7 +110,7 @@ export const route: Route = { parameters: { category: '分类,默认为全部,见下表' }, description: `::: tip 若订阅 [中华人民共和国农业农村部数据](http://zdscxx.moa.gov.cn:8080/nyb/pc/messageList.jsp) 的 \`价格指数\` 报告主题。此时路由为 [\`/gov/moa/zdscxx/价格指数\`](https://rsshub.app/gov/moa/zdscxx/价格指数)。 - + 若订阅 \`央视网\` 报告来源 的 \`蔬菜生产\` 报告主题。此时路由为 [\`/gov/moa/zdscxx/央视网/蔬菜生产\`](https://rsshub.app/gov/moa/zdscxx/央视网/蔬菜生产)。 ::: diff --git a/lib/routes/iguoguo/index.ts b/lib/routes/iguoguo/index.ts index 7003b9804..bb7686ce8 100644 --- a/lib/routes/iguoguo/index.ts +++ b/lib/routes/iguoguo/index.ts @@ -1,27 +1,37 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { load } from 'cheerio'; import { parseDate } from '@/utils/parse-date'; -import timezone from '@/utils/timezone'; +import { config } from '@/config'; +import type { Context } from 'hono'; const rootUrl = 'https://www.iguoguo.net'; -const getChildrenFromCheerioRoot = (cheerioInstance) => { - const root = cheerioInstance.root(); - const rootKeys = Object.keys(root).filter((n) => n % 1 === 0); - const rootChildren = rootKeys.map((key) => root[key].children); - return rootChildren[0]; -}; +const getCategoryIdFromSlug = (slug) => + cache.tryGet(`iguoguo:category:${slug}`, async () => { + const response = await ofetch(`${rootUrl}/wp-json/wp/v2/categories`, { + query: { + slug, + }, + }); + return response[0].id; + }); -const getComments = (a, node) => { - if (node.type === 'comment') { - return [...a, node.data]; - } else if (node.type === 'tag' && node.children && node.children.length > 0) { - return [...a, ...node.children.reduce((accumulator, element) => getComments(accumulator, element), [])]; - } else { - return a; - } -}; +const getPostsByCategory = (categoryId, limit) => + cache.tryGet( + `iguoguo:posts:${categoryId}`, + async () => { + const response = await ofetch(`${rootUrl}/wp-json/wp/v2/posts`, { + query: { + categories: categoryId, + per_page: limit, + }, + }); + return response; + }, + config.cache.routeExpire, + false + ); export const route: Route = { path: '/html5', @@ -41,50 +51,42 @@ export const route: Route = { handler, }; -async function handler() { - const currentUrl = rootUrl.concat('/html5'); - const response = await got({ - method: 'get', - url: currentUrl, - }); - const $ = load(response.data); - const list = $('a', '.post') - .filter((_, x) => $(x).attr('href').endsWith('.html')) - .filter((_, x) => $(x).children().eq(0).attr('src')) - .map((_, item) => ({ - link: $(item).attr('href'), - cover: $(item).children().eq(0).attr('src'), - })) - .get(); +async function handler(ctx: Context) { + const limit = Number.parseInt(ctx.req.query('limit') ?? '10'); + const currentUrl = `${rootUrl}/html5`; + const categorySlug = 'h5'; + + const categoryId = await getCategoryIdFromSlug(categorySlug); + const posts = await getPostsByCategory(categoryId, limit); const mime = { jpg: 'jpeg', png: 'png', }; - const items = await Promise.all( - list.map((item) => - cache.tryGet(item.link, async () => { - const detailResponse = await got({ - method: 'get', - url: item.link, - }); - const content = load(detailResponse.data); - item.title = content('h1', '.post-info').text(); - item.description = content('div.clearfix', '.post_content').html(); - const comments = getChildrenFromCheerioRoot(content).reduce((accumulator, element) => getComments(accumulator, element), []); - const date = comments.at(-1).trim().split(' ').slice(9, 11); - item.pubDate = timezone(parseDate(date[0] + date[1], 'YYYY-MM-DDHH:mm:ss'), +8); - item.media = { - content: { - url: item.cover, - type: `image/${mime[item.cover.split('.').pop()]}`, - }, - }; - return item; - }) - ) - ); + const items = posts.map((item) => { + const $ = load(item.content.rendered); + const cover = $('p > img').first().attr('src'); + $('p > img').first().remove(); + $('h4').each((_, el) => { + if ($(el).text().includes('扫码欣赏')) { + $(el).remove(); + } + }); + return { + title: item.title.rendered, + description: $.html(), + link: item.link, + cover, + pubDate: parseDate(item.date_gmt), + media: cover && { + content: { + url: cover, + type: `image/${mime[cover.split('.').pop()]}`, + }, + }, + }; + }); return { title: '爱果果', link: currentUrl, diff --git a/lib/routes/jiemian/account.ts b/lib/routes/jiemian/account.ts new file mode 100644 index 000000000..641ada837 --- /dev/null +++ b/lib/routes/jiemian/account.ts @@ -0,0 +1,16 @@ +import { Route } from '@/types'; + +import { handler } from './common'; + +export const route: Route = { + path: '/account/main/1', + parameters: { id: '分类 id,见下表,可在对应分类页 URL 中找到' }, + name: '界面号', + example: '/jiemian/account/main/1', + maintainers: ['nczitzk'], + handler, + description: `| [财经号](https://www.jiemian.com/account/main/1.html) | [城市号](https://www.jiemian.com/account/main/2.html) | [媒体号](https://www.jiemian.com/account/main/3.html) | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| 1 | 2 | 3 | +`, +}; diff --git a/lib/routes/jiemian/common.ts b/lib/routes/jiemian/common.ts new file mode 100644 index 000000000..8625e4497 --- /dev/null +++ b/lib/routes/jiemian/common.ts @@ -0,0 +1,101 @@ +import { Data } from '@/types'; + +import cache from '@/utils/cache'; +import ofetch from '@/utils/ofetch'; +import { load } from 'cheerio'; +import { parseDate } from '@/utils/parse-date'; +import { art } from '@/utils/render'; +import path from 'node:path'; + +export const handler = async (ctx): Promise => { + const { category = '' } = ctx.req.param(); + const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit'), 10) : 50; + + const rootUrl = 'https://www.jiemian.com'; + const currentUrl = new URL(category ? `${category}.html` : '', rootUrl).href; + + const response = await ofetch(currentUrl); + + const $ = load(response); + + let items = {}; + const links = $('a').toArray(); + for (const el of links) { + const item = $(el); + const href = item.prop('href'); + const link = href ? (href.startsWith('/') ? new URL(href, rootUrl).href : href) : undefined; + + if (link && /\/(article|video)\/\w+\.html/.test(link)) { + items[link] = { + title: item.text(), + link, + }; + } + } + + items = await Promise.all( + Object.values(items) + .slice(0, limit) + .map((item) => + cache.tryGet(item.link, async () => { + const detailResponse = await ofetch(item.link); + + const content = load(detailResponse); + const image = content('div.article-img img').first(); + const video = content('#video-player').first(); + + item.title = content('div.article-header h1').eq(0).text(); + item.description = art(path.join(__dirname, 'templates/description.art'), { + image: image + ? { + src: image.prop('src'), + alt: image.next('p').text() || item.title, + } + : undefined, + video: video + ? { + src: video.prop('data-url'), + poster: video.prop('data-poster'), + width: video.prop('width'), + height: video.prop('height'), + } + : undefined, + intro: content('div.article-header p').text(), + description: content('div.article-content').html(), + }); + item.author = content('span.author') + .first() + .find('a') + .toArray() + .map((a) => content(a).text()) + .join('/'); + item.category = content('meta.meta-container a') + .toArray() + .map((c) => content(c).text()); + item.pubDate = parseDate(content('div.article-info span[data-article-publish-time]').prop('data-article-publish-time'), 'X'); + item.upvotes = content('span.opt-praise__count').text() ? Number.parseInt(content('span.opt-praise__count').text(), 10) : 0; + item.comments = content('span.opt-comment__count').text() ? Number.parseInt(content('span.opt-comment__count').text(), 10) : 0; + + return item; + }) + ) + ); + + const title = $('title').text(); + const titleSplits = title.split(/_/); + const image = $('div.logo img').prop('src'); + const icon = new URL($('link[rel="icon"]').prop('href'), rootUrl).href; + + return { + item: items, + title, + link: currentUrl, + description: $('meta[name="description"]').prop('content'), + language: $('html').prop('lang'), + image, + icon, + logo: icon, + subtitle: titleSplits[0], + author: titleSplits.pop(), + }; +}; diff --git a/lib/routes/jiemian/list.ts b/lib/routes/jiemian/list.ts deleted file mode 100644 index 95637ee14..000000000 --- a/lib/routes/jiemian/list.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Route } from '@/types'; -export const route: Route = { - path: '/list/:id', - name: 'Unknown', - maintainers: [], - handler, -}; - -function handler(ctx) { - const id = ctx.req.param('id'); - - const redirectTo = `/jiemian${id ? `/lists/${id}` : ''}`; - ctx.set('redirect', redirectTo); -} diff --git a/lib/routes/jiemian/lists.ts b/lib/routes/jiemian/lists.ts index 4e0ea0c8e..638d605f8 100644 --- a/lib/routes/jiemian/lists.ts +++ b/lib/routes/jiemian/lists.ts @@ -1,110 +1,99 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; -import got from '@/utils/got'; -import { load } from 'cheerio'; -import { parseDate } from '@/utils/parse-date'; -import { art } from '@/utils/render'; -import path from 'node:path'; +import { handler } from './common'; export const route: Route = { - path: '/:category{.+}?', - name: 'Unknown', - maintainers: [], + path: '/lists/:id', + parameters: { id: '分类 id,见下表,可在对应分类页 URL 中找到' }, + name: '栏目', + example: '/jiemian/lists/65', + maintainers: ['WenhuWee', 'nczitzk'], handler, + description: `| [首页](https://www.jiemian.com) | [商业](https://www.jiemian.com/lists/2.html) | [财经](https://www.jiemian.com/lists/800.html) | [新闻](https://www.jiemian.com/lists/801.html) | [文化生活](https://www.jiemian.com/lists/130.html) | [快报](https://www.jiemian.com/lists/4.html) | +| ------------------------------- | -------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | -------------------------------------------------- | -------------------------------------------- | +| | 2 | 800 | 801 | 130 | 4 | + +::: details 更多分类 + +#### [首页](https://www.jiemian.com) + +| [科技](https://www.jiemian.com/lists/65.html) | [金融](https://www.jiemian.com/lists/9.html) | [证券](https://www.jiemian.com/lists/112.html) | [地产](https://www.jiemian.com/lists/62.html) | [汽车](https://www.jiemian.com/lists/51.html) | [健康](https://www.jiemian.com/lists/472.html) | +| --------------------------------------------- | -------------------------------------------- | ---------------------------------------------- | --------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | +| 65 | 9 | 112 | 62 | 51 | 472 | + +| [大湾区](https://www.jiemian.com/lists/680.html) | [元宇宙](https://www.jiemian.com/lists/704.html) | [文旅](https://www.jiemian.com/lists/105.html) | [数据](https://www.jiemian.com/lists/154.html) | [ESG](https://www.jiemian.com/lists/712.html) | [双碳](https://www.jiemian.com/lists/877.html) | +| ------------------------------------------------ | ------------------------------------------------ | ---------------------------------------------- | ---------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | +| 680 | 704 | 105 | 154 | 712 | 877 | + +| [电厂](https://www.jiemian.com/lists/872.html) | +| ---------------------------------------------- | +| 872 | + +#### [商业](https://www.jiemian.com/lists/2.html) + +| [科技](https://www.jiemian.com/lists/65.html) | [地产](https://www.jiemian.com/lists/62.html) | [ 汽车](https://www.jiemian.com/lists/51.html) | [消费](https://www.jiemian.com/lists/31.html) | [工业](https://www.jiemian.com/lists/28.html) | [时尚](https://www.jiemian.com/lists/68.html) | +| --------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | +| 65 | 62 | 51 | 31 | 28 | 68 | + +| [交通](https://www.jiemian.com/lists/30.html) | [医药](https://www.jiemian.com/lists/472.html) | [互联网](https://www.jiemian.com/lists/851.html) | [创投 ](https://www.jiemian.com/lists/858.html) | [能源](https://www.jiemian.com/lists/856.html) | [数码](https://www.jiemian.com/lists/853.html) | +| --------------------------------------------- | ---------------------------------------------- | ------------------------------------------------ | ----------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| 30 | 472 | 851 | 858 | 856 | 853 | + +| [教育](https://www.jiemian.com/lists/256.html) | [食品](https://www.jiemian.com/lists/845.html) | [新能源](https://www.jiemian.com/lists/857.html) | [家电](https://www.jiemian.com/lists/850.html) | [健康](https://www.jiemian.com/lists/854.html) | [酒业](https://www.jiemian.com/lists/676.html) | +| ---------------------------------------------- | ---------------------------------------------- | ------------------------------------------------ | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| 256 | 845 | 857 | 850 | 854 | 676 | + +| [物流](https://www.jiemian.com/lists/841.html) | [零售](https://www.jiemian.com/lists/847.html) | [美妆](https://www.jiemian.com/lists/838.html) | [楼市](https://www.jiemian.com/city/main/181.html) | [家居](https://www.jiemian.com/lists/694.html) | [餐饮](https://www.jiemian.com/lists/848.html) | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | -------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| 841 | 847 | 838 | city/main/181 | 694 | 848 | + +| [日用](https://www.jiemian.com/lists/846.html) | [企服](https://www.jiemian.com/lists/852.html) | [珠宝](https://www.jiemian.com/lists/839.html) | [腕表](https://www.jiemian.com/lists/840.html) | [ 商学院](https://www.jiemian.com/lists/605.html) | [元宇宙](https://www.jiemian.com/lists/704.html) | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ------------------------------------------------- | ------------------------------------------------ | +| 846 | 852 | 839 | 840 | 605 | 704 | + +| [电厂](https://www.jiemian.com/lists/872.html) | [农业](https://www.jiemian.com/lists/883.html) | +| ---------------------------------------------- | ---------------------------------------------- | +| 872 | 883 | + +#### [财经](https://www.jiemian.com/lists/800.html) + +| [金融](https://www.jiemian.com/lists/9.html) | [投资](https://www.jiemian.com/lists/86.html) | [证券](https://www.jiemian.com/lists/112.html) | [IPO](https://www.jiemian.com/lists/699.html) | [宏观](https://www.jiemian.com/lists/174.html) | [股市](https://www.jiemian.com/lists/418.html) | +| -------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| 9 | 86 | 112 | 699 | 174 | 418 | + +| [财富](https://www.jiemian.com/lists/410.html) | [有连云](https://www.jiemian.com/lists/889.html) | +| ---------------------------------------------- | ------------------------------------------------ | +| 410 | 889 | + +#### [新闻](https://www.jiemian.com/lists/801.html) + +| [天下](https://www.jiemian.com/lists/32.html) | [中国](https://www.jiemian.com/lists/71.html) | [ 评论](https://www.jiemian.com/lists/8.html) | [数据](https://www.jiemian.com/lists/154.html) | [职场](https://www.jiemian.com/lists/50.html) | [国是](https://www.jiemian.com/lists/422.html) | +| --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | --------------------------------------------- | ---------------------------------------------- | +| 32 | 71 | 8 | 154 | 50 | 422 | + +| [体育](https://www.jiemian.com/lists/82.html) | [文娱](https://www.jiemian.com/lists/63.html) | [ 影像](https://www.jiemian.com/lists/225.html) | [营销](https://www.jiemian.com/lists/49.html) | [大 湾区](https://www.jiemian.com/lists/680.html) | [ESG](https://www.jiemian.com/lists/712.html) | +| --------------------------------------------- | --------------------------------------------- | ----------------------------------------------- | --------------------------------------------- | ------------------------------------------------- | --------------------------------------------- | +| 82 | 63 | 225 | 49 | 680 | 712 | + +| [双碳](https://www.jiemian.com/lists/877.html) | [长三角](https://www.jiemian.com/lists/917.html) | +| ---------------------------------------------- | ------------------------------------------------ | +| 877 | 917 | + +#### [文化生活](https://www.jiemian.com/lists/130.html) + +| [文化](https://www.jiemian.com/lists/130.html) | [文旅](https://www.jiemian.com/lists/105.html) | [生活方式](https://www.jiemian.com/lists/135.html) | [美食美酒](https://www.jiemian.com/lists/865.html) | [艺术](https://www.jiemian.com/lists/643.html) | [游戏](https://www.jiemian.com/lists/118.html) | +| ---------------------------------------------- | ---------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| 130 | 105 | 135 | 865 | 643 | 118 | + +| [正午](https://www.jiemian.com/lists/53.html) | [箭厂](https://www.jiemian.com/video/lists/195_1.html) | +| --------------------------------------------- | ------------------------------------------------------ | +| 53 | video/lists/195\_1 | + +#### [快报](https://www.jiemian.com/lists/4.html) + +| [今日热点](https://www.jiemian.com/lists/1324kb.html) | [公司头条](https://www.jiemian.com/lists/1322kb.html) | [股市前沿](https://www.jiemian.com/lists/1327kb.html) | [监管通报](https://www.jiemian.com/lists/1330kb.html) | [财经速览](https://www.jiemian.com/lists/1326kb.html) | [时事追踪](https://www.jiemian.com/lists/1325kb.html) | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| 1324kb | 1322kb | 1327kb | 1330kb | 1326kb | 1325kb | + +:::`, }; - -async function handler(ctx) { - const { category = '' } = ctx.req.param(); - const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit'), 10) : 50; - - const rootUrl = 'https://www.jiemian.com'; - const currentUrl = new URL(category ? `${category}.html` : '', rootUrl).href; - - const { data: response } = await got(currentUrl); - - const $ = load(response); - - let items = $('a') - .toArray() - .reduce((acc, item) => { - item = $(item); - - const href = item.prop('href'); - const link = href ? (href.startsWith('/') ? new URL(href, rootUrl).href : href) : undefined; - - if (link && /\/(article|video)\/\w+\.html/.test(link)) { - acc[link] = { - title: item.text(), - link, - }; - } - return acc; - }, {}); - - items = await Promise.all( - Object.values(items) - .slice(0, limit) - .map((item) => - cache.tryGet(item.link, async () => { - const { data: detailResponse } = await got(item.link); - - const content = load(detailResponse); - const image = content('div.article-img img').first(); - const video = content('#video-player').first(); - - item.title = content('div.article-header h1').eq(0).text(); - item.description = art(path.join(__dirname, 'templates/description.art'), { - image: image - ? { - src: image.prop('src'), - alt: image.next('p').text() || item.title, - } - : undefined, - video: video - ? { - src: video.prop('data-url'), - poster: video.prop('data-poster'), - width: video.prop('width'), - height: video.prop('height'), - } - : undefined, - intro: content('div.article-header p').text(), - description: content('div.article-content').html(), - }); - item.author = content('span.author') - .first() - .find('a') - .toArray() - .map((a) => content(a).text()) - .join('/'); - item.category = content('meta.meta-container a') - .toArray() - .map((c) => content(c).text()); - item.pubDate = parseDate(content('div.article-info span[data-article-publish-time]').prop('data-article-publish-time'), 'X'); - item.upvotes = content('span.opt-praise__count').text() ? Number.parseInt(content('span.opt-praise__count').text(), 10) : 0; - item.comments = content('span.opt-comment__count').text() ? Number.parseInt(content('span.opt-comment__count').text(), 10) : 0; - - return item; - }) - ) - ); - - const title = $('title').text(); - const titleSplits = title.split(/_/); - const image = $('div.logo img').prop('src'); - const icon = new URL($('link[rel="icon"]').prop('href'), rootUrl).href; - - return { - item: items, - title, - link: currentUrl, - description: $('meta[name="description"]').prop('content'), - language: $('html').prop('lang'), - image, - icon, - logo: icon, - subtitle: titleSplits[0], - author: titleSplits.pop(), - }; -} diff --git a/lib/routes/jiemian/special.ts b/lib/routes/jiemian/special.ts new file mode 100644 index 000000000..0cbb13937 --- /dev/null +++ b/lib/routes/jiemian/special.ts @@ -0,0 +1,12 @@ +import { Route } from '@/types'; + +import { handler } from './common'; + +export const route: Route = { + path: '/special/1192', + parameters: { id: '分类 id,见下表,可在对应分类页 URL 中找到' }, + name: '专题', + example: '/jiemian/special/1192', + maintainers: ['nczitzk'], + handler, +}; diff --git a/lib/routes/jiemian/video.ts b/lib/routes/jiemian/video.ts new file mode 100644 index 000000000..357992003 --- /dev/null +++ b/lib/routes/jiemian/video.ts @@ -0,0 +1,19 @@ +import { Route } from '@/types'; + +import { handler } from './common'; + +export const route: Route = { + path: '/video/lists/258_1', + parameters: { id: '分类 id,见下表,可在对应分类页 URL 中找到' }, + name: '视频', + example: '/jiemian/video/lists/258_1', + maintainers: ['nczitzk'], + handler, + description: `| [界面 Vnews](https://www.jiemian.com/video/lists/258_1.html) | [直播](https://www.jiemian.com/videoLive/lists_1.html) | [箭厂](https://www.jiemian.com/video/lists/195_1.html) | [面谈](https://www.jiemian.com/video/lists/111_1.html) | [品牌创酷](https://www.jiemian.com/video/lists/226_1.html) | [番 茄社](https://www.jiemian.com/video/lists/567_1.html) | +| ------------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ | ---------------------------------------------------------- | --------------------------------------------------------- | +| 258\_1 | videoLive/lists\_1 | 195\_1 | 111\_1 | 226\_1 | 567\_1 | + +| [商业微史记](https://www.jiemian.com/video/lists/882_1.html) | +| ------------------------------------------------------------ | +| 882\_1 |`, +}; diff --git a/lib/routes/jiemian/vip.ts b/lib/routes/jiemian/vip.ts new file mode 100644 index 000000000..f0a7949c1 --- /dev/null +++ b/lib/routes/jiemian/vip.ts @@ -0,0 +1,20 @@ +import { Route } from '@/types'; + +import { handler } from './common'; + +export const route: Route = { + path: '/pro/lists/12', + parameters: { id: '分类 id,见下表,可在对应分类页 URL 中找到' }, + name: 'VIP', + example: '/jiemian/pro/lists/12', + maintainers: ['nczitzk'], + handler, + description: `| [投资早晚报](https://www.jiemian.com/pro/lists/12.html) | [宏观晚 6 点](https://www.jiemian.com/pro/lists/20.html) | [打新早报](https://www.jiemian.com/pro/lists/21.html) | [盘前机会前瞻](https://www.jiemian.com/pro/lists/13.html) | [公告快评](https://www.jiemian.com/pro/lists/14.html) | [盘中必读](https://www.jiemian.com/pro/lists/15.html) | +| ------------------------------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| 12 | 20 | 21 | 13 | 14 | 15 | + +| [金股挖掘](https://www.jiemian.com/pro/lists/16.html) | [调研早知道](https://www.jiemian.com/pro/lists/17.html) | [研报新知](https://www.jiemian.com/pro/lists/18.html) | [大势侦察](https://www.jiemian.com/pro/lists/1.html) | [市场风向标](https://www.jiemian.com/pro/lists/19.html) | +| ----------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------- | +| 16 | 17 | 18 | 1 | 19 | +`, +}; diff --git a/lib/routes/jike/utils.ts b/lib/routes/jike/utils.ts index 6ea6f6b69..747e0deca 100644 --- a/lib/routes/jike/utils.ts +++ b/lib/routes/jike/utils.ts @@ -178,7 +178,6 @@ const constructTopicEntry = async (ctx, url) => { return { title: '主题 ID 不存在,或该主题暂无内容', }; - return null; } const topic = data.topic; diff --git a/lib/routes/juejin/pins.ts b/lib/routes/juejin/pins.ts index 2f19d2bc7..98dbd699a 100644 --- a/lib/routes/juejin/pins.ts +++ b/lib/routes/juejin/pins.ts @@ -59,12 +59,10 @@ async function handler(ctx) { const link = `https://juejin.cn/pin/${guid}`; const pubDate = parseDate(item.msg_Info.ctime * 1000); const author = item.author_user_info.user_name; - const imgs = item.msg_Info.pic_list.reduce((imgs, item) => { - imgs += ` -
- `; - return imgs; - }, ''); + let imgs = ''; + for (const img of item.msg_Info.pic_list) { + imgs += `
`; + } const description = ` ${content.replaceAll('\n', '
')}
${imgs}
diff --git a/lib/routes/keep/templates/user.art b/lib/routes/keep/templates/user.art index e40d36bae..c5c30c4cf 100644 --- a/lib/routes/keep/templates/user.art +++ b/lib/routes/keep/templates/user.art @@ -1,16 +1,18 @@ - 项目: +项目: {{ if item.meta.name === item.meta.workoutName }} -{{ item.meta.name }} + {{ item.meta.name }} {{ else }} -{{ item.meta.name }} - {{ item.meta.workoutName }} + {{ item.meta.name }} - {{ item.meta.workoutName }} {{ /if }}
时长:{{ minute }}分{{ second }}秒 {{ if item.content }} -
-备注:{{ item.content }} +
+ 备注:{{ item.content }} {{ /if }} -{{ if imagesTpl }} -
-{{@ imagesTpl }} +{{ if images }} +
+ {{ each images image }} + + {{ /each }} {{ /if }} diff --git a/lib/routes/keep/user.ts b/lib/routes/keep/user.ts index a02ddb55e..e8658ed72 100644 --- a/lib/routes/keep/user.ts +++ b/lib/routes/keep/user.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { art } from '@/utils/render'; import path from 'node:path'; @@ -30,53 +30,47 @@ export const route: Route = { async function handler(ctx) { const id = ctx.req.param('id'); - const response = await got({ - method: 'get', - url: `https://api.gotokeep.com/social/v3/people/${id}/home`, + const response = await ofetch(`https://api.gotokeep.com/social/v3/people/${id}/home`, { headers: { Referer: `https://show.gotokeep.com/users/${id}`, }, }); // check user have post or not - if (response.data.data.entries.length === 0) { + if (response.data.entries.length === 0) { throw new Error('该用户运动日记为空'); } - response.data.data.entries[0] = response.data.data.entries[0].entries; - const data = response.data.data.entries.reduce((all, current) => [...all, ...current.entries]); + const items = response.data.entries.flatMap((entry) => + entry.entries.map((item) => { + let images: string[] = []; + if (item.images) { + images = item.meta.picture ? [item.meta.picture, ...item.images] : item.images; + } else if (item.meta.picture) { + images = [item.meta.picture]; + } + + const minute = Math.floor(item.meta.secondDuration / 60); + const second = item.meta.secondDuration - minute * 60; + return { + title: item.meta.title.trim(), + pubDate: item.created, + link: `https://show.gotokeep.com/entries/${item.id}`, + author: item.author.username, + description: art(path.join(__dirname, 'templates/user.art'), { + item, + minute, + second, + images, + }), + }; + }) + ); return { - title: `${data[0].author.username} 的 Keep 动态`, + title: `${items[0].author} 的 Keep 动态`, link: `https://show.gotokeep.com/users/${id}`, language: 'zh-cn', - item: data - .filter((item) => 'title' in item.meta) - .map((item) => { - let images = []; - if (item.images) { - images = item.meta.picture ? [...item.images, ...item.meta.picture] : item.images; - } else if (item.meta.picture) { - images = [item.meta.picture]; - } - let imagesTpl = ''; - for (const item of images) { - imagesTpl += ``; - } - - const minute = Math.floor(item.meta.secondDuration / 60); - const second = item.meta.secondDuration - minute * 60; - return { - title: item.meta.title.trim(), - pubDate: item.created, - link: `https://show.gotokeep.com/entries/${item.id}`, - description: art(path.join(__dirname, 'templates/user.art'), { - item, - minute, - second, - imagesTpl, - }), - }; - }), + item: items, }; } diff --git a/lib/routes/kpopping/kpics.ts b/lib/routes/kpopping/kpics.ts index 05f36d9ac..e993b2cec 100644 --- a/lib/routes/kpopping/kpics.ts +++ b/lib/routes/kpopping/kpics.ts @@ -109,30 +109,29 @@ export const handler = async (ctx: Context): Promise => { }; const mediaEls: Element[] = $$('div.pics').first().find('img').toArray(); - const medias: Record> = mediaEls.reduce((acc: Record>, mediaEl) => { + const medias: Record> = {}; + let imageCount = 1; + for (const mediaEl of mediaEls) { const $$mediaEl: Cheerio = $$(mediaEl); const url: string | undefined = $$mediaEl.attr('src') ? new URL($$mediaEl.attr('src') as string, baseUrl).href : undefined; if (!url) { - return acc; + continue; } const medium: string = 'image'; - const count: number = Object.values(acc).filter((m) => m.medium === medium).length + 1; - const key: string = `${medium}${count}`; + const key: string = `${medium}${imageCount++}`; - acc[key] = { + medias[key] = { url, medium, title: $$mediaEl.attr('alt') || title, description: $$mediaEl.attr('alt') || title, thumbnail: url, }; + } - return acc; - }, {}); - - if (medias) { + if (Object.keys(medias).length > 0) { processedItem = { ...processedItem, media: medias, diff --git a/lib/routes/manhuagui/comic.ts b/lib/routes/manhuagui/comic.ts index 32a4dd41a..96418ed24 100644 --- a/lib/routes/manhuagui/comic.ts +++ b/lib/routes/manhuagui/comic.ts @@ -10,38 +10,37 @@ const getChapters = ($) => { let time_mark = 100; // 用于一次更新多个新章节的排序 let new_time_mark = 0; - return $('h4') - .toArray() - .map((ele) => { - const categoryName = $(ele).text(); - while (!$(ele.next).hasClass('chapter-list')) { - ele = ele.next; - } - ele = ele.next; - return $(ele) - .children('ul') - .toArray() - .reverse() - .reduce((acc, curr) => [...acc, ...$(curr).children('li').toArray()], []) - .map((ele) => { - const a = $(ele).children('a'); - // 通过操作发布时间来对章节进行排序,如果是刚刚更新的单行本或者番外,保留最新更新时间 - let pDate = new Date(new Date($.pubDate) - time_mark++ * 1000); - if (a.find('em').length > 0) { - // 对更新的章节也进行排序 - pDate = new Date(new Date($.pubDate) - new_time_mark++ * 1000); - $.newChapterCnt++; - } - return { - link: new URL(a.attr('href'), baseUrl).href, - title: a.attr('title'), - pub_date: pDate, - num: a.find('i').text(), - category: categoryName, - }; + const result: DataItem[] = []; + $('h4').each((_, ele) => { + const categoryName = $(ele).text(); + let nextEle = ele.next; + while (nextEle && !$(nextEle).hasClass('chapter-list')) { + nextEle = nextEle.next; + } + if (!nextEle) { + return; + } + for (const ul of $(nextEle).children('ul').toArray().reverse()) { + for (const li of $(ul).children('li').toArray()) { + const a = $(li).children('a'); + // 通过操作发布时间来对章节进行排序,如果是刚刚更新的单行本或者番外,保留最新更新时间 + let pDate = new Date(new Date($.pubDate) - time_mark++ * 1000); + if (a.find('em').length > 0) { + // 对更新的章节也进行排序 + pDate = new Date(new Date($.pubDate) - new_time_mark++ * 1000); + $.newChapterCnt++; + } + result.push({ + link: new URL(a.attr('href'), baseUrl).href, + title: a.attr('title'), + pub_date: pDate, + num: a.find('i').text(), + category: categoryName, }); - }) - .reduce((acc, curr) => [...acc, ...curr]); + } + } + }); + return result; }; export const route: Route = { diff --git a/lib/routes/mycard520/news.ts b/lib/routes/mycard520/news.ts index 02c377ba7..65c312b3c 100644 --- a/lib/routes/mycard520/news.ts +++ b/lib/routes/mycard520/news.ts @@ -70,16 +70,7 @@ export const handler = async (ctx: Context): Promise => { const pubDateStr: string | undefined = $$('div.date').first().text(); const upDatedStr: string | undefined = pubDateStr; - const clearIndex = $$pageBox - .children() - .toArray() - .map((el, index) => ({ el, index })) - .filter(({ el }) => el.tagName === 'div' && el.attributes.some((attr) => attr.name === 'style' && attr.value.split(';').some((prop) => prop.trim() === 'clear:both'))) - .reduce((_, { index }) => index, -1); - - if (clearIndex !== -1) { - $$pageBox.children().slice(0, clearIndex).remove(); - } + $$pageBox.find('h2, div.date, .the_champ_sharing_container').remove(); const description: string | undefined = $$pageBox.html() ?? item.description; diff --git a/lib/routes/mydrivers/cid.ts b/lib/routes/mydrivers/cid.ts index bd16717e0..028dbeb08 100644 --- a/lib/routes/mydrivers/cid.ts +++ b/lib/routes/mydrivers/cid.ts @@ -1,16 +1,202 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; import { parseDate } from '@/utils/parse-date'; import parser from '@/utils/rss-parser'; import { rootUrl, rootRSSUrl, title, categories, getInfo, processItems } from './util'; export const route: Route = { - path: ['/cid/:id?', '/zhibo'], - name: 'Unknown', - maintainers: [], + path: '/cid/:id?', + name: '更多分类', + parameters: { id: '分类,见下表,留空为直播' }, + example: '/mydrivers/cid/2', + maintainers: ['nczitzk'], handler, url: 'm.mydrivers.com/', + radar: [ + { + source: ['m.mydrivers.com/'], + target: '/zhibo', + }, + ], + description: `::: details 更多分类 + +| 电脑配件 | 手机之家 | 家用电器 | 网络设备 | 办公外设 | 游戏之家 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/2 | cid/3 | cid/4 | cid/5 | cid/6 | cid/7 | + +| 电脑软件 | 业内动向 | 品牌整机 | 其它资讯 | 显卡 | CPU | +| -------- | -------- | -------- | -------- | ------ | ------ | +| cid/8 | cid/9 | cid/10 | cid/11 | cid/12 | cid/13 | + +| 主板 | 内存 | 硬盘 | 机箱 | 电源 | 散热器 | +| ------ | ------ | ------ | ------ | ------ | ------ | +| cid/14 | cid/15 | cid/16 | cid/17 | cid/18 | cid/19 | + +| 光驱 | 声卡 | 键鼠 | 音箱 | 手机厂商 | 手机配件 | +| ------ | ------ | ------ | ------ | -------- | -------- | +| cid/20 | cid/21 | cid/22 | cid/23 | cid/24 | cid/25 | + +| PDA | MP3/MP4 | 摄像机 | 数码相机 | 摄像头 | 数码配件 | +| ------ | ------- | ------ | -------- | ------ | -------- | +| cid/26 | cid/27 | cid/29 | cid/30 | cid/31 | cid/32 | + +| 电子书 | 导航产品 | 录音笔 | 交换机 | 路由器 | 防火墙 | +| ------ | -------- | ------ | ------ | ------ | ------ | +| cid/33 | cid/34 | cid/35 | cid/37 | cid/38 | cid/40 | + +| 网卡 | 网络存储 | UPS | 打印机 | 复印机 | 复合机 | +| ------ | -------- | ------ | ------ | ------ | ------ | +| cid/41 | cid/43 | cid/44 | cid/45 | cid/46 | cid/47 | + +| 投影仪 | 扫描仪 | 传真机 | 电脑游戏 | 主机游戏 | 游戏主机 | +| ------ | ------ | ------ | -------- | -------- | -------- | +| cid/48 | cid/49 | cid/51 | cid/52 | cid/53 | cid/54 | + +| 掌机游戏 | 电脑驱动 | 桌面系统 | 视点人物 | 数据报告 | 科技前沿 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/55 | cid/57 | cid/58 | cid/62 | cid/63 | cid/65 | + +| 笔记本 | 台式机 | 服务器 | 一体机 | 其他 | PC硬件 | +| ------ | ------ | ------ | ------ | ------ | ------ | +| cid/66 | cid/67 | cid/68 | cid/69 | cid/73 | cid/74 | + +| 时尚数码 | 软件驱动 | 显示器 | 音箱耳机 | 投影机 | 便携机 | +| -------- | -------- | ------ | -------- | ------- | ------- | +| cid/78 | cid/79 | cid/80 | cid/92 | cid/100 | cid/108 | + +| 手机 | MP3 | MP4 | 闪存盘 | DV摄像机 | U盘 | +| ------- | ------- | ------- | ------- | -------- | ------- | +| cid/109 | cid/112 | cid/113 | cid/114 | cid/115 | cid/116 | + +| GPS | 移动硬盘 | 操作系统 | 驱动 | 软件 | 软件更新 | +| ------- | -------- | -------- | ------- | ------- | -------- | +| cid/117 | cid/119 | cid/120 | cid/121 | cid/122 | cid/123 | + +| 新软推荐 | 业界动态 | 软件评测 | 软件技巧 | 游戏相关 | 驱动研究 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/124 | cid/125 | cid/126 | cid/127 | cid/128 | cid/130 | + +| 游戏试玩 | 硬件学堂 | 实用技巧 | 新软体验 | 资讯教程 | 软件横评 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/131 | cid/132 | cid/133 | cid/134 | cid/135 | cid/136 | + +| Windows | Mac | Linux | 其它 | 使用技巧 | 深入研究 | +| ------- | ------- | ------- | ------- | -------- | -------- | +| cid/137 | cid/138 | cid/139 | cid/140 | cid/141 | cid/142 | + +| 游戏机 | 显示 | 存储 | 音频 | 外设 | 数码 | +| ------- | ------- | ------- | ------- | ------- | ------- | +| cid/144 | cid/145 | cid/146 | cid/147 | cid/148 | cid/151 | + +| 网络 | 办公 | 维修 | 安全 | 聊天 | 影音 | +| ------- | ------- | ------- | ------- | ------- | ------- | +| cid/152 | cid/154 | cid/155 | cid/156 | cid/157 | cid/158 | + +| 国内 | 国外 | 办公应用 | 设计创意 | 基础知识 | 程序 | +| ------- | ------- | -------- | -------- | -------- | ------- | +| cid/159 | cid/160 | cid/161 | cid/162 | cid/163 | cid/164 | + +| 其他硬件 | 电视卡/盒 | 游戏体验 | 平板电视 | 企业动态 | 天文航天 | +| -------- | --------- | -------- | -------- | -------- | -------- | +| cid/166 | cid/170 | cid/172 | cid/173 | cid/174 | cid/175 | + +| MID设备 | 数码相框 | 耳机 | 通讯运营商 | 电视盒 | 线材线缆 | +| ------- | -------- | ------- | ---------- | ------- | -------- | +| cid/176 | cid/177 | cid/179 | cid/180 | cid/182 | cid/183 | + +| 小家电 | 网络游戏 | 行情信息 | 科学动态 | 生物世界 | 历史考古 | +| ------- | -------- | -------- | -------- | -------- | -------- | +| cid/184 | cid/186 | cid/188 | cid/192 | cid/193 | cid/194 | + +| 生科医学 | 地理自然 | 工程建筑 | 苹果手机 | 谷歌Android | 塞班手机 | +| -------- | -------- | -------- | -------- | ----------- | -------- | +| cid/195 | cid/196 | cid/197 | cid/201 | cid/202 | cid/203 | + +| 黑莓手机 | 微软手机 | 移动处理器 | 山寨机 | 手机游戏 | 安卓应用 | +| -------- | -------- | ---------- | ------- | -------- | -------- | +| cid/204 | cid/205 | cid/206 | cid/208 | cid/209 | cid/210 | + +| 娱乐生活 | 明星全接触 | 电影影讯 | 电视节目 | 音乐戏曲 | 国际风云 | +| -------- | ---------- | -------- | -------- | -------- | -------- | +| cid/212 | cid/213 | cid/214 | cid/215 | cid/216 | cid/217 | + +| 国内传真 | 社会民生 | 生活百态 | 医药健康 | 家居尚品 | 星座旅游 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/218 | cid/219 | cid/220 | cid/221 | cid/222 | cid/223 | + +| 评论分析 | 体育竞技 | IT八卦 | 科技动态 | 游戏动态 | 手机系统 | +| -------- | -------- | ------- | -------- | -------- | -------- | +| cid/224 | cid/225 | cid/226 | cid/227 | cid/228 | cid/232 | + +| 智能设备 | 生活电器 | 汽车相关 | 飞机航空 | 手机周边 | 网络运营商 | +| -------- | -------- | -------- | -------- | -------- | ---------- | +| cid/233 | cid/234 | cid/235 | cid/236 | cid/237 | cid/238 | + +| 平板电脑 | 苹果iPad | 安卓平板 | Windows平板 | 创业路上 | 网友热议 | +| -------- | -------- | -------- | ----------- | -------- | -------- | +| cid/239 | cid/240 | cid/241 | cid/242 | cid/243 | cid/244 | + +| IT圈 | 数码周边 | 智能手环 | 智能眼镜 | 智能手表 | iOS应用 | +| ------- | -------- | -------- | -------- | -------- | ------- | +| cid/246 | cid/247 | cid/248 | cid/249 | cid/250 | cid/251 | + +| 壁纸主题 | 游戏厂商 | 数理化学 | 科普知识 | 奇趣探险 | 汽车世界 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/252 | cid/253 | cid/254 | cid/255 | cid/256 | cid/257 | + +| 传统汽车 | 电动汽车 | 新能源汽车 | 无人驾驶汽车 | 车载系统 | 车载配件 | +| -------- | -------- | ---------- | ------------ | -------- | -------- | +| cid/258 | cid/259 | cid/260 | cid/261 | cid/262 | cid/263 | + +| 汽车厂商 | 影音动漫 | 精彩影视 | 电影动画 | 艺术设计 | 摄影达人 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/264 | cid/265 | cid/266 | cid/267 | cid/269 | cid/270 | + +| 固件 | 样张赏析 | 创意摄影 | WP应用 | 教育未来 | 安卓手机 | +| ------- | -------- | -------- | ------- | -------- | -------- | +| cid/272 | cid/273 | cid/274 | cid/284 | cid/285 | cid/288 | + +| 智能穿戴 | 移动应用 | 电子竞技 | 游戏八卦 | 游戏评测 | 生活百科 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/290 | cid/292 | cid/297 | cid/298 | cid/299 | cid/301 | + +| 智能家居 | 智能插座 | 智能摄像头 | 智能路由器 | 智能体重秤 | 智能血压计 | +| -------- | -------- | ---------- | ---------- | ---------- | ---------- | +| cid/302 | cid/303 | cid/304 | cid/305 | cid/306 | cid/307 | + +| 空气净化器 | 智能净水器 | 电动两轮车 | 公司财报 | 智能行车记录仪 | 网络影视 | +| ---------- | ---------- | ---------- | -------- | -------------- | -------- | +| cid/308 | cid/309 | cid/310 | cid/311 | cid/312 | cid/313 | + +| 多轴无人机 | 摩托车 | 自行车 | 共享经济 | 生活周边 | 网络安全 | +| ---------- | ------- | ------- | -------- | -------- | -------- | +| cid/314 | cid/316 | cid/317 | cid/320 | cid/321 | cid/322 | + +| 考勤机 | 网络红人 | 火车高铁 | 机器人 | 其他网络 | 快递物流 | +| ------- | -------- | -------- | ------- | -------- | -------- | +| cid/323 | cid/324 | cid/325 | cid/326 | cid/327 | cid/328 | + +| 科技资讯 | 好货推荐 | 日常用品 | 餐饮零食 | 化妆品 | 运动健康 | +| -------- | -------- | -------- | -------- | ------- | -------- | +| cid/329 | cid/334 | cid/335 | cid/336 | cid/339 | cid/340 | + +| 酒水饮料 | 个人洗护 | 电子产品 | 服装鞋帽 | 会员卡 | 用户投稿 | +| -------- | -------- | -------- | -------- | ------- | -------- | +| cid/341 | cid/342 | cid/343 | cid/345 | cid/346 | cid/351 | + +| APP投稿 | PC投稿 | 视频快讯 | 新品开箱 | 技巧教程 | 科技快讯 | +| ------- | ------- | -------- | -------- | -------- | -------- | +| cid/352 | cid/353 | cid/354 | cid/355 | cid/356 | cid/357 | + +| 产品评测 | 人物专访 | 会议活动 | 数码影音 | 数码影像 | 游戏周边 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| cid/358 | cid/359 | cid/360 | cid/361 | cid/362 | cid/368 | + +| 汽车周边 | 个人交通 | 其他交通 | +| -------- | -------- | -------- | +| cid/369 | cid/370 | cid/371 | + +:::`, }; async function handler(ctx) { @@ -35,11 +221,11 @@ async function handler(ctx) { })); if (id) { - items = await processItems(items, cache.tryGet); + items = await processItems(items); } return { - ...(await getInfo(currentUrl, cache.tryGet)), + ...(await getInfo(currentUrl)), item: items, title: `${title} - ${feed.title.split(/_/).pop() || categories.zhibo}`, diff --git a/lib/routes/mydrivers/index.ts b/lib/routes/mydrivers/index.ts index 0f2abef41..5e7859c7c 100644 --- a/lib/routes/mydrivers/index.ts +++ b/lib/routes/mydrivers/index.ts @@ -1,6 +1,5 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; import got from '@/utils/got'; import { load } from 'cheerio'; import timezone from '@/utils/timezone'; @@ -12,9 +11,44 @@ import { rootUrl, title, categories, convertToQueryString, getInfo, processItems export const route: Route = { path: '/:category{.+}?', - name: 'Unknown', - maintainers: [], + name: '分类', + parameters: { category: '分类,见下表,默认为最新' }, + example: '/mydrivers/bcid/801', + maintainers: ['kt286', 'nczitzk'], handler, + radar: [ + { + source: ['m.mydrivers.com/'], + target: '/zhibo', + }, + ], + description: ` +#### 板块 + +| 电脑 | 手机 | 汽车 | 业界 | 游戏 | +| -------- | -------- | -------- | -------- | -------- | +| bcid/801 | bcid/802 | bcid/807 | bcid/803 | bcid/806 | + +#### 话题 + +| 科学 | 排行 | 评测 | 一图 | +| -------- | -------- | -------- | -------- | +| tid/1000 | tid/1001 | tid/1002 | tid/1003 | + +#### 品牌 + +| 安卓 | 阿里 | 微软 | 百度 | PS5 | Xbox | 华为 | +| -------- | -------- | ------- | ------- | --------- | -------- | -------- | +| icid/121 | icid/270 | icid/90 | icid/67 | icid/6950 | icid/194 | icid/136 | + +| 小米 | VIVO | 三星 | 魅族 | 一加 | 比亚迪 | 小鹏 | +| --------- | -------- | -------- | -------- | -------- | -------- | --------- | +| icid/9355 | icid/288 | icid/154 | icid/140 | icid/385 | icid/770 | icid/7259 | + +| 蔚来 | 理想 | 奔驰 | 宝马 | 大众 | +| --------- | ---------- | -------- | -------- | -------- | +| icid/7318 | icid/12947 | icid/429 | icid/461 | icid/481 | +`, }; async function handler(ctx) { @@ -57,15 +91,11 @@ async function handler(ctx) { }; }); - items = await processItems(items, cache.tryGet); + items = await processItems(items); return { - ...(await getInfo(currentUrl, cache.tryGet)), - ...Object.fromEntries( - Object.entries({ - item: items, - title: newTitle, - }).filter(([value]) => value) - ), + ...(await getInfo(currentUrl)), + ...(newTitle ? { title: newTitle } : {}), + item: items, }; } diff --git a/lib/routes/mydrivers/rank.ts b/lib/routes/mydrivers/rank.ts index e769f6d98..95c3fc081 100644 --- a/lib/routes/mydrivers/rank.ts +++ b/lib/routes/mydrivers/rank.ts @@ -1,5 +1,4 @@ import { Route } from '@/types'; -import cache from '@/utils/cache'; import got from '@/utils/got'; import { load } from 'cheerio'; @@ -61,10 +60,10 @@ async function handler(ctx) { }; }); - items = await processItems(items, cache.tryGet); + items = await processItems(items); return { item: items, - ...(await getInfo(currentUrl, cache.tryGet, Number.parseInt(range, 10))), + ...(await getInfo(currentUrl, Number.parseInt(range, 10))), }; } diff --git a/lib/routes/mydrivers/util.ts b/lib/routes/mydrivers/util.ts index 48a119063..e24f6a9d7 100644 --- a/lib/routes/mydrivers/util.ts +++ b/lib/routes/mydrivers/util.ts @@ -2,6 +2,7 @@ import got from '@/utils/got'; import { load } from 'cheerio'; import timezone from '@/utils/timezone'; import { parseDate } from '@/utils/parse-date'; +import cache from '@/utils/cache'; const domain = 'mydrivers.com'; const rootUrl = `https://m.${domain}`; @@ -25,15 +26,12 @@ const convertToQueryString = (path) => { const parts = path.split('/'); const queryStringParams = []; - for (const [key, value] of parts.reduce((acc, part, index) => { - if (index % 2 === 0) { - acc.push([part]); - } else { - acc.at(-1).push(part); + for (let i = 0; i < parts.length; i += 2) { + const key = parts[i]; + const value = parts[i + 1]; + if (key !== undefined && value !== undefined) { + queryStringParams.push(`${key}=${value}`); } - return acc; - }, [])) { - queryStringParams.push(`${key}=${value}`); } return `?${queryStringParams.join('&')}`; @@ -42,12 +40,11 @@ const convertToQueryString = (path) => { /** * Retrieves information from a given URL using a provided tryGet function. * @param {string} url - The URL to retrieve information from. - * @param {function} tryGet - The tryGet function that handles the retrieval process. * @param {number|undefined} [range] - The index value of the range (optional). * @returns {Promise} - A promise that resolves to an object containing the retrieved information. */ -const getInfo = (url, tryGet, range) => - tryGet(url, async () => { +const getInfo = (url, range) => + cache.tryGet(url, async () => { const { data: response } = await got(url); const $ = load(response); @@ -79,10 +76,10 @@ const getInfo = (url, tryGet, range) => * @param {function} tryGet - The tryGet function that handles the retrieval process. * @returns {Promise>} Returns a Promise that resolves to an array of processed items. */ -const processItems = async (items, tryGet) => +const processItems = async (items) => await Promise.all( items.map((item) => - tryGet(`${domain}#${item.guid}`, async () => { + cache.tryGet(`${domain}#${item.guid}`, async () => { const { data: detailResponse } = await got(`${rootUrl}/newsview/${item.guid}.html`); const { data: voteResponse } = await got.post(apiVoteUrl, { diff --git a/lib/routes/newrank/utils.ts b/lib/routes/newrank/utils.ts index 066cd5b73..6abdf1169 100644 --- a/lib/routes/newrank/utils.ts +++ b/lib/routes/newrank/utils.ts @@ -42,7 +42,17 @@ const decrypt_douyin_detail_xyz = (nonce) => { return md5(str); }; -const flatten = (arr) => arr.reduce((acc, val) => (Array.isArray(val) ? [...acc, ...flatten(val)] : [...acc, val]), []); +const flatten = (arr) => { + const result = []; + for (const val of arr) { + if (Array.isArray(val)) { + result.push(...flatten(val)); + } else { + result.push(val); + } + } + return result; +}; function shouldUpdateCookie(forcedUpdate = false) { if (forcedUpdate) { diff --git a/lib/routes/nhk/news-web-easy.ts b/lib/routes/nhk/news-web-easy.ts index 85e3ad12d..538206bc4 100644 --- a/lib/routes/nhk/news-web-easy.ts +++ b/lib/routes/nhk/news-web-easy.ts @@ -1,7 +1,7 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { load } from 'cheerio'; import timezone from '@/utils/timezone'; import { parseDate } from '@/utils/parse-date'; @@ -33,33 +33,28 @@ export const route: Route = { }; async function handler(ctx) { - const { data } = await got('https://www3.nhk.or.jp/news/easy/news-list.json'); + const data = await ofetch('https://www3.nhk.or.jp/news/easy/news-list.json'); const dates = data[0]; - let items = Object.values(dates).reduce((acc, articles) => { - for (const article of articles) { - const date = timezone(parseDate(article.news_prearranged_time), +9); - - acc.push({ - title: article.title, - description: art(path.join(__dirname, 'templates/news_web_easy.art'), { - title: article.title_with_ruby, - image: article.news_web_image_uri, - }), - guid: article.news_id, - pubDate: date, - link: `https://www3.nhk.or.jp/news/easy/${article.news_id}/${article.news_id}.html`, - }); - } - return acc; - }, []); + let items = Object.values(dates).flatMap((articles) => + articles.map((article) => ({ + title: article.title, + description: art(path.join(__dirname, 'templates/news_web_easy.art'), { + title: article.title_with_ruby, + image: article.news_web_image_uri, + }), + guid: article.news_id, + pubDate: timezone(parseDate(article.news_prearranged_time), +9), + link: `https://www3.nhk.or.jp/news/easy/${article.news_id}/${article.news_id}.html`, + })) + ); items = items.sort((a, b) => b.pubDate - a.pubDate).slice(0, ctx.req.query('limit') ? Number(ctx.req.query('limit')) : 30); items = await Promise.all( items.map((item) => cache.tryGet(item.link, async () => { - const { data } = await got(item.link); + const data = await ofetch(item.link); const $ = load(data); item.description += $('.article-body').html(); return item; diff --git a/lib/routes/nikkei/cn/index.ts b/lib/routes/nikkei/cn/index.ts index 50a96f572..823f19df8 100644 --- a/lib/routes/nikkei/cn/index.ts +++ b/lib/routes/nikkei/cn/index.ts @@ -97,6 +97,7 @@ async function handler(ctx) { $ = load(response.data); + const seenLinks = new Set(); items = $('dt a') .toArray() .map((item) => { @@ -107,7 +108,13 @@ async function handler(ctx) { link: new URL(item.attr('href'), currentUrl).href, }; }) - .reduce((prev, cur) => (prev.length && prev.at(-1).link === cur.link ? prev : [...prev, cur]), []) + .filter((item) => { + if (seenLinks.has(item.link)) { + return false; + } + seenLinks.add(item.link); + return true; + }) .slice(0, limit); } diff --git a/lib/routes/rattibha/templates/description.art b/lib/routes/rattibha/templates/description.art new file mode 100644 index 000000000..e68717eaf --- /dev/null +++ b/lib/routes/rattibha/templates/description.art @@ -0,0 +1,12 @@ +{{ if media }} + {{ if media.type === 1 }} + + {{ else if media.type === 2 }} + + {{ /if }} +
+{{ /if }} + +{{@ text }} diff --git a/lib/routes/rattibha/user.ts b/lib/routes/rattibha/user.ts index ea0e89da8..77aea5ce7 100644 --- a/lib/routes/rattibha/user.ts +++ b/lib/routes/rattibha/user.ts @@ -1,7 +1,13 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; +import { config } from '@/config'; import { parseDate } from '@/utils/parse-date'; +import path from 'node:path'; +import { getCurrentPath } from '@/utils/helpers'; +import { art } from '@/utils/render'; + +const __dirname = getCurrentPath(import.meta.url); export const route: Route = { path: '/user/:user', @@ -30,38 +36,41 @@ async function handler(ctx) { const baseUrl = 'https://rattibha.com'; const { user: twitterUser } = ctx.req.param(); - const { - data: { user: userData }, - } = await got(`${baseUrl}/user?id=${twitterUser}`, { - headers: { - accept: 'application/json', - }, + const userData = await cache.tryGet(`rattibha:user:${twitterUser}`, async () => { + const data = await ofetch(`${baseUrl}/user`, { + query: { id: twitterUser }, + }); + return data.user; }); - const { data: userThreads } = await got(`${baseUrl}/u_threads?id=${userData.account_user_id}`, { headers: { accept: 'application/json' } }); + + const userThreads = await cache.tryGet( + `rattibha:userThreads:${twitterUser}`, + () => + ofetch(`${baseUrl}/u_threads`, { + query: { + id: userData.account_user_id, + page: 0, + post_type: 0, + }, + }), + config.cache.routeExpire, + false + ); // extract the relevant data from the API response - const list = userThreads.map((item) => ({ - title: item.thread.t.info.text, + const items = userThreads.map((item) => ({ + title: item.thread.t.info.text.split('\n')[0], link: `${baseUrl}/thread/${item.thread_id}`, pubDate: parseDate(item.thread.created_at), updated: parseDate(item.thread.updated_at), author: userData.name, - threadData1URL: `${baseUrl}/thread?id=${item.thread_id}`, - threadData2URL: `${baseUrl}/threads?id=${item.thread_id}`, + category: item.thread.categories.map((category) => category.tag.name), + description: art(path.join(__dirname, 'templates/description.art'), { + text: item.thread.t.info.text.replaceAll('\n', '
'), + media: item.thread.m, + }), })); - // Get tweet full text - const items = await Promise.all( - list.map((item) => - cache.tryGet(item.link, async () => { - const { data: data1 } = await got(item.threadData1URL, { headers: { accept: 'application/json' } }); - const { data: data2 } = await got(item.threadData2URL, { headers: { accept: 'application/json' } }); - item.description = [...data1.tweets, ...data2].reduce((accumulator, tweet) => `${accumulator}${tweet.tweet_detail.info.text}
`, ''); - return item; - }) - ) - ); - return { title: `سلاسل تغريدات ${twitterUser}`, link: `${baseUrl}/${twitterUser}`, diff --git a/lib/routes/scmp/index.ts b/lib/routes/scmp/index.ts index 98a3a050d..b3eb8dae4 100644 --- a/lib/routes/scmp/index.ts +++ b/lib/routes/scmp/index.ts @@ -29,6 +29,19 @@ export const route: Route = { description: `See the [official RSS page](https://www.scmp.com/rss) to get the ID of each category. This route provides fulltext that the offical feed doesn't.`, }; +const getAttribs = (attribs?: { [key: string]: string }) => { + if (!attribs) { + return; + } + const obj: { [key: string]: string } = {}; + for (const key in attribs) { + if (Object.hasOwn(attribs, key)) { + obj[key] = attribs[key]; + } + } + return obj; +}; + async function handler(ctx) { const categoryId = ctx.req.param('category_id'); const rssUrl = `https://www.scmp.com/rss/${categoryId}/feed`; @@ -54,16 +67,8 @@ async function handler(ctx) { enclosure_length: enclosure?.attr('length'), enclosure_type: enclosure?.attr('type'), media: { - content: Object.keys(mediaContent.attribs).reduce((data, key) => { - data[key] = mediaContent.attribs[key]; - return data; - }, {}), - thumbnail: thumbnail?.attribs - ? Object.keys(thumbnail.attribs).reduce((data, attr) => { - data[attr] = thumbnail.attribs[attr]; - return data; - }, {}) - : undefined, + content: mediaContent ? getAttribs(mediaContent.attribs) : {}, + thumbnail: thumbnail?.attribs ? getAttribs(thumbnail.attribs) : undefined, }, }; }); diff --git a/lib/routes/sse/convert.ts b/lib/routes/sse/convert.ts index 478f76467..622d55ece 100644 --- a/lib/routes/sse/convert.ts +++ b/lib/routes/sse/convert.ts @@ -24,6 +24,16 @@ async function handler(ctx) { const query = ctx.req.param('query') ?? ''; // beginDate=2018-08-18&endDate=2019-08-18&companyCode=603283&title=股份 const pageUrl = 'https://bond.sse.com.cn/disclosure/announ/convertible/'; const host = 'https://www.sse.com.cn'; + const queries: Record = {}; + if (query) { + const pairs = query.split('&'); + for (const pair of pairs) { + const [key, value] = pair.split('='); + if (key) { + queries[key] = value; + } + } + } const response = await got('https://query.sse.com.cn/infodisplay/queryBulletinKzzTipsNew.do', { searchParams: { @@ -31,11 +41,7 @@ async function handler(ctx) { 'pageHelp.pageSize': 20, flag: 0, _: Date.now(), - ...query.split('&').reduce((acc, cur) => { - const [key, value] = cur.split('='); - acc[key] = value; - return acc; - }, {}), + ...queries, }, headers: { Referer: pageUrl, diff --git a/lib/routes/sse/disclosure.ts b/lib/routes/sse/disclosure.ts index 3cce8842f..5d4dce1fc 100644 --- a/lib/routes/sse/disclosure.ts +++ b/lib/routes/sse/disclosure.ts @@ -22,11 +22,15 @@ export const route: Route = { async function handler(ctx) { const query = ctx.req.param('query') ?? ''; // beginDate=2018-08-18&endDate=2020-09-01&productId=600696 - const queries = query.split('&').reduce((acc, cur) => { - const [key, value] = cur.split('='); - acc[key] = value; - return acc; - }, {}); + const queries: Record = {}; + if (query) { + for (const pair of query.split('&')) { + const [key, value] = pair.split('='); + if (key) { + queries[key] = value; + } + } + } const pageUrl = `https://www.sse.com.cn/assortment/stock/list/info/announcement/index.shtml?productId=${queries.productId}`; const response = await got('https://query.sse.com.cn/security/stock/queryCompanyBulletin.do', { diff --git a/lib/routes/sspai/series.ts b/lib/routes/sspai/series.ts index ef1f208a9..653ab8244 100644 --- a/lib/routes/sspai/series.ts +++ b/lib/routes/sspai/series.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { load } from 'cheerio'; export const route: Route = { @@ -29,33 +29,31 @@ export const route: Route = { }; async function handler() { - const response = await got('https://sspai.com/api/v1/series/tag/all/get'); + const response = await ofetch('https://sspai.com/api/v1/series/tag/all/get', { + parseResponse: JSON.parse, + }); - const products = response.data.data.reduce((acc, cate) => { - if (Array.isArray(cate.children)) { - const result = cate.children - .filter((item) => item.sell_status) - .map((item) => { - const price = item.price / 100; - return { - id: item.id, - title: `¥${price} - ${item.title}`, - link: `https://sspai.com/series/${item.id}`, - author: item.author.nickname, - }; - }); - return [...acc, ...result]; - } else { - return acc; - } - }, []); + const products = response.data.flatMap((category) => + category.children + .filter((item) => item.sell_status) + .map((item) => { + const price = item.price / 100; + return { + id: item.id, + title: `¥${price} - ${item.title}`, + link: `https://sspai.com/series/${item.id}`, + author: item.author.nickname, + }; + }) + ); const item = await Promise.all( products.map((item) => cache.tryGet(item.link, async () => { - const res = await got(`https://sspai.com/api/v1/series/info/get?id=${item.id}&view=second`); - const banner = ``; - const description = banner + res.data.data.intro; + const res = await ofetch(`https://sspai.com/api/v1/series/info/get?id=${item.id}&view=second`); + const data = res.data; + const banner = ``; + const description = banner + data.intro; const $ = load(description); $('img').css('max-width', '100%'); item.description = $.html(); diff --git a/lib/routes/sysu/ygafz.ts b/lib/routes/sysu/ygafz.ts index c056329bc..017b52c96 100644 --- a/lib/routes/sysu/ygafz.ts +++ b/lib/routes/sysu/ygafz.ts @@ -1,11 +1,8 @@ import { Route } from '@/types'; import cache from '@/utils/cache'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { load } from 'cheerio'; import { parseDate } from '@/utils/parse-date'; -import logger from '@/utils/logger'; -import { CookieJar } from 'tough-cookie'; -import puppeteer from '@/utils/puppeteer'; export const route: Route = { path: '/ygafz/:type?', @@ -42,30 +39,9 @@ async function handler(ctx) { const baseUrl = 'https://ygafz.sysu.edu.cn'; const url = `${baseUrl}/${type}`; - const browser = await puppeteer(); - const page = await browser.newPage(); - await page.setRequestInterception(true); - page.on('request', (request) => { - request.resourceType() === 'document' || request.resourceType() === 'script' ? request.continue() : request.abort(); - }); - - logger.http(`Requesting ${url}`); - await page.goto(url, { - waitUntil: 'domcontentloaded', - }); - await page.waitForSelector('[data-block-plugin-id]'); - const response = await page.content(); - - const cookieJar = new CookieJar(); - const cookies = await page.cookies(); - cookies.reduce((jar, cookie) => { - jar.setCookie(`${cookie.name}=${cookie.value}`, url); - return jar; - }, cookieJar); - - await browser.close(); - + const response = await ofetch(url); const $ = load(response); + const list = $('.list-content a') .toArray() .map((item) => { @@ -80,15 +56,13 @@ async function handler(ctx) { const items = await Promise.all( list.map((item) => cache.tryGet(item.link, async () => { - const { data } = await got(item.link, { - cookieJar, - }); + const data = await ofetch(item.link); const $ = load(data); item.author = $('.article-submit') .text() .match(/发布人:(.*)/)[1]; - item.description = $('div[data-block-plugin-id="entity_field:node:body"]').html(); + item.description = $('div[data-block-plugin-id="entity_field:node:body"]').html() + ($('div[data-block-plugin-id="entity_field:node:attachments"]').html() ?? ''); return item; }) ) diff --git a/lib/routes/trending/all-trending.ts b/lib/routes/trending/all-trending.ts deleted file mode 100644 index 8b6f5fac4..000000000 --- a/lib/routes/trending/all-trending.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { Route } from '@/types'; - -import cache from '@/utils/cache'; -import dayjs from 'dayjs'; -import utc from 'dayjs/plugin/utc.js'; -import timezone from 'dayjs/plugin/timezone.js'; -dayjs.extend(utc); -dayjs.extend(timezone); -import ofetch from '@/utils/ofetch'; -import { art } from '@/utils/render'; -import path from 'node:path'; -import { config } from '@/config'; -import md5 from '@/utils/md5'; -import InvalidParameterError from '@/errors/types/invalid-parameter'; - -// Constants -const CACHE_KEY = 'trending-all-in-one'; -const DATA_REPO_BASE_URL = 'https://raw.githubusercontent.com/huqi-pr/trending-in-one/master/raw'; -const DATE_FORMAT = 'YYYY-MM-DD'; -// TODO: support custom data repo urls -const CHANNELS = { - 'toutiao-search': { - baseUrl: 'https://so.toutiao.com/search?keyword=', - name: '今日头条热搜', - }, - 'weibo-search': { - baseUrl: 'https://s.weibo.com/weibo?q=', - name: '微博热搜', - }, - 'zhihu-search': { - baseUrl: 'https://www.zhihu.com/search?q=', - name: '知乎热搜', - }, - 'zhihu-questions': { - baseUrl: 'https://www.zhihu.com/search?type=question&q=', - name: '知乎热门话题', - }, - 'zhihu-video': { - baseUrl: 'https://www.zhihu.com/search?type=video&q=', - name: '知乎热门视频', - }, -}; - -// Helper Functions -const processRawDataByChannel = { - 'toutiao-search': ({ word: title }) => ({ - // 源 url 存在 encoding 问题,暂时不使用 - url: CHANNELS['toutiao-search'].baseUrl + encodeURIComponent(title), - title, - }), - 'weibo-search': ({ title }) => ({ - // 源 url 存在 encoding 问题,暂时不使用 - url: CHANNELS['weibo-search'].baseUrl + encodeURIComponent(title), - title, - }), - 'zhihu-questions': (item) => item, - 'zhihu-search': ({ query }) => { - const title = query.trim(); - return { - // 源 url 存在 encoding 问题,暂时不使用 - url: CHANNELS['zhihu-search'].baseUrl + encodeURIComponent(title), - title, - }; - }, - 'zhihu-video': (item) => item, -}; - -const hasKeyword = (str, keywordList) => keywordList.some((keyword) => str.includes(keyword)); -const toShanghaiTimezone = (date) => dayjs.tz(date, 'Asia/Shanghai'); -const processRawData = (channel) => (res) => res.map((item) => processRawDataByChannel[channel](item)); -const filterKeyword = (keywordList) => (res) => res.filter(({ title }) => hasKeyword(title, keywordList)); - -// Data Fetcher -// TODO: support channel selection -const fetchAllData = async (keywordList = [], dateList = [], cache) => { - const cachedGetData = (url) => cache.tryGet(url, () => ofetch(url), config.cache.contentExpire, false); - - let data = await Promise.all( - dateList.map(async (dateTime) => ({ - dateTime, - data: await Promise.all( - Object.keys(CHANNELS).map(async (channel) => ({ - name: CHANNELS[channel].name, - data: await cachedGetData(`${DATA_REPO_BASE_URL}/${channel}/${dateTime.format(DATE_FORMAT)}.json`) - .then(processRawData(channel)) - .then(filterKeyword(keywordList)), - })) - ), - })) - ); - - for (const i of data) { - i.count = i.data.reduce((acc, { data }) => acc + data.length, 0); - } - - data = data.filter(({ count }) => count > 0); - - if (data.length === 0) { - return data; - } - - const prev = cache.get(CACHE_KEY + ':latest-items'); - - const latest = data[0]; - latest.newItemCount = 0; - if (latest.count > 0 && prev) { - // Mark new items in latest - for (const channel in latest.data) { - for (const i of latest.data[channel].data) { - i.new = !(i.url in prev); - latest.newItemCount += i.new ? 1 : 0; - } - } - // Save latest data to cache - const cachedItems = latest.data.reduce((acc, { data: channel }) => { - for (const item of channel) { - acc[item.url] = true; - } - return acc; - }, {}); - cache.set(CACHE_KEY + ':latest-items', cachedItems, config.cache.contentExpire); - - latest.count = Object.keys(cachedItems).length; - } - - return data; -}; - -// Generate Feed Items -const searchLinkUrls = (keyword) => [ - `https://tophub.today/search?e=tophub&q=${keyword}`, - `https://www.baidu.com/s?wd=${keyword}`, - `https://www.google.com/search?q=${keyword}`, - `https://www.zhihu.com/search?type=content&q=${keyword}`, - `https://s.weibo.com/weibo/${keyword}`, - `https://www.douyin.com/search/${keyword}`, - `https://so.toutiao.com/search?keyword=${keyword}`, -]; - -const searchLinkNames = ['热榜', '百度', '谷歌', '知乎', '微博', '抖音', '头条']; - -const createItem = ({ dateTime, data, count, newItemCount }, keywords, isToday) => { - const EOD = dateTime.endOf('day'); - const pubDate = isToday ? new Date() : EOD.toDate(); - const countStr = isToday && newItemCount ? newItemCount + '🆕' : count; - - return { - title: `${keywords.join(', ')} | ${dateTime.format(DATE_FORMAT)} 热点追踪 (${countStr})`, - author: 'Trending All In One', - pubDate, - description: art(path.join(__dirname, 'templates/content.art'), { - data, - queries: keywords.map((query) => ({ - links: searchLinkUrls(encodeURIComponent(query)).map((url, index) => `${searchLinkNames[index]}`), - key: query, - })), - }), - guid: `trending-all-in-one-${EOD.toISOString()}-${md5(JSON.stringify(data))}-${keywords.join('-')}`, - }; -}; - -// Main -export const route: Route = { - path: '/:keywords/:numberOfDays?', - categories: ['other'], - example: '/trending/唐山,打人/3', - parameters: { keywords: '通过逗号区隔的关键词列表', numberOfDays: '向前追溯的天数,默认为3天' }, - features: { - requireConfig: false, - requirePuppeteer: false, - antiCrawler: false, - supportBT: false, - supportPodcast: false, - supportScihub: false, - }, - name: '关键词聚合追踪', - maintainers: ['Jkker'], - handler, - description: `追踪各大热搜榜上包含特定关键词的条目。 - -当前收录榜单:*微博热搜*、*今日头条热搜*、*知乎热搜*、*知乎热门视频*、*知乎热门话题*。 - -数据源: [trending-in-one](https://github.com/huqi-pr/trending-in-one)`, -}; - -async function handler(ctx) { - // Prevent making over 100 requests per invocation - if (ctx.req.param('numberOfDays') > 14) { - throw new InvalidParameterError('days must be less than 14'); - } - const numberOfDays = ctx.req.param('numberOfDays') || 3; - const currentShanghaiDateTime = dayjs(toShanghaiTimezone(new Date())); - const currentShanghaiDateStr = currentShanghaiDateTime.format(DATE_FORMAT); - const dateList = []; - for (let i = 0; i < numberOfDays; i++) { - const d = currentShanghaiDateTime.subtract(i, 'day'); - dateList.push(d); - } - - const keywordList = ctx.req - .param('keywords') - .replace(',', ',') - .split(',') - .map((keyword) => keyword.trim()); - const keywordStr = keywordList.join(', '); - - const data = await fetchAllData(keywordList, dateList, cache).catch(() => []); - const item = - data.length > 0 - ? data.map((i, index) => createItem(i, keywordList, index === 0)) - : [ - { - title: `${keywordStr} | ${currentShanghaiDateStr} 热点追踪 (0)`, - author: 'Trending All In One', - description: `近${numberOfDays}日的热搜都不包含下列关键词:${keywordStr}
请耐心等待,或添加更多关键词试试。`, - guid: `trending-all-in-one-${md5(JSON.stringify(data))}-${keywordList.join('-')}`, - }, - ]; - - return { - title: `${keywordStr} | 热点聚合`, - description: `${keywordStr} | 今日头条热搜,知乎热门视频,知乎热搜榜,知乎热门话题,微博热搜榜聚合追踪`, - language: 'zh-cn', - item, - }; -} diff --git a/lib/routes/trending/namespace.ts b/lib/routes/trending/namespace.ts deleted file mode 100644 index 937478e11..000000000 --- a/lib/routes/trending/namespace.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Namespace } from '@/types'; - -export const namespace: Namespace = { - name: '热搜聚合', - url: 'so.toutiao.com', - lang: 'zh-CN', -}; diff --git a/lib/routes/trending/templates/content.art b/lib/routes/trending/templates/content.art deleted file mode 100644 index 047463438..000000000 --- a/lib/routes/trending/templates/content.art +++ /dev/null @@ -1,25 +0,0 @@ -
-

热榜内容

- {{each data channel}} - {{if channel.data.length !== 0}} -

{{channel.name}}

-
    - {{each channel.data item}} -
  • - {{item.title}} - {{if item.new}}🆕{{/if}} -
  • - {{/each}} -
- {{/if}} - {{/each}} -

搜索关键词

- {{each queries q}} -

{{q.key}}

-

- {{each q.links l}} - {{@l}}   - {{/each}} -

- {{/each}} -
\ No newline at end of file diff --git a/lib/routes/twitter/utils.ts b/lib/routes/twitter/utils.ts index b954ae3ab..01aeaac9b 100644 --- a/lib/routes/twitter/utils.ts +++ b/lib/routes/twitter/utils.ts @@ -94,19 +94,20 @@ const ProcessFeed = (ctx, { data = [] }, params = {}) => { const formatVideo = (media, extraAttrs = '') => { let content = ''; - const video = media.video_info.variants.reduce((video, item) => { - if ((item.bitrate || 0) > (video.bitrate || -Infinity)) { - video = item; - } - return video; - }, {}); + let bestVideo = null; - if (video.url) { + for (const item of media.video_info.variants) { + if (!bestVideo || (item.bitrate || 0) > (bestVideo.bitrate || -Infinity)) { + bestVideo = item; + } + } + + if (bestVideo && bestVideo.url) { const gifAutoPlayAttr = media.type === 'animated_gif' ? `autoplay loop muted webkit-playsinline playsinline` : ''; if (!readable) { content += '
'; } - content += ``; + content += ``; } return content; diff --git a/lib/routes/yoasobi-music/media.ts b/lib/routes/yoasobi-music/media.ts index 99e71e833..01c87e845 100644 --- a/lib/routes/yoasobi-music/media.ts +++ b/lib/routes/yoasobi-music/media.ts @@ -1,6 +1,6 @@ import { Route } from '@/types'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { parseJSONP } from './jsonp-helper'; import { art } from '@/utils/render'; import path from 'node:path'; @@ -38,13 +38,10 @@ async function handler() { const officialUrl = 'https://www.yoasobi-music.jp/media'; const title = 'LATEST MEDIA'; - const response = await got({ - method: 'get', - url: api, - }); + const response = await ofetch(api); const data = Object.values(parseJSONP(response.data).items) - .reduce((p, c) => [...p, ...c]) + .flat() .sort((a, b) => new Date(b.date) - new Date(a.date)) .map((item) => ({ date: item.date, diff --git a/lib/routes/zhihu/pin/utils.ts b/lib/routes/zhihu/pin/utils.ts index b1ea9329b..0709c423b 100644 --- a/lib/routes/zhihu/pin/utils.ts +++ b/lib/routes/zhihu/pin/utils.ts @@ -1,7 +1,7 @@ import { parseDate } from '@/utils/parse-date'; -const generateDescription = (target, init) => - target.content.reduce((description, item) => { +const generateDescription = (target, description = '') => { + for (const item of target.content) { switch (item.type) { case 'text': description += `
${item.content}
`; @@ -38,9 +38,9 @@ const generateDescription = (target, init) => default: description += '未知类型,请点击链接提交issue'; } - - return description; - }, init); + } + return description; +}; const generateData = (data) => data.map((item) => { diff --git a/lib/utils/camelcase-keys.ts b/lib/utils/camelcase-keys.ts index 9797d698e..ec67f5229 100644 --- a/lib/utils/camelcase-keys.ts +++ b/lib/utils/camelcase-keys.ts @@ -11,11 +11,12 @@ export const camelcaseKeys = (obj: any): T => { } if (isPlainObject(obj)) { - return Object.keys(obj).reduce((result: any, key) => { + const result: any = {}; + for (const key of Object.keys(obj)) { const nextKey = isMongoId(key) ? key : camelcase(key); result[nextKey] = camelcaseKeys(obj[key]); - return result; - }, {}) as any; + } + return result as any; } return obj;