Commit 22bf6962 authored by 何娜's avatar 何娜

增加ws

parent 412d9ef5
Pipeline #27997 passed with stage
in 1 minute 45 seconds
...@@ -27,18 +27,6 @@ class TaskController extends Controller { ...@@ -27,18 +27,6 @@ class TaskController extends Controller {
this.taskIdRule = { this.taskIdRule = {
taskId: { type: 'string', format: /\d+/ }, taskId: { type: 'string', format: /\d+/ },
}; };
this.cityListRule = {
sign: 'string',
params: {
type: 'object',
rule: {
token: 'string',
appKey: 'string',
timestamp: 'string',
},
},
};
} }
async configs() { async configs() {
......
This diff is collapsed.
'use strict';
window.onerror = function(errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {
const enabled_log_back = console.enabled_server_log;
console.enabled_server_log = true;
console.log(arguments);
console.enabled_server_log = enabled_log_back;
};
function getURLParams(url) {
const urlParts = url.split('?');
const result = {};
if (urlParts[1]) {
const params = urlParts[1].split('&');
for (let i = 0; i < params.length; ++i) {
const item = params[i].split('=');
const key = decodeURIComponent(item[0]);
const uri_encoded = item[1].replace(/%([^\da-fA-f].)/, '%25$1');
const val = decodeURIComponent(uri_encoded);
result[key] = val;
}
}
return result;
}
function serializeParams(data) {
let serializedParams = '';
for (const pro in data) {
serializedParams += (serializedParams.length ? '&' : '') + pro + '=' + encodeURIComponent(data[pro]);
}
return serializedParams;
}
function getParams(data, key, default_value) {
if (data != undefined) {
return key in data ? data[key] : default_value;
}
return default_value;
}
function isFunction(fn) {
return typeof fn === 'function';
}
function defineReactive(obj, key, val, before_change, after_change, flags) {
let blocking = false,
setter,
getter;
flags = flags || 0; // 第1位 值一样的情况下是否触发
if (val instanceof Object && isFunction(val.set) && isFunction(val.get)) {
setter = val.set;
getter = val.get;
} else {
getter = function() { return val; };
setter = function(newVal) { val = newVal; };
}
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter() {
return getter.call(obj);
},
set: function reactiveSetter(newVal) {
if (blocking) {
return;
}
blocking = true;
do {
if (val === newVal && !(flags & 1)) {
break;
}
if (isFunction(before_change) && before_change.call(obj, val, newVal) === true) {
break;
}
const originVal = val;
try {
setter.call(obj, newVal);
isFunction(after_change) && after_change.call(obj, originVal, val);
} catch (e) {
blocking = false;
throw e;
}
} while (false);
blocking = false;
},
});
}
function loadScript(url, fn, error) {
const script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
isFunction(fn) && fn();
}
};
} else {
script.onload = function() {
isFunction(fn) && fn();
};
script.onerror = function() {
isFunction(error) && error();
};
}
script.src = url;
document.body.appendChild(script);
}
function doAjax(args) {
let request = new XMLHttpRequest(),
url = getParams(args, 'url', ''),
data = getParams(args, 'data', {}),
contentType = getParams(args, 'contentType', 'application/x-www-form-urlencoded'),
type = getParams(args, 'type', 'get');
request.onreadystatechange = function() {
console.log(args, '【doAjax】request=====', JSON.stringify(request))
if (request.readyState == 4) {
if (request.status == 200) {
let dataType = null;
if ('dataType' in args) {
dataType = args.dataType;
} else {
if (/\bContent\-Type\s*:\s* ([^\n;]+)(?=\n|;)/i.test(request.getAllResponseHeaders())) {
const contentType = RegExp.$1;
if (/\bjson\b/i.test(contentType)) {
dataType = 'json';
} else {
dataType = 'text';
}
}
}
let data = null;
if (/^json$/i.test(dataType)) {
data = JSON.parse(request.responseText);
} else {
data = request.responseText;
}
try {
if (typeof args.success === 'function') {
args.success(data);
}
} catch (e) {
}
} else {
if (typeof args.error === 'function') {
args.error(request.status);
}
}
}
};
request.onloadstart = function() {
if (typeof args.loadstart === 'function') {
args.loadstart();
}
};
request.onprogress = function(event) {
if (typeof args.progress === 'function') {
args.progress(event);
}
};
request.timeout = getParams(args, 'timeout', 0);
if (/^post$/gi.test(type)) {
request.open('POST', url, true);
request.setRequestHeader('Content-Type', contentType);
if (contentType == 'application/x-www-form-urlencoded') {
var content = typeof data === 'string' ? data : serializeParams(data);
request.send(content);
} else if (contentType == 'application/json') {
var content = typeof data === 'string' ? data : JSON.stringify(data);
request.send(content);
}
} else {
url += (url.indexOf('?') >= 0 ? '&' : '?') + serializeParams(data);
request.open('GET', url, true);
request.send();
}
}
function doJsonAjax(url, data, success, failed, loadstart, progress) {
doAjax({
url,
type: 'post',
data,
contentType: 'application/json',
success,
error: failed,
loadstart,
progress,
});
}
function extendMethod(class_name, method_set) {
for (const method_name in method_set) {
class_name.prototype[method_name] = method_set[method_name];
}
}
function EventListener() {
}
extendMethod(EventListener, {
on(event, func) {
if (typeof event === 'string' && typeof func === 'function') {
const list = this['on' + event + 'list'];
if (list instanceof Array) {
for (let i = 0; i < list.length; i++) {
if (list[i] === func) {
return this;
}
}
list.push(func);
} else {
this['on' + event + 'list'] = [func];
}
}
return this;
},
off(event, func) {
const list = this['on' + event + 'list'];
if (list instanceof Array) {
if (!func) {
list.length && list.splice(0, list.length);
} else {
for (let i = 0; i < list.length; i++) {
if (list[i] === func) {
list.splice(i, 1);
break;
}
}
}
}
return this;
},
trigger(event) {
let result = false,
list = this['on' + event + 'list'];
if (list instanceof Array) {
for (let i = 0; i < list.length; i++) {
const func = list[i];
if (typeof func !== 'function') {
continue;
}
const args = Array.prototype.slice.call(arguments, 0);
args.shift();
result = result || func.apply(this, args);
}
}
return result;
},
});
function __() {
this.timer = 0;
this.queue = [];
this.complete = null;
}
__.prototype.then = function(cb, delay) {
this.queue.push({ callback: cb, delay });
return this;
};
__.prototype.end = function(cb) {
this.complete = cb;
return this;
};
__.prototype.abort = function() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = 0;
}
return this;
};
__.prototype.commit = function() {
const self = this;
if (this.queue.length && !this.timer) {
const top = this.queue.shift();
if (typeof top.callback === 'function') {
if (typeof top.delay !== 'number' || top.delay <= 0) {
top.callback.apply(self);
this.commit();
} else {
this.timer = setTimeout(function() {
top.callback.apply(self);
self.timer = 0;
self.commit();
}, top.delay);
}
} else {
self.commit();
}
} else if (!this.queue.length && !this.timer) {
if (typeof this.complete === 'function') {
this.complete.apply(this);
this.complete = null;
}
}
return this;
};
function then(cb, delay) {
return (new __()).then(cb, delay);
}
$(function() {
document.body.addEventListener('touchstart', function() {});
});
window.console = (function() {
const log = console.log;
let message_queue = new Array();
function _() {
this._init();
}
_.prototype = console;
console._init = function() {
this.enabled_server_log = false;
this.enabled_window_log = false;
};
console.log = function(msg) {
log.call(this, msg);
this._server_log(msg);
this._window_log(msg);
};
console._server_log = function(msg) {
if (!this.enabled_server_log) {
return;
}
if (msg instanceof Object) {
msg = JSON.stringify(msg);
} else {
msg = '' + msg;
}
message_queue.push({ time: +new Date(), message: msg });
this._check_queue();
};
console._window_log = function(msg) {
};
console._check_queue = function() {
if (this._server_flag) {
return;
}
if (message_queue.length > 0) {
// 消息队列队首元素
this._server_flag = true;
setTimeout(function() {
const data = message_queue;
message_queue = [];
doJsonAjax(constant.project_root + 'log', data, function() {
message_queue.shift();
this._server_flag = false;
this._check_queue();
}.bind(this));
}.bind(this), 20);
}
};
return new _();
})();
This diff is collapsed.
'use strict';
function Scheduler(option) {
option = option || {};
this.timeout = option.timeout || 60 * 2 * 1000;
this.duration = option.duration || 2000;
this.abort = false;
this.doing = false;
}
Scheduler.prototype._get_delay = function() {
let delay = typeof this.duration === 'function' ? this.duration(this.start_time) : this.duration;
delay = +delay;
return delay <= 0 && (delay = 2000), delay;
};
Scheduler.prototype.update = function() {
const delay = this._get_delay() - (+new Date() - this.last_time);
if (this.abort || this.doing) {
return;
}
this.doing = true;
setTimeout(function() {
if (this.abort) {
return;
}
this.last_time = +new Date();
this.doing = false;
this.callback();
}.bind(this), delay);
};
Scheduler.prototype.begin = function(callback, success, failed) {
this.start_time = +new Date();
this.last_time = this.start_time;
this.callback = callback;
this.success = success;
this.failed = failed;
this.abort = false;
this.callback();
this.timeout_timer = setTimeout(function() {
this.abort = true;
if (typeof this.failed === 'function') {
this.failed({ code: 1, TIMEOUT: 1, CANCEL: 2, UNKNOWN_ERROR: 3 });
}
delete this.timeout_timer;
}.bind(this), this.timeout);
return this;
};
Scheduler.prototype.cancel = function() {
this.abort = true;
if (this.timeout_timer) {
clearTimeout(this.timeout_timer);
delete this.timeout_timer;
}
if (typeof this.failed === 'function') {
this.failed({ code: 2, TIMEOUT: 1, CANCEL: 2, UNKNOWN_ERROR: 3 });
}
return this;
};
Scheduler.prototype.end = function() {
this.abort = true;
if (this.timeout_timer) {
clearTimeout(this.timeout_timer);
delete this.timeout_timer;
}
if (typeof this.success === 'function') {
this.success.apply(this, arguments);
}
return this;
};
This diff is collapsed.
$.extend($.fn, {
valMap() {
const data = {};
for (let i = 0; i < this.length; i++) {
let ele = $(this[i]),
name = ele.attr('name'),
val = ele.val();
if (ele.is('[type=hidden]') || ele.is('select')) {
// 自动转换
if (/^\s*([1-9]\d*|0)\s*$/.test(val)) {
val = +val;
} else if (val == 'true') {
val = true;
} else if (val == 'false') {
val = false;
}
} else if (ele.is('[type=number]')) {
val = +val;
}
if (name) {
name = name.replace(/^\s*|\s*$/gi, '');
if (/^([^\[]+)(?:\s*\[\s*([^\]]+)\s*\])+$/.test(name)) {
let keys = [name.substr(0, name.indexOf('[')).replace(/^\s*|\s*$/gi, '')];
keys = keys.concat(name.substr(keys[0].length).replace(/^\s*\[|\]\s*$/gi, '').split(/\]\s*\[/));
let node = data;
while (keys.length) {
const key = keys.shift();
if (keys.length == 0) {
node[key] = val;
} else {
if (typeof node[key] !== 'object') {
node = node[key] = {};
} else {
node = node[key];
}
}
}
} else {
data[name] = val;
}
}
}
return data;
},
inputValidate(config) {
for (let i = 0; i < this.length; i++) {
let ele = $(this[i]),
name = ele.attr('name').replace(/^\s*|\s*$/gi, ''),
val = ele.val();
if (!!name && !!config[name]) {
let rules = config[name];
if (!rules instanceof Array) {
rules = [rules];
}
for (let j = 0; j < rules.length; j++) {
const rule = rules[j];
if (rule.match) {
if (rule.match == 'phone') {
if (!/^1\d{10}$/.test(val)) {
ele.trigger('inputerror', rule.error);
return true;
}
} else if (rule.match == 'IDCard') {
if (!/^\d{14}(\d{3})?[\dXx]$/.test(val)) {
ele.trigger('inputerror', rule.error);
return true;
}
}
} else if (rule.pattern) {
const regexp = new RegExp(rule.pattern);
if (!regexp.test(val)) {
ele.trigger('inputerror', rule.error);
return true;
}
}
}
}
}
return false;
},
submitFields(selector) {
if (typeof selector === 'string') {
selector = $(selector);
} else if (!selector) {
selector = new $();
}
const callback = (function(selector, target) {
return function() {
const fields = selector.filter(function() { return $(this).is('.required,[required],[type=checkbox].required-checked'); });
for (let i = 0; i < fields.length; i++) {
const r = $(fields[i]);
if ('|text|password|'.indexOf(('|' + r.attr('type') + '|').toLowerCase()) >= 0 && !r.is(':visible')) {
continue;
}
if (r.hasClass('required') || r.is('[required]')) {
if (/^\s*$/.test(r.val())) {
target.attr('disabled', 'disabled');
return;
}
}
if (r.hasClass('required-checked') && r.is('[type=checkbox]')) {
if (!r.is(':checked')) {
target.attr('disabled', 'disabled');
return;
}
}
}
target.removeAttr('disabled');
};
})(selector, this);
this.trigger('uninstall').off('uninstall');
selector.length && this.on('uninstall', function() {
selector.off('input change', callback);
}) && selector
.on('input change', callback)
.eq(0).trigger('input');
return this;
},
lock(cd) {
let self = $(this),
text = self.html(),
i = cd;
self.data('origin-text', '免费获取');
const call = function() {
if (i > 0) {
self.html(i + '秒后重试');
self.attr('disabled', 'disabled');
} else {
self.html(self.data('origin-text'));
self.removeAttr('disabled');
self.data('timer', 0);
clearInterval(timer);
self.trigger('clickready');
}
i--;
};
var timer = setInterval(call, 1000);
self.data('timer', timer);
call();
const id = self.data('id');
if (window.localStorage && id) {
let cache = window.localStorage.lock_cd;
if (cache) {
cache = JSON.parse(cache);
} else {
cache = {};
}
cache[id] = Math.round(new Date().getTime() / 1000) + cd;
window.localStorage.lock_cd = JSON.stringify(cache);
}
},
unlock() {
const self = $(this);
self.html(self.data('origin-text'));
self.removeAttr('disabled');
const timer = self.data('timer');
timer && clearInterval(timer);
const id = self.data('id');
if (window.localStorage) {
let cache = window.localStorage.lock_cd;
if (cache) {
cache = JSON.parse(cache);
} else {
cache = {};
}
delete cache[id];
window.localStorage.lock_cd = JSON.stringify(cache);
}
},
restoreLock() {
const self = $(this);
if (window.localStorage) {
let cache = window.localStorage.lock_cd;
if (cache) {
cache = JSON.parse(cache);
}
const now = Math.round(new Date().getTime() / 1000);
for (const id in cache) {
const cdt = cache[id];
if (cdt - now > 0) {
(self.data('id') == id ? self : self.find('[data-id=' + id + ']')).lock(cdt - now);
}
}
}
},
lockCD() {
const self = $(this);
const lock_id = self.data('id');
try {
if (window.localStorage && lock_id) {
let cache = window.localStorage.lock_cd;
if (cache) {
cache = JSON.parse(cache);
}
const now = Math.round(new Date().getTime() / 1000);
if (lock_id in cache) {
const cdt = cache[lock_id];
if (cdt - now > 0) {
return cdt - now;
}
}
}
} catch (e) {
}
return 0;
},
});
$(function() {
$(document).restoreLock();
$('script[type*=json]').each(function() {
let self = $(this),
id = self.attr('id');
if (id) {
try {
window[id] = JSON.parse(self.html());
} catch (e) {
window[id] = undefined;
}
}
});
});
This diff is collapsed.
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @param {Egg.Application} app - egg application * @param {Egg.Application} app - egg application
*/ */
module.exports = app => { module.exports = app => {
const { router, controller } = app; const { router, controller, io } = app;
const yysRouter = router.namespace(app.config.projectRootPath); const yysRouter = router.namespace(app.config.projectRootPath);
yysRouter.get('/index', controller.index.index);// H5页面 yysRouter.get('/index', controller.index.index);// H5页面
...@@ -20,7 +20,8 @@ module.exports = app => { ...@@ -20,7 +20,8 @@ module.exports = app => {
yysRouter.post('/dataCallback', controller.task.dataCallback);// 数据处理完成结果,不对外 yysRouter.post('/dataCallback', controller.task.dataCallback);// 数据处理完成结果,不对外
yysRouter.post('/newdataCallback', controller.task.newdataCallback);// 运营报告处理完成结果,不对外 yysRouter.post('/newdataCallback', controller.task.newdataCallback);// 运营报告处理完成结果,不对外
yysRouter.ws('/ws', controller.task.wslink); // yysRouter.ws('/', controller.task.wslink);
io.route('/ws', controller.task.wslink);
// yysRouter.get('/scripts', controller.script.fetchScripts); // 获取所有脚本信息 // yysRouter.get('/scripts', controller.script.fetchScripts); // 获取所有脚本信息
// yysRouter.get('/scripts/:phone');// 手机号获取脚本信息 // yysRouter.get('/scripts/:phone');// 手机号获取脚本信息
......
...@@ -36,5 +36,15 @@ module.exports = appInfo => { ...@@ -36,5 +36,15 @@ module.exports = appInfo => {
}, },
}; };
config.io = {
init: { }, // passed to engine.io
namespace: {
'/': {
connectionMiddleware: [],
packetMiddleware: [],
},
},
};
return config; return config;
}; };
...@@ -37,3 +37,8 @@ exports.handlebars = { ...@@ -37,3 +37,8 @@ exports.handlebars = {
enable: true, enable: true,
package: 'egg-view-handlebars', package: 'egg-view-handlebars',
}; };
exports.io = {
enable: true,
package: 'egg-socket.io',
};
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
"egg-router-plus": "^1.3.0", "egg-router-plus": "^1.3.0",
"egg-scripts": "^2.5.0", "egg-scripts": "^2.5.0",
"egg-sequelize": "^4.2.0", "egg-sequelize": "^4.2.0",
"egg-socket.io": "^4.1.6",
"egg-validate": "^2.0.2", "egg-validate": "^2.0.2",
"egg-view-handlebars": "^2.0.1", "egg-view-handlebars": "^2.0.1",
"md5-node": "^1.0.1", "md5-node": "^1.0.1",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment