| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134 |
- window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
- var FastChat = {
- ws: {
- SocketTask: null,
- Timer: null,
- ErrorMsg: [],
- MaxRetryCount: 3,// 最大重连次数
- CurrentRetryCount: 0,
- url: null
- },
- audio: {
- context: new window.AudioContext(),
- source: null,
- buffer: null
- },
- cookie_prefix:'',// 同config.php里边的cookie前缀设置,未修改过请忽略
- config: null,
- url: null,
- window_is_show: false,
- fast_move: false,
- session_id: 0,
- is_cross_domain: false,// 是否跨域,若为站外调用,则在js中建立游客cookie
- allowed_close_window: true,// 是否允许ecs关闭窗口(当预览图片时,不允许关闭),
- initialize: function (url = document.domain, modulename = 'index', initSuccess = null) {
- FastChat.url = url;
- if(document.domain !== url){
- FastChat.is_cross_domain = true;
- }
- var initialize_url = FastChat.buildUrl(url, modulename, 'initialize');
- $.ajax({
- url: initialize_url,
- success: function (data) {
- if (data.code === 403) {
- return;
- } else if (data.code !== 1) {
- layer.msg(data.msg);
- return;
- }
- FastChat.config = data.data;
- FastChat.bulidChat(data.data);
- FastChat.show_popover((!FastChat.getCookie('new_user')) ? data.data.new_user_tip : data.data.new_msg);
- // 站外调用游客身份cookie建立
- if (FastChat.is_cross_domain) {
- FastChat.setCookie('fastchat_tourists', FastChat.config.token_list.fastchat_tourists_token, 10);
- }
- // 构建ws的url
- FastChat.ws.url = FastChat.buildUrl('billiards.websocket.xunsoftware.com', modulename, 'ws', data.data.websocket_port);
- if (modulename === 'admin') {
- // 立即链接 Websocket
- FastChat.ConnectSocket();
- } else {
- // 若用户 N 秒后任在此页面,链接Socket
- setTimeout(function () {
- if (!FastChat.ws.SocketTask || FastChat.ws.SocketTask.readyState === 3 || FastChat.ws.SocketTask.readyState === 2) {
- FastChat.ConnectSocket();
- }
- }, 10000);
- }
- if (typeof initSuccess == 'function') {
- initSuccess();
- }
- if (data.data.new_msg) {
- // 抖动按钮和播放提示音
- FastChat.new_message_prompt('#chat_button');
- }
- }
- });
- FastChat.eventReg();
- },
- ConnectSocket: function () {
- if ("WebSocket" in window) {
- var ws = new WebSocket(FastChat.ws.url);
- FastChat.ws.SocketTask = ws;
- ws.onopen = function () {
- FastChat.ws.CurrentRetryCount = 0;
- // 重新发送所有出错的消息
- if (FastChat.ws.ErrorMsg.length > 0) {
- for (let i in FastChat.ws.ErrorMsg) {
- FastChat.ws_send(FastChat.ws.ErrorMsg[i]);
- }
- FastChat.ws.ErrorMsg = [];
- }
- if (FastChat.ws.Timer != null) {
- clearInterval(FastChat.ws.Timer);
- }
- if ($('#error_warning').html()) {
- $('#error_warning').html('');
- $('#chat_button').popover('hide');
- }
- FastChat.ws.Timer = setInterval(FastChat.ws_send, 28000);//定时发送心跳
- };
- ws.onmessage = function (evt) {
- var msg = $.parseJSON(evt.data);
- if (msg.code === 0) {
- layer.msg(msg.msg);
- }
- FastChat.domsg(msg);
- };
- ws.onclose = function (e) {
- if (FastChat.ws.Timer != null) {
- clearInterval(FastChat.ws.Timer);
- }
- $('#error_warning').html('网络链接已断开');
- FastChat.show_popover('WebSocket 链接已断开');
- if (FastChat.ws.MaxRetryCount) {
- FastChat.ws.Timer = setInterval(FastChat.retry_webSocket, 3000);//每3秒重新连接一次
- }
- };
- ws.onerror = function (e) {
- // 错误
- console.error('websocket 错误:', e);
- $('#error_warning').html('WebSocket 发生错误');
- FastChat.show_popover('WebSocket 发生错误,请查看控制台');
- };
- } else {
- layer.msg(FastChat.config.chat_name + ':您的浏览器不支持 WebSocket!');
- }
- },
- retry_webSocket: function () {
- if (FastChat.ws.CurrentRetryCount < FastChat.ws.MaxRetryCount) {
- FastChat.ws.CurrentRetryCount++;
- FastChat.ConnectSocket();
- console.log('重连 WebSocket 第' + FastChat.ws.CurrentRetryCount + '次');
- } else {
- if (FastChat.ws.Timer != null) {
- clearInterval(FastChat.ws.Timer);
- }
- if (FastChat.ws.ReConnection) {
- console.log('每隔10秒将再次尝试重连 WebSocket')
- FastChat.ws.Timer = setInterval(FastChat.ConnectSocket, 10000);//每10秒重新连接一次
- }
- }
- },
- bulidChat: function (data) {
- $("<div>")
- .attr({
- 'data-toggle': "popover",
- 'data-title': '新消息',
- 'data-placement': "auto left",
- 'data-content': '',
- 'style': 'position: fixed;top: 100px;width: 48px;height: 48px;right: 90px;z-index: 9999;',
- 'data-html': true,
- 'data-template': '<div class="chat_button_popover popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>',
- id: 'chat_button',
- class: 'chat_button'
- })
- .appendTo("body");
- $("<img>")
- .attr({
- src: FastChat.config.__CDN__ + "/assets/addons/fastchat/img/fastchat.png",
- ondragstart: "return false;",
- style: 'width: 100%;height: 100%;'
- })
- .appendTo("#chat_button");
- $("body").append(data.window_html);
- $('#search_input').attr('placeholder', data.search_tip);
- if (!FastChat.ws.SocketTask || FastChat.ws.SocketTask.readyState === 3 || FastChat.ws.SocketTask.readyState === 2) {
- $('#error_warning').html('链接中...');
- }
- let send_tis_key = parseInt(data.send_message_key) === 1 ? 'Enter' : 'Ctrl+Enter';
- $('#send_tis').html('按下' + send_tis_key + '发送消息');
- var username = data.user_info ? data.user_info.username : '未登录';
- $('#modal-title').html(data.chat_name + ' - ' + username);
- },
- buildSession: function (item) {
- if (item.existing_session || $('#session_list').children("[data-session='" + item.id + "']").length) {
- // 去掉该会话再添加最新的
- $('#session_list').children("[data-session='" + item.id + "']").remove();
- }
- $('#session_list').prepend(
- '<li class="person" data-session="' + item.id + '" data-session_user="' + item.session_user + '">' +
- '<img class="person_avatar" src="' + item.avatar + '" alt="" />' +
- '<div class="session_info_item">' +
- '<span class="name">' + item.nickname + '</span>' +
- '<span class="time">' + item.last_time + '</span>' +
- '</div><div class="session_info_item">' +
- '<span class="preview">' + item.last_message + '</span>' +
- (item.unread_msg_count ? '<span class="unread_msg_count">' + item.unread_msg_count + '</span>' : '<span class="unread_msg_count count_hide"></span>') +
- '</div>' +
- '</li>'
- );
- if (!item.online) {
- // 把头像变灰色
- FastChat.edit_online_status(item.session_user, 0);
- }
- },
- buildSessionTime: function (data, page) {
- if (parseInt(page) === 1) {
- $('.chat_scroll').append('<div class="conversation-start"><span>' + data + '</span></div>');
- } else {
- $('.chat_scroll').prepend('<div class="conversation-start"><span>' + data + '</span></div>');
- }
- },
- buildRecord: function (data, page) {
- if (parseInt(page) === 1) {
- $('.chat_scroll').append('<div class="bubble ' + data.sender + '">' + data.message + '</div>');
- } else {
- $('.chat_scroll').prepend('<div class="bubble ' + data.sender + '">' + data.message + '</div>');
- }
- },
- changeSession: function (event) {
- if (event.length === 0) {
- FastChat.session_id = 0;
- $('#session_user_name').html('无会话');
- return;
- }
- $('.person').removeClass("active");
- if ($('.chat-container .right').css('display') != 'none' &&
- $('.chat-container .left').css('display') != 'none') {
- event.addClass("active");
- }
- let session_id = event.data('session');
- // 加载聊天记录
- var load_message = {
- c: 'Message',
- a: 'chat_record',
- data: {
- session_id: session_id,
- page: 1
- }
- };
- FastChat.session_id = session_id;
- FastChat.ws_send(load_message);
- // 清理红点
- event.children(".session_info_item").children(".unread_msg_count").eq(0).hide(200);
- // 获取焦点
- $('#message').focus();
- $('.chat_emoji').hide();
- },
- buildChatImg: function (filename, facename, is_filepath = false) {
- if (is_filepath) {
- return '<img title="' + facename + '" src="' + filename + '" />';
- } else {
- return '<img title="' + facename + '" src="' + FastChat.config.__CDN__ + '/assets/addons/fastchat/img/emoji/' + filename + '" />';
- }
- },
- buildChatA: function (filepath, file_suffix) {
- return '<a href="' + filepath + '">点击下载:' + file_suffix + ' 文件</a>';
- },
- buildUrl: function (url, modulename, type = 'ws', wsport = 8282) {
- // 用户的身份通过读取 cookie 来识别
- var protocol = window.location.protocol + '//';
- var port = window.location.port;
- port = port ? ':' + port:'';
- if (type === 'ws') {
- // 用户的身份通过 FastChat.config.token_list.kefu_token 来识别
- // 游客的身份通过 FastChat.config.token_list.fastchat_tourists_token 来识别
- let token = '&token=' + (FastChat.config.token_list.fastchat_token ? FastChat.config.token_list.fastchat_token : '');
- let fastchat_user = '&fastchat_user=' + (FastChat.config.token_list.fastchat_tourists_token ? FastChat.config.token_list.fastchat_tourists_token : '');
- protocol = parseInt(FastChat.config.wss_switch) === 1 ? 'wss://':'ws://';
- return protocol + url + ':' + wsport + '?modulename=' +
- modulename + token + fastchat_user;
- } else if (type === 'initialize') {
- if (FastChat.is_cross_domain){
- return protocol + url + port + '/addons/fastchat/index/initialize?modulename=' +
- modulename + '&tourists_token=' + FastChat.getCookie('fastchat_tourists');
- }
- return protocol + url + port + '/addons/fastchat/index/initialize?modulename=' +
- modulename;
- } else if (type === 'upload') {
- return protocol + url + port + '/addons/fastchat/index/upload?modulename=' +
- modulename;
- } else if (type === 'load_message_prompt') {
- return protocol + url + port + '/addons/fastchat/index/load_message_prompt?modulename=' +
- modulename;
- }
- },
- // 设置搜索框选中的预选词
- setSelectedItem: function () {
- if (FastChat.search_primary < 0) {
- FastChat.search_primary = $('#search_users').find('li').length - 1;
- } else if (FastChat.search_primary > $('#search_users').find('li').length - 1) {
- FastChat.search_primary = 0;
- }
- $('#search_users').find('li').removeClass('select_item')
- .eq(FastChat.search_primary).addClass('select_item');
- // 将预选词放入输入框
- $('#search_input').val($('#search_users').find('li').eq(FastChat.search_primary).data('nickname'));
- FastChat.search_select_id = $('#search_users').find('li').eq(FastChat.search_primary).data('userid');
- },
- postAddSession: function () {
- if (!FastChat.search_select_id) {
- layer.msg('用户找不到啦!');
- }
- $('#search_input').val('');
- var load_message = {
- c: 'Message',
- a: 'add_session',
- data: {
- user_id: FastChat.search_select_id
- }
- };
- FastChat.ws_send(load_message);
- },
- sendMessage: function (message) {
- var load_message = {
- c: 'Message',
- a: 'send_message',
- data: {
- message: message,
- session_id: FastChat.session_id
- }
- };
- FastChat.ws_send(load_message);
- var data = {
- sender: 'me',
- message: message
- }
- FastChat.buildRecord(data, 1);
- $('#message').html('');
- var re = new RegExp("<img(.*)>", "g");
- message = message.replace(re, '[图片]');
- re = new RegExp("<a(.*)</a>", "g");
- message = message.replace(re, '[链接]');
- // 修改该会话的最后消息
- let session = $('#session_list').children("[data-session='" + FastChat.session_id + "']");
- session.children(".session_info_item").children(".time").eq(0).html('刚刚');
- session.children(".session_info_item").children(".preview").eq(0).html(message);
- let first_session = $('#session_list li').eq(0);
- first_session.before(session);
- if ($('#chat_scroll').children('.conversation-start').children('span').eq(0).html() === '还没有消息') {
- $('#chat_scroll').children('.conversation-start').children('span').eq(0).html('刚刚');
- }
- $('.chat_scroll').scrollTop($('.chat_scroll')[0].scrollHeight);
- },
- show_window: function () {
- FastChat.window_is_show = true;
- if (!FastChat.getCookie('new_user')) {
- FastChat.setCookie('new_user', true, 365);
- }
- // 检查 websocket 是否连接
- if (!FastChat.ws.SocketTask || FastChat.ws.SocketTask.readyState === 3 || FastChat.ws.SocketTask.readyState === 2) {
- FastChat.ConnectSocket();
- }
- // 隐藏会话按钮和提示消息
- $('#chat_button').popover('hide');
- $('#chat_button').hide(200);
- $('#FastChat').modal({
- keyboard: false,
- show: true
- });
- // 找到当前会话,去掉红点标记(直接重载当前会话)
- if (FastChat.session_id) {
- var load_message = {
- c: 'Message',
- a: 'chat_record',
- data: {
- session_id: FastChat.session_id,
- page: 1
- }
- };
- FastChat.ws_send(load_message);
- // 清理红点
- let session = $('#session_list').children("[data-session='" + FastChat.session_id + "']");
- session.children(".session_info_item").children(".unread_msg_count").eq(0).hide(200);
- } else {
- FastChat.changeSession($('.person').eq(0));
- }
- },
- forecast_add_session: function (e) {
- // 预添加会话
- FastChat.search_select_id = $(e.currentTarget).data('userid');
- FastChat.postAddSession();//添加会话
- $('#search_users').hide(200);
- $('#search_input').val('');
- FastChat.search_select_id = 0;
- // 显示会话窗口
- FastChat.show_window();
- },
- show_popover: function (content) {
- if (!FastChat.window_is_show && content) {
- $('#chat_button').attr("data-content", content);
- $('#chat_button').popover('show');
- }
- },
- edit_online_status: function (user_id, status) {
- if (status) {
- $('#session_list').children("[data-session_user='" + user_id + "']").children(".person_avatar").removeClass("person_head_gray");
- } else {
- $('#session_list').children("[data-session_user='" + user_id + "']").children(".person_avatar").addClass("person_head_gray");
- }
- },
- edit_shielding_status: function (blacklist, code, session_id) {
- // code:1=屏蔽成功,2=解除屏蔽成功,3=通过blacklist判断屏蔽状态
- if (code === 3) {
- if (blacklist) {
- $('.shielding').html('取消屏蔽');
- } else {
- $('.shielding').html('屏蔽此人');
- }
- return;
- }
- if (code === 1 && parseInt(session_id) === parseInt(FastChat.session_id)) {
- $('.shielding').html('取消屏蔽');
- } else if (code === 2 && parseInt(session_id) === parseInt(FastChat.session_id)) {
- $('.shielding').html('屏蔽此人');
- }
- },
- domsg: function (msg) {
- if (msg.msgtype === 'config') {
- // 加载会话列表
- var load_message = {
- c: 'Message',
- a: 'session_list'
- };
- FastChat.ws_send(load_message);
- if (!FastChat.window_is_show && msg.data.new_msg) {
- // 窗口关闭状态
- FastChat.show_popover(msg.data.new_msg);
- // 抖动按钮和播放提示音
- FastChat.new_message_prompt('#chat_button');
- }
- // console.log('接受到config',msg);
- } else if (msg.msgtype === 'offline') {
- FastChat.edit_online_status(msg.user_id, 0);
- } else if (msg.msgtype === 'online') {
- FastChat.edit_online_status(msg.user_id, 1);
- } else if (msg.msgtype === 'test') {
- console.log(msg)
- } else if (msg.msgtype === 'shielding_session') {
- FastChat.edit_shielding_status(false, msg.code, msg.session_id);
- } else if (msg.msgtype === 'welcome_tourists') {
- if (msg.code == 1) {
- FastChat.setCookie('fastchat_tourists', msg.data, 10);
- }
- } else if (msg.msgtype === 'search_user') {
- if (msg.data.length) {
- FastChat.search_primary = -1;
- $('#search_users').html('');
- $.each(msg.data, function (index, item) {
- $('#search_users').show(200);
- $('#search_users').append(
- '<li class="fastchat_user" data-userid="' + item.id + '" data-nickname="' + item.nickname + '">' +
- '<img src="' + item.avatar + '" alt="" />' +
- '<span class="name">' + item.nickname + '</span>' +
- '<span class="go_chat">聊天</span>' +
- '</li>'
- );
- })
- } else {
- $('#search_users').html('');
- $('#search_users').show(200);
- $('#search_users').append(
- '<li class="fastchat_user" data-userid="0">' +
- '<span class="name">找不到该用户!</span>' +
- '</li>'
- );
- }
- } else if (msg.msgtype === 'add_session') {
- if (msg.code === 1) {
- FastChat.buildSession(msg.data);
- FastChat.changeSession($('.person').eq(0));
- FastChat.edit_shielding_status(msg.data.blacklist, 3);
- }
- } else if (msg.msgtype === 'message_list') {
- $('#session_list').html('');
- for (let i in msg.data) {
- FastChat.buildSession(msg.data[i]);
- }
- if (FastChat.window_is_show) {
- FastChat.changeSession($('.person').eq(0));
- }
- } else if (msg.msgtype === 'chat_record') {
- // 聊天记录
- if (msg.code === 0) {
- return;
- }
- if (parseInt(msg.data.page) === 1) {
- $('.chat_scroll').html('');
- }
- var chat_record = msg.data.chat_record
- $('#session_user_name').html(msg.data.session_info.nickname ? msg.data.session_info.nickname : '游客');
- FastChat.chat_record_page = msg.data.next_page;
- for (let i in chat_record) {
- if (msg.data.page === 1) {
- FastChat.buildSessionTime(chat_record[i].datetime, msg.data.page);
- }
- for (let y in chat_record[i].data) {
- FastChat.buildRecord(chat_record[i].data[y], msg.data.page)
- }
- if (msg.data.page !== 1) {
- FastChat.buildSessionTime(chat_record[i].datetime, msg.data.page);
- }
- }
- FastChat.edit_shielding_status(msg.data.session_info.blacklist, 3);
- setTimeout(() => {
- $('.chat_scroll').scrollTop($('.chat_scroll')[0].scrollHeight);
- }, 500)
- } else if (msg.msgtype === 'clear') {
- FastChat.ws.MaxRetryCount = 0;
- FastChat.ws.ReConnection = false;
- // 删除
- var delTimer = setInterval(function () {
- if ($('#chat_button').length != 0) {
- console.warn('禁止匿名聊天,清退链接!');
- $('#chat_button').popover('hide');
- $('#chat_button').remove();
- $('#FastChat').modal('hide');
- clearInterval(delTimer);
- }
- }, 100);
- var load_message = {
- c: 'Message',
- a: 'clear'
- };
- FastChat.ws_send(load_message);
- } else if (msg.msgtype === 'new_message') {
- var message_content = msg.data.nickname + '发来新的消息!';
- let mp3 = new Audio("https://pbbaby.xunsoftware.com/uploads/audio/order.mp3");
- mp3.loop = false;
- mp3.play();
- if (FastChat.window_is_show) {
- // 窗口打开状态
- FastChat.new_message_prompt('#FastChat');
- } else {
- // 窗口关闭状态
- FastChat.show_popover(message_content);
- // 抖动按钮和播放提示音
- FastChat.new_message_prompt('#chat_button');
- }
- // 检查是否有该会话
- let session = $('#session_list').children("[data-session='" + msg.data.id + "']");
- if (session.length === 0) {
- FastChat.buildSession(msg.data);
- } else {
- // 修改该会话的最后消息
- session.children(".session_info_item").children(".time").eq(0).html(msg.data.last_time);
- session.children(".session_info_item").children(".preview").eq(0).html(msg.data.last_message);
- // 将会话移动到第一位
- let first_session = $('#session_list li').eq(0);
- first_session.before(session);
- if ($('#chat_scroll').children('.conversation-start').children('span').eq(0).html() === '还没有消息') {
- $('#chat_scroll').children('.conversation-start').children('span').eq(0).html('刚刚');
- }
- // 必要时,直接去除红点
- if (parseInt(msg.data.id) === parseInt(FastChat.session_id) && FastChat.window_is_show) {
- FastChat.buildRecord(msg.data, 1);
- var load_message = {
- c: 'Message',
- a: 'read_message',
- data: {
- record_id: msg.data.record_id
- }
- };
- FastChat.ws_send(load_message);
- $('.chat_scroll').scrollTop($('.chat_scroll')[0].scrollHeight);
- return;
- }
- if (msg.data.unread_msg_count > 0) {
- session.children(".session_info_item").children(".unread_msg_count").eq(0).html(msg.data.unread_msg_count).show(200);
- } else {
- session.children(".session_info_item").children(".unread_msg_count").eq(0).hide(200);
- }
- }
- }
- },
- playSound: function () {
- FastChat.audio.source = FastChat.audio.context.createBufferSource();
- FastChat.audio.source.buffer = FastChat.audio.buffer;
- FastChat.audio.source.loop = false;
- FastChat.audio.source.connect(FastChat.audio.context.destination);
- FastChat.audio.source.start(0); //立即播放
- },
- loadAudioFile: function (url) {
- var xhr = new XMLHttpRequest(); //通过XHR下载音频文件
- xhr.open('GET', url, true);
- xhr.responseType = 'arraybuffer';
- xhr.onload = function (e) { //下载完成
- FastChat.audio.context.decodeAudioData(this.response,
- function (buffer) { //解码成功时的回调函数
- FastChat.audio.buffer = buffer;
- FastChat.playSound();
- },
- function (e) { //解码出错时的回调函数
- console.log('音频解码失败', e);
- });
- };
- xhr.send();
- },
- new_message_prompt: function (event) {
- // 抖动元素和播放提示音乐
- $(event).addClass('fastchat-shake-horizontal');
- setTimeout(function () {
- $(event).removeClass('fastchat-shake-horizontal');
- }, 400);
- if (FastChat.audio.buffer) {
- FastChat.playSound();
- } else {
- let url = FastChat.buildUrl(FastChat.url, 'index', 'load_message_prompt');
- FastChat.loadAudioFile(url);
- }
- },
- getCookie: function (cname) {
- var name = FastChat.cookie_prefix + cname + "=";
- var decodedCookie = document.cookie;
- var ca = decodedCookie.split(';');
- for (var i = 0; i < ca.length; i++) {
- var c = ca[i];
- while (c.charAt(0) === ' ') {
- c = c.substring(1);
- }
- if (c.indexOf(name) === 0) {
- return c.substring(name.length, c.length);
- }
- }
- return '';
- },
- setCookie: function (cname, cvalue, exdays) {
- var d = new Date();
- d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
- var expires = "expires=" + d.toUTCString();
- document.cookie = FastChat.cookie_prefix + cname + "=" + cvalue + ";" + expires + ";path=/";
- },
- ws_send: function (message) {
- if (!message) {
- message = {c: 'Message', a: 'ping'};
- }
- if (FastChat.ws.SocketTask && FastChat.ws.SocketTask.readyState == 1) {
- FastChat.ws.SocketTask.send(JSON.stringify(message));
- } else {
- console.log('消息发送出错', message);
- FastChat.ws.ErrorMsg.push(message);
- }
- },
- eventReg: function () {
- // 点击轻提示和FastChat悬浮球的事件
- $(document).on('click', '.chat_button_popover,#chat_button', function () {
- FastChat.show_window();
- });
- // 拖动悬浮球的事情
- $(document).on('mousedown', '#chat_button', function (e) {
- $(document).find("iframe").css("pointer-events", "none");
- FastChat.fast_move = true;
- FastChat.fast_x = e.pageX - parseInt($("#chat_button").css("left"));
- FastChat.fast_y = e.pageY - parseInt($("#chat_button").css("top"));
- $(document).on('mousemove', function (e) {
- if (FastChat.fast_move) {
- var x = e.pageX - FastChat.fast_x;//控件左上角到屏幕左上角的相对位置
- var y = e.pageY - FastChat.fast_y;
- $("#chat_button").css({"top": y, "left": x});
- }
- }).mouseup(function () {
- $(document).find("iframe").css("pointer-events", "auto");
- FastChat.fast_move = false;
- });
- });
- // 滑动聊天记录的事件
- document.addEventListener('scroll', function (event) {
- if (event.target.id === 'chat_scroll') {
- if (parseInt($(event.target).scrollTop()) === 0 && FastChat.chat_record_page !== 'done') {
- // 加载历史聊天记录
- var load_message = {
- c: 'Message',
- a: 'chat_record',
- data: {
- session_id: FastChat.session_id,
- page: FastChat.chat_record_page
- }
- };
- FastChat.ws_send(load_message);
- }
- }
- }, true);
- // 隐藏窗口时
- $(document).on('hidden.bs.modal', '#FastChat', function (e) {
- $('#chat_button').show(200);
- FastChat.window_is_show = false;
- });
- // 屏蔽用户
- $(document).on('click', '.shielding', function () {
- var load_message = {
- c: 'Message',
- a: 'shielding_session',
- data: {
- session_id: FastChat.session_id
- }
- };
- FastChat.ws_send(load_message);
- });
- // 监听子框架的点击事件-一键添加会话窗口
- /*$('iframe').contents().find('.fastchat_user').bind('click',function(e){
- FastChat.forecast_add_session(e);
- });*/
- // 添加会话窗口
- $(document).on('click', '.fastchat_user', function (e) {
- FastChat.forecast_add_session(e);
- });
- // 显示表情选择面板
- $(document).on('click', '.smiley', function (e) {
- $('.chat_emoji').toggle(200);
- // 获取焦点
- $('#message').focus();
- });
- // 选择表情
- $(document).on('click', '.chat_emoji img', function (e) {
- $('#message').append(e.target);
- $('.chat_emoji').hide();
- $('#message').focus();
- });
- // 用户选择了文件
- $(document).on('change', '#chatfile', function (e) {
- if (!$('#chatfile')[0].files[0]) {
- return;
- }
- // 上传文件
- var formData = new FormData();
- formData.append("file", $('#chatfile')[0].files[0]);
- var url = FastChat.buildUrl(FastChat.url, 'index', 'upload');
- $.ajax({
- url: url, /*接口域名地址*/
- type: 'post',
- data: formData,
- contentType: false,
- processData: false,
- success: function (res) {
- if (res.code === 1) {
- var file_name = res.data.url.split('.');
- var file_suffix = file_name[file_name.length - 1];
- if (file_suffix === 'png' ||
- file_suffix === 'jpg' ||
- file_suffix === 'gif' ||
- file_suffix === 'jpeg') {
- var message = FastChat.buildChatImg(res.data.url, '', true);
- FastChat.sendMessage(message);
- } else {
- var file_name = res.data.url.split('.');
- var file_suffix = file_name[file_name.length - 1];
- var message = FastChat.buildChatA(res.data.url, file_suffix);
- FastChat.sendMessage(message);
- }
- } else {
- layer.msg(res.msg);
- }
- },
- error: function (e) {
- layer.msg('文件上传失败,请重试!');
- },
- complete: function () {
- $('#chatfile').val('');
- }
- })
- });
- // 用户点击聊天记录窗口,隐藏表情面板
- $(document).on('click', '#chat_scroll', function () {
- if ($('.chat_emoji').css('display') === 'block') {
- $('.chat_emoji').hide();
- }
- });
- // 右键菜单
- $(document).on('contextmenu', '.person', function (e) {
- FastChat.select_session_id = $(e.currentTarget).data('session');
- var popupmenu = $('.fastchat_menu');
- popupmenu.hide();
- let l = ($(document).width() - e.clientX) < popupmenu.width() ? (e.clientX - popupmenu.width()) : e.clientX;
- let t = ($(document).height() - e.clientY) < popupmenu.height() ? (e.clientY - popupmenu.height()) : e.clientY;
- popupmenu.css({left: l, top: t}).show(200);
- e.preventDefault();
- }).click(function () {
- // 菜单的隐藏
- $('.fastchat_menu').hide();
- });
- // 点击右键菜单项
- $(document).on('click', '.fastchat_menu_item', function (e) {
- var action = $(e.currentTarget).data('action');
- if (FastChat.select_session_id && action === 'del') {
- // 删除会话
- $('#session_list').children("[data-session='" + FastChat.select_session_id + "']").remove();
- var load_message = {
- c: 'Message',
- a: 'del_session',
- data: {
- session_id: FastChat.select_session_id
- }
- };
- FastChat.ws_send(load_message);
- } else if (FastChat.select_session_id && action === 'shielding') {
- // FastChat.shielding_session(window.FastChat.select_session_id);
- }
- });
- // 切换会话人
- $(document).on('click', '#session_list li', function (e) {
- if ($('.chat-container .right').css('display') === 'none') {
- $('.chat-container .right').show();
- $('.chat-container .left').hide();
- }
- FastChat.changeSession($(e.currentTarget));
- });
- // 手机版聊天窗口兼容
- $(document).on('hide.bs.modal', '#FastChat', function (e) {
- if ($('.chat-container .left').css('display') === 'none') {
- $('.chat-container .left').show(200);
- $('.chat-container .right').hide();
- return false;
- }
- });
- // 预览图片
- $(document).on('click', '.chat_scroll .bubble img', function (e) {
- var img_obj = $(e.target)[0];
- FastChat.allowed_close_window = false;// 按下ecs不允许关闭会话窗口
- layer.photos({
- photos: {
- "title":"聊天图片预览",
- "id":"record",
- data:[
- {
- "src":img_obj.src
- }
- ]
- },
- end:function () {
- // 图片预览已关闭
- FastChat.allowed_close_window = true;
- },anim: 5 //0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
- });
- })
- // 搜索框失去焦点
- $(document).on('blur', '#search_input', function () {
- // $('#search_input').val('');
- setTimeout(function () {
- // 等待点击事件冒泡-防止搜索结果中的蓝色聊天文字不能被点击
- $('#search_users').hide(200);
- FastChat.search_select_id = 0;
- }, 250);
- })
- // 禁止回车键换行
- $(document).on('keypress', '#message', function (event) {
- if (parseInt(FastChat.config.send_message_key) === 1 && parseInt(event.keyCode) === 13 && !event.ctrlKey) {
- event.preventDefault()
- }
- });
- // 按键监听 FastChat.config.ecs_exit == 1
- $(document).on('keyup', function (event) {
- // 对ecs键的监听
- if (parseInt(event.keyCode) === 27 && FastChat.window_is_show) {
- if (parseInt(FastChat.config.ecs_exit) === 1 && FastChat.allowed_close_window) {
- $('#FastChat').modal('hide');
- } else {
- layer.closeAll();
- }
- }
- });
- // 按键发送消息监听
- $(document).on('keydown', '#message', function (event) {
- var message = $(event.currentTarget).html();
- if (parseInt(FastChat.config.send_message_key) === 1 && parseInt(event.keyCode) === 13 && !event.ctrlKey) {
- if (message) {
- FastChat.sendMessage(message);
- }
- } else if (parseInt(FastChat.config.send_message_key) === 1 && parseInt(event.keyCode) === 13 && event.ctrlKey) {
- // Enter发送消息时,用户按下了ctrl+Enter
- if (FastChat.browserType() === "IE" || FastChat.browserType() === "Edge") {
- $(event.currentTarget).html(message + "<div></div>");
- } else if (FastChat.browserType() === "FF") {
- $(event.currentTarget).html(message + "<br/><br/>");
- } else {
- $(event.currentTarget).html(message + "<div><br/></div>");
- }
- // 获得焦点
- var o = document.getElementById("message").lastChild;
- var sel = window.getSelection();
- var range = document.createRange();
- range.selectNodeContents(event.currentTarget);
- range.collapse(false);
- range.setEndAfter(o);
- range.setStartAfter(o);
- sel.removeAllRanges();
- sel.addRange(range);
- } else if (parseInt(FastChat.config.send_message_key) === 0 && parseInt(event.keyCode) === 13 && event.ctrlKey) {
- if (message) {
- FastChat.sendMessage(message);
- }
- }
- });
- $(document).on('keyup', '#search_input', function (event) {
- if (parseInt(event.keyCode) === 13) {
- var user = $('#search_input').val();
- if (user.length <= 0) {
- // 无搜索词,且预选框已显示,隐藏预选框
- if ($('#search_users').css('display') !== 'none') {
- $('#search_users').hide(200);
- FastChat.search_select_id = 0;
- } else {
- layer.msg('请输入要查找的用户!');
- }
- return;
- } else {
- // 有预选人,添加会话
- if ($('#search_users').css('display') !== 'none' && FastChat.search_select_id) {
- FastChat.postAddSession();
- $('#search_users').hide(200);
- FastChat.search_select_id = 0;
- return;
- }
- }
- var load_message = {
- c: 'Message',
- a: 'search_user',
- data: user
- };
- FastChat.ws_send(load_message);
- } else if (parseInt(event.keyCode) === 38) {
- FastChat.search_primary--;
- FastChat.setSelectedItem();
- } else if (parseInt(event.keyCode) === 40) {
- FastChat.search_primary++;
- FastChat.setSelectedItem();
- }
- event.preventDefault()
- })
- },
- browserType: function () {
- var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
- var isOpera = false;
- if (userAgent.indexOf('Edge') > -1) {
- return "Edge";
- }
- if (userAgent.indexOf('.NET') > -1) {
- return "IE";
- }
- if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
- isOpera = true;
- return "Opera"
- }
- ; //判断是否Opera浏览器
- if (userAgent.indexOf("Firefox") > -1) {
- return "FF";
- } //判断是否Firefox浏览器
- if (userAgent.indexOf("Chrome") > -1) {
- return "Chrome";
- }
- if (userAgent.indexOf("Safari") > -1) {
- return "Safari";
- } //判断是否Safari浏览器
- if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
- return "IE";
- }
- ; //判断是否IE浏览器
- }
- }
|