diff --git a/docs/README.md b/docs/README.md index 36376b98b8..fdb5ba304f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3089,3 +3089,7 @@ type 为 all 时,category 参数不支持 cost 和 free + +### 12306 + + diff --git a/lib/router.js b/lib/router.js index 56b4ee220b..3c02c54786 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1101,4 +1101,7 @@ router.get('/ui-cn/user/:id', require('./routes/ui-cn/user')); // Dcard router.get('/dcard/posts/:type?', require('./routes/dcard/posts')); +// 12306 +router.get('/12306/zxdt/:id?', require('./routes/12306/zxdt')); + module.exports = router; diff --git a/lib/routes/12306/zxdt.js b/lib/routes/12306/zxdt.js new file mode 100644 index 0000000000..49e0162b2a --- /dev/null +++ b/lib/routes/12306/zxdt.js @@ -0,0 +1,77 @@ +const axios = require('../../utils/axios'); +const cheerio = require('cheerio'); +const url = require('url'); + +module.exports = async (ctx) => { + const id = ctx.params.id || -1; + + let link; + if (id === -1) { + link = 'https://www.12306.cn/mormhweb/zxdt/index_zxdt.html'; + } else { + link = `https://www.12306.cn/mormhweb/1/${id}/index_fl.html`; + } + + const response = await axios.get(link); + const data = response.data; + const $ = cheerio.load(data); + const name = $('div.nav_center > a:nth-child(4)').text(); + + const list = $('#newList > ul > li') + .slice(0, 10) + .map(function() { + const info = { + title: $(this) + .find('a') + .text(), + link: $(this) + .find('a') + .attr('href'), + date: $(this) + .find('span') + .text() + .slice(1, -1), + }; + return info; + }) + .get(); + + const out = await Promise.all( + list.map(async (info) => { + const title = info.title; + const date = info.date; + const itemUrl = url.resolve(link, info.link); + + const cache = await ctx.cache.get(itemUrl); + if (cache) { + return Promise.resolve(JSON.parse(cache)); + } + + const response = await axios.get(itemUrl); + const $ = cheerio.load(response.data); + let description = $('.article-box').html(); + if (description) { + description = description.replace(/src="/g, `src="${url.resolve(itemUrl, '.')}`).trim(); + } else { + description = $('.content_text') + .html() + .trim(); + } + + const single = { + title: title, + link: itemUrl, + description: description, + pubDate: new Date(date).toUTCString(), + }; + ctx.cache.set(itemUrl, JSON.stringify(single), 24 * 60 * 60); + return Promise.resolve(single); + }) + ); + + ctx.state.data = { + title: `${name}最新动态`, + link: link, + item: out, + }; +};