rss.js 2.44 KB
/**
 * 逛rss订阅
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 2016/09/13
 */
'use strict';

const mRoot = '../models';
const RssModel = require(`${mRoot}/rss`);
const Feed = require('feed');
const _ = require('lodash');
const moment = require('moment');

/**
 * [订阅逛最新的资讯]
 */
const index = (req, res, next) => {
    let gender = req.query.gender || '1,2,3';

    return req.ctx(RssModel).getRssArticle(gender).then((result) => {
        if (!result) {
            return next();
        }
        res.setHeader('Content-Type', 'text/xml; charset=utf-8');
        let feed = new Feed({
            id: 'http://yohobuy.com',
            title: '有货逛',
            description: 'Yoho!Buy有货 | 年轻人潮流购物中心',
            link: 'http://yohobuy.com',
            copyright: '2015 yoho.inc',
            generator: 'http://m.yohobuy.com',
            updated: new Date(),
        });

        _.forEach(result, item => {
            feed.addItem({
                title: item.title,
                link: `https://m.yohobuy.com/guang/${item.id}.html?ref=rss`,
                description: item.intro,
                author: [{
                    name: (item.author && item.author.name) || ' '
                }],
                date: new Date(item.publishTimeLong &&
                    parseFloat(item.publishTimeLong) || moment(item.publishTime, 'MM月DD日 HH:mm'))
            });
        });
        if (req.params[0] && req.params[0] === '/atom') {
            return res.send(feed.atom1());
        }
        return res.send(feed.rss2());
    }).catch(next);
};
const rss = (req, res, next, gmt) => {
    let gender = req.query.gender || '1,2,3';

    res.setHeader('Content-Type', 'text/xml; charset=utf-8');
    return req.ctx(RssModel).getRssArticle(gender).then((result) => {
        if (!result) {
            return next();
        }
        _.forEach(result, item => {
            item.url = `https://m.yohobuy.com/guang/${item.id}.html?ref=rss`;
            let time = new Date(item.publishTimeLong &&
                parseFloat(item.publishTimeLong) || moment(item.publishTime, 'MM月DD日 HH:mm'));
            let format = gmt ? 'ddd, MM MMM YYYY hh:mm:ss +0800' : 'YYYY-MM-DD hh:mm:ss +0800';

            item.publishTime = moment(time).format(format);
        });
        return res.render('rss/index', {
            layout: false,
            items: result
        });
    }).catch(next);
};

module.exports = {
    index,
    rss
};