receive.js 2.62 KB
/**
 * 消息接收模块
 * @author LQ <qi.li@yoho.cn>
 * @date 2017/03/20
 */
var socketConf = require('./config');
var utility = require('../utility');
var allTypes = socketConf.recType;
var assetsPath = $('input[name=assetsPrefix]').val() || '';

/**
 * 表情图片路径解析
 * @param path
 * @returns {*}
 */
var _emjPath = function(path) {
    var reg = /src="(\d{3}).gif"/g;
    var subFolder = '/img/service/emoji/';
    var prePath = ['src="', assetsPath, subFolder].join('');

    if (typeof path !== 'string') {
        return '';
    }
    return path.replace(reg, prePath + '$1.gif"');
};

/**
 * 用户头像处理
 * @param url
 * @returns {*}
 */
var _userAvatar = function(url, mode, w, h) {
    if (!url || typeof url !== 'string') {
        return assetsPath + socketConf.defaultUserHead;
    }

    return url.replace(/\{mode\}/, mode || 2)
        .replace(/\{width\}/, w || 100)
        .replace(/\{height\}/, h || 100);
};

/**
 * 图片添加img标签
 * @param url 图片链接
 * @private
 */
var _imgMsg = function(url) {
    url = utility.autoProtocol(url);
    return '<img class="img-msg" src="' + url + '">';
};

/**
 * 图片标签添加
 * @param msg 内部消息体
 * @private
 */
var _createImgEl = function(msg) {
    if (msg.type === 2) {
        msg.newContent = _imgMsg(msg.content);
        msg.content = utility.autoProtocol(msg.content);
        msg.newContent = utility.autoProtocol(msg.newContent);
    }
};

/**
 * 接收消息体预处理
 * @param rec 接收对象
 */
exports.preProcess = function(rec) {
    var chatMsg = rec.chatMessage;
    var recType = rec.type;

    switch (recType) {
        case allTypes.CU_SEND:
            rec.userHead = utility.autoProtocol(rec.userHead);
            rec.userHead = _userAvatar(rec.userHead);
            chatMsg.newContent = _emjPath(chatMsg.newContent);
            _createImgEl(chatMsg);
            break;

        case allTypes.CS_SEND:
            rec.csHead = utility.autoProtocol(rec.csHead);
            chatMsg.newContent = _emjPath(chatMsg.newContent);
            _createImgEl(chatMsg);
            break;

        default:
            break;
    }
};

/**
 * 是否显示留言
 * @param rec 接收对象
 */
exports.leaMsgTip = function(rec) {
    var SHOW_LEAVE_MSG = 2; // 显示留言
    var chatMsg = rec.chatMessage;
    var canLeave = rec.isLeaveMessage === SHOW_LEAVE_MSG;
    var append = canLeave ? '您也可以选择<a class="leave-msg">留言</a>' : '';
    var reg = /[,|,]$/g;

    chatMsg.content = canLeave ?
        chatMsg.content :
        (chatMsg.content = chatMsg.content.replace(reg, ''));

    return [chatMsg.content, append].join('');
};