From f9b85f5742dd768c39c4c0c3fc59846c0a3ddb4e Mon Sep 17 00:00:00 2001 From: la3rence Date: Sat, 30 Aug 2025 07:48:42 +0800 Subject: [PATCH] feat(zaobao): replace art template with hono jsx (#19900) * feat(zaobao): replace art template with hono jsx * fix(lint): find funciton reference * refactor(zaobao): remove ctx parameter from parseList calls in handlers * fix: hk version * fix: rework interactive-graphics * fix: sg version * fix: update pubDate type to Date in parseList return type * fix: update host to origin in parseList for correct URL fetching --------- Co-authored-by: lawrence --- lib/routes/zaobao/interactive.ts | 25 +++- lib/routes/zaobao/other.ts | 5 +- lib/routes/zaobao/realtime.ts | 5 +- lib/routes/zaobao/templates/zaobao.art | 17 --- lib/routes/zaobao/util.ts | 198 ------------------------- lib/routes/zaobao/util.tsx | 185 +++++++++++++++++++++++ lib/routes/zaobao/zaobao.tsx | 23 +++ lib/routes/zaobao/znews.ts | 5 +- 8 files changed, 235 insertions(+), 228 deletions(-) delete mode 100644 lib/routes/zaobao/templates/zaobao.art delete mode 100644 lib/routes/zaobao/util.ts create mode 100644 lib/routes/zaobao/util.tsx create mode 100644 lib/routes/zaobao/zaobao.tsx diff --git a/lib/routes/zaobao/interactive.ts b/lib/routes/zaobao/interactive.ts index e2b3a624c..84ef1710f 100644 --- a/lib/routes/zaobao/interactive.ts +++ b/lib/routes/zaobao/interactive.ts @@ -1,6 +1,7 @@ import { Route } from '@/types'; -import { parseList } from './util'; -const baseUrl = 'https://www.zaobao.com'; +import { logo } from './util'; +import ofetch from '@/utils/ofetch'; +import { parseDate } from '@/utils/parse-date'; export const route: Route = { path: '/interactive-graphics', @@ -11,15 +12,25 @@ export const route: Route = { handler, }; -async function handler(ctx) { +async function handler() { + const baseUrl = 'https://www.zaobao.com.sg'; // SG Only const sectionLink = '/interactive-graphics'; - const { resultList } = await parseList(ctx, sectionLink); + const response = await ofetch(`${baseUrl}/_plat/api/v2/page-content/interactive-graphics`); + + const items = response.response.articles.map((i) => ({ + title: i.title, + description: i.summary, + link: new URL(i.href, baseUrl).href, + pubDate: parseDate(i.timestamp, 'X'), + image: i.thumbnail, + })); return { - title: '《联合早报》互动新闻', + title: response.seoMetaInfo.seoTitle, link: baseUrl + sectionLink, - description: '新加坡、中国、亚洲和国际的即时、评论、商业、体育、生活、科技与多媒体新闻,尽在联合早报。', - item: resultList, + description: response.seoMetaInfo.seoDescription, + image: logo, + item: items, }; } diff --git a/lib/routes/zaobao/other.ts b/lib/routes/zaobao/other.ts index 5bd482d43..44bbe867a 100644 --- a/lib/routes/zaobao/other.ts +++ b/lib/routes/zaobao/other.ts @@ -1,5 +1,5 @@ import { Route } from '@/types'; -import { parseList } from './util'; +import { logo, parseList } from './util'; const baseUrl = 'https://www.zaobao.com'; export const route: Route = { @@ -18,12 +18,13 @@ async function handler(ctx) { const section = ctx.req.param('section') ?? 'china'; const sectionLink = `/${type}/${section}`; - const { title, resultList } = await parseList(ctx, sectionLink); + const { title, resultList } = await parseList(sectionLink); return { title: `《联合早报》${title}`, link: baseUrl + sectionLink, description: '新加坡、中国、亚洲和国际的即时、评论、商业、体育、生活、科技与多媒体新闻,尽在联合早报。', + image: logo, item: resultList, }; } diff --git a/lib/routes/zaobao/realtime.ts b/lib/routes/zaobao/realtime.ts index 9c3761ed5..3c3799dc5 100644 --- a/lib/routes/zaobao/realtime.ts +++ b/lib/routes/zaobao/realtime.ts @@ -1,5 +1,5 @@ import { Route } from '@/types'; -import { parseList } from './util'; +import { logo, parseList } from './util'; const baseUrl = 'https://www.zaobao.com'; export const route: Route = { @@ -48,12 +48,13 @@ async function handler(ctx) { break; } - const { resultList } = await parseList(ctx, sectionLink); + const { resultList } = await parseList(sectionLink); return { title: `《联合早报》-${name}-即时`, link: baseUrl + sectionLink, description: '新加坡、中国、亚洲和国际的即时、评论、商业、体育、生活、科技与多媒体新闻,尽在联合早报。', + image: logo, item: resultList, }; } diff --git a/lib/routes/zaobao/templates/zaobao.art b/lib/routes/zaobao/templates/zaobao.art deleted file mode 100644 index b331fe3d5..000000000 --- a/lib/routes/zaobao/templates/zaobao.art +++ /dev/null @@ -1,17 +0,0 @@ -{{ each imageDataArray imageData }} - {{ if imageData.type == 'normalHTML' }} - {{@ imageData.html }} - {{ /if }} - {{ if imageData.type == 'data' }} -
- -
- {{ imageData.title }} -
-
- {{ /if }} -{{ /each }} - -{{ if articleBody }} - {{@ articleBody }} -{{ /if }} diff --git a/lib/routes/zaobao/util.ts b/lib/routes/zaobao/util.ts deleted file mode 100644 index 04f0d94c2..000000000 --- a/lib/routes/zaobao/util.ts +++ /dev/null @@ -1,198 +0,0 @@ -import cache from '@/utils/cache'; -import got from '@/utils/got'; -import { load } from 'cheerio'; -import { parseRelativeDate } from '@/utils/parse-date'; -import timezone from '@/utils/timezone'; -import { art } from '@/utils/render'; -import path from 'node:path'; -import { base32 } from 'rfc4648'; - -const baseUrl = 'https://www.zaobao.com'; -const got_ins = got.extend({ - headers: { - Referer: baseUrl, - }, -}); - -/** - * 通用解析页面类似 https://www.zaobao.com/realtime/china 的网站 - * - * @param {*} ctx RSSHub 的 ctx 参数,用来设置缓存 - * @param {string} sectionUrl 形如 /realtime/china 的字符串 - * @returns 新闻标题以及新闻列表 - */ -const parseList = async ( - ctx, - sectionUrl: string -): Promise<{ - title: string; - resultList: { - title: string; - description: string; - pubDate: string; - link: string; - }[]; -}> => { - const response = await got_ins.get(baseUrl + sectionUrl); - const $ = load(response.data); - let data = $('.card-listing .card .content-header a'); - if (data.length === 0) { - // for HK version - data = $('[data-testid="article-list"] article a.article-link'); - } - - const title = $('meta[property="og:title"]').attr('content'); - - const resultList = await Promise.all( - data.toArray().map((item) => { - const $item = $(item); - // addBack: for HK version - let link = $item.attr('href'); - - if (link[0] !== '/') { - // https://www.zaobao.com/interactive-graphics - const title = $item.find('a').text(); - let dateNodes = $item.find('.meta-published-date'); - if (dateNodes.length === 0) { - dateNodes = $item.find('.datestamp'); - } - let dateString; - let pubDate; - if (dateNodes.length !== 0) { - dateString = dateNodes.text().trim(); - const dateParts = dateString.split('/'); - dateParts.reverse(); - dateString = dateParts.join('-'); - pubDate = parseRelativeDate(dateString); - // if conversion was no success, pubDate === dateString - // zaobao seems always UTC+8 - pubDate = pubDate === dateString ? undefined : timezone(pubDate, +8); - } - - return { - title, - description: title, - pubDate, - link, - }; - } - - link = baseUrl + link; - - return cache.tryGet(link, async () => { - const article = await got_ins.get(link); - const $1 = load(article.data); - - let title, time; - if ($1('#seo-article-page').text() === '') { - // HK - title = $1('h1.article-title').text(); - const jsonText = $1("head script[type='application/ld+json']") - .eq(0) - .text() - .replaceAll(/[\u0000-\u001F\u007F-\u009F]/g, ''); - time = new Date(JSON.parse(jsonText)?.datePublished); - } else { - // SG - const jsonText = $1('#seo-article-page') - .text() - .replaceAll(/[\u0000-\u001F\u007F-\u009F]/g, ''); - const json = JSON.parse(jsonText); - title = json['@graph'][0]?.headline; - time = new Date(json['@graph'][0]?.datePublished); - } - - $1('.overlay-microtransaction').remove(); - $1('#video-freemium-player').remove(); - $1('script').remove(); - $1('.bff-google-ad').remove(); - $1('.bff-recommend-article').remove(); - - let articleBodyNode = $1('.articleBody'); - if (articleBodyNode.length === 0) { - // for HK version - $1('.read-on-app-cover').remove(); - $1('astro-island').remove(); - $1('.further-reading').remove(); - articleBodyNode = $1('.article-body'); - } - - const articleBody = articleBodyNode.html(); - - const imageDataArray = processImageData($1); - - return { - // <- for HK version -> for SG version - title, - description: art(path.join(__dirname, 'templates/zaobao.art'), { - articleBody, - imageDataArray, - }), - pubDate: time, - link, - }; - }); - }) - ); - return { - title, - resultList, - }; -}; - -const orderContent = (parent) => { - for (const [i, e] of parent - .children() - .toArray() - .sort((a, b) => { - const index = Buffer.from(base32.parse('GM======')).toString(); // substring(3) - a = Buffer.from(base32.parse(parent.find(a).data('s').slice(index))).toString(); - b = Buffer.from(base32.parse(parent.find(b).data('s').slice(index))).toString(); - return a - b; - }) - .entries()) { - parent.find(e).attr('s', i); - parent.append(e); - } -}; - -interface ImageData { - type: string; - html: string; - src?: string; - title?: string; -} - -const processImageData = ($1) => { - const imageDataArray: ImageData[] = []; - - const imageSelectors = [ - '.inline-figure-img', // for SG version - '.body-content .loadme picture img', // Unused? - '.inline-figure-gallery', // for SG version - '#carousel-article', // for HK version, HK version of multi images use same selector as single image, so g is needed for all pages - ]; - - for (const selector of imageSelectors) { - if ($1(selector).length) { - let html = $1(selector === '#carousel-article' ? '#carousel-article .carousel-inner' : selector).html(); - - if (html) { - html = html.replaceAll(/\/\/.*\.com\/s3fs-public/g, '//static.zaobao.com/s3fs-public').replaceAll('s3/files', 's3fs-public'); - - imageDataArray.push({ - type: selector === '.body-content .loadme picture img' ? 'data' : 'normalHTML', - html, - ...(selector === '.body-content .loadme picture img' && { - src: $1('.body-content .loadme picture source').attr('data-srcset'), - title: $1(selector).attr('title'), - }), - }); - } - } - } - - return imageDataArray; -}; - -export { parseList, orderContent }; diff --git a/lib/routes/zaobao/util.tsx b/lib/routes/zaobao/util.tsx new file mode 100644 index 000000000..808e61c66 --- /dev/null +++ b/lib/routes/zaobao/util.tsx @@ -0,0 +1,185 @@ +import cache from '@/utils/cache'; +import ofetch from '@/utils/ofetch'; +import { load } from 'cheerio'; +import { parseDate } from '@/utils/parse-date'; +import { renderToString } from 'hono/jsx/dom/server'; +import { base32 } from 'rfc4648'; +import Zaobao from './zaobao'; + +const baseUrl = 'https://www.zaobao.com'; +export const logo = 'https://www.zaobao.com.sg/favicon.ico'; + +/** + * 通用解析页面类似 https://www.zaobao.com/realtime/china 的网站 + * + * @param {string} sectionUrl 形如 /realtime/china 的字符串 + * @returns 新闻标题以及新闻列表 + */ +export const parseList = async ( + sectionUrl: string +): Promise<{ + title: string; + resultList: { + title: string; + description: string; + pubDate: Date; + link: string; + category: string[]; + }[]; +}> => { + const pageResponse = await ofetch.raw(baseUrl + sectionUrl); + const $ = load(pageResponse._data); + let data = $('.card-listing .card .content-header a'); + if (data.length === 0) { + // for HK version + data = $('[data-testid="article-list"] article div div a.article-link'); + } + const origin = new URL(pageResponse.url).origin; + + const title = $('meta[property="og:title"]').attr('content'); + + const resultList = await Promise.all( + data.toArray().map((item) => { + const $item = $(item); + const link = baseUrl + $item.attr('href'); + + return cache.tryGet(link, async () => { + const response = await ofetch.raw(origin + $item.attr('href')); + let $1 = load(response._data); + + let title, pubDate, category, images; + const jsonText = $1('head script[type="application/ld+json"]') + .text() + .replaceAll(/[\u0000-\u001F\u007F-\u009F]/g, ''); + const ldJson = JSON.parse(jsonText); + + const isSingapore = response.url.startsWith('https://www.zaobao.com.sg/'); + if (isSingapore) { + const hydrationData = JSON.parse( + JSON.parse( + `"${ + $1('script:contains("__staticRouterHydrationData")') + .text() + .match(/__staticRouterHydrationData = JSON.parse\("(.*)"\);/)?.[1] + }"` + ) + ); + const article = hydrationData.loaderData['0-0'].context.payload.article; + title = article.headline; + pubDate = parseDate(article.create_time, 'X'); + category = article.tags.map((t) => t.name); + $1 = load(article.body_cn, null, false); + images = article.images; + } else { + title = ldJson.headline; + pubDate = parseDate(ldJson.datePublished); + category = ldJson.keywords.split(','); + } + + // $1('.overlay-microtransaction').remove(); + // $1('#video-freemium-player').remove(); + $1('.bff-google-ad, .bff-recommend-article').remove(); // SG + $1('button.cursor-pointer').remove(); // SG + $1('.bff-inline-image-expand-icon').remove(); // SG + $1('img[alt="expend icon"]').remove(); // HK + + let articleBodyNode; + if (isSingapore) { + articleBodyNode = $1; + } else { + // for HK version + $1('astro-island, .further-reading, .read-on-app-cover').remove(); + articleBodyNode = $1('.article-body'); + } + + const articleBody = articleBodyNode.html(); + const imageDataArray = processImageData(isSingapore, images, $1); + + // use JSX as template + const dom = ; + const description = renderToString(dom); + + return { + title, + description, + pubDate, + link, + category, + }; + }); + }) + ); + return { + title, + resultList, + }; +}; + +export const orderContent = (parent) => { + for (const [i, e] of parent + .children() + .toArray() + .sort((a, b) => { + const index = Buffer.from(base32.parse('GM======')).toString(); // substring(3) + a = Buffer.from( + base32.parse( + parent + .find((element) => a(element)) + .data('s') + .slice(index) + ) + ).toString(); + b = Buffer.from( + base32.parse( + parent + .find((element) => b(element)) + .data('s') + .slice(index) + ) + ).toString(); + return a - b; + }) + .entries()) { + parent.find((element) => e(element)).attr('s', i); + parent.append(e); + } +}; + +export interface ImageData { + type: string; + html: string; + src?: string; + title?: string; +} + +const processImageData = (isSg, images, $1) => { + if (isSg && images) { + return images.map((img) => ({ + type: 'data', + html: '', + src: img.url + .replaceAll(/\/\/.*\.com\/s3fs-public/g, '//static.zaobao.com/s3fs-public') + .replaceAll('s3/files', 's3fs-public') + .split('?')[0], + title: img.caption, + })) as ImageData[]; + } + + const hkImg = $1('[data-testid="article-banner"] img'); + if (hkImg.length) { + return [ + { + type: 'data', + html: hkImg.prop('outerHTML'), + src: hkImg + .attr('src') + .replaceAll(/\/\/.*\.com\/s3fs-public/g, '//static.zaobao.com/s3fs-public') + .replaceAll('s3/files', 's3fs-public') + .split('?')[0], + title: hkImg.attr('title'), + }, + ] as ImageData[]; + } + + return []; +}; diff --git a/lib/routes/zaobao/zaobao.tsx b/lib/routes/zaobao/zaobao.tsx new file mode 100644 index 000000000..35575a8db --- /dev/null +++ b/lib/routes/zaobao/zaobao.tsx @@ -0,0 +1,23 @@ +import { ImageData } from './util'; + +function zaobao({ imageDataArray, articleBody }) { + return ( + <> + {imageDataArray.map((imageData: ImageData) => + imageData.type === 'normalHTML' ? ( +
+ ) : ( + imageData.type === 'data' && ( +
+ +
{imageData.title}
+
+ ) + ) + )} + {articleBody &&
} + + ); +} + +export default zaobao; diff --git a/lib/routes/zaobao/znews.ts b/lib/routes/zaobao/znews.ts index 7aa4daa09..c1c51a71f 100644 --- a/lib/routes/zaobao/znews.ts +++ b/lib/routes/zaobao/znews.ts @@ -1,5 +1,5 @@ import { Route } from '@/types'; -import { parseList } from './util'; +import { logo, parseList } from './util'; const baseUrl = 'https://www.zaobao.com'; export const route: Route = { @@ -60,12 +60,13 @@ async function handler(ctx) { sectionLink = '/news/china'; } - const { resultList } = await parseList(ctx, sectionLink); + const { resultList } = await parseList(sectionLink); return { title: `《联合早报》-${info}-新闻`, link: baseUrl + sectionLink, description: '新加坡、中国、亚洲和国际的即时、评论、商业、体育、生活、科技与多媒体新闻,尽在联合早报。', + image: logo, item: resultList, }; }