|
| 1 | +import { Route, ViewType } from '@/types'; |
| 2 | +import ofetch from '@/utils/ofetch'; |
| 3 | +import { load } from 'cheerio'; |
| 4 | +import { parseDate } from '@/utils/parse-date'; |
| 5 | +import timezone from '@/utils/timezone'; |
| 6 | +import { isValidHost } from '@/utils/valid-host'; |
| 7 | +import InvalidParameterError from '@/errors/types/invalid-parameter'; |
| 8 | + |
| 9 | +import MarkdownIt from 'markdown-it'; |
| 10 | +const md = MarkdownIt({ |
| 11 | + html: true, |
| 12 | +}); |
| 13 | + |
| 14 | +export const route: Route = { |
| 15 | + path: '/posts/:site', |
| 16 | + categories: ['blog'], |
| 17 | + example: '/posts/walnut', |
| 18 | + parameters: { site: '站点名,原则上只要是 `{site}.hedwig.pub` 都可以匹配' }, |
| 19 | + features: { |
| 20 | + supportRadar: false, |
| 21 | + }, |
| 22 | + name: 'Posts', |
| 23 | + url: 'hedwig.pub', |
| 24 | + maintainers: ['zwithz', 'GetToSet'], |
| 25 | + view: ViewType.Articles, |
| 26 | + handler: async (ctx) => { |
| 27 | + const { site } = ctx.req.param(); |
| 28 | + |
| 29 | + if (!isValidHost(site)) { |
| 30 | + throw new InvalidParameterError('Invalid site'); |
| 31 | + } |
| 32 | + |
| 33 | + const baseUrl = `https://${site}.hedwig.pub`; |
| 34 | + |
| 35 | + const response = await ofetch(baseUrl); |
| 36 | + const $ = load(response); |
| 37 | + |
| 38 | + const text = $('script#__NEXT_DATA__').text(); |
| 39 | + const json = JSON.parse(text); |
| 40 | + |
| 41 | + const pageProps = json.props.pageProps; |
| 42 | + |
| 43 | + const list = pageProps.issuesByNewsletter.map((item) => { |
| 44 | + const description = item.blocks.reduce((desc, block) => desc + md.render(block.markdown.text), ''); |
| 45 | + return { |
| 46 | + title: item.subject, |
| 47 | + description, |
| 48 | + pubDate: timezone(parseDate(item.publishAt, 'YYYY-MM-DDTHH:mm:ss.SSS[Z]'), +0), |
| 49 | + link: `${baseUrl}/i/${item.urlFriendlyName}`, |
| 50 | + }; |
| 51 | + }); |
| 52 | + |
| 53 | + return { |
| 54 | + title: pageProps.newsletter.name, |
| 55 | + description: pageProps.newsletter.about, |
| 56 | + link: baseUrl, |
| 57 | + item: list, |
| 58 | + }; |
| 59 | + }, |
| 60 | +}; |
0 commit comments