|
1 | 1 | import { load } from 'cheerio'
|
2 |
| -import { IMediaMiddleware } from '../types' |
| 2 | +import { IMediaMiddleware, IMediaContext } from '../types' |
3 | 3 | import { fetchText } from 'utils/http'
|
4 | 4 | import { MEDIA_USER_AGENT } from 'constants/http'
|
5 | 5 |
|
| 6 | +const parseTitle = ($: CheerioStatic) => |
| 7 | + $('title') |
| 8 | + .text() |
| 9 | + .trim() |
| 10 | + |
| 11 | +/** Prefer non-ico icons. */ |
| 12 | +const sortIcons = (a: CheerioElement, b: CheerioElement) => { |
| 13 | + const aIco = a.attribs.href.includes('.ico') |
| 14 | + const bIco = b.attribs.href.includes('.ico') |
| 15 | + |
| 16 | + if (aIco && !bIco) return 1 |
| 17 | + if (!aIco && bIco) return -1 |
| 18 | + return 0 |
| 19 | +} |
| 20 | + |
| 21 | +const parseFavicon = (ctx: IMediaContext, $: CheerioStatic) => { |
| 22 | + const icons = Array.from($('head link')).filter(icon => { |
| 23 | + const rel = new Set((icon.attribs.rel || '').split(' ')) |
| 24 | + if (!rel.has('icon')) return false |
| 25 | + return true |
| 26 | + }) |
| 27 | + |
| 28 | + if (icons.length === 0) return |
| 29 | + |
| 30 | + icons.sort(sortIcons) |
| 31 | + |
| 32 | + const icon = icons[0] |
| 33 | + let url |
| 34 | + |
| 35 | + try { |
| 36 | + url = new URL(icon.attribs.href).href |
| 37 | + } catch {} |
| 38 | + |
| 39 | + if (!url) { |
| 40 | + try { |
| 41 | + url = new URL(`${ctx.req.url.origin}${icon.attribs.href}`).href |
| 42 | + } catch {} |
| 43 | + } |
| 44 | + |
| 45 | + return url |
| 46 | +} |
| 47 | + |
6 | 48 | const mware: IMediaMiddleware = {
|
7 | 49 | match({ protocol }) {
|
8 | 50 | return protocol === 'http:' || protocol === 'https:'
|
@@ -35,8 +77,12 @@ const mware: IMediaMiddleware = {
|
35 | 77 | ctx.state.body = text
|
36 | 78 | const $ = (ctx.state.$ = load(text))
|
37 | 79 |
|
38 |
| - // prettier-ignore |
39 |
| - ctx.res.title = $('title').text().trim() || ctx.res.title |
| 80 | + try { |
| 81 | + ctx.res.title = parseTitle($) || ctx.res.title |
| 82 | + ctx.res.favicon = parseFavicon(ctx, $) |
| 83 | + } catch (e) { |
| 84 | + console.error(e) |
| 85 | + } |
40 | 86 |
|
41 | 87 | return next()
|
42 | 88 | }
|
|
0 commit comments