// 缓存机制 var foowwLocalStorage = { set: function (key, value, ttl_ms) { var data = { value: value, expirse: new Date(ttl_ms).getTime() }; localStorage.setItem(key, JSON.stringify(data)); }, get: function (key) { var data = JSON.parse(localStorage.getItem(key)); if (data !== null) { // debugger if (data.expirse != null && data.expirse < new Date().getTime()) { localStorage.removeItem(key); } else { return data.value; } } return null; } } function RandomIndex(min, max, i) { let index = Math.floor(Math.random() * (max - min + 1) + min), numStart = _charStr.length - 10; //如果字符串第one位是数字,则递归重新获取 if (i == 0 && index >= numStart) { index = RandomIndex(min, max, i); } //返回最终索引值 return index; } var clientMsgContextTarget = null; /** Escape text for HTML text nodes (not for trusted rich HTML). */ function escapeChatText(str) { if (str == null || str === '') { return ''; } return String(str) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /** Allow basic markup from server (links) but drop scripts and inline handlers. */ function sanitizeMessageHtml(html) { if (html == null || html === '') { return ''; } const $wrap = $('
').html(String(html)); $wrap.find('script, style, iframe, object, embed').remove(); $wrap.find('*').each(function () { const el = this; $.each(el.attributes, function () { const n = (this.name || '').toLowerCase(); if (n.indexOf('on') === 0) { $(el).removeAttr(this.name); } }); }); return $wrap.html(); } function safeChatMessageBody(text) { const raw = text == null ? '' : String(text); if (raw.indexOf('<') !== -1 && raw.indexOf('>') !== -1) { return sanitizeMessageHtml(raw); } return escapeChatText(raw); } function safeJsStringInAttr(str) { return escapeChatText(str).replace(/\\/g, '\\\\'); } function bindAutoReplyProblemButtons(problems) { const $box = $("#chatAutoReplyProblems"); $box.off('click.autoProblem', 'button[data-auto-problem-title]'); $box.empty(); if (!problems || !problems.length) { return; } $.each(problems, function (i, item) { const title = item.title == null ? '' : String(item.title); $('') .attr('data-auto-problem-title', title) .text('+ ' + title) .appendTo($box); }); $box.on('click.autoProblem', 'button[data-auto-problem-title]', function () { postAutoQuestion($(this).attr('data-auto-problem-title') || ''); }); } function hideClientMsgContextMenu() { $('#clientMsgContextMenu').hide(); clientMsgContextTarget = null; } function clientOwnMessageBlockAttrs(tempId, contentId) { let attrs = ' class="chat-block chatR" data-own="1"'; if (contentId) { attrs += ' data-uuid="' + contentId + '"'; } if (tempId) { attrs += ' data-temp-id="' + tempId + '"'; } return attrs; } function removeClientMessageBlocks(contentIds) { if (!contentIds || !contentIds.length) { return; } contentIds.forEach(function (cid) { $('.chatMeassge .chat-block[data-uuid="' + cid + '"]').remove(); }); $('.chatMeassge .chat-block.msg-selected').removeClass('msg-selected'); } function collectClientDeleteContentIds($blocks) { let ids = []; $blocks.each(function () { const uuid = $(this).attr('data-uuid'); if (uuid) { ids.push(uuid); } }); return ids; } function emitClientDeleteMessages(contentIds) { if (!contentIds.length) { return; } let chatUsid = foowwLocalStorage.get(chatUsidKey); let chatSession = foowwLocalStorage.get(chatSessionKey); if (!chatUsid || !chatSession) { return; } socket_app.emit('customerDeleteMessage', { 'content_ids': contentIds, 'chatUsid': chatUsid, 'chatSession': chatSession, }); } function bindClientMessageDeleteUi() { const $menu = $('#clientMsgContextMenu'); $('.chatMeassge').on('contextmenu', '.chat-block.chatR[data-own="1"]', function (e) { e.preventDefault(); const $block = $(this); if (!$block.attr('data-uuid') && !$block.attr('data-temp-id')) { return false; } if (!$block.hasClass('msg-selected')) { $('.chatMeassge .chat-block.msg-selected').removeClass('msg-selected'); $block.addClass('msg-selected'); } clientMsgContextTarget = $block; $menu.css({ left: e.clientX + 'px', top: e.clientY + 'px' }).show(); return false; }); $('.chatMeassge').on('click', '.chat-block.chatR[data-own="1"]', function (e) { if (e.ctrlKey || e.metaKey) { $(this).toggleClass('msg-selected'); hideClientMsgContextMenu(); } }); $('#clientMsgDeleteBtn').on('click', function () { let $targets = $('.chatMeassge .chat-block.msg-selected[data-own="1"]'); if (!$targets.length && clientMsgContextTarget) { $targets = clientMsgContextTarget; } const contentIds = collectClientDeleteContentIds($targets); if (!contentIds.length) { hideClientMsgContextMenu(); return; } emitClientDeleteMessages(contentIds); hideClientMsgContextMenu(); }); $(document).on('click', function (e) { if (!$(e.target).closest('#clientMsgContextMenu').length) { hideClientMsgContextMenu(); } }); } // 生成随机字符串 function getRandomString(len) { let min = 0, max = _charStr.length - 1, _str = ''; //判断是否指定长度,否则默认长度为15 len = len || 15; //循环生成字符串 for (var i = 0, index; i < len; i++) { index = RandomIndex(min, max, i); _str += _charStr[index]; } return _str; } // 时间格式化 function formatDate(date, fmt) { if (typeof date == 'string') { return date; } if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss"; if (!date || date == null) return null; var o = { 'M+': date.getMonth() + 1, // 月份 'd+': date.getDate(), // day 'h+': date.getHours(), // 小时 'm+': date.getMinutes(), // 分 's+': date.getSeconds(), // 秒 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 'S': date.getMilliseconds() // 毫秒 } if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } return fmt } // day期格式化:月-day 时:分:秒 function getShiQuTime(msgtime) { let timezoneOffset = 0 - new Date().getTimezoneOffset() / 60; let ddl = msgtime.replace(/-/g, "/"); let dvv = new Date(ddl); const TODAY = new Date(dvv.setHours(dvv.getHours() + timezoneOffset)) return formatDate(TODAY, 'MM-dd hh:mm'); } // 聊天窗口激活反馈 function customerWinFocus_func() { let infoData = { 'site_code': sessionCode, } if (foowwLocalStorage.get(chatUsidKey)) { infoData['chatUsid'] = foowwLocalStorage.get(chatUsidKey); } if (foowwLocalStorage.get(chatSessionKey)) { infoData['chatSession'] = foowwLocalStorage.get(chatSessionKey); } socket_app.emit('customerWinFocus', infoData) } // 请求初始化访客信息 function send_request_init() { let infoData = { site_code: sessionCode, username: realname, email: mail, telephone: telephone, telegram: telegram, category: category, address: address, note: note, gender: gender }; console.log(infoData, '---------------info-------------'); if (foowwLocalStorage.get(chatUsidKey)) { infoData['chatUsid'] = foowwLocalStorage.get(chatUsidKey); } if (foowwLocalStorage.get(chatSessionKey)) { infoData['chatSession'] = foowwLocalStorage.get(chatSessionKey); } socket_app.emit('initVisitor', infoData) } // 上传文件 function upload_file() { let filepathObj = $("#filepath"); var imgpath = filepathObj.get(0).files[0]; if (imgpath === '') { alert('Please select file!') } else { var formdata = new FormData(); formdata.append("upload", imgpath); formdata.append("site_code", sessionCode); formdata.append("filename", imgpath.name); formdata.append("filesize", imgpath.size); formdata.append("action", 'uploadImage'); params = { 'data': formdata, 'contentType': false, 'processData': false, 'success': function (data) { if (data.code === 200) { filepathObj.val(''); $("#problemImage").val(data.message); $(".demoIMage img").attr('src', data.message); $(".uploadImageb").hide(); $(".demoIMage").show(); } else { xtalert.alertError(data.message); } } }; xtajax.post(params); } } // 快捷Enter customer service function advance_chat_func() { $(".blockScreen").show(); $("#fastBox").hide(); send_request_init(); } // submit快捷信息 function subFastFunc() { let problem = $.trim($("input[name='problem']:checked").data('title')); if (!problem) return; let title = $.trim($("#title").val()); let fqTime = $.trim($("#fqTime").val()); let content = $.trim($("#content").val()); let problemImage = $.trim($("#problemImage").val()); // Let's assume we have flags to indicate which fields are required let titleRequired = $("#title").attr("required"); let fqTimeRequired = $("#fqTime").attr("required"); let contentRequired = $("#content").attr("required"); let problemImageRequired = $("#problemImage").attr("required"); // Create an array for required fields that need to be validated let requiredFields = []; if (titleRequired) { requiredFields.push({ field: title, name: "Title" }); } if (fqTimeRequired) { requiredFields.push({ field: fqTime, name: "Time" }); } if (contentRequired) { requiredFields.push({ field: content, name: "Content" }); } if (problemImageRequired) { requiredFields.push({ field: problemImage, name: "Problem Image" }); } // Validate only required fields for (let i = 0; i < requiredFields.length; i++) { if (!requiredFields[i].field) { alert(requiredFields[i].name + " is required."); // Display an error message return; // Stop the function execution if any required field is missing } } let infoData = { 'site_code': sessionCode, 'problem': problem, 'enter': true } if (title) infoData['title'] = title infoData['enter'] = false if (fqTime) infoData['fqTime'] = fqTime infoData['enter'] = false if (content) infoData['content'] = content infoData['enter'] = false if (problemImage) infoData['problemImage'] = problemImage infoData['enter'] = false if (foowwLocalStorage.get(chatUsidKey)) { infoData['chatUsid'] = foowwLocalStorage.get(chatUsidKey); } if (foowwLocalStorage.get(chatSessionKey)) { infoData['chatSession'] = foowwLocalStorage.get(chatSessionKey); } socket_app.emit('initVisitor', infoData) $("#fastBox").hide(); $(".blockScreen").show(); } // Function to toggle the visibility of elements based on the problem states function toggleVisibility(problem) { // Title state if (problem.title_state) { $("#title").parent().parent().show(); $('#title').prev('span').html(`${problem.title_label}:`); $('#title').attr('placeholder', problem.title_label); if (problem.title_require) { $('#title').attr('required', 'required'); } else { $('#title').removeAttr('required'); } } else { $("#title").parent().parent().hide(); } // Content state if (problem.content_state) { $("#content").parent().parent().show(); $('#content').prev('span').html(`${problem.content_label}:`); $('#content').attr('placeholder', problem.content_label); if (problem.content_require) { $('#content').attr('required', 'required'); } else { $('#content').removeAttr('required'); } } else { $("#content").parent().parent().hide(); } // Time state if (problem.time_state) { $("#fqTime").parent().parent().show(); $('#fqTime').prev('span').html(`${problem.time_label}:`); $('#fqTime').attr('placeholder', problem.time_label); if (problem.time_require) { $('#fqTime').attr('required', 'required'); } else { $('#fqTime').removeAttr('required'); } } else { $("#fqTime").parent().parent().hide(); } // Picture state if (problem.picture_state) { $("#problemImage").parent().parent().show(); $('#problemImage').prev('span').html(`${problem.picture_label}:`); $('#problemImage').attr('placeholder', problem.picture_label); if (problem.picture_require) { $('#problemImage').attr('required', 'required'); } else { $('#problemImage').removeAttr('required'); } } else { $("#problemImage").parent().parent().hide(); } } function fetch_fastQuestion() { xtajax.get({ 'url': 'https://easychat.im/site_admin/siteManage', 'data': { 'action': 'get_fastQuestion_datas', 'site_code': sessionCode }, 'success': function (data) { if (data.code === 200) { $('.problemCheck').empty(); // Loop through each problem and add it to the DOM problems = JSON.parse(data.data.problems) problems.forEach(problem => { const title = problem.question_title == null ? '' : String(problem.question_title); const pid = problem.uuid || ('problem_' + Math.random().toString(36).slice(2)); const $row = $('
'); $('', { type: 'radio', class: 'form-check-input', name: 'problem', id: pid, value: pid, }).attr('data-title', title).appendTo($row); $('