汇融云链2

This commit is contained in:
2023-02-13 18:43:39 +08:00
parent 76dca84266
commit a29788866e
331 changed files with 95753 additions and 0 deletions

View File

@@ -0,0 +1,453 @@
var eonfox = function(config){
if( config ){
if( config.debug ){
eonfox.prototype.debug = true;
}
if( config.application ){
eonfox.prototype.application = config.application;
}
if( config.api_server_url ){
eonfox.prototype.api_server_url = config.api_server_url;
}
}
};
eonfox.prototype = {
constructor : eonfox,
//是否开启调试模式
debug : false,
//文件服务器URL
file_server_url : 'http://img.eonfox.cc/',
//接口地址 应用ID
api_server_url : 'http://server.test.eapie.com/',
application : "test",
//会话名称
session_name : 'Eonfox_API_Engine_Session',
/*
转换时间格式
*/
switchingTime: function(timestamp) {
var date = new Date(timestamp * 1000); //时间戳为10位需*1000时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
return Y + M + D + h + m + s;
},
//提交的有效等待时间
submit_sleep_expire_time : 30,
//请求任务
submit_task : null,
/**
* 提交队列
*/
submit_queue : [],
/**
* 提交登记
*/
submit_register : function( config ){
config.time = ((new Date()).getTime()/1000);//赋值是 时间戳 (秒),用于有效时间
eonfox.prototype.submit_queue.push(config);
},
/**
* 运行提交
*/
submit_run : function(){
if( eonfox.prototype.submit_queue.length < 1 ){
return false;//没有执行的提交
}
if( eonfox.prototype.submit_queue[0].runtime ){
return false;//正在执行
}
//检查是否已经失效
if( (eonfox.prototype.submit_queue[0].time + eonfox.prototype.submit_sleep_expire_time) < ((new Date()).getTime()/1000) ){
//已经过了有效期
//删除第一个元素
eonfox.prototype.submit_queue.shift();
//再次提交
return eonfox.prototype.submit_run();
}
eonfox.prototype.submit_queue[0].runtime = true;
var config = eonfox.prototype.submit_queue[0];
//从本地缓存中同步获取指定 key 对应的内容。
var token = eonfox.prototype.token(function(e){
config.error(e);
});
if( !(function(){try{ return token['session_right_token'];}catch(e){return false;}}()) ){
config.right_data.session = "start";
config.right_data.application = this.application;
}else{
config.right_data.token = token['session_right_token'];
config.left_data.token = token['session_left_token'];
config.left_data.session = "start";
config.left_data.application = this.application;
}
var request = {
url : config.url,
method : "POST",
dataType : "json",
responseType : "text",
header: {"Content-Type":"application/x-www-form-urlencoded"},//跨域防止请求options
complete : function(){
//当请求完成之后调用这个函数无论成功或失败。执行时间比success晚
//删除第一个元素
eonfox.prototype.submit_queue.shift();
//再次提交
eonfox.prototype.submit_run();
},
success : function(){},
fail : function(err){
config.error(err);
}
}
//右令牌
var right_token_post = function(){
request.data = config.right_data;
request.success = function(success_data_all){
//这里要注意,这里是包含了 data
if(typeof success_data_all != 'object'){
success_data_all = (function(){try{ return JSON.parse(success_data_all);}catch(e){return false;}}());
}
var success_data = success_data_all.data? success_data_all.data : null;
if(typeof success_data != 'object'){
console.warn("应用接口响应异常");
return config.callback(false, success_data_all);
}
//如果存在请求令牌,直接返回数据
if( (function(){try{ return success_data['token'];}catch(e){return false;}}()) ){
//储存令牌
eonfox.prototype.storage_token(success_data);
//返回到回调函数
return config.callback(success_data, success_data_all);
}else{
//否则说明没有这个会话,再进行左令牌查询
return left_token_post();
}
};
if( eonfox.prototype.debug ){
console.log("post():右令牌提交:", request);
}
eonfox.prototype.submit_task = uni.request(request);
};
//左令牌
var left_token_post = function(){
request.data = config.left_data;
request.success = function(success_data_all){
//这里要注意,这里是包含了 data
if(typeof success_data_all != 'object'){
success_data_all = (function(){try{ return JSON.parse(success_data_all);}catch(e){return false;}}());
}
var success_data = success_data_all.data? success_data_all.data : null;
if(typeof success_data != 'object'){
console.warn("应用接口响应异常");
return config.callback(false, success_data_all);
}
//如果没有报错
if( (function(){try{ return success_data['token'];}catch(e){return false;}}()) ){
//储存令牌
eonfox.prototype.storage_token(success_data);
}
//返回到回调函数
return config.callback(success_data, success_data_all);
};
if( eonfox.prototype.debug ){
console.log("post():左令牌提交:", request);
}
eonfox.prototype.submit_task = uni.request(request);
};
return right_token_post();
},
/**
* 获取左token
* 如果没用传入回调函数,那么则直接返回当前左令牌,但是有可能会出现左令牌失效
* 正常操作是,传入一个回调函数,左令牌始终是保持最新的。
*
* @param {Function} #fn
*/
websocketToken : function(fn){
if(typeof fn != "function"){
var storage_token = eonfox.prototype.token();
if( (function(){try{ return storage_token['session_websocket_token'];}catch(e){return false;}}()) ){
return storage_token['session_websocket_token'];
}else{
return '';
}
}else{
eonfox.prototype.submit({
callback: function(){
//从本地缓存中同步获取指定 key 对应的内容。
var websocket_token = "";
var websocket_token = eonfox.prototype.token();
if( (function(){try{ return storage_token['session_websocket_token'];}catch(e){return false;}}()) ){
websocket_token = storage_token['session_websocket_token'];
}
fn(websocket_token);
}
});
return true;
}
},
/* 中断请求任务 */
abort : function(){
//清理等待的请求
eonfox.prototype.submit_queue = [];
//中断请求任务
if( eonfox.prototype.submit_task.abort ){
eonfox.prototype.submit_task.abort();
}
},
/* 提交请求
* 暂时只支持 POST
* {
* url : this.api_server_url,默认接口地址
* data : {},
* callback : 回调函数 第一个是单个 data第二个是 全部的返回数据
* error : 错误回调函数
* }
*
*/
submit : function(config){
if( eonfox.prototype.debug ){
console.log("submit()传入参数:", config);
}
//回调函数
if( !config.callback || config.callback.constructor != Function ){
config.callback = function(){};
}
if( !config.error || config.error.constructor != Function ){
config.error = function(){};
}
//路由
if(typeof config.url == 'undefined' || typeof config.url != 'string'){
config.url = this.api_server_url;
}
config.right_data = {};
config.left_data = {};
//请求字符串
if( config.request ){
//如果是对象,则先转换为字符串
if(typeof config.request == "object"){
config.request = JSON.stringify(config.request)
}
if(typeof config.request == "string"){
config.right_data.data = config.request;
config.left_data.data = config.request;
}
}
//用户传入的data数据
if( config.data && typeof config.data == "object" ){
for(var i in config.data){
config.right_data[i] = config.data[i];
config.left_data[i] = config.data[i];
}
}
if( eonfox.prototype.debug ){
console.log("post()right_data、left_data:", config.right_data, config.left_data);
}
/*//是否强制提交
config.recursion = config.recursion? true : false;
//大于0说明存在队列
if( this.submit_queue.length > 0 ){
//判断是否强制提交
if( config.recursion ){
//去登记注册
eonfox.prototype.submit_register(config);
}else{
//否则返回错误信息
console.warn("应用接口提交队列个数:", this.submit_queue.length);
return config.error("应用接口出现重复提交,前方正在提交队列个数:", this.submit_queue.length);
}
}else{
//去登记注册
eonfox.prototype.submit_register(config);
} */
//去登记注册
eonfox.prototype.submit_register(config);
//并且调用执行
eonfox.prototype.submit_run();
},
/**
* 储存token
*
* @param {Object} data
*/
storage_token : function(data){
if( !data ){
return false;
}
var token_data = null;
var exist_right_token = false;
var exist_left_token = false;
exist_right_token = (function(){try{ return data['token']['session_right_token'];}catch(e){return false;}}());
exist_left_token = (function(){try{ return data['token']['session_left_token'];}catch(e){return false;}}());
if(exist_right_token && exist_left_token){
token_data = data['token'];
}else{
//有可能是顶级关联对象
exist_right_token = (function(){try{ return data['session_right_token'];}catch(e){return false;}}());
exist_left_token = (function(){try{ return data['session_left_token'];}catch(e){return false;}}());
if(exist_right_token && exist_left_token){
token_data = data;
}
}
if(!token_data){
return false;
}
//从本地缓存中同步获取指定 key 对应的内容。
var storage_token = eonfox.prototype.token();
if( (function(){try{ return storage_token['session_right_token'];}catch(e){return false;}}()) &&
(function(){try{ return storage_token['session_left_token'];}catch(e){return false;}}()) ){
if(storage_token['session_right_token'] == token_data['session_right_token'] ||
storage_token['session_left_token'] == token_data['session_left_token'] ){
if( eonfox.prototype.debug ){
console.log("需要对比旧token中的当前时间戳,为true则不需要更新token", storage_token['session_now_time'], token_data['session_now_time'], parseInt(storage_token['session_now_time']) > parseInt(token_data['session_now_time']));
}
if( parseInt(storage_token['session_now_time']) > parseInt(token_data['session_now_time']) ){
if( eonfox.prototype.debug ){
console.log("并发异步不需要更新token" );
}
return false;
}
}
}
//console.log( uni.setStorageSync );
try {
uni.setStorageSync(this.session_name +":"+ this.application, JSON.stringify(token_data));
} catch (e) {
console.warn(e);
return false;
}
return true;
},
/**
* 获取token
*
* @param {Function} error_function
*/
token : function(error_function){
//异步可能存在覆盖的问题所以对比已存在的token,如果右左有一个相同则比较当前时间,即最大的当前时间是最新的。
var storage_token = false;
try {
storage_token = uni.getStorageSync(this.session_name +":"+ this.application);
if( storage_token ){
storage_token = (function(){try{ return JSON.parse(storage_token);}catch(e){return false;}}());
}
} catch (e) {
console.warn(e);
if(error_function){
error_function(e);
}
return false;
}
return storage_token;
},
/**
* 获取左token
* 如果没用传入回调函数,那么则直接返回当前左令牌,但是有可能会出现左令牌失效
* 正常操作是,传入一个回调函数,左令牌始终是保持最新的。
*
* @param {Function} #fn
*/
left_token : function(fn){
if(typeof fn != "function"){
var storage_token = eonfox.prototype.token();
if( (function(){try{ return storage_token['session_left_token'];}catch(e){return false;}}()) ){
return storage_token['session_left_token'];
}else{
return '';
}
}else{
eonfox.prototype.submit({
callback: function(){
//从本地缓存中同步获取指定 key 对应的内容。
var left_token = "";
var storage_token = eonfox.prototype.token();
if( (function(){try{ return storage_token['session_left_token'];}catch(e){return false;}}()) ){
left_token = storage_token['session_left_token'];
}
fn(left_token);
}
});
return true;
}
},
/* 获取 websocket 数据 */
websocket_data : function(res){
console.log(res);
if( !res.data ){
return false;
}
return JSON.parse( res.data );
}
};
export default eonfox;

