From 1a6c47a4897cdec4301ea68cee0b2481bf41557d Mon Sep 17 00:00:00 2001 From: junfengP <840282629@qq.com> Date: Sun, 2 Feb 2020 18:11:00 +0800 Subject: [PATCH] feat: support discuz 7.x (#3861) --- lib/routes/discuz/discuz.js | 90 ++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 17 deletions(-) diff --git a/lib/routes/discuz/discuz.js b/lib/routes/discuz/discuz.js index fa27cc5328..0e82bf370f 100644 --- a/lib/routes/discuz/discuz.js +++ b/lib/routes/discuz/discuz.js @@ -1,21 +1,77 @@ -const buildData = require('@/utils/common-config'); +const got = require('@/utils/got'); +const cheerio = require('cheerio'); +const iconv = require('iconv-lite'); +const dateUtil = require('@/utils/date'); module.exports = async (ctx) => { let link = ctx.params.link; link = link.replace(/:\/\//, ':/').replace(/:\//, '://'); - ctx.state.data = await buildData({ - link, - url: link, - title: `%title%`, - params: { - title: `$('head > title').text()`, - }, - item: { - item: 'tbody[id^="normalthread"] tr', - title: `$('a.xst').text()`, - link: `$('a.xst').attr('href')`, - description: `$('a.xst').text()`, - pubDate: `require('@/utils/date')($('td.by:nth-child(3) em span').last().text())`, - guid: `$('a.xst').attr('href')`, - }, - }); + + const response = await got.get(link); + const contentType = response.headers['content-type'] || ''; + // 若没有指定编码,则默认utf-8 + let charset = 'utf-8'; + for (const attr of contentType.split(';')) { + if (attr.indexOf('charset=') >= 0) { + charset = attr.split('=').pop(); + } + } + const responseData = charset === 'utf-8' ? response.data : iconv.decode((await got.get({ url: link, responseType: 'buffer' })).data, charset); + const $ = cheerio.load(responseData); + if ( + $('div#footer p em') + .text() + .startsWith('7') + ) { + // discuz 7.x 系列 + const list = $('tbody[id^="normalthread"] tr'); + ctx.state.data = { + title: $('head > title').text(), + link: link, + item: + list && + list + .map((index, item) => { + item = $(item); + return { + title: item.find('span[id^=thread] a').text(), + description: item.find('span[id^=thread] a').text(), + link: item.find('span[id^=thread] a').attr('href'), + pubDate: dateUtil(item.find('td.author em').text()), + }; + }) + .get(), + }; + } else if ( + $('div#frt p em') + .text() + .toUpperCase() + .startsWith('X') + ) { + // discuz X 系列 + const list = $('tbody[id^="normalthread"] tr'); + ctx.state.data = { + title: $('head > title').text(), + link: link, + item: + list && + list + .map((index, item) => { + item = $(item); + return { + title: item.find('a.xst').text(), + description: item.find('a.xst').text(), + link: item.find('a.xst').attr('href'), + pubDate: dateUtil( + item + .find('td.by:nth-child(3) em span') + .last() + .text() + ), + }; + }) + .get(), + }; + } else { + throw Error('不支持当前Discuz版本.'); + } };