images.js 2.69 KB
/**
 * 登录判断
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/4/25
 */

'use strict';

const _ = require('lodash');

const // domain = '.static.yhbimg.com',
    defaultImage = '/2015/08/25/02/01dd632a6e07bfef457ce4beda21dd6413.png',
    qiniuDomain = 'yhfair.qiniudn.com',
    domainList = {
        '01': ['img10.static.yhbimg.com', 'img11.static.yhbimg.com'],
        '02': ['img12.static.yhbimg.com', 'img13.static.yhbimg.com'],
        'yhb-head': 'head.static.yhbimg.com'
    };

const regexp = /(?:\{)([a-zA-z][^\s\}]+)(?:\})/g;

const myReplace = (tem, data) => {
    return tem.replace(regexp, function(fullMatch, capture) {
        if (data[capture]) {
            return data[capture];
        } else {
            return fullMatch;
        }

    });
};

const makeBaseUrl = (domain, key) =>{
    encodeURIComponent(key).replace('%2F', '/');
    return `http://${domain}/${key}`;
};

const makeTemplateRequest = url => {
    let ops = ['{mode}', 'w/{width}', 'h/{height}'];

    if (ops.length === 0) {
        return url;
    }

    return url + '?imageView/' + ops.join('/');
};

const getImgTemplateUrl = (fileName, mode, domain) =>{
    // 默认值
    if (!mode) {
        mode = 1;
    }
    if (!domain) {
        domain = null;
    }

    if (domain === null) {
        domain = qiniuDomain;
    }

    let baseUrl = makeBaseUrl(domain, fileName);

    return makeTemplateRequest(baseUrl);
};

const getDomain = (bucket, fileName) => {
    let domain = '';

    if (bucket in domainList) {
        domain = domainList.bucket;
    } else {
        let node = fileName.substr(15, 2);

        if (node in domainList) {
            let urlList = domainList[node];
            let nodeNum = _.random(urlList.length - 1);

            domain = urlList[nodeNum];
        }
    }

    return domain;
};

const url = (fileName, bucket, mode) =>{
    // 默认值
    if (!mode) {
        mode = 1;
    }
    if (!bucket) {
        bucket = 'yhfair';
    }

    let domain = getDomain(bucket, fileName);

    return getImgTemplateUrl(bucket + fileName, mode, domain);
};

const template = (fileName, bucket, mode) => {
    // 默认值
    if (!mode) {
        mode = 1;
    }
    if (!bucket) {
        bucket = 'yhfair';
    }

    return url(fileName, bucket, mode);
};


exports.getImageUrl = (fileName, width, height, mode, bucket) => {
    // 默认值
    if (!mode) {
        mode = 2;
    }
    if (!bucket) {
        bucket = 'goodsimg';
    }

    if (typeof(fileName) !== 'string') {
        return template(defaultImage, bucket, mode);
    }
    if (fileName.indexOf('http://') !== 0) {
        fileName = template(fileName, bucket, mode);
    }
    return myReplace(fileName, {width: width, height: height, mode: mode});
};