set-yoho-data.js 2.57 KB
/**
 * 设置 YOHO 数据
 * @author: 赵彪<bill.zhao@yoho.cn>
 * @date: 2016/6/16
 */

'use strict';

const uuid = require('uuid');
const _ = require('lodash');
const config = global.yoho.config;
const helpers = global.yoho.helpers;
const logger = global.yoho.logger;

const _getGender = (channel) => {
    switch (channel) {
        case 'boys':
            return '1,3';
        case 'girls':
            return '2,3';
        default:
            return '1,2,3';
    }
};

const CHANNEL = {
    boys: 'boys',
    girls: 'girls',
    kids: 'kids',
    lifestyle: 'lifestyle'
};

const CHANNEL_NUM = {
    boys: 1,
    girls: 2,
    kids: 3,
    lifestyle: 4
};

module.exports = () => {
    return (req, res, next) => {
        let yoho = {
            pageChannel: {}
        };

        const channel = CHANNEL[req.query.channel || req.cookies._Channel] || CHANNEL.boys;

        if (req.query.channel) {
            req.query.channel = channel;
        }

        // 用于头部颜色控制
        yoho.pageChannel[channel] = true;

        // 当前频道设置
        yoho.channel = channel;

        // 当前频道数
        yoho.channelNum = CHANNEL_NUM[channel] || CHANNEL_NUM.boys;

        // 当前性别
        yoho.gender = _getGender(channel);

        yoho.isApp = req.query.app_version || req.query.appVersion;

        // client ip
        yoho.clientIp = (function() {
            let remoteIp = req.get('X-Forwarded-For') || req.get('X-Real-IP') || req.ip;
            let realIp = req.get('X-Real-IP');
            let forwardedIp = req.get('X-Forwarded-For');

            logger.info(`docker debug real ip: ${realIp}, x-forwarded-for ip: ${forwardedIp}, ip: ${req.ip}`);

            if (remoteIp.indexOf(',') > 0) {
                let arr = remoteIp.split(',');

                remoteIp = arr[arr.length - 1];
            }

            return _.trim(remoteIp);
        }());


        // uuid
        yoho.udid = (function() {
            let udid = req.cookies.udid;

            if (!udid) {
                udid = uuid.v4();

                if (res && res.cookie) {
                    res.cookie('udid', udid, {
                        domain: config.cookieDomain,
                        expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)
                    });
                }
            }

            req.cookies.udid = udid;

            return udid;
        }());

        if (!req.xhr) {
            yoho.mobileRefer = helpers.urlFormat(req.url, null, 'm');
        }

        Object.assign(res.locals, yoho);
        Object.assign(req.yoho, yoho);
        next();
    };
};