One Hat Cyber Team
  • Dir : ~/www/server/panel/BTPanel/static/js/
  • Edit File: tools.js
    '; break; case 'select': var options = config.options, optionsHtml = ''; for (var i = 0; i < options.length; i++) { var item = options[i],newItem = item; if(typeof item === 'string') newItem = { label: item, value: item } optionsHtml += '' } $form = ''; break; case 'text': $form = ''; break; } $form = $($form); $form.width(config.width || '100%').attr(props); if(!config.on) config.on = {}; for (var onKey in config.on) { (function (onKey) { $form.on(onKey,function (ev){ config.on[onKey].apply(this, [ev,$(this).val()]); }); })(onKey); } return $form }, /** * @description 渲染表单行组 * @param {object} el 配置参数 * @param {object} config 配置参数 * @param {object|undefined} formData 表单数据 */ fromGroup: function (el,config,formData){ var $el = $(el), lineList = {} for (var i = 0; i < config.length; i++) { var item = config[i]; if(item.type === 'tips'){ $el.append(this.help(item)); }else{ var line = this.line(item); if(typeof formData != "undefined") line.$form.val(formData[item.name] || ''); lineList[line.$form.attr('name')] = line; $el.append(line.$line); } } return lineList }, /** * @description 渲染Form表单 * @param {*} config * @return 当前实例对象 */ form: function (config) { var _that = this; function ReaderForm(config) { this.config = config; this.el = config.el this.submit = config.submit this.data = config.data || {}; this.$load(); } ReaderForm.prototype = { element: null, style_list: [], // 样式列表 event_list: {}, // 事件列表,已绑定事件 event_type: ['click', 'event', 'focus', 'keyup', 'blur', 'change', 'input'], hide_list: [], form_element: {}, form_config: {}, random: bt.get_random(5), $load: function () { var that = this; if (this.el) { $(this.el).html(this.$reader_content()) this.$event_bind(); } }, /** * @description 渲染Form内容 * @param {Function} callback 回调函数 */ $reader_content: function (callback) { var that = this, html = '', _content = ''; $.each(that.config.form, function (index, item) { if (item.separate) { html += '
    ' + item.separate + '
    ' } else { html += that.$reader_content_row(index, item); } }); that.element = $('' + html + '
    '); _content = $('
    '); _content.append(that.element); if (callback) callback(); return _content[0].outerHTML; }, /** * @description 渲染行内容 * @param {object} data Form数据 * @param {number} index 下标 * @return {string} HTML结构 */ $reader_content_row: function (index, data) { try { var that = this, help = data.help || false, labelWidth = data.formLabelWidth || this.config.formLabelWidth; if (data.display === false) return ''; return '
    ' + (typeof data.label !== "undefined" ? '' + (typeof data.must !== "undefined" && data.must != '' ? ''+data.must+'':'') + data.label + '' : '') + '
    ' + that.$reader_form_element(data.group, index) + (help ? ('
    ' + help.list.join('
    ') + '
    ') : '') + '
    ' + '
    '; } catch (error) { console.log(error) } }, /** * @description 渲染form类型 * @param {object} data 表单数据 * @param {number} index 下标 * @return {string} HTML结构 */ $reader_form_element: function (data, index) { var that = this, html = ''; if (!Array.isArray(data)) data = [data]; $.each(data, function (key, item) { item.find_index = index; html += that.$reader_form_find(item); that.form_config[item.name] = item; }); return html; }, /** * @descripttion 渲染单个表单元素 * @param {Object} item 配置 * @return: viod */ $reader_form_find: function (item) { var that = this, html = '', style = that.$reader_style(item.style) + _that.$verify(item.width, 'width', 'style'), attribute = that.$verify_group(item, ['name', 'placeholder', 'disabled', 'readonly', 'autofocus', 'autocomplete', 'min', 'max']), event_group = that.$create_event_config(item), eventName = '', index = item.find_index; if (item.display === false) return html html += item.label ? '' + item.label + '' : ''; if (typeof item['name'] !== "undefined") { that.$check_event_bind(item.name, event_group) } html += '
    '; var _value = typeof that.data[item.name] !== "undefined" && that.data[item.name] != '' ? that.data[item.name] : (item.value || '') switch (item.type) { case 'text': // 文本选择 case 'checkbox': // 复选框 case 'password': // 密码 case 'radio': // 单选框 case 'number': // 数字 var _event = 'event_' + item.name + '_' + that.random; switch (item.type) { case 'checkbox': // 复选框 html += ''; if (!(typeof item.disabled != 'undefined' && item.disabled)) { that.$check_event_bind(_event, { input: { type: 'checkbox', config: item, event: item.event } }); } break; default: html += ''; break; } if (item.btn && !item.disabled) { html += '' + item.btn.title + ''; if (typeof item.btn.event !== 'undefined') { that.$check_event_bind(item.name + '_btn', { 'click': { config: item, event: item.btn.event } }) } } if (item.icon) { html += ''; if (typeof item.icon.event !== 'undefined') { that.$check_event_bind(item.name + '_icon', { 'click': { type: 'select_path', select: item.icon.select || '', config: item, children: '.' + item.name + '_icon', event: item.icon.event, callback: item.icon.callback } }) } } break; case 'textarea': html += ''; $.each(['blur', 'focus', 'input'], function (index, items) { if (item.tips) { var added = null, event = {} switch (items) { case 'blur': added = function (ev, item, element) { if ($(this).val() === '') $(this).next().show(); layer.close(item.tips.loadT); $(ev.target).data('layer', ''); } break; case 'focus': added = function (ev, item) { $(this).next().hide(); item.tips.loadT = layer.tips(tips, $(this), { tips: [1, '#20a53a'], time: 0, area: $(this).width() }); } break; } } that.event_list[item.name][items] ? (that.event_list[item.name][items]['added'] = added) : (that.event_list[item.name][items] = { type: item.type, cust: false, event: item[items], added: added }); }); if (item.tips) { var tips = ''; if (typeof item.tips.list === "undefined") { tips = item.tips.text; } else { tips = item.tips.list.join('
    '); } html += '
    ' + tips + '
    '; that.$check_event_bind(item.name + '_tips', { 'click': { type: 'textarea_tips', config: item } }) } break; case 'select': html += that.$reader_select(item, style, attribute, index); that.$check_event_bind('custom_select', { 'click': { type: 'custom_select', children: '.bt_select_value' } }) that.$check_event_bind('custom_select_item', { 'click': { type: 'custom_select_item', children: 'li.item' } }) break; case 'link': eventName = 'event_link_' + that.random + '_' + item.name; html += '' + item.title + ''; that.$check_event_bind(eventName, { 'click': { type: 'link_event', event: item.event } }) break; case 'button': html += '' break; case 'help': var _html = ''; $.each(item.list, function (index, items) { _html += '
  • ' + items + '
  • '; }) html += ''; break; case 'other': html += item.boxcontent; } html += item.unit ? '' + item.unit + '' : ''; html += '
    ' return html; }, /** * @descripttion 检测检测名称 * @param {string} eventName 配置 * @param {object} config 事件配置 */ $check_event_bind: function (eventName, config) { if (!this.event_list[eventName]) { if (!this.event_list.hasOwnProperty(eventName)) { this.event_list[eventName] = config } } }, /** * @description 创建事件配置 * @param {object} item 行内配置 * @return {object} 配置信息 */ $create_event_config: function (item) { var config = {}; if (typeof item['name'] === "undefined") return {}; $.each(this.event_type, function (key, items) { if (item[items]) { config[(items === 'event' ? 'click' : items)] = { type: item.type, event: item[items], cust: (['select', 'checkbox', 'radio'].indexOf(item.type) > -1), config: item }; } }); return config; }, /** * @description 渲染样式 * @param {object|string} data 样式配置 * @return {string} 样式 */ $reader_style: function (data) { var style = ''; if (typeof data === 'string') return data; if (typeof data === 'undefined') return ''; $.each(data, function (key, item) { style += key + ':' + item + ';'; }); return style; }, /** * @descripttion 局部刷新form表单元素 * @param {String} name 需要刷新的元素 * @param {String} name 元素新数据 * @return: viod */ $local_refresh: function (name, config) { var formFind = this.element.find('[data-name=' + name + ']') if (this.element.find('[data-name=' + name + ']').length === 0) formFind = this.element.find('[name=' + name + ']') formFind.parent().replaceWith(this.$reader_form_find(config)) }, /** * @description 渲染下拉,内容方法 */ $reader_select: function (item, style, attribute, index) { var that = this, list = '', option = '', active = {}; if (typeof item.list === 'function') { var event = item.list; event.call(this, this.config.form); item.list = []; } if (!Array.isArray(item.list)) { var config = item.list; bt_tools.send({ url: config.url, data: config.param || config.data || {} }, function (res) { if (res.status !== false) { var list = item.list.dataFilter ? item.list.dataFilter(res, that) : res; if (item.list.success) item.list.success(res, that, that.config.form[index], list) item.list = list if (!item.list.length) { item.disabled = true layer.msg(item.placeholder || '数据获取为空', {icon: 2}) } that.$replace_render_content(index); } else { bt.msg(res); } }); return false } if (typeof that.data[item.name] === "undefined") active = item.list[0] $.each(item.list, function (key, items) { if (items.value === item.value || items.value === that.data[item.name]) { active = items return false } }) $.each(item.list, function (key, items) { list += '
  • ' + items.title + '
  • '; option += ''; }); var title = !Array.isArray(item.list) ? 'Getting data...' : (active ? active.title : item.placeholder) return '
    ' + '' + (title || item.placeholder) + '' + '' + '' + (option || '') + '' + '
    '; }, /** * @description 替换渲染内容 */ $replace_render_content: function (index) { var that = this, config = this.config.form[index], html = that.$reader_content_row(index, config); $('[data-form=' + that.random + ']').find('.line:eq(' + index + ')').replaceWith(html); this.$event_bind() }, /** * @description 重新渲染内容 * @param {object} formConfig 配置 */ $again_render_form: function (formConfig) { var formElement = $('[data-form=' + this.random + ']'), that = this; formConfig = formConfig || this.config.form formElement.empty() for (var i = 0; i < formConfig.length; i++) { var config = formConfig[i] if (config.display === false) continue formElement.append(that.$reader_content_row(i, config)) } this.config.form = formConfig this.$event_bind() }, /** * @description 事件绑定功能 * @param {Object} eventList 事件列表 * @param {Function} callback 回调函数 * @return void */ $event_bind: function (eventList, callback) { var that = this, _event = {}; that.element = $(typeof eventList === 'object' ? that.element : ('[data-form=' + that.random + ']')); _event = eventList if (typeof eventList === 'undefined') _event = that.event_list; $.each(_event, function (key, item) { if ($.isEmptyObject(item)) return true; $.each(item, function (keys, items) { if (!!item.type) return false; if (!items.hasOwnProperty('bind')) { items.bind = true } else { return false } var childNode = ''; if (typeof items.cust === "boolean") { childNode = '[' + (items.cust ? 'data-' : '') + 'name=' + key + ']'; } else { childNode = '.' + key; } (function (items, key) { if (items.onEvent === false) { switch (items.type) { case 'input_checked': $(childNode).on(keys != 'event' ? keys : 'click', function (ev) { items.event.apply(this, [ev, that]); }); break; } return true; } else { if (items.type === 'select') return true that.element.on(keys !== 'event' ? keys : 'click', items.children ? items.children : childNode, function (ev) { var form = that.$get_form_element(true), config = that.form_config[key]; switch (items.type) { case 'textarea_tips': $(this).hide().prev().focus(); break; case 'custom_select': if ($(this).parent().hasClass('bt-disabled')) return false; var select_value = $(this).next(); if (!select_value.hasClass('show')) { var $target = $(ev.currentTarget); var $layer = $target.parents('.layui-layer'); var layerTop = $layer.length > 0 ? parseFloat($layer.css('top')) : 0 var layerLeft = $layer.length > 0 ? parseFloat($layer.css('left')) : 0 var offset = $target[0].getBoundingClientRect(); var top = offset.top - layerTop + offset.height + 2 var left = offset.left - layerLeft $('.bt_select_list').css({ position: 'fixed', width: offset.width + 'px', top: top + 'px', left: left + 'px' }) $('.bt_select_list').removeClass('show'); select_value.addClass('show'); } else { select_value.removeClass('show'); } $(document).click(function () { that.element.find('.bt_select_list').removeClass('show'); $(this).unbind('click'); return false; }); return false; break; case 'custom_select_item': config = that.form_config[$(this).parents('.bt_select_updown').attr('data-name')] var item_config = config.list[$(this).index()] if ($(this).hasClass('disabled')) { $(this).parent().removeClass('show'); if (item_config.tips) layer.msg(item_config.tips, {icon: 2}); return true; } if (!$(this).hasClass('active') && !$(this).hasClass('disabled')) { var value = item_config.value.toString(); $(this).parent().prev().find('.bt_select_content').text($(this).text()); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().next().val(value) $(this).parent().removeClass('show'); } that.data[config.name] = value if (items.event) items.event = null if (config.change) items.event = config.change break; case 'select_path': bt.select_path('event_' + $(this).prev().attr('name') + '_' + that.random, items.select || "", !items.callback || items.callback.bind(that)); break; case 'checkbox': var checked = $(this).is(':checked'); if (checked) { $(this).prev().addClass('active'); } else { $(this).prev().removeClass('active'); } break; } if (items.event) items.event.apply(this, [that.$get_form_value(), form, that, config, ev]); // 事件 if (items.added) items.added.apply(this, [ev, config, form]); }); } }(items, key)); }); }); if (callback) callback(); }, /** * @description 获取表单数据 * @return {object} 表单数据 */ $get_form_value: function () { var form = {} this.element.find('input,textarea[disabled="disabled"]').each(function (index, item) { var val = $(this).val(); if ($(this).attr('type') === 'checkbox') { val = $(this).prop('checked') } form[$(this).attr('name')] = val }) return $.extend({}, this.element.serializeObject(), form) }, /** * @description 设置指定数据 * */ $set_find_value: function (name, value) { var config = {}, that = this; typeof name != 'string' ? config = name : config[name] = value; $.each(config, function (key, item) { that.form_element[key].val(item); }); }, /** * @description 获取Form,jquery节点 * @param {Boolean} afresh 是否强制刷新 * @return {object} */ $get_form_element: function (afresh) { var form = {}, that = this; if (afresh || $.isEmptyObject(that.form_element)) { this.element.find(':input').each(function (index) { form[$(this).attr('name')] = $(this); }); that.form_element = form; return form; } else { return that.form_element; } }, /** * @description 验证值整个列表是否存在,存在则转换成属性字符串格式 */ $verify_group: function (config, group) { var that = this, str = ''; $.each(group, function (index, item) { if (typeof config[item] === "undefined") return true; if (['disabled', 'readonly'].indexOf(item) > -1) { str += ' ' + (config[item] ? (item + '="' + item + '"') : ''); } else { str += ' ' + item + '="' + config[item] + '"'; } }); return str; }, /** * @description 验证绑定事件 * @param {String} value */ $verify_bind_event: function (eventName, row, group) { var event_list = {}; $.each(group, function (index, items) { var event_fun = row[items]; if (event_fun) { if (typeof event_list[eventName] === "object") { if (!Array.isArray(event_list[eventName])) event_list[eventName] = [event_list[eventName]]; event_list[eventName].push({ event: event_fun, eventType: items }); } else { event_list[eventName] = { event: event_fun, eventType: items }; } } }); return event_list; }, /** * @description 验证值是否存在 * @param {String} value 内容/值 * @param {String|Boolean} attr 属性 * @param {String} type 属性 */ $verify: function (value, attr, type) { if (!value) return ''; if (type === true) return value ? ' ' + attr : ''; if (type === 'style') return attr ? attr + ':' + value + ';' : value; return attr ? ' ' + attr + '="' + value + '"' : ' ' + value; }, /** * @description 验证form表单 */ $verify_form: function () { var form_list = {}, form = this.config.form, form_value = this.$get_form_value(), form_element = this.$get_form_element(true); for (var key = 0; key < form.length; key++) { var item = form[key]; if (!Array.isArray(item.group)) item.group = [item.group]; if (item.separate) continue for (var i = 0; i < item.group.length; i++) { var items = item.group[i], name = items.name; if (items.type === 'help') continue; if (typeof items.verify != "undefined") { var value = items.verify(form_value[name], form_element[name], items, true); if (value === false && form_value[name] !== false) return false; form_list[name] = value; } else { form_list[name] = (typeof form_value[name] === "undefined" && items.disabled) ? $('[name="' + name + '"]').val() : form_value[name]; } } } return form_list; }, /** * @description 提交内容,需要传入url * @param {Object|Function} param 附加参数或回调函数 * @param {Function} callback 回调 */ $submit: function (param, callback, tips) { var form = this.$verify_form(); if (typeof param === "function") tips = callback, callback = param, param = {}; if (!form) return false; form = $.extend(form, param); if (typeof this.config.url == "undefined") { bt_tools.msg('Request Submission address cannot be empty!', false); return false; } bt_tools.send({ url: this.config.url, data: form }, function (res) { if (callback) { callback(res, form); } else { bt_tools.msg(res); } }, (tips || 'Submit')); } } return new ReaderForm(config); }, /** * @description tab切换,支持三种模式 * @param {object} config * @return 当前实例对象 */ tab: function (config) { var _that = this; function ReaderTab(config) { this.config = config; this.theme = this.config.theme || {}; this.$load(); } ReaderTab.prototype = { type: 1, theme_list: [{ content: 'tab-body', nav: 'tab-nav', body: 'tab-con', active: 'on' }, { content: 'bt-w-body', nav: 'bt-w-menu', body: 'bt-w-con' } ], random: bt.get_random(5), $init: function () { var that = this, active = this.config.active, config = that.config.list, _theme = {}; this.$event_bind(); if (config[that.active].success) config[that.active].success(); config[that.active]['init'] = true; }, $load: function () { var that = this; }, $reader_content: function () { var that = this, _list = that.config.list, _tab = '', _tab_con = '', _theme = that.theme, config = that.config; if (typeof that.active === "undefined") that.active = 0; if (!$.isEmptyObject(config.theme)) { _theme = this.theme_list[that.active]; $.each(config.theme, function (key, item) { if (_theme[key]) _theme[key] += ' ' + item; }); that.theme = _theme; } if (config.type && $.isEmptyObject(config.theme)) this.theme = this.theme_list[that.active]; $.each(_list, function (index, item) { var active = (that.active === index), _active = _theme['active'] || 'active'; _tab += '' + item.title + ''; _tab_con += '
    ' + (active ? item.content : '') + '
    '; }); that.element = $('
    ' + _tab + '
    ' + _tab_con + '
    '); return that.element[0].outerHTML; }, /** * @description 事件绑定 * */ $event_bind: function () { var that = this, _theme = that.theme, active = _theme['active'] || 'active'; if (!that.el) that.element = $('#tab_' + that.random); that.element.on('click', ('.' + _theme['nav'].replace(/\s+/g, '.') + ' span'), function () { var index = $(this).index(), config = that.config.list[index]; $(this).addClass(active).siblings().removeClass(active); $('#tab_' + that.random + ' .' + _theme['body'] + '>div:eq(' + index + ')').addClass(active).siblings().removeClass(active); that.active = index; if (!config.init) { // console.log(_theme) var contentItem = $('#tab_' + that.random + ' .' + _theme['body'] + '>div:eq(' + index + ')') contentItem.html(config.content); if (config.success) config.success(contentItem); config.init = true; } }); } } return new ReaderTab(config); }, /** * @description loading过渡 * @param {*} title * @param {*} is_icon * @return void */ load: function (title) { var random = bt.get_random(5), layel = $('
    ' + title + ',please wait...
    '), mask = '', loadT = ''; $('body').append(layel); var win = $(window), msak = $('.layer-loading-mask'), layel = $('#' + random); layel.css({'top': ((win.height() - 64) / 2), 'left': ((win.width() - 320) / 2)}); if (title === true) loadT = layer.load(); return { close: function () { if (typeof loadT == "number") { layer.close(loadT); } else { $('body').find('#' + random + ',#layer-mask-' + random).remove(); } } } }, /** * @description 弹窗方法,有默认的参数和重构的参数 * @param {object} config 和layer参数一致 * @require 当前关闭弹窗方法 */ open: function (config) { var _config = {}, layerT = null, form = null; _config = $.extend({type: 1, area: '640px', closeBtn: 2, btn: ['Yes', 'No']}, config); if (typeof _config.content == "object") { var param = _config.content; form = bt_tools.form(param); _config.success = function (layero, indexs) { form.$event_bind(); if (typeof config.success != "undefined") config.success(layero, indexs); } _config.yes = function (indexs, layero) { var form_val = form.$verify_form(); if (!form_val) return false; if (typeof config.yes != "undefined") { var yes = config.yes.apply(form, [form_val, indexs, layero]); if (!yes) return false; } } _config.content = form.$reader_content(); } layerT = layer.open(_config); return { close: function () { layer.close(layerT); }, form: form } }, /** * @description 封装msg方法 * @param {object|string} param1 配置参数,请求方法参数 * @param {number} param2 图标ID * @require 当前关闭弹窗方法 */ msg: function (param1, param2) { var layerT = null, msg = '', config = {}; if (typeof param1 === "object") { if (typeof param1.status === "boolean") { msg = param1.msg, config = {icon: param1.status ? 1 : 2}; if (!param1.status) config = $.extend(config, {time: (!param2 ? 0 : 3000), closeBtn: 2, shade: .3}); } } if (typeof param1 === "string") { msg = param1, config = { icon: typeof param2 !== 'undefined' ? param2 : 1 } } layerT = layer.msg(msg, config); return { close: function () { layer.close(layerT); } } }, /** * @description 成功提示 * @param {string} msg 信息 */ success: function (msg) { this.msg({ msg: msg, status: true }); }, /** * @description 错误提示 * @param {string} msg 信息 */ error: function (msg) { this.msg({msg: msg, status: false }); }, /** * @description 请求封装 * @param {string|object} conifg ajax配置参数/请求地址 * @param {function|object} callback 回调函数/请求参数 * @param {function} callback1 回调函数/可为空 * @returns void 无 */ send: function (param1, param2, param3, param4, param5, param6) { var params = {}, success = null, error = null, config = [], param_one = ''; $.each(arguments, function (index, items) { config.push([items, typeof items]); }); function diff_data (i) { try { success = config[i][1] == "function" ? config[i][0] : null; error = config[(i + 1)][1] == "function" ? config[(i + 1)][0] : null; } catch (error) { } } param_one = config[0]; switch (param_one[1]) { case "string": $.each(config, function (index, items) { var value = items[0], type = items[1]; if (index > 1 && (type == "boolean" || type == "string" || type == "object")) { var arry = param_one[0].split('/'); params['url'] = '/' + arry[0] + '?action=' + arry[1]; if (type == "object") { params['load'] = value.load; params['verify'] = value.verify; if (value.plugin) params['url'] = '/plugin?action=a&name=' + arry[0] + '&s=' + arry[1]; } else if (type == 'string') { params['load'] = value; } return false; } else { params['url'] = param_one[0]; } }); if (config[1][1] === "object") { params['data'] = config[1][0]; diff_data(2); } else { diff_data(1); } break; case 'object': params['url'] = param_one[0].url; params['data'] = param_one[0].data || {}; $.each(config, function (index, items) { var value = items[0], type = items[1]; if (index > 1 && (type == "boolean" || type == "string" || type == "object")) { switch (type) { case "object": params['load'] = value.load; params['verify'] = value.verify; break; case "string": params['load'] = value; break; } return true; } }); if (config[1][1] === "object") { params['data'] = config[1][0]; diff_data(2); } else { diff_data(1); } break; } if (params.load) params.load = this.load(params.load); $.ajax({ type: params.type || "POST", url: params.url, data: params.data || {}, dataType: params.dataType || "JSON", complete: function (res) { if (params.load) params.load.close(); }, success: function (res) { if (typeof params.verify == "boolean" && !params.verify) { if (success) success(res); return false; } if (typeof res === "string") { layer.msg(res, { icon: 2, time: 0, closeBtn: 2 }); return false; } if (params.batch) { if (success) success(res); return false; } if (res.status === false && (res.hasOwnProperty('msg') || res.hasOwnProperty('error_msg'))) { if (error) { error(res) } else { bt_tools.msg({ status: res.status, msg: !res.hasOwnProperty('msg') ? res.error_msg : res.msg }); } return false; } if (params.tips) { bt_tools.msg(res); } if (success) success(res); } }); }, /** * @description 命令行输入 */ command_line_output: function (config) { var _that = this, uuid = bt.get_random(15); /** * @description 渲染 * @param config * @return {object} * @constructor */ function ReaderCommand(config) { var that = this; for (var key in _that.commandConnectionPool) { var item = _that.commandConnectionPool[key], element = $(item.config.el) if (config.shell === item.config.shell && element.length) { item.el = element return item } } if (typeof config === "undefined") config = {} this.config = $.extend({route: '/sock_shell'}, config) this.xterm_config = $.extend(this.xterm_config, this.config.xterm) this.el = $(this.config.el); this.open = config.open; this.close = config.close; this.message = config.message; if (!this.config.hasOwnProperty('el')) { _that.msg({msg: '请输入选择器element,不可为空', status: false}) return false; } if (!this.config.hasOwnProperty('shell')) { _that.msg({msg: '请输入命令,不可为空', status: false}) return false; } if (this.config.hasOwnProperty('time')) { setTimeout(function () { that.close_connect() }, this.config.time) } this.init() } ReaderCommand.prototype = { socket: null, //websocket 连接保持的对象 socketToken: null, timeout: 0, // 连接到期时间,为0代表永久有效 monitor_interval: 2000, element_detection: null, uuid: uuid, fragment: [], error: 0, // 错误次数,用于监听元素内容是否还存在 retry: 0, // 重试次数 forceExit: false, // 强制断开连接 /** * @description 程序初始化 */ init: function () { var oldUUID = bt.get_cookie('commandInputViewUUID'), that = this; if (!this.el[0]) { if (this.error > 10) return false; setTimeout(function () { that.init() this.error++; }, 2000) return false; } this.error = 0 if (this.el[0].localName !== 'pre') { this.el.append('
    ');
                        this.el = this.el.find('pre');
                        this.config.el = this.config.el + ' pre'
                    } else {
                        this.el.addClass('command_output_pre');
                    }
                    if (Array.isArray(this.config.area)) {
                        this.el.css({width: this.config.area[0], height: this.config.area[1]})
                    } else {
                        this.el.css({width: '100%', height: '100%'})
                    }
                    if (oldUUID && typeof _that.commandConnectionPool[oldUUID] != "undefined") {
                        _that.commandConnectionPool[oldUUID].close_connect();
                        delete _that.commandConnectionPool[oldUUID];
                    }
                    bt.set_cookie('commandInputViewUUID', this.uuid);
                    this.element_detection = setInterval(function () {
                        if (!$(that.config.el).length) {
                            clearInterval(that.element_detection)
                            that.forceExit = true;
                            that.close_connect();
                        }
                    }, 1 * 60 * 1000)
                    this.set_full_screen()
                    this.create_websocket_connect(this.config.route, this.config.shell)
                    this.monitor_element()
                },
                /**
                 * @description 创建websocket连接
                 * @param {string} url websocket连接地址
                 * @param {string} shell 需要传递的命令
                 */
                create_websocket_connect: function (url, shell) {
                    var that = this;
                    this.socket = new WebSocket((location.protocol === 'http:' ? 'ws://' : 'wss://') + location.host + url)
                    this.socket.addEventListener('open', function (ev) {
                        if (!this.socketToken) {
                            var _token = document.getElementById('request_token_head').getAttribute('token');
                            this.socketToken = {'x-http-token': _token}
                        }
                        this.send(JSON.stringify(this.socketToken))
                        this.send(shell)
                        if (that.open) that.open()
                        that.retry = 0
                    });
                    this.socket.addEventListener('close', function (ev) {
                        if (!that.forceExit) {
                            if (ev.code !== 1000 && that.retry <= 10) {
                                that.socket = that.create_websocket_connect(that.config.route, that.config.shell)
                                that.retry++;
                            }
                            if (that.close) that.close(ev)
                        }
                    });
                    this.socket.addEventListener('message', function (ws_event) {
                        var result = ws_event.data
                        if (!result) return;
                        that.refresh_data(result)
                        if (that.message) that.message(result)
    
                    })
                    return this.socket
                },
    
                /**
                 * @description 设置全屏视图
                 */
                set_full_screen: function () {
    // 1
                },
    
                htmlEncodeByRegExp: function (str) {
                    if (str.length == 0) return "";
                    return str.replace(/&/g, "&")
                        .replace(//g, ">")
                        .replace(/ /g, " ")
                        .replace(/\'/g, "'")
                        .replace(/\"/g, """);
                },
    
                /**
                 * @description 刷新Pre数据
                 * @param {object} data 需要插入的数据
                 */
                refresh_data: function (data) {
                    var data = this.htmlEncodeByRegExp(data)
                    this.fragment.push(data)
                    if (this.fragment.length >= 300) {
                        this.fragment.splice(0, 150)
                        this.el.html(this.fragment.join(''))
                    } else {
                        this.el.append(data)
                    }
    								if (this.el.length > 0) {
    									this.el.scrollTop(this.el[0].scrollHeight)
    								}
                },
    
                /**
                 * @description 监听元素状态,判断是否移除当前的ws连接
                 *
                 */
                monitor_element: function () {
                    var that = this;
                    this.monitor_interval = setInterval(function () {
                        if (!that.el.length) {
                            that.close_connect()
                            clearInterval(that.monitor_interval)
                        }
                    }, that.config.monitorTime || 2000)
                },
    
                /**
                 * @description 断开命令响应和websocket连接
                 */
                close_connect: function () {
                    this.socket.send('')
                    this.socket.close()
                    delete _that.commandConnectionPool[this.uuid];
                }
            }
            this.commandConnectionPool[uuid] = new ReaderCommand(config)
            return this.commandConnectionPool[uuid]
        },
    
    
        /**
         * @description 清理验证提示样式
         * @param {object} element  元素节点
         */
        $clear_verify_tips: function (element) {
            element.removeClass('bt-border-error bt-border-sucess');
            layer.close('tips');
        },
    
        /**
         * @description 验证提示
         * @param {object} element  元素节点
         * @param {string} tips 警告提示
         * @return void
         */
        $verify_tips: function (element, tips, is_error) {
            if (typeof is_error === "undefined") is_error = true;
            element.removeClass('bt-border-error bt-border-sucess').addClass(is_error ? 'bt-border-error' : 'bt-border-sucess');
            element.focus();
            layer.tips('' + tips + "", element, {
                tips: [1, is_error ? 'red' : '#20a53a'],
                time: 3000,
                area: element.width()
            });
        },
        /**
         * @description 验证值是否存在
         * @param {String} value 内容/值
         * @param {String|Boolean} attr 属性
         * @param {String} type 属性
         */
        $verify: function (value, attr, type) {
            if (!value) return '';
            if (type === true) return value ? ' ' + attr : '';
            if (type === 'style') return attr ? attr + ':' + value + ';' : value;
            return attr ? ' ' + attr + '="' + value + '"' : ' ' + value;
        },
    
        /**
         * @description 批量操作的结果
         * @param {*} config
         */
        $batch_success_table: function (config) {
            var _that = this, length = $(config.html).length;
            bt.open({
                type: 1,
                title: config.title,
                area: config.area || ['400px'],
                shadeClose: false,
                closeBtn: 2,
                content: config.content || '
    ' + config.title + ' ' + lan['public'].success + '
    ' + config.html + '
    ' + config.th + '' + lan['public'].result + '
    ', success: function () { if (length > 4) _that.$fixed_table_thead('.fiexd_thead'); } }); }, /** * @description 固定表头 * @param {string} el DOM选择器 * @return void */ $fixed_table_thead: function (el) { $(el).scroll(function () { var scrollTop = this.scrollTop; this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; }); }, /** * @description 插件视图设置 * @param {object|string} layid dom元素或layer_id * @param {object} config 插件宽度高度或其他配置 */ $piugin_view_set: function (layid, config) { var element = $(typeof layid === "string" ? ('#layui-layer' + layid) : layid).hide(), win = $(window); setTimeout(function () { var width = config.width || element.width(), height = config.height || element.height(); element.css($.extend(config, { left: ((win.width() - width) / 2), top: ((win.height() - height) / 2) })).addClass('custom_layer'); }, 50); setTimeout(function () { element.show(); }, 500) } }; setTimeout(function () { $.fn.serializeObject = function () { var hasOwnProperty = Object.prototype.hasOwnProperty; return this.serializeArray().reduce(function (data, pair) { if (!hasOwnProperty.call(data, pair.name)) { data[pair.name] = pair.value; } return data; }, {}); }; }, 300) function arryCopy(arrys) { var list = arrys.concat(), arry = [] for (var i = 0; i < list.length; i++) { arry.push($.extend(true, {}, list[i])) } return arry }