View File

@@ -0,0 +1,285 @@
var fns = {
//--------------
//api接口验证
checkError: function(data, ids, error){
if(typeof(error)!='function'){
error=function(){
}
}
if(data.errno){
error(data.errno, data.error);
return false;
}
if(!data.data){
error(1, "未知错误");
return false;
}
if(ids){
if(typeof ids =='object'){
for( var i in ids){
if(typeof ids[i] != "undefined"){
var id = ids[i];
if( data.data[id] && data.data[id].errno ){
error(data.data[id].errno, data.data[id].error);
return false;
}
}else{
error(1, "“"+ids[i]+"”目标,未知错误");
return false;
}
}
}else if(typeof ids =='string' || typeof ids == 'number'){
if(typeof data.data[ids] != "undefined" ){
if( data.data[ids].errno ){
error(data.data[ids].errno, data.data[ids].error);
return false;
}
}else{
error(1, "“"+ids+"”目标,未知错误");
return false;
}
}else{
error(1, "“"+ids+"”目标,未知错误");
return false;
}
}
var data_list = {};
if(data.data){
for(var i in data.data){
if(typeof data.data[i].data != "undefined"){
data_list[i] = data.data[i].data;
}
}
}
return data_list;
},
//数据处理 ceil向上取整
number_pre:function(number,pre){
switch(pre){
case 'ceil':
return Math.ceil(number)
break;
}
},
//保留两位小数
number_floor_2:function(number){
var number = number * 100;
number = Math.floor(number)
number = number/100;
return number.toFixed(2);
},
//错误信息处理
err:function(title,data,_json,fun){
if(data){
if(_json){
data=JSON.stringify(data)
}
console.log(title+' :',data)
uni.showToast({
title:title+' : '+data,
icon:'none',
duration:1500,
success() {
if(fun){
fun();
}
}
})
}else{
console.log(title)
uni.showToast({
title:title,
icon:'none',
duration:1500,
success() {
if(fun){
fun();
}
}
})
}
},
//成功信息处理
success(title,fun){
if(fun){
fun();
}
uni.hideLoading();
/* uni.showToast({
title:title,
icon:'success',
success() {
if(fun){
fun();
}
}
}) */
},
//敬请期待
waiting:function(){
uni.showToast({
title:'敬请期待',
icon:'none'
})
},
//授权验证
oauth_:function(){
uni.setStorage({
key:'oauth',
data:true
})
},
noauth:function(){
uni.setStorage({
key:'oauth',
data:false
})
},
//绑定验证
unionid:function(){
uni.setStorage({
key:'unionid',
data:true
})
},
nunionid:function(){
uni.setStorage({
key:'unionid',
data:false
})
},
//绑定
bind:function(){
console.log('oauth');
uni.getStorage({
key:'oauth',
success(re) {
console.log('oauth',re);
}
})
},
//获取指定url参数
getUrlQuery:function (urlStr) {
// var urlStr = location.search.substr(1) ? location.search.substr(1) : "";
var urlArr = [];
for(var i = 0; i < urlStr.split("&").length; i++) {
urlArr.push(urlStr.split("&")[i].split("=")[0] ? urlStr.split("&")[i].split("=")[0] : "");
urlArr.push(urlStr.split("&")[i].split("=")[1] ? urlStr.split("&")[i].split("=")[1] : "onlyKey")
}
if(urlStr == "") {
return;
} else {
var urlObj = {}
for(var i = 0; i < urlArr.length; i += 2) {
if(urlArr[i] != "") {
urlObj[urlArr[i]] = decodeURIComponent(urlArr[i + 1]);
}
}
return urlObj;
}
}
,
// url参数解析
getUrlkey:function(url) {
var params = {};
var urls = url.split("?"); console.log('1_分割url:', urls)
var arr = urls[1].split("&"); console.log('2_分割urls[1]:', arr)
for (var i = 0, l = arr.length; i < l; i++) {
var a = arr[i].split("="); console.log('3_遍历 arr 并分割后赋值给a:', a[0], a[1])
params[a[0]] = a[1]; console.log('4_a给params对象赋值:', params)
} console.log('5_结果:', params)
return params;
}
,
toast(tit,url,time){
if(!time){
time=1500
}
uni.showToast({
title:tit,
success() {
setTimeout(function(){
uni.reLaunch({
url:url
})
},time)
}
})
},
setSystemInfoSync(){
uni.getStorage({
key:'SystemInfoSync',
fail(err) {
console.log('设置缓存');
try {
console.log('star');
const res = uni.getSystemInfoSync();
console.log('config'+JSON.stringify(res));
uni.setStorage({
key:'SystemInfoSync',
data:res
})
console.log('ok');
} catch (e) {
console.log('catch+'+JSON.stringify(e));
// error
}
},
})
},
getCompare(Version,newVersion,fun){
if(Version==newVersion){
console.log('没有更新');
return
}
console.log('接收到参数');
uni.getStorage({
key:'SystemInfoSync',
success(res) {
console.log('缓存:'+JSON.stringify(res));
if(res.data){
var SystemInfoSync=res.data;
console.log('json:'+JSON.stringify(SystemInfoSync));
console.log('设备:'+SystemInfoSync.platform);
if(SystemInfoSync.platform=='android'){
console.log('设备:安卓');
fun();
}
}else{
return this.setSystemInfo();
}
},
fail(err) {
console.log('缓存获取失败'+JSON.stringify(err));
const res = uni.getSystemInfoSync();
console.log('config'+JSON.stringify(res));
uni.setStorage({
key:'SystemInfoSync',
data:res,
success() {
if(res.platform=='android'){
console.log('设备:安卓');
fun();
}
}
})
},
complete() {
console.log('获取缓存');
}
})
}
//------------------------
};
export default fns;

