index.js 5.04 KB
const cheerio = require('cheerio');
const superAgent = require('superagent');
const NO_MAGAZINE_ID = '无效的电子刊编号'; // 没有杂志id
const READ_MAGAZINE_URL_ERROR = '电子刊内容读取失败,请重试'; // superagent抓取页面内容失败
const NO_HYPE_CONTAINER_ID = '电子刊格式错误!'; // 找不到hype_container的id
const NO_HYPE_SCRIPT = '无效的电子刊内容!'; // 找不到hype_script
const WRONG_INVIROMENT = '电子刊获取失败!'; // 不在有货app也不在小程序中打开的时候提示
const ERROR_MSG = {
    4001: '您未购买该电子刊',
    4002: '未获取到电子刊信息',
    4003: '该电子刊已被删除'
};

const headerModel = require('../../../doraemon/models/header');
const indexModel = require('../models/index');

/**
 * 获取到杂志的url之后使用superAgent读取html内容并进行处理后输出
 * @param req
 * @param res
 * @param next
 */
const index = async function(req, res, next) {

    let userAgent = req.get('User-Agent');
    let {test, uid, app_version, app_client_type, session_key, e_id} = req.query;
    let isMiniApp = /miniprogram/i.test(userAgent) || false;
    let isApp = /yohobuy/i.test(userAgent) || false;
    let appSessionType = app_client_type || 'h5';

    /**
     * 用于渲染错误结果页面
     * @param result
     * @returns {*}
     */
    function renderErroPage(result) {
        return res.render('index/error', {
            pageHeader: headerModel.setNav({
                navTitle: false,
                navBtn: false
            }),
            module: 'magazine',
            page: 'error',
            title: '错误提示',
            localCss: true,
            result: result
        });
    }

    // 如果不在小程序或app中打开则返回
    if (!isMiniApp && !isApp) {
        if (!test) {
            return renderErroPage({msg: WRONG_INVIROMENT});
        }
    }

    // 没有杂志id,返回
    if (!e_id) {
        return renderErroPage({msg: NO_MAGAZINE_ID});
    }

    if (isMiniApp) {
        appSessionType = 'miniapp';
    } else if (isApp) {
        if (/i(phone|pad|pod)/i.test(userAgent)) {
            appSessionType = 'iphone';
        } else {
            appSessionType = 'android';
        }
    }

    let user_id = {};

    // 查看session中是否有登录信息
    if (req.user.uid) {
        user_id = {
            toString: () => {
                return req.user.uid.toString();
            },
            appVersion: req.user.uid.appVersion || global.yoho.config.appVersion,
            sessionKey: req.user.uid.sessionKey,
            appSessionType: req.user.uid.appSessionType || appSessionType
        };
    } else { // session中没有都情况下查看url参数中有没有登录信息
        if (!uid || !session_key) {
            return res.redirect(`//m.yohobuy.com/magazine/${e_id}.html`);
        } else {
            let intUid = parseInt(uid, 10);

            user_id = {
                toString: () => {
                    return intUid ? intUid : 0;
                },
                appVersion: app_version || global.yoho.config.appVersion,
                sessionKey: session_key,
                appSessionType: app_client_type || appSessionType
            };
        }
    }

    let magazineInfo = await req.ctx(indexModel).getMagazineInfo(user_id, e_id).catch(next);

    if (magazineInfo && magazineInfo.code === 200 && magazineInfo.data) {
        let code = magazineInfo.data.code; // 4000:获取成功 4001: 未购买该电子刊 4002:未获取到电子刊 4003:电子刊已删除

        if (code === 4000) {
            let url = magazineInfo.data.link;
            let resourceUrl = url.substring(0, url.lastIndexOf('/') + 1);

            superAgent.get(url).end(function(err, response) {
                if (err) {
                    return renderErroPage({msg: READ_MAGAZINE_URL_ERROR});
                }

                let $ = cheerio.load(response.text);
                let idMatch = response.text.match(/id="(.*)_hype_container/);

                if (idMatch && idMatch.length >= 2) {
                    let name = idMatch[1];
                    let id = `${name}_hype_container`;
                    let script = $(`#${id}`).html();

                    let scriptSrc = script.match(/src="(.*)"/);

                    if (scriptSrc && scriptSrc.length >= 2) {
                        let src = scriptSrc[1];
                        let newScript = '<script type="text/javascript" charset="utf-8" src="' +
                            resourceUrl + src + '">';

                        $(`#${id}`).html(newScript);

                        return res.send($.html());
                    } else {
                        return renderErroPage({msg: NO_HYPE_SCRIPT});
                    }
                } else {
                    return renderErroPage({msg: NO_HYPE_CONTAINER_ID});
                }
            });
        } else {
            return renderErroPage({msg: ERROR_MSG[code]});
        }


    } else {
        return res.redirect(`//m.yohobuy.com/magazine/${e_id}.html`);
    }
};

module.exports = {
    index
};