add 12306最新动态 (#1644)

closes #1642
This commit is contained in:
Chenyang Shi
2019-03-01 18:25:24 +08:00
committed by DIYgod
parent ea065e1fa6
commit aa96364422
3 changed files with 84 additions and 0 deletions

View File

@@ -3089,3 +3089,7 @@ type 为 all 时category 参数不支持 cost 和 free
<route name="推荐文章" author="WenryXu" example="/ui-cn/article" path="/ui-cn/article"/> <route name="推荐文章" author="WenryXu" example="/ui-cn/article" path="/ui-cn/article"/>
<route name="个人作品" author="WenryXu" example="/ui-cn/user/85974" path="/ui-cn/user/:id" :paramsDesc="['用户id']"/> <route name="个人作品" author="WenryXu" example="/ui-cn/user/85974" path="/ui-cn/user/:id" :paramsDesc="['用户id']"/>
### 12306
<route name="最新动态" author="LogicJake" example="/12306/zxdt" path="/12306/zxdt/:id?" :paramsDesc="['铁路局id可在 URL 中找到,不填默认显示所有铁路局动态']"/>

View File

@@ -1101,4 +1101,7 @@ router.get('/ui-cn/user/:id', require('./routes/ui-cn/user'));
// Dcard // Dcard
router.get('/dcard/posts/:type?', require('./routes/dcard/posts')); router.get('/dcard/posts/:type?', require('./routes/dcard/posts'));
// 12306
router.get('/12306/zxdt/:id?', require('./routes/12306/zxdt'));
module.exports = router; module.exports = router;

77
lib/routes/12306/zxdt.js Normal file
View File

@@ -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,
};
};