rss.js 2.55 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 helpers = global.yoho.helpers;

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

    return rssModel.getRssArticle(gender).then((result) => {
        if (!result) {
            return next();
        }
        res.setHeader('Content-Type', 'text/xml; charset=utf-8');
        var 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 => {
            item.url = item.url.indexOf('http') >= 0 ? item.url : 'http://' + item.url;
            feed.addItem({
                title: item.title,
                link: `${item.url}&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.render('atom-1.0'));
        }
        return res.send(feed.render('rss-2.0'));
    }).catch(next);
};
const rss = (req, res, next, gmt) => {
    let gender = req.query.gender || '1,2,3',
        items = [];

    res.setHeader('Content-Type', 'text/xml; charset=utf-8');
    return rssModel.getRssArticle(gender).then((result) => {
        if (!result) {
            return next();
        }
        _.forEach(result, item => {
            item.url = item.url.indexOf('http') >= 0 ? item.url : 'http://' + item.url;
            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
};