fix(route/tfc-taiwan): rework route (#18930)

This commit is contained in:
Tony
2025-04-23 23:37:20 +08:00
committed by GitHub
parent df320988d0
commit 2650ecc1dc
6 changed files with 105 additions and 108 deletions
+53
View File
@@ -0,0 +1,53 @@
import { Route } from '@/types';
import ofetch from '@/utils/ofetch';
import { baseUrl, parsePost, parseItem } from './utils';
import InvalidParameterError from '@/errors/types/invalid-parameter';
const handler = async (ctx) => {
const { category } = ctx.req.param();
const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit'), 10) : undefined;
const isNumericCategory = !Number.isNaN(Number.parseInt(category, 10));
const categoryResponse = await ofetch(`${baseUrl}/wp-json/wp/v2/categories${isNumericCategory ? `/${category}` : ''}`, {
query: {
slug: isNumericCategory ? undefined : category,
},
});
if (Array.isArray(categoryResponse) && !categoryResponse.length) {
throw new InvalidParameterError(`Category "${category}" not found`);
}
const categoryInfo = isNumericCategory ? categoryResponse : categoryResponse[0];
if (!categoryInfo.id) {
throw new InvalidParameterError(`Category "${category}" not found`);
}
const postsResponse = await parsePost(limit, categoryInfo.id);
const items = parseItem(postsResponse);
return {
title: categoryInfo.yoast_head_json.title,
description: categoryInfo.yoast_head_json.og_site_name,
image: categoryInfo.yoast_head_json.og_image[0].url,
logo: categoryInfo.yoast_head_json.og_image[0].url,
icon: categoryInfo.yoast_head_json.og_image[0].url,
link: categoryInfo.link,
lang: 'zh-TW',
item: items,
};
};
export const route: Route = {
name: '分類',
maintainers: ['TonyRL'],
example: '/tfc-taiwan/category/weekly-top-ten-rumors',
path: '/category/:category',
parameters: {
category: '分類,見下表,預設為 `weekly-top-ten-rumors`',
},
handler,
url: 'tfc-taiwan.org.tw/category/rumor-mill/',
description: `| 謠言風向球 | 議題觀察室 | TOP10 | 名家專欄 | 國際視野 |
| ---------- | ----------------- | --------------------- | -------------- | -------------------- |
| rumor-mill | issue-observatory | weekly-top-ten-rumors | expert-columns | research-and-updates |`,
};
-38
View File
@@ -1,38 +0,0 @@
import cache from '@/utils/cache';
import got from '@/utils/got';
import { load } from 'cheerio';
import { baseUrl, parseList, parseItems } from './utils';
import { getSubPath } from '@/utils/common-utils';
export async function handler(ctx) {
const requestPath = getSubPath(ctx);
const isTopic = requestPath.startsWith('/topic/');
let link = baseUrl;
if (isTopic) {
link += `/topic/${ctx.req.param('id')}`;
} else if (requestPath === '/') {
link += `/articles/report`;
} else {
link += `/articles${requestPath}`;
}
const { data: response } = await got(link);
const $ = load(response);
const list = $(`${isTopic ? '.view-grouping' : '.pane-clone-of-article'} .views-row-inner`)
.toArray()
.map((item) => parseList($(item)));
const items = await parseItems(list, cache.tryGet);
return {
title: $('head title').text(),
description: $('head meta[name="description"]').attr('content'),
image: $('head meta[property="og:image"]').attr('content'),
logo: $('head link[rel="shortcut icon"]').attr('href'),
icon: $('head link[rel="shortcut icon"]').attr('href'),
link,
item: items,
};
}
+26 -10
View File
@@ -1,17 +1,33 @@
import { Route } from '@/types';
import { handler } from './common';
import ofetch from '@/utils/ofetch';
import { baseUrl, parsePost, parseItem } from './utils';
const handler = async (ctx) => {
const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit'), 10) : undefined;
const pageResponse = await ofetch(`${baseUrl}/wp-json/wp/v2/pages/89173`);
const postsResponse = await parsePost(limit, undefined);
const pageInfo = pageResponse.yoast_head_json;
const items = parseItem(postsResponse);
return {
title: pageInfo.title,
description: pageInfo.og_site_name,
image: pageInfo.og_image[0].url,
logo: pageInfo.og_image[0].url,
icon: pageInfo.og_image[0].url,
link: pageInfo.canonical,
lang: 'zh-TW',
item: items,
};
};
export const route: Route = {
name: '最新相關資訊 / 最新查核報告',
name: '最新查核報告',
maintainers: ['TonyRL'],
example: '/tfc-taiwan',
path: '/:type?',
parameters: {
type: '分類,見下表,預設為 `report`',
},
path: '/',
handler,
url: 'tfc-taiwan.org.tw/articles/report',
description: `| 最新相關資訊 | 最新查核報告 |
| ------------ | ------------ |
| info | report |`,
url: 'tfc-taiwan.org.tw/latest-news/',
};
+4 -1
View File
@@ -1,7 +1,10 @@
import type { Namespace } from '@/types';
export const namespace: Namespace = {
name: '台灣事實查核中心',
name: 'Taiwan FactCheck Center',
url: 'tfc-taiwan.org.tw',
lang: 'zh-TW',
'zh-TW': {
name: '台灣事實查核中心',
},
};
-17
View File
@@ -1,17 +0,0 @@
import { Route } from '@/types';
import { handler } from './common';
export const route: Route = {
name: '專題 / 重點專區',
maintainers: ['TonyRL'],
example: '/tfc-taiwan/category/242',
path: '/:type/:id{.+}',
parameters: {
type: '分類,見下表,預設為 `report`',
},
handler,
url: 'tfc-taiwan.org.tw/articles/report',
description: `| 專題 | 重點專區 |
| -------- | -------- |
| category | topic |`,
};
+22 -42
View File
@@ -1,47 +1,27 @@
import got from '@/utils/got';
import { load } from 'cheerio';
import path from 'node:path';
import { art } from '@/utils/render';
import pMap from 'p-map';
import ofetch from '@/utils/ofetch';
import { parseDate } from '@/utils/parse-date';
import cache from '@/utils/cache';
const baseUrl = 'https://tfc-taiwan.org.tw';
export const baseUrl = 'https://tfc-taiwan.org.tw';
const parseList = (item) => {
const a = item.find('.entity-list-title a');
return {
title: a.text(),
description: item.find('.entity-list-body').text(),
link: new URL(a.attr('href'), baseUrl).href,
pubDate: item.find('.post-date').length ? parseDate(item.find('.post-date').text(), 'YYYY-MM-DD') : undefined,
image: item.find('.entity-list-img img').attr('src').split('?')[0],
};
};
export const parseItem = (postsResponse) =>
postsResponse.map((item) => ({
title: item.title.rendered,
pubDate: parseDate(item.date_gmt),
updated: parseDate(item.modified_gmt),
link: item.link,
description: item.content.rendered,
image: item.yoast_head_json.og_image[0].url,
author: item.author_info.display_name,
category: item.category_info.map((cat) => cat.name),
}));
const parseItems = (list, tryGet) =>
pMap(
list,
(item) =>
tryGet(item.link, async () => {
const { data: response } = await got(item.link);
const $ = load(response);
$('.field-name-field-addthis, #fb-root, .fb-comments, .likecoin-embed, style[type="text/css"]').remove();
item.description = art(path.join(__dirname, 'templates/article.art'), {
headerImage: item.image,
content: $('#block-system-main .node-content').html(),
});
item.pubDate = $('meta[property="article:published_time"]').attr('content');
item.updated = $('meta[property="article:modified_time"]').attr('content');
item.category = $('.node-tags .field-item')
.toArray()
.map((item) => $(item).text());
return item;
}),
{ concurrency: 10 }
export const parsePost = (limit, categoryId) =>
cache.tryGet(`tfc-taiwan:posts:${categoryId ?? 'latest'}:${limit ?? 10}`, () =>
ofetch(`${baseUrl}/wp-json/wp/v2/posts`, {
query: {
categories: categoryId,
per_page: limit,
},
})
);
export { baseUrl, parseList, parseItems };