View File

@@ -0,0 +1,39 @@
import eonfox from '@/components/eonfox/eonfox.js';
var ef=new eonfox()
import f from '@/components/eonfox/fns.js';
var pay= {
shoppingCar:function(groupId,method,pass,fun){
ef.submit({
request:{
s:['SHOPGROUPGOODSSELFPAY',[{id:groupId,pay_method:method,pay_password:pass}]]
},
callback:function(data){
const dataList=(data=f.checkError(data,'s',function(errno,error){
f.err(error)
}))
console.log('da...',dataList)
if(dataList.s==true){
fun()
}
// var dataList=data.s
// if(dataList.data){
// if(dataList.data==true){
// f.err('支付成功')
// }else{
// f.err('支付失败')
// }
//
// }
console.log('支付结果');
},
error(err){
f.err('',err,1)
}
})
}
}
export default pay;

View File

@@ -0,0 +1,12 @@
/* 商家模块 */
var merchant = function(){};
merchant.prototype = {
constructor : merchant,
//收银员的订单列表是否需要刷新
cashierOrderListRefresh : false
};
export default merchant;

View File

@@ -0,0 +1,72 @@
import eonfox from '@/components/eonfox/eonfox.js';
var ef = new eonfox();
var order = {
/* 检查支付状态
order_id 要检查的订单ID
frequency 检查的次数当等于0时则返回回调
callback 回调。成功时callback.success 失败时callback.fail
因为有 frequency 次数,所以每次进来 -1 。如果不等于0那么要继续递归
order.checkPayState({
order_id: order_id,
frequency: 3,
success:function(){
},
fail:function(){
}
})
*/
checkPayState : function(data){
var _this = this;
if(typeof data.success != 'function') data.success = function(){};
if(typeof data.fail != 'function') data.fail = function(){};
if( typeof data.frequency != 'number') data.frequency = 3;
if( !data.frequency || !data.order_id ){
return data.fail('参数不正确', data);
}
//如果不等于0那么要继续递归
data.frequency --;
//开始查询状态 0表示未支付1表示支付成功。
ef.submit({
request:{
s:['APPLICATIONORDERSELFPAYSTATE',[{order_id: data.order_id}]]
},
callback: function(r){
console.log('order.checkPayState:::',r);
// console.log('支付查询回调成功',r.data.s.data) ;return r.data.s.data;
if( !r.errno && !r.data.s.errno && r.data.s.data){
console.log('支付成功');
//获取成功,无错误信息时
return data.success();
} else {
console.log('支付状态查询失败或者未支付');
if( !data.frequency ){
return data.fail();
}else{
setTimeout(function() {
return _this.checkPayState(data);
}, 2000);
}
}
},
error(err){
data.fail(err);
}
})
}
};
export default order;

View File

@@ -0,0 +1,70 @@
import eonfox from '@/components/eonfox/eonfox.js';
var ef=new eonfox()
import f from '@/components/eonfox/fns.js';
var pay= {
set_password:function(pass,pass_confirm,fun){
ef.submit({
request:{
set_pass:['setpass',[{password:pass}]]
},
callback:function(data){
if(data=f.checkError(data,'set_pass',function(errno,error){
f.err(error)
})){
fun()
}else{
f.err('设置失败')
}
console.log('支付结果');
},
error(err){
f.err('',err,1)
}
})
},
shoppingCar:function(id,method,pass,fun){
ef.submit({
request:{
s:['SHOPORDERSELFPAYMENT',[{order_id:id,pay_method:method,pay_password:pass}]]
},
callback:function(data){
const dataList=(data=f.checkError(data,'s',function(errno,error){
f.err(error)
}))
console.log('da...',dataList)
if(dataList.s.order_id){
f.err('支付成功')
return ok
}
console.log('支付结果');
},
error(err){
f.err('',err,1)
}
})
},
//取消订单
cancel_order:function(id,fun){
ef.submit({
request:{
cancel_order:['SHOPORDERSELFCANCEL',[{id:id}]]
},
callback:function(data){
if(data=f.checkError(data,'cancel_order',function(errno,error){
f.err(error)
})){
fun()
}else{
f.err('订单取消失败')
}
},
error(err){
f.err('',err,1)
}
})
},
}
export default pay;

View File

@@ -0,0 +1,61 @@
var polling = {
//定时器ID
_interval_id : null,
_switch : false,
//关闭
close : function(){
clearInterval(this._interval_id);
this._interval_id = null;
},
//暂停
stop : function(){
this._switch = false;
},
//启动
start : function(){
this._switch = true;
},
/**
* 开启
*
* @param {Time} ms 毫秒数
* @param {Function} fn 回调函数
*/
run : function(ms, fn){
if( !ms || typeof ms != 'number'){
ms = 3000;//默认3秒
}
if(!fn || typeof fn != 'function'){
fn = function(){};
}
var _this = this;
//如果已经存在,则要关闭轮询
if( _this._interval_id ){
_this.start();
return true;
}
var i = 0;
_this._switch = true;
_this._interval_id = setInterval(function(){
if( !_this._switch ){
return false;
}
i ++;
fn(i);
}, ms);
return true;
}
};
export default polling;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
// 版本控制文件
var version='0.0.12';
export default version;

View File

@@ -0,0 +1,541 @@
import eonfoxObject from '@/components/eonfox/eonfox.js';
var eonfox = new eonfoxObject();
var websocket_app = false;
//#ifdef APP-PLUS
websocket_app = true;
//#endif
var websocket = function(config){};
websocket.prototype = {
// url :'wss://developer.eapie.eonfox.com:9997',//测试版
url :'wss://eapie.eonfox.com:9999',//正式版
connect_type : 0,//连接类型。0是安卓1是非安卓
debug: false,//是否调试
close_type : 0,//1是手动关闭不会再尝试连接
token:'',//websocket令牌
open:false,//打开状态
client_id:'',//连接ID
server_time: 0,//websocket 服务器时间
messages:[],//接受的websocket消息的集合
message_max_number:10,//最大消息个数
messages_change:function(){},//变动时执行的函数
heartbeat_interval_id: null,//心跳检测的定时器ID
heartbeat_ms: 15000,//心跳检测毫秒
heartbeat_messages:[],//心跳检测的信息集合
heartbeat_message_max_number:10,//最大消息个数
heartbeat_messages_change:function(){},//变动时执行的函数
connect_parameter: null,//连接websocket的参数
/* 调试信息 */
debug_message:function(message, fn){
if( !websocket.prototype.debug ){
return false;
}
console.log(message);
uni.showToast({
title: message,
icon: 'none',
duration: 3000
});
if(typeof fn == 'function'){
fn();
}
},
/* 获取 websocket 数据 */
get_data : function(res){
if( !res.data ){
return false;
}
return JSON.parse( res.data );
},
/* 设置心跳检测的信息集合 */
set_heartbeat_messages: function(message){
if( this.heartbeat_messages.length >= this.heartbeat_message_max_number ){
this.heartbeat_messages.pop();//删除最后一个元素
}
//往前面添加
this.heartbeat_messages.unshift(message);
if(typeof websocket.prototype.heartbeat_messages_change == 'function') websocket.prototype.heartbeat_messages_change();
},
/* 设置心跳检测的信息集合 */
set_messages: function(message){
if( this.messages.length >= this.message_max_number ){
this.messages.pop();//删除最后一个元素
}
//往前面添加
this.messages.unshift(message);
if(typeof websocket.prototype.messages_change == 'function') websocket.prototype.messages_change();
},
messages_change_function: function(fn){
websocket.prototype.messages_change = fn;
},
heartbeat_messages_change_function: function(fn){
websocket.prototype.heartbeat_messages_change = fn;
},
/**
* 获取左 websocket_token
* 如果没用传入回调函数,那么则直接返回当前左令牌,但是有可能会出现左令牌失效
* 正常操作是,传入一个回调函数,左令牌始终是保持最新的。
*
* @param {Function} #fn
*/
session_websocket_token : function(fn){
if(typeof fn != "function"){
var storage_token = eonfox.token();
if( (function(){try{ return storage_token['session_websocket_token'];}catch(e){return false;}}()) ){
return storage_token['session_websocket_token'];
}else{
return '';
}
}else{
eonfox.submit({
callback: function(){
//从本地缓存中同步获取指定 key 对应的内容。
var websocket_token = "";
var storage_token = eonfox.token();
if( (function(){try{ return storage_token['session_websocket_token'];}catch(e){return false;}}()) ){
websocket_token = storage_token['session_websocket_token'];
}
fn(websocket_token);
}
});
return true;
}
},
/*
* 获取 websocket 令牌
* 传入一个回调函数
*/
get_token : function(fn){
var websocket_token = websocket.prototype.session_websocket_token();
if( websocket_token ){
console.log('get_websocket_token 已存在', websocket_token);
fn(websocket_token);
}else{
console.log('get_websocket_token 不存在,异步获取');
websocket.prototype.session_websocket_token(function(websocket_token){
fn(websocket_token);
});
}
},
/* 连接 websocket */
connect: function(connectParameter){
websocket.prototype.connect_type = 1;//连接类型。0是安卓1是非安卓
websocket.prototype.not_android_connect(connectParameter);
// if( websocket_app && plus.os.name == 'Android'){
// websocket.prototype.connect_type = 0;//连接类型。0是安卓1是非安卓
// websocket.prototype.android_connect(connectParameter);
// }else{
// websocket.prototype.connect_type = 1;//连接类型。0是安卓1是非安卓
// websocket.prototype.not_android_connect(connectParameter);
// }
},
//安卓程序
android_connect: function(connectParameter){},
//非安卓程序
//data.onSocketOpen
not_android_connect: function(connectParameter){
var _this = this;
websocket.prototype.debug_message('websocket.connect 连接 websocket');
websocket.prototype.connect_parameter = connectParameter;
websocket.prototype.get_token(function(token){
if( !token ){
//这里弹出错误消息
websocket.prototype.debug_message('websocket.connect 连接失败!没有获取到 websocket token');
}
//链接
uni.connectSocket({
url: websocket.prototype.url,
success(){
_this.set_messages({
state:true,
content:'连接webscoket成功',
});
websocket.prototype.token = token;
websocket.prototype.debug_message(' uni.connectSocket 连接webscoket成功!token:'+token);
},
fail(){
_this.set_messages({
state:false,
content:'连接webscoket失败',
});
websocket.prototype.debug_message(' uni.connectSocket 连接webscoket失败!token:'+token);
}
});
});
//WebSocket连接打开监听
uni.onSocketOpen(function () {
websocket.prototype.close_type = 0;
websocket.prototype.open = true;
websocket.prototype.debug_message('uni.onSocketOpen WebSocket连接已经打开监听!');
if(connectParameter && typeof connectParameter.onSocketOpen == 'function'){
connectParameter.onSocketOpen();
}
});
uni.onSocketClose(function (res) {
websocket.prototype.token = '';
websocket.prototype.open = false;
websocket.prototype.client_id = '';
//关闭心跳检测
if( websocket.prototype.heartbeat_interval_id ){
clearInterval( websocket.prototype.heartbeat_interval_id );
}
if(connectParameter && typeof connectParameter.onSocketClose == 'function'){
connectParameter.onSocketClose(res);
}
//开启心跳检测
if( websocket.prototype.close_type == 0){
websocket.prototype.debug_message('uni.onSocketClose 非手动关闭,开启心跳守护');
setTimeout(function(){
websocket.prototype.connect(connectParameter);
}, websocket.prototype.heartbeat_ms);
}
websocket.prototype.debug_message('uni.onSocketClose WebSocket 已关闭!');
});
//收到服务器内容
uni.onSocketMessage(function (res) {
console.log('onSocketMessage!!!!!!!!');
//给一个超时器
setTimeout(function(){
console.log('setTimeout!!!!!!!!');
websocket.prototype.debug_message('onSocketMessage 获取 websocket 数据:' + JSON.stringify(res));
var websocket_token = eonfox.websocketToken();
var r = websocket.prototype.get_data(res);
//websocket 检查连接ID值(旧-新)
if( (r.data && r.data.client_id && websocket.prototype.client_id != r.data.client_id) ||
(r.data && r.data.server_time && websocket.prototype.server_time != r.data.server_time) ||
(websocket.prototype.token != websocket_token) ){
if(r.data && r.data.client_id && websocket.prototype.client_id != r.data.client_id){
websocket.prototype.debug_message('websocket 连接ID 不一致',function(){
console.log('websocket.prototype.client_id != r.data.client_id', websocket.prototype.client_id, r.data.client_id);
});
}
if(r.data && r.data.server_time && websocket.prototype.server_time != r.data.server_time){
websocket.prototype.debug_message('websocket 服务器时间 不一致',function(){
console.log('websocket.prototype.server_time != r.data.server_time', websocket.prototype.server_time, r.data.server_time);
});
}
if(websocket.prototype.token != websocket_token){
websocket.prototype.debug_message('websocket_token 不一致',function(){
console.log('websocket.prototype.token != websocket_token', websocket.prototype.token, websocket_token);
});
}
return websocket.prototype.init( r.data.client_id, r.data.server_time, websocket_token, connectParameter, function(){
if(typeof connectParameter.onSocketMessage == 'function'){
connectParameter.onSocketMessage(res);
}
});//初始化
}else{
if(connectParameter && typeof connectParameter.onSocketMessage == 'function'){
connectParameter.onSocketMessage(res);
}
}
}, 0);
});
uni.onSocketError(function (res) {
//开启心跳检测
setTimeout(function(){
websocket.prototype.connect(connectParameter);
}, websocket.prototype.heartbeat_ms);
if(connectParameter && typeof connectParameter.onSocketError == 'function'){
connectParameter.onSocketError(res);
}
_this.set_messages({
state:false,
content:'连接webscoket失败',
error: res
});
websocket.prototype.debug_message('uni.onSocketError WebSocket连接打开失败请检查!error:'+res);
});
},
/* 初始化 */
init : function( client_id, server_time, token, connectParameter, callback){
var errorData = {
open : websocket.prototype.open,
token : websocket.prototype.token,
client_id : client_id
};
if( !websocket.prototype.open || !client_id ){
_this.set_messages({
state:false,
content:'websocket 初始化失败',
error: ''
});
websocket.prototype.debug_message('websocket 初始化失败!');
};
eonfox.submit({
request: {
s: ['SESSIONWEBSOCKETSELFCLIENT', [{
client_id: client_id, //连接id
server_time: server_time // 服务器时间
}]]
},
callback: function(){
//必须是在初始化成功之后 才更新连接ID值
websocket.prototype.client_id = client_id;
websocket.prototype.server_time = server_time;
//再次重置 websoket 令牌
websocket.prototype.token = token;
//开启心跳检测
if( websocket.prototype.heartbeat_interval_id ){
clearInterval( websocket.prototype.heartbeat_interval_id );
}
websocket.prototype.heartbeat_interval_id = setInterval(function(){
websocket.prototype.debug_message('websocket init 心跳检测');
websocket.prototype.heartbeat(function(errorData){
websocket.prototype.debug_message('websocket init 心跳检测失败', function(){
console.log('websocket_init 心跳检测失败返回值:', errorData);
});
clearInterval( websocket.prototype.heartbeat_interval_id );
websocket.prototype.connect(connectParameter);
});
}, websocket.prototype.heartbeat_ms);
if(typeof connectParameter.initSuccess != 'function') connectParameter.initSuccess = function(){};
connectParameter.initSuccess();
websocket.prototype.debug_message('websocket init 初始化成功');
websocket.prototype.set_heartbeat_messages({
state:true,
content:'websocket init 初始化成功!'
});
if(typeof callback != 'function') callback = function(){};
callback();
},
error : function(errorData){
websocket.prototype.debug_message('websocket init 初始化错误');
websocket.prototype.set_heartbeat_messages({
state:false,
content:'websocket init 初始化错误!',
error:errorData
});
return connectParameter.initError(errorData);
}
});
},
/* 发送心跳 */
heartbeat: function(errorFunction){
var errorData = {
open : websocket.prototype.open,
token : websocket.prototype.token,
client_id : websocket.prototype.client_id
};
if( !websocket.prototype.open || !websocket.prototype.token ){
if(typeof errorFunction != 'function') errorFunction = function(){};
websocket.prototype.debug_message('websocket heartbeat 初始化失败!');
websocket.prototype.set_heartbeat_messages({
state:false,
content:'websocket 初始化失败!'
});
return errorFunction(errorData);
};
var heartbeat = JSON.stringify({
module:'heartbeat',
application: eonfox.application,
token: websocket.prototype.token
});
uni.sendSocketMessage({
data: heartbeat,
success: function(res){
websocket.prototype.debug_message('websocket heartbeat 保持心跳成功!');
websocket.prototype.set_heartbeat_messages({
state:true,
content:'websocket heartbeat 保持心跳成功!'
});
},
fail: function(data){
websocket.prototype.debug_message('websocket heartbeat 保持心跳失败!');
websocket.prototype.set_heartbeat_messages({
state:false,
content:'websocket heartbeat 保持心跳失败!',
error: data
});
return errorFunction(errorData);
}
});
},
//重启 websocket
restart : function(){
websocket.prototype.close();
//重启
websocket.prototype.connect(websocket.prototype.connect_parameter);
websocket.prototype.debug_message('重启 websocket');
},
//关闭
close : function(){
//关闭
if( websocket.prototype.open ){
//连接类型。0是安卓1是非安卓
if( websocket.prototype.connect_type == 1 ){
uni.closeSocket();
}else{
//
}
}
websocket.prototype.close_type = 1;
websocket.prototype.token = '';
websocket.prototype.open = false;
websocket.prototype.client_id = '';
//关闭心跳检测
if( websocket.prototype.heartbeat_interval_id ){
clearInterval( websocket.prototype.heartbeat_interval_id );
}
},
/* 用户向用户推送 */
user_push : function(user_id, message, errorFunction){
var data = {
open : websocket.prototype.open,
token : websocket.prototype.token
}
if( !websocket.prototype.open || !websocket.prototype.token ){
if(typeof errorFunction != 'function') errorFunction = function(){};
return errorFunction(data);
}
var user_push = JSON.stringify({
module:'user_push',
application: eonfox.application,
token: websocket.prototype.token,
user_id:user_id,
message: message,
});
uni.sendSocketMessage({
data: user_push,
success: function(res){
websocket.prototype.debug_message('websocket 消息推送成功!', function(){
console.log('user_push', res)
});
websocket.prototype.set_messages({
state:true,
content:'websocket user_push 消息推送成功!',
});
},
fail: function(faildata){
websocket.prototype.debug_message('websocket 消息推送失败!', function(){
console.log('user_push', faildata)
});
websocket.prototype.set_messages({
state:false,
content:'websocket user_push 消息推送失败!',
error:faildata
});
return errorFunction(errorData);
}
});
},
/* 用户向后台推送 */
admin_push : function(message, errorFunction){
var data = {
open : websocket.prototype.open,
token : websocket.prototype.token
}
if( !websocket.prototype.open || !websocket.prototype.token ){
if(typeof errorFunction != 'function') errorFunction = function(){};
return errorFunction(data);
}
var admin_push = JSON.stringify({
module:'admin_push',
application: eonfox.application,
token: websocket.prototype.token,
message: message,
});
uni.sendSocketMessage({
data: admin_push,
success: function(res){
websocket.prototype.debug_message('websocket 消息推送成功!', function(){
console.log('admin_push', res)
});
websocket.prototype.set_messages({
state:true,
content:'websocket admin_push 消息推送成功!',
});
},
fail: function(faildata){
websocket.prototype.debug_message('websocket 消息推送失败!', function(){
console.log('admin_push', faildata)
});
websocket.prototype.set_messages({
state:false,
content:'websocket admin_push 消息推送失败!',
error:faildata
});
return errorFunction(errorData);
}
});
},
};
export default websocket;