image2.js 2.05 KB
'use strict';

var cdnDomains = require('../../../../config/dns-prefetch');

function cdnReplace(cdn, imgUrl) {
    if (cdn === 'qcloud') {
        for (var key in cdnDomains) {
            if (imgUrl.indexOf(key) >= 0) {
                imgUrl = imgUrl.replace(key, cdnDomains[key]);
            }
        }
    }
    return imgUrl;
}

module.exports = function(imageUrl, opts) {
    var cdn = window.cdn;

    if (imageUrl) {
        var params = opts.hash;
        var urls = imageUrl.split('?');
        var query = urls[1] || '';
        var uri = urls[0];

        if (uri.indexOf('http:') === 0) {
            uri = uri.replace('http:', '');
        }

        uri = cdnReplace(cdn, uri);

        if (query) {
            query = query.replace(/{width}/g, params.w).replace(/{height}/g, params.h).replace(/{mode}/g, (params.mode || 2));

            if (query.indexOf('imageView2') === 0) {
                if (params.q && query.indexOf('/q/') > 0) {
                    query = query.replace(/\/q\/\d+/g, '/q/' + params.q);
                } else if (params.q) {
                    query += '/q/' + params.q;
                }
            } else if (query.indexOf('imageMogr2') === 0) {
                if (params.q && query.indexOf('/quality/') > 0) {
                    query = query.replace(/\/quality\/\d+/g, '/quality/' + params.q);
                } else if (params.q) {
                    query += '/quality/' + params.q;
                }
            } else if (query.indexOf('imageView/') === 0) {
                if (params.q && query.indexOf('/q/') > 0) {
                    query = query.replace(/\/q\/\d+/g, '/q/' + params.q);
                } else if (params.q) {
                    query += '/q/' + params.q;
                }

                if (params.mode) {
                    query = query.replace(/imageView\/\d{1}\//, 'imageView/' + params.mode + '/');
                }
            }
        } else {
            query = 'imageView2/2/interlace/1/q/' + (params.q || 75);
        }
        return uri + '?' + query;
    } else {
        return imageUrl;
    }
};