podchat-browser 12.7.2-snapshot.4 → 12.7.2-snapshot.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node/chat.js CHANGED
@@ -1,4 +1,5 @@
1
- 'use strict';var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof3=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _podasyncWsOnly=_interopRequireDefault(require("podasync-ws-only"));var _utility=_interopRequireDefault(require("./utility/utility"));var _dexie=_interopRequireDefault(require("dexie"));var _call=_interopRequireDefault(require("./call.module"));var _events=_interopRequireWildcard(require("./events.module"));var _messaging=_interopRequireDefault(require("./messaging.module"));var _constants=require("./lib/constants");var _deviceManager=_interopRequireDefault(require("./lib/call/deviceManager.js"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof3(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function Chat(params){/*******************************************************
1
+ 'use strict';var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof3=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _podasyncWsOnly=_interopRequireDefault(require("podasync-ws-only"));var _utility=_interopRequireDefault(require("./utility/utility"));var _dexie=_interopRequireDefault(require("dexie"));var _call=_interopRequireDefault(require("./call.module"));var _events=_interopRequireWildcard(require("./events.module"));var _messaging=_interopRequireDefault(require("./messaging.module"));var _constants=require("./lib/constants");var _deviceManager=_interopRequireDefault(require("./lib/call/deviceManager.js"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof3(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}// import {externalLogger as externalLog, init as initExternalLogger} from "./lib/logger";
2
+ function Chat(params){/*******************************************************
2
3
  * P R I V A T E V A R I A B L E S *
3
4
  *******************************************************/var asyncClient,peerId,oldPeerId,token=params.token,generalTypeCode=params.typeCode||'default',mapApiKey=params.mapApiKey||'8b77db18704aa646ee5aaea13e7370f4f88b9e8c',deviceId,productEnv=typeof navigator!='undefined'?navigator.product:'undefined',db,queueDb,forceWaitQueueInMemory=params.forceWaitQueueInMemory&&typeof params.forceWaitQueueInMemory==='boolean'?params.forceWaitQueueInMemory:false,hasCache=productEnv!=='ReactNative'&&typeof _dexie["default"]!='undefined',cacheInMemory=forceWaitQueueInMemory?true:!hasCache,enableCache=params.enableCache&&typeof params.enableCache==='boolean'?params.enableCache:false,canUseCache=hasCache&&enableCache,isCacheReady=false,cacheDeletingInProgress=false,cacheExpireTime=params.cacheExpireTime||2*24*60*60*1000,cacheSecret='VjaaS9YxNdVVAd3cAsRPcU5FyxRcyyV6tG6bFGjjK5RV8JJjLrXNbS5zZxnqUT6Y',cacheSyncWorker,grantDeviceIdFromSSO=params.grantDeviceIdFromSSO&&typeof params.grantDeviceIdFromSSO==='boolean'?params.grantDeviceIdFromSSO:false,messagesDelivery={},messagesSeen={},deliveryInterval,deliveryIntervalPitch=params.deliveryIntervalPitch||2000,seenInterval,seenIntervalPitch=params.seenIntervalPitch||2000,getImageFromLinkObjects={},locationPingTypes={'CHAT':1,'THREAD':2,'CONTACTS':3},systemMessageIntervalPitch=params.systemMessageIntervalPitch||1000,isTypingInterval,protocol=params.protocol||'websocket',queueHost=params.queueHost,queuePort=params.queuePort,queueUsername=params.queueUsername,queuePassword=params.queuePassword,queueReceive=params.queueReceive,queueSend=params.queueSend,queueConnectionTimeout=params.queueConnectionTimeout,socketAddress=params.socketAddress,serverName=params.serverName||'',wsConnectionWaitTime=params.wsConnectionWaitTime,connectionRetryInterval=params.connectionRetryInterval,msgPriority=params.msgPriority||1,messageTtl=params.messageTtl||10000,reconnectOnClose=params.reconnectOnClose,asyncLogging=params.asyncLogging,chatPingMessageInterval=20000,getUserInfoTimeout,config={getHistoryCount:50},SERVICE_ADDRESSES={SSO_ADDRESS:params.ssoHost||'https://accounts.pod.ir',PLATFORM_ADDRESS:params.platformHost||'https://api.pod.ir/srv/core',FILESERVER_ADDRESS:params.fileServer||'https://core.pod.ir',PODSPACE_FILESERVER_ADDRESS:params.podSpaceFileServer||'https://podspace.pod.ir',MAP_ADDRESS:params.mapServer||'https://api.neshan.org/v2'},SERVICES_PATH={// Grant Devices
4
5
  SSO_DEVICES:'/oauth2/grants/devices',SSO_GENERATE_KEY:'/handshake/users/',SSO_GET_KEY:'/handshake/keys/',// Contacts
@@ -20,9 +21,19 @@ REVERSE:'/reverse',SEARCH:'/search',ROUTING:'/routing',STATIC_IMAGE:'/static'},C
20
21
  6300:'Error in uploading File!',6301:'Not an image!',6302:'No file has been selected!',6303:'File upload has been canceled!',6304:'User Group Hash is needed for file sharing!',// Cache Database Errors
21
22
  6600:'Your Environment doesn\'t have Databse compatibility',6601:'Database is not defined! (missing db)',6602:'Database Error',// Map Errors
22
23
  6700:'You should Enter a Center Location like {lat: " ", lng: " "}'},getUserInfoRetry=5,getUserInfoRetryCount=0,chatFullStateObject={},httpRequestObject={},connectionCheckTimeout=params.connectionCheckTimeout,connectionCheckTimeoutThreshold=params.connectionCheckTimeoutThreshold,httpRequestTimeout=params.httpRequestTimeout>=0?params.httpRequestTimeout:0,asyncRequestTimeout=typeof params.asyncRequestTimeout==='number'&&params.asyncRequestTimeout>=0?params.asyncRequestTimeout:0,//callRequestTimeout = (typeof params.callRequestTimeout === 'number' && params.callRequestTimeout >= 0) ? params.callRequestTimeout : 10000,
23
- httpUploadRequestTimeout=params.httpUploadRequestTimeout>=0?params.httpUploadRequestTimeout:0,actualTimingLog=params.asyncLogging.actualTiming&&typeof params.asyncLogging.actualTiming==='boolean'?params.asyncLogging.actualTiming:false,consoleLogging=params.asyncLogging.consoleLogging&&typeof params.asyncLogging.consoleLogging==='boolean'?params.asyncLogging.consoleLogging:false,minIntegerValue=Number.MAX_SAFE_INTEGER*-1,maxIntegerValue=Number.MAX_SAFE_INTEGER,chatSendQueue=[],chatWaitQueue=[],chatUploadQueue=[],fullResponseObject=params.fullResponseObject||false;if(!consoleLogging){/**
24
+ httpUploadRequestTimeout=params.httpUploadRequestTimeout>=0?params.httpUploadRequestTimeout:0,actualTimingLog=params.asyncLogging.actualTiming&&typeof params.asyncLogging.actualTiming==='boolean'?params.asyncLogging.actualTiming:false,consoleLogging=params.asyncLogging.consoleLogging&&typeof params.asyncLogging.consoleLogging==='boolean'?params.asyncLogging.consoleLogging:false,minIntegerValue=Number.MAX_SAFE_INTEGER*-1,maxIntegerValue=Number.MAX_SAFE_INTEGER,chatSendQueue=[],chatWaitQueue=[],chatUploadQueue=[],fullResponseObject=params.fullResponseObject||false,//,
25
+ // externalLogging = {
26
+ // enable: ( params.externalLogging && params.externalLogging.enable !== undefined ? params.externalLogging.enable : true),
27
+ // url: (params.externalLogging && params.externalLogging.url !== undefined ? params.externalLogging.url : null),
28
+ // username: (params.externalLogging && params.externalLogging.username !== undefined ? params.externalLogging.username : null),
29
+ // password: (params.externalLogging && params.externalLogging.password !== undefined ? params.externalLogging.password : null)
30
+ // };
31
+ isAsyncReconnecting=false;if(!consoleLogging){/**
24
32
  * Disable kurento-utils logs
25
- */window.Logger={error:function error(){},log:function log(){},debug:function debug(){}};}(0,_events.initEventHandler)(Object.assign(params,{consoleLogging:consoleLogging}));var/*chatEvents = new ChatEvents(Object.assign(params, {
33
+ */window.Logger={error:function error(){},log:function log(){},debug:function debug(){}};}// if(externalLogging.enabled) {
34
+ // initExternalLogger(externalLogging);
35
+ // }
36
+ (0,_events.initEventHandler)(Object.assign(params,{consoleLogging:consoleLogging}));var/*chatEvents = new ChatEvents(Object.assign(params, {
26
37
 
27
38
  //Utility: Utility,
28
39
  consoleLogging,
@@ -41,15 +52,16 @@ consoleLogging:consoleLogging,chatEvents:_events.chatEvents,asyncClient:asyncCli
41
52
  *
42
53
  * @return {undefined}
43
54
  * @return {undefined}
44
- */initAsync=function initAsync(){var asyncGetReadyTime=new Date().getTime();asyncClient=new _podasyncWsOnly["default"]({protocol:protocol,queueHost:queueHost,queuePort:queuePort,queueUsername:queueUsername,queuePassword:queuePassword,queueReceive:queueReceive,queueSend:queueSend,queueConnectionTimeout:queueConnectionTimeout,socketAddress:socketAddress,serverName:serverName,deviceId:deviceId,wsConnectionWaitTime:wsConnectionWaitTime,connectionRetryInterval:connectionRetryInterval,connectionCheckTimeout:connectionCheckTimeout,connectionCheckTimeoutThreshold:connectionCheckTimeoutThreshold,messageTtl:messageTtl,reconnectOnClose:reconnectOnClose,asyncLogging:asyncLogging,logLevel:consoleLogging?3:1});callModule.asyncInitialized(asyncClient);chatMessaging.asyncInitialized(asyncClient);asyncClient.on('asyncReady',function(){if(actualTimingLog){_utility["default"].chatStepLogger('Async Connection ',new Date().getTime()-asyncGetReadyTime);}peerId=asyncClient.getPeerId();if(!chatMessaging.userInfo){var getUserInfoTime=new Date().getTime();getUserInfo(function(userInfoResult){if(actualTimingLog){_utility["default"].chatStepLogger('Get User Info ',new Date().getTime()-getUserInfoTime);}if(!userInfoResult.hasError){chatMessaging.userInfo=userInfoResult.result.user;getAllThreads({summary:true,cache:false});/**
55
+ */initAsync=function initAsync(){var asyncGetReadyTime=new Date().getTime();asyncClient=new _podasyncWsOnly["default"]({protocol:protocol,queueHost:queueHost,queuePort:queuePort,queueUsername:queueUsername,queuePassword:queuePassword,queueReceive:queueReceive,queueSend:queueSend,queueConnectionTimeout:queueConnectionTimeout,socketAddress:socketAddress,serverName:serverName,deviceId:deviceId,wsConnectionWaitTime:wsConnectionWaitTime,connectionRetryInterval:connectionRetryInterval,connectionCheckTimeout:connectionCheckTimeout,connectionCheckTimeoutThreshold:connectionCheckTimeoutThreshold,messageTtl:messageTtl,reconnectOnClose:reconnectOnClose,asyncLogging:asyncLogging,logLevel:consoleLogging?3:1});callModule.asyncInitialized(asyncClient);chatMessaging.asyncInitialized(asyncClient);asyncClient.on('asyncReady',function(){chatMessaging.startChatPing();if(actualTimingLog){_utility["default"].chatStepLogger('Async Connection ',new Date().getTime()-asyncGetReadyTime);}peerId=asyncClient.getPeerId();if(!chatMessaging.userInfo){var getUserInfoTime=new Date().getTime();getUserInfo(function(userInfoResult){if(actualTimingLog){_utility["default"].chatStepLogger('Get User Info ',new Date().getTime()-getUserInfoTime);}if(!userInfoResult.hasError){chatMessaging.userInfo=userInfoResult.result.user;getAllThreads({summary:true,cache:false});/**
45
56
  * Check if user has KeyId stored in their cache or not?
46
57
  */if(canUseCache){if(db){db.users.where('id').equals(parseInt(chatMessaging.userInfo.id)).toArray().then(function(users){if(users.length>0&&typeof users[0].keyId!='undefined'){var user=users[0];getEncryptionKey({keyId:user.keyId},function(result){if(!result.hasError){cacheSecret=result.secretKey;chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}else{if(result.message!==''){try{var response=JSON.parse(result.message);if(response.error==='invalid_param'){generateEncryptionKey({keyAlgorithm:'AES',keySize:256},function(){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();});}}catch(e){consoleLogging&&console.log(e);}}}});}else{generateEncryptionKey({keyAlgorithm:'AES',keySize:256},function(){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();});}})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}else{chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}}});}else if(chatMessaging.userInfo.id>0){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}deliveryInterval&&clearInterval(deliveryInterval);deliveryInterval=setInterval(function(){if(Object.keys(messagesDelivery).length){messagesDeliveryQueueHandler();}},deliveryIntervalPitch);seenInterval&&clearInterval(seenInterval);seenInterval=setInterval(function(){if(Object.keys(messagesSeen).length){messagesSeenQueueHandler();}},seenIntervalPitch);//shouldReconnectCall();
47
- });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;switch(state.socketState){case 1:// CONNECTED
58
+ });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;if(![0,2].includes(state.socketState)){isAsyncReconnecting=false;}else if([0,2].includes(state.socketState)){isAsyncReconnecting=true;}switch(state.socketState){case 1:// CONNECTED
48
59
  if(state.deviceRegister&&state.serverRegister){chatMessaging.chatState=true;chatMessaging.ping();}break;case 0:// CONNECTING
49
60
  case 2:// CLOSING
50
61
  case 3:// CLOSED
51
62
  chatMessaging.chatState=false;// TODO: Check if this is OK or not?!
52
- chatMessaging.sendPingTimeout&&clearTimeout(chatMessaging.sendPingTimeout);break;}});asyncClient.on('connect',function(newPeerId){asyncGetReadyTime=new Date().getTime();peerId=newPeerId;_events.chatEvents.fireEvent('connect');chatMessaging.ping();});asyncClient.on('disconnect',function(event){oldPeerId=peerId;peerId=undefined;_events.chatEvents.fireEvent('disconnect',event);_events.chatEvents.fireEvent('callEvents',{type:'CALL_ERROR',code:7000,message:'Call Socket is closed!',error:event});});asyncClient.on('reconnect',function(newPeerId){peerId=newPeerId;_events.chatEvents.fireEvent('reconnect');});asyncClient.on('message',function(params,ack){receivedAsyncMessageHandler(params);ack&&ack();});asyncClient.on('error',function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error.errorEvent});});},/**
63
+ //chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
64
+ break;}});asyncClient.on('connect',function(newPeerId){asyncGetReadyTime=new Date().getTime();peerId=newPeerId;_events.chatEvents.fireEvent('connect');chatMessaging.ping();});asyncClient.on('disconnect',function(event){oldPeerId=peerId;peerId=undefined;_events.chatEvents.fireEvent('disconnect',event);_events.chatEvents.fireEvent('callEvents',{type:'CALL_ERROR',code:7000,message:'Call Socket is closed!',error:event});});asyncClient.on('reconnect',function(newPeerId){peerId=newPeerId;_events.chatEvents.fireEvent('reconnect');});asyncClient.on('message',function(params,ack){receivedAsyncMessageHandler(params);ack&&ack();});asyncClient.on('error',function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error.errorEvent});});},/**
53
65
  * Get Device Id With Token
54
66
  *
55
67
  * If ssoGrantDevicesAddress set as TRUE, chat agent gets Device ID
@@ -2115,7 +2127,10 @@ content:[]};if(params){if(Array.isArray(params.assistants)&&(0,_typeof2["default
2115
2127
  content:[]};if(params){if(Array.isArray(params.assistants)&&(0,_typeof2["default"])(params.assistants[0])==='object'){for(var i=0;i<params.assistants.length;i++){if((0,_typeof2["default"])(params.assistants[i])==='object'&&params.assistants[i].hasOwnProperty('assistant')&&params.assistants[i].assistant.hasOwnProperty('id')&&params.assistants[i].assistant.hasOwnProperty('idType')&&params.assistants[i].assistant.id.length&&_constants.inviteeVOidTypes[params.assistants[i].assistant.idType]>0){sendData.content.push({assistant:{id:params.assistants[i].assistant.id,idType:+_constants.inviteeVOidTypes[params.assistants[i].assistant.idType]}});}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of an assistant!'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of an assistant!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Unblock Assistants!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result;returnData.result=messageContent;}callback&&callback(returnData);}});};publicized.getAssistantsList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.GET_ASSISTANTS,typeCode:generalTypeCode,//params.typeCode,
2116
2128
  content:{},pushMsgType:3,token:token};if(params){if(typeof params.contactType==='string'&&params.contactType.length){sendData.content.contactType=params.contactType;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Enter a ContactType to get all related Assistants!'});return;}sendData.content.count=!!params.count?+params.count:50;sendData.content.offset=!!params.offset?+params.offset:0;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get Assistants list!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getBlockedAssistantsList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCKED_ASSISTANTS,typeCode:generalTypeCode,//params.typeCode,
2117
2129
  content:{},pushMsgType:3,token:token};if(params){if(typeof params.contactType==='string'&&params.contactType.length){sendData.content.contactType=params.contactType;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Enter a ContactType to get all Blocked Assistants!'});return;}sendData.content.count=!!params.count?+params.count:50;sendData.content.offset=!!params.offset?+params.offset:0;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get Blocked Assistants list!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getAssistantsHistory=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ASSISTANT_HISTORY,typeCode:generalTypeCode,//params.typeCode,
2118
- content:{offset:+params.offset>0?+params.offset:0,count:+params.count>0?+params.count:config.getHistoryCount}};if(+params.fromTime>0&&+params.fromTime<9999999999999){sendData.content.fromTime=+params.fromTime;}if(+params.toTime>0&&+params.toTime<9999999999999){sendData.content.toTime=+params.toTime;}if(!!params.actionType&&_constants.assistantActionTypes.hasOwnProperty(params.actionType.toUpperCase())){sendData.content.actionType=_constants.assistantActionTypes[params.actionType.toUpperCase()];}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={participants:formatDataToMakeAssistantHistoryList(messageContent),contentCount:result.contentCount,hasNext:sendData.content.offset+sendData.content.count<result.contentCount&&messageLength>0,nextOffset:sendData.content.offset*1+messageLength*1};returnData.result=resultData;}callback&&callback(returnData);callback=undefined;}});};publicized.mapReverse=mapReverse;publicized.mapSearch=mapSearch;publicized.mapRouting=mapRouting;publicized.mapStaticImage=mapStaticImage;publicized.setAdmin=function(params,callback){setRoleToUser(params,callback);};publicized.removeAdmin=function(params,callback){removeRoleFromUser(params,callback);};publicized.setAuditor=function(params,callback){setRoleToUser(params,callback);};publicized.removeAuditor=function(params,callback){removeRoleFromUser(params,callback);};function requestExportChat(stackArr,wantedCount,stepCount,offset,sendData){sendData.content.offset=offset;sendData.content.count=stepCount;return new Promise(function(resolve,reject){return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){for(var i in result.result){stackArr.push(result.result[i]);}consoleLogging&&console.log("[SDK][exportChat] a step passed...");wantedCount=wantedCount>result.contentCount?result.contentCount:wantedCount;setTimeout(function(){_events.chatEvents.fireEvent('threadEvents',{type:'EXPORT_CHAT',subType:'IN_PROGRESS',threadId:sendData.subjectId,percent:Math.floor(stackArr.length/wantedCount*100)});if(stackArr.length<wantedCount){stepCount=wantedCount-stackArr.length<stepCount?wantedCount-stackArr.length:stepCount;//setTimeout(function () {
2130
+ content:{offset:+params.offset>0?+params.offset:0,count:+params.count>0?+params.count:config.getHistoryCount}};if(+params.fromTime>0&&+params.fromTime<9999999999999){sendData.content.fromTime=+params.fromTime;}if(+params.toTime>0&&+params.toTime<9999999999999){sendData.content.toTime=+params.toTime;}if(!!params.actionType&&_constants.assistantActionTypes.hasOwnProperty(params.actionType.toUpperCase())){sendData.content.actionType=_constants.assistantActionTypes[params.actionType.toUpperCase()];}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={participants:formatDataToMakeAssistantHistoryList(messageContent),contentCount:result.contentCount,hasNext:sendData.content.offset+sendData.content.count<result.contentCount&&messageLength>0,nextOffset:sendData.content.offset*1+messageLength*1};returnData.result=resultData;}callback&&callback(returnData);callback=undefined;}});};publicized.mapReverse=mapReverse;publicized.mapSearch=mapSearch;publicized.mapRouting=mapRouting;publicized.mapStaticImage=mapStaticImage;publicized.setAdmin=function(params,callback){setRoleToUser(params,callback);};publicized.removeAdmin=function(params,callback){removeRoleFromUser(params,callback);};publicized.setAuditor=function(params,callback){setRoleToUser(params,callback);};publicized.removeAuditor=function(params,callback){removeRoleFromUser(params,callback);};function requestExportChat(stackArr,wantedCount,stepCount,offset,sendData){sendData.content.offset=offset;sendData.content.count=stepCount;return new Promise(function(resolve,reject){return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){/* for(var i in result.result) {
2131
+ stackArr.push(result.result[i]);
2132
+ } */stackArr.push.apply(stackArr,(0,_toConsumableArray2["default"])(result.result));consoleLogging&&console.log("[SDK][exportChat] a step passed...");// wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
2133
+ if(result.result.length<stepCount){wantedCount=stackArr.length;}setTimeout(function(){_events.chatEvents.fireEvent('threadEvents',{type:'EXPORT_CHAT',subType:'IN_PROGRESS',threadId:sendData.subjectId,percent:Math.floor(stackArr.length/wantedCount*100)});if(stackArr.length<wantedCount){stepCount=wantedCount-stackArr.length<stepCount?wantedCount-stackArr.length:stepCount;//setTimeout(function () {
2119
2134
  resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));//}, 1000)
2120
2135
  }else{resolve(stackArr);}});}else{if(result.errorCode!==21){consoleLogging&&console.log("[SDK][exportChat] Problem in one step... . Rerunning the request.",wantedCount,stepCount,stackArr.length,sendData,result);setTimeout(function(){resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));},2000);}else{reject(result);}}}});});}publicized.exportChat=function(params,callback){var stackArr=[],wantedCount=10000,stepCount=500,offset=0;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.EXPORT_CHAT,typeCode:generalTypeCode,//params.typeCode,
2121
2136
  content:{offset:+params.offset>0?+params.offset:offset,count:+params.count>0?+params.count:wantedCount//config.getHistoryCount,
@@ -2151,7 +2166,7 @@ content:{count:count,offset:offset}};if(params){if((0,_typeof2["default"])(param
2151
2166
  * + locationPingRequest {object}
2152
2167
  * + content {list} A map of { location: string, locationId: int }
2153
2168
  */var locationPingData={chatMessageVOType:_constants.chatMessageVOTypes.LOCATION_PING,typeCode:generalTypeCode,//params.typeCode,
2154
- pushMsgType:3,token:token},content={};if(params){if(typeof params.location==='string'&&locationPingTypes.hasOwnProperty(params.location.toUpperCase())){content.location=locationPingTypes[params.location.toUpperCase()];if(params.location.toUpperCase()==='THREAD'){if(typeof params.threadId==='number'&&params.threadId>0){content.locationId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'You set the location to be a thread, you have to send a valid ThreadId'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Send a valid location type (CHAT / THREAD / CONTACTS)'});return;}locationPingData.content=JSON.stringify(content);}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to LocationPing!'});return;}return chatMessaging.sendMessage(locationPingData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.clearChatServerCaches=clearChatServerCaches;publicized.deleteCacheDatabases=deleteCacheDatabases;publicized.clearCacheDatabasesOfUser=clearCacheDatabasesOfUser;publicized.getChatState=function(){return chatFullStateObject;};publicized.reconnect=function(){asyncClient.reconnectSocket();};publicized.setToken=function(newToken){if(typeof newToken!=='undefined'){token=newToken;callModule.updateToken(token);chatMessaging.updateToken(token);_events.chatEvents.updateToken(token);}};publicized.generateUUID=_utility["default"].generateUUID;publicized.logout=function(){clearChatServerCaches();_events.chatEvents.clearEventCallbacks();chatMessaging.messagesCallbacks={};chatMessaging.sendMessageCallbacks={};chatMessaging.threadCallbacks={};asyncClient.logout();};publicized.inviteeIdTypes=_constants.inviteeVOidTypes;/**
2169
+ pushMsgType:3,token:token},content={};if(params){if(typeof params.location==='string'&&locationPingTypes.hasOwnProperty(params.location.toUpperCase())){content.location=locationPingTypes[params.location.toUpperCase()];if(params.location.toUpperCase()==='THREAD'){if(typeof params.threadId==='number'&&params.threadId>0){content.locationId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'You set the location to be a thread, you have to send a valid ThreadId'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Send a valid location type (CHAT / THREAD / CONTACTS)'});return;}locationPingData.content=JSON.stringify(content);}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to LocationPing!'});return;}return chatMessaging.sendMessage(locationPingData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.clearChatServerCaches=clearChatServerCaches;publicized.deleteCacheDatabases=deleteCacheDatabases;publicized.clearCacheDatabasesOfUser=clearCacheDatabasesOfUser;publicized.getChatState=function(){return chatFullStateObject;};publicized.reconnect=function(callback){if(!isAsyncReconnecting){asyncClient.reconnectSocket();isAsyncReconnecting=true;callback&&callback({hasError:false,message:"Reconnecting..."});}else{callback&&callback({hasError:true,message:"Socket state is not suitable for reconnecting."});consoleLogging&&console.log("[SDK] Socket state is not suitable for reconnecting.");}};publicized.setToken=function(newToken){if(typeof newToken!=='undefined'){token=newToken;callModule.updateToken(token);chatMessaging.updateToken(token);_events.chatEvents.updateToken(token);}};publicized.generateUUID=_utility["default"].generateUUID;publicized.logout=function(){clearChatServerCaches();_events.chatEvents.clearEventCallbacks();chatMessaging.messagesCallbacks={};chatMessaging.sendMessageCallbacks={};chatMessaging.threadCallbacks={};chatMessaging.stopChatPing();asyncClient.logout();};publicized.inviteeIdTypes=_constants.inviteeVOidTypes;/**
2155
2170
  * Check a turn server availability
2156
2171
  *
2157
2172
  * @param turnIp
@@ -10,6 +10,8 @@ exports.initEventHandler = initEventHandler;
10
10
 
11
11
  var _utility = _interopRequireDefault(require("./utility/utility"));
12
12
 
13
+ var _logger = require("./lib/logger");
14
+
13
15
  // import Sentry from "./lib/sentry.js"
14
16
  var chatEvents = null;
15
17
  exports.chatEvents = chatEvents;
@@ -76,8 +78,8 @@ function ChatEvents(params) {
76
78
  if (eventName === "error" || eventName === "callEvents" && param.type === "CALL_ERROR") {
77
79
  try {
78
80
  throw new PodChatErrorException(param);
79
- } catch (err) {
80
- console.error(err);
81
+ } catch (err) {//externalLogger(err);
82
+ // console.error(err);
81
83
  }
82
84
  }
83
85
 
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.externalLogger = externalLogger;
7
+ exports.init = init;
8
+ var config = {
9
+ url: 'http://10.56.34.61:8080/twitter/tweet/1',
10
+ username: 'chat',
11
+ password: 'chat123'
12
+ };
13
+
14
+ function externalLogger(message) {
15
+ var msg;
16
+ if (typeof message !== "string") msg = JSON.stringify(message);
17
+ fetch(config.url, {
18
+ method: 'POST',
19
+ headers: {
20
+ 'Authorization': 'Basic ' + btoa("".concat(config.username, ":").concat(config.password)),
21
+ 'Content-Type': 'application/x-www-form-urlencoded'
22
+ },
23
+ body: new URLSearchParams({
24
+ 'js-browser': msg
25
+ })
26
+ })["catch"](function (error) {
27
+ console.error("[SDK][ExternalLogger] Error while putting log, details: ", error);
28
+ });
29
+ }
30
+
31
+ function init(externalLogging) {
32
+ if (externalLogging.url) config.url = externalLogging.url;
33
+ if (externalLogging.username) config.username = externalLogging.username;
34
+ if (externalLogging.password) config.password = externalLogging.password;
35
+ }
@@ -40,10 +40,25 @@ function ChatMessaging(params) {
40
40
  this.threadCallbacks = {};
41
41
  this.sendMessageCallbacks = {};
42
42
  this.messagesCallbacks = {};
43
- this.asyncRequestTimeouts = {};
44
- this.sendPingTimeout = null;
43
+ this.asyncRequestTimeouts = {}; // this.sendPingTimeout = null;
44
+
45
45
  this.chatState = false;
46
46
  this.userInfo = null;
47
+ /**
48
+ * sendPingTimeout removed,
49
+ *
50
+ * TODO: remove the interval when socket statet changes to closed
51
+ */
52
+
53
+ this.startChatPing = function () {
54
+ chatPingMessageInterval = setInterval(function () {
55
+ currentModuleInstance.ping();
56
+ }, 20000); //TODO: chatPingMessageInterval
57
+ };
58
+
59
+ this.stopChatPing = function () {
60
+ clearInterval(chatPingMessageInterval);
61
+ };
47
62
 
48
63
  this.asyncInitialized = function (client) {
49
64
  asyncClient = client;
@@ -280,11 +295,12 @@ function ChatMessaging(params) {
280
295
  }
281
296
  }, asyncRequestTimeout);
282
297
  }
298
+ /* currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
299
+ currentModuleInstance.sendPingTimeout = setTimeout(function () {
300
+ currentModuleInstance.ping();
301
+ }, chatPingMessageInterval); */
302
+
283
303
 
284
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
285
- currentModuleInstance.sendPingTimeout = setTimeout(function () {
286
- currentModuleInstance.ping();
287
- }, chatPingMessageInterval);
288
304
  recursiveCallback && recursiveCallback();
289
305
  return {
290
306
  uniqueId: uniqueId,
@@ -316,9 +332,11 @@ function ChatMessaging(params) {
316
332
  chatMessageVOType: _constants.chatMessageVOTypes.PING,
317
333
  pushMsgType: 3
318
334
  });
319
- } else {
320
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
321
335
  }
336
+ /*else {
337
+ currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
338
+ }*/
339
+
322
340
  };
323
341
  } // if (typeof module !== 'undefined' && typeof module.exports != 'undefined') {
324
342
  // module.exports = ChatMessaging;
@@ -39199,15 +39199,15 @@ module.exports = function (thing, encoding, name) {
39199
39199
  isDeviceRegister = false;
39200
39200
  oldPeerId = peerId;
39201
39201
 
39202
- socketState = socketStateType.CLOSED;
39203
-
39204
- fireEvent('stateChange', {
39205
- socketState: socketState,
39206
- timeUntilReconnect: 0,
39207
- deviceRegister: isDeviceRegister,
39208
- serverRegister: isServerRegister,
39209
- peerId: peerId
39210
- });
39202
+ // socketState = socketStateType.CLOSED;
39203
+ //
39204
+ // fireEvent('stateChange', {
39205
+ // socketState: socketState,
39206
+ // timeUntilReconnect: 0,
39207
+ // deviceRegister: isDeviceRegister,
39208
+ // serverRegister: isServerRegister,
39209
+ // peerId: peerId
39210
+ // });
39211
39211
 
39212
39212
  fireEvent('disconnect', event);
39213
39213
 
@@ -39237,7 +39237,7 @@ module.exports = function (thing, encoding, name) {
39237
39237
  }, 1000 * retryStep);
39238
39238
 
39239
39239
  if (retryStep < 64) {
39240
- retryStep *= 2;
39240
+ retryStep += 8;
39241
39241
  }
39242
39242
 
39243
39243
  // socketReconnectCheck && clearTimeout(socketReconnectCheck);
@@ -39775,7 +39775,8 @@ module.exports = function (thing, encoding, name) {
39775
39775
  waitForSocketToConnectTimeoutId,
39776
39776
  socketRealTimeStatusInterval,
39777
39777
  logLevel = params.logLevel,
39778
- pingController = new PingManager({waitTime: connectionCheckTimeout});
39778
+ pingController = new PingManager({waitTime: connectionCheckTimeout}),
39779
+ socketWatchTimeout;
39779
39780
 
39780
39781
 
39781
39782
  function PingManager(params) {
@@ -39834,15 +39835,24 @@ module.exports = function (thing, encoding, name) {
39834
39835
 
39835
39836
  socket = new WebSocket(address, []);
39836
39837
 
39837
- socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
39838
- socketRealTimeStatusInterval = setInterval(function() {
39839
- switch (socket.readyState) {
39840
- case 2:
39841
- onCloseHandler(null);
39842
- break;
39843
- case 3:
39844
- socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
39845
- break;
39838
+ // socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
39839
+ // socketRealTimeStatusInterval = setInterval(function() {
39840
+ // switch (socket.readyState) {
39841
+ // case 2:
39842
+ // onCloseHandler(null);
39843
+ // socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
39844
+ // break;
39845
+ // case 3:
39846
+ //
39847
+ // break;
39848
+ // }
39849
+ // }, 5000);
39850
+
39851
+ socketWatchTimeout && clearTimeout(socketWatchTimeout);
39852
+ socketWatchTimeout = setTimeout(() => {
39853
+ if(socket.readyState !== 1) {
39854
+ onCloseHandler(null);
39855
+ socket.close();
39846
39856
  }
39847
39857
  }, 5000);
39848
39858
 
@@ -45890,8 +45900,9 @@ invitees.forEach(function(item){item.idType=_constants.inviteeVOidTypes[item.idT
45890
45900
  }
45891
45901
  }*/return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};this.deviceManager=_deviceManager["default"];this.resetCallStream=function(_ref6,callback){var userId=_ref6.userId,_ref6$streamType=_ref6.streamType,streamType=_ref6$streamType===void 0?'audio':_ref6$streamType;return new Promise(function(resolve,reject){if(userId==='screenShare'||streamType==='video'){if(callUsers[userId]){callUsers[userId].videoTopicManager.recreateTopic().then(function(){resolve();callback&&callback({hasError:false});})["catch"](function(){reject();callback&&callback({hasError:true});});}}else{callUsers[userId].audioTopicManager.recreateTopic().then(function(){resolve();callback&&callback({hasError:false});})["catch"](function(){reject();callback&&callback({hasError:true});});}});};this.callStop=callStop;this.restartMedia=restartMedia;}var _default=ChatCall;exports["default"]=_default;
45892
45902
 
45893
- },{"./events.module.js":268,"./lib/call/deviceManager.js":269,"./lib/constants":270,"./lib/errorHandler":271,"./utility/utility":273,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/toConsumableArray":9,"@babel/runtime/helpers/typeof":10,"kurento-utils":190}],267:[function(require,module,exports){
45894
- 'use strict';var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof3=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _podasyncWsOnly=_interopRequireDefault(require("podasync-ws-only"));var _utility=_interopRequireDefault(require("./utility/utility"));var _dexie=_interopRequireDefault(require("dexie"));var _call=_interopRequireDefault(require("./call.module"));var _events=_interopRequireWildcard(require("./events.module"));var _messaging=_interopRequireDefault(require("./messaging.module"));var _constants=require("./lib/constants");var _deviceManager=_interopRequireDefault(require("./lib/call/deviceManager.js"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof3(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function Chat(params){/*******************************************************
45903
+ },{"./events.module.js":268,"./lib/call/deviceManager.js":269,"./lib/constants":270,"./lib/errorHandler":271,"./utility/utility":274,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/toConsumableArray":9,"@babel/runtime/helpers/typeof":10,"kurento-utils":190}],267:[function(require,module,exports){
45904
+ 'use strict';var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof3=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _podasyncWsOnly=_interopRequireDefault(require("podasync-ws-only"));var _utility=_interopRequireDefault(require("./utility/utility"));var _dexie=_interopRequireDefault(require("dexie"));var _call=_interopRequireDefault(require("./call.module"));var _events=_interopRequireWildcard(require("./events.module"));var _messaging=_interopRequireDefault(require("./messaging.module"));var _constants=require("./lib/constants");var _deviceManager=_interopRequireDefault(require("./lib/call/deviceManager.js"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof3(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}// import {externalLogger as externalLog, init as initExternalLogger} from "./lib/logger";
45905
+ function Chat(params){/*******************************************************
45895
45906
  * P R I V A T E V A R I A B L E S *
45896
45907
  *******************************************************/var asyncClient,peerId,oldPeerId,token=params.token,generalTypeCode=params.typeCode||'default',mapApiKey=params.mapApiKey||'8b77db18704aa646ee5aaea13e7370f4f88b9e8c',deviceId,productEnv=typeof navigator!='undefined'?navigator.product:'undefined',db,queueDb,forceWaitQueueInMemory=params.forceWaitQueueInMemory&&typeof params.forceWaitQueueInMemory==='boolean'?params.forceWaitQueueInMemory:false,hasCache=productEnv!=='ReactNative'&&typeof _dexie["default"]!='undefined',cacheInMemory=forceWaitQueueInMemory?true:!hasCache,enableCache=params.enableCache&&typeof params.enableCache==='boolean'?params.enableCache:false,canUseCache=hasCache&&enableCache,isCacheReady=false,cacheDeletingInProgress=false,cacheExpireTime=params.cacheExpireTime||2*24*60*60*1000,cacheSecret='VjaaS9YxNdVVAd3cAsRPcU5FyxRcyyV6tG6bFGjjK5RV8JJjLrXNbS5zZxnqUT6Y',cacheSyncWorker,grantDeviceIdFromSSO=params.grantDeviceIdFromSSO&&typeof params.grantDeviceIdFromSSO==='boolean'?params.grantDeviceIdFromSSO:false,messagesDelivery={},messagesSeen={},deliveryInterval,deliveryIntervalPitch=params.deliveryIntervalPitch||2000,seenInterval,seenIntervalPitch=params.seenIntervalPitch||2000,getImageFromLinkObjects={},locationPingTypes={'CHAT':1,'THREAD':2,'CONTACTS':3},systemMessageIntervalPitch=params.systemMessageIntervalPitch||1000,isTypingInterval,protocol=params.protocol||'websocket',queueHost=params.queueHost,queuePort=params.queuePort,queueUsername=params.queueUsername,queuePassword=params.queuePassword,queueReceive=params.queueReceive,queueSend=params.queueSend,queueConnectionTimeout=params.queueConnectionTimeout,socketAddress=params.socketAddress,serverName=params.serverName||'',wsConnectionWaitTime=params.wsConnectionWaitTime,connectionRetryInterval=params.connectionRetryInterval,msgPriority=params.msgPriority||1,messageTtl=params.messageTtl||10000,reconnectOnClose=params.reconnectOnClose,asyncLogging=params.asyncLogging,chatPingMessageInterval=20000,getUserInfoTimeout,config={getHistoryCount:50},SERVICE_ADDRESSES={SSO_ADDRESS:params.ssoHost||'https://accounts.pod.ir',PLATFORM_ADDRESS:params.platformHost||'https://api.pod.ir/srv/core',FILESERVER_ADDRESS:params.fileServer||'https://core.pod.ir',PODSPACE_FILESERVER_ADDRESS:params.podSpaceFileServer||'https://podspace.pod.ir',MAP_ADDRESS:params.mapServer||'https://api.neshan.org/v2'},SERVICES_PATH={// Grant Devices
45897
45908
  SSO_DEVICES:'/oauth2/grants/devices',SSO_GENERATE_KEY:'/handshake/users/',SSO_GET_KEY:'/handshake/keys/',// Contacts
@@ -45913,9 +45924,19 @@ REVERSE:'/reverse',SEARCH:'/search',ROUTING:'/routing',STATIC_IMAGE:'/static'},C
45913
45924
  6300:'Error in uploading File!',6301:'Not an image!',6302:'No file has been selected!',6303:'File upload has been canceled!',6304:'User Group Hash is needed for file sharing!',// Cache Database Errors
45914
45925
  6600:'Your Environment doesn\'t have Databse compatibility',6601:'Database is not defined! (missing db)',6602:'Database Error',// Map Errors
45915
45926
  6700:'You should Enter a Center Location like {lat: " ", lng: " "}'},getUserInfoRetry=5,getUserInfoRetryCount=0,chatFullStateObject={},httpRequestObject={},connectionCheckTimeout=params.connectionCheckTimeout,connectionCheckTimeoutThreshold=params.connectionCheckTimeoutThreshold,httpRequestTimeout=params.httpRequestTimeout>=0?params.httpRequestTimeout:0,asyncRequestTimeout=typeof params.asyncRequestTimeout==='number'&&params.asyncRequestTimeout>=0?params.asyncRequestTimeout:0,//callRequestTimeout = (typeof params.callRequestTimeout === 'number' && params.callRequestTimeout >= 0) ? params.callRequestTimeout : 10000,
45916
- httpUploadRequestTimeout=params.httpUploadRequestTimeout>=0?params.httpUploadRequestTimeout:0,actualTimingLog=params.asyncLogging.actualTiming&&typeof params.asyncLogging.actualTiming==='boolean'?params.asyncLogging.actualTiming:false,consoleLogging=params.asyncLogging.consoleLogging&&typeof params.asyncLogging.consoleLogging==='boolean'?params.asyncLogging.consoleLogging:false,minIntegerValue=Number.MAX_SAFE_INTEGER*-1,maxIntegerValue=Number.MAX_SAFE_INTEGER,chatSendQueue=[],chatWaitQueue=[],chatUploadQueue=[],fullResponseObject=params.fullResponseObject||false;if(!consoleLogging){/**
45927
+ httpUploadRequestTimeout=params.httpUploadRequestTimeout>=0?params.httpUploadRequestTimeout:0,actualTimingLog=params.asyncLogging.actualTiming&&typeof params.asyncLogging.actualTiming==='boolean'?params.asyncLogging.actualTiming:false,consoleLogging=params.asyncLogging.consoleLogging&&typeof params.asyncLogging.consoleLogging==='boolean'?params.asyncLogging.consoleLogging:false,minIntegerValue=Number.MAX_SAFE_INTEGER*-1,maxIntegerValue=Number.MAX_SAFE_INTEGER,chatSendQueue=[],chatWaitQueue=[],chatUploadQueue=[],fullResponseObject=params.fullResponseObject||false,//,
45928
+ // externalLogging = {
45929
+ // enable: ( params.externalLogging && params.externalLogging.enable !== undefined ? params.externalLogging.enable : true),
45930
+ // url: (params.externalLogging && params.externalLogging.url !== undefined ? params.externalLogging.url : null),
45931
+ // username: (params.externalLogging && params.externalLogging.username !== undefined ? params.externalLogging.username : null),
45932
+ // password: (params.externalLogging && params.externalLogging.password !== undefined ? params.externalLogging.password : null)
45933
+ // };
45934
+ isAsyncReconnecting=false;if(!consoleLogging){/**
45917
45935
  * Disable kurento-utils logs
45918
- */window.Logger={error:function error(){},log:function log(){},debug:function debug(){}};}(0,_events.initEventHandler)(Object.assign(params,{consoleLogging:consoleLogging}));var/*chatEvents = new ChatEvents(Object.assign(params, {
45936
+ */window.Logger={error:function error(){},log:function log(){},debug:function debug(){}};}// if(externalLogging.enabled) {
45937
+ // initExternalLogger(externalLogging);
45938
+ // }
45939
+ (0,_events.initEventHandler)(Object.assign(params,{consoleLogging:consoleLogging}));var/*chatEvents = new ChatEvents(Object.assign(params, {
45919
45940
 
45920
45941
  //Utility: Utility,
45921
45942
  consoleLogging,
@@ -45934,15 +45955,16 @@ consoleLogging:consoleLogging,chatEvents:_events.chatEvents,asyncClient:asyncCli
45934
45955
  *
45935
45956
  * @return {undefined}
45936
45957
  * @return {undefined}
45937
- */initAsync=function initAsync(){var asyncGetReadyTime=new Date().getTime();asyncClient=new _podasyncWsOnly["default"]({protocol:protocol,queueHost:queueHost,queuePort:queuePort,queueUsername:queueUsername,queuePassword:queuePassword,queueReceive:queueReceive,queueSend:queueSend,queueConnectionTimeout:queueConnectionTimeout,socketAddress:socketAddress,serverName:serverName,deviceId:deviceId,wsConnectionWaitTime:wsConnectionWaitTime,connectionRetryInterval:connectionRetryInterval,connectionCheckTimeout:connectionCheckTimeout,connectionCheckTimeoutThreshold:connectionCheckTimeoutThreshold,messageTtl:messageTtl,reconnectOnClose:reconnectOnClose,asyncLogging:asyncLogging,logLevel:consoleLogging?3:1});callModule.asyncInitialized(asyncClient);chatMessaging.asyncInitialized(asyncClient);asyncClient.on('asyncReady',function(){if(actualTimingLog){_utility["default"].chatStepLogger('Async Connection ',new Date().getTime()-asyncGetReadyTime);}peerId=asyncClient.getPeerId();if(!chatMessaging.userInfo){var getUserInfoTime=new Date().getTime();getUserInfo(function(userInfoResult){if(actualTimingLog){_utility["default"].chatStepLogger('Get User Info ',new Date().getTime()-getUserInfoTime);}if(!userInfoResult.hasError){chatMessaging.userInfo=userInfoResult.result.user;getAllThreads({summary:true,cache:false});/**
45958
+ */initAsync=function initAsync(){var asyncGetReadyTime=new Date().getTime();asyncClient=new _podasyncWsOnly["default"]({protocol:protocol,queueHost:queueHost,queuePort:queuePort,queueUsername:queueUsername,queuePassword:queuePassword,queueReceive:queueReceive,queueSend:queueSend,queueConnectionTimeout:queueConnectionTimeout,socketAddress:socketAddress,serverName:serverName,deviceId:deviceId,wsConnectionWaitTime:wsConnectionWaitTime,connectionRetryInterval:connectionRetryInterval,connectionCheckTimeout:connectionCheckTimeout,connectionCheckTimeoutThreshold:connectionCheckTimeoutThreshold,messageTtl:messageTtl,reconnectOnClose:reconnectOnClose,asyncLogging:asyncLogging,logLevel:consoleLogging?3:1});callModule.asyncInitialized(asyncClient);chatMessaging.asyncInitialized(asyncClient);asyncClient.on('asyncReady',function(){chatMessaging.startChatPing();if(actualTimingLog){_utility["default"].chatStepLogger('Async Connection ',new Date().getTime()-asyncGetReadyTime);}peerId=asyncClient.getPeerId();if(!chatMessaging.userInfo){var getUserInfoTime=new Date().getTime();getUserInfo(function(userInfoResult){if(actualTimingLog){_utility["default"].chatStepLogger('Get User Info ',new Date().getTime()-getUserInfoTime);}if(!userInfoResult.hasError){chatMessaging.userInfo=userInfoResult.result.user;getAllThreads({summary:true,cache:false});/**
45938
45959
  * Check if user has KeyId stored in their cache or not?
45939
45960
  */if(canUseCache){if(db){db.users.where('id').equals(parseInt(chatMessaging.userInfo.id)).toArray().then(function(users){if(users.length>0&&typeof users[0].keyId!='undefined'){var user=users[0];getEncryptionKey({keyId:user.keyId},function(result){if(!result.hasError){cacheSecret=result.secretKey;chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}else{if(result.message!==''){try{var response=JSON.parse(result.message);if(response.error==='invalid_param'){generateEncryptionKey({keyAlgorithm:'AES',keySize:256},function(){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();});}}catch(e){consoleLogging&&console.log(e);}}}});}else{generateEncryptionKey({keyAlgorithm:'AES',keySize:256},function(){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();});}})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}else{chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}}});}else if(chatMessaging.userInfo.id>0){chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}deliveryInterval&&clearInterval(deliveryInterval);deliveryInterval=setInterval(function(){if(Object.keys(messagesDelivery).length){messagesDeliveryQueueHandler();}},deliveryIntervalPitch);seenInterval&&clearInterval(seenInterval);seenInterval=setInterval(function(){if(Object.keys(messagesSeen).length){messagesSeenQueueHandler();}},seenIntervalPitch);//shouldReconnectCall();
45940
- });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;switch(state.socketState){case 1:// CONNECTED
45961
+ });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;if(![0,2].includes(state.socketState)){isAsyncReconnecting=false;}else if([0,2].includes(state.socketState)){isAsyncReconnecting=true;}switch(state.socketState){case 1:// CONNECTED
45941
45962
  if(state.deviceRegister&&state.serverRegister){chatMessaging.chatState=true;chatMessaging.ping();}break;case 0:// CONNECTING
45942
45963
  case 2:// CLOSING
45943
45964
  case 3:// CLOSED
45944
45965
  chatMessaging.chatState=false;// TODO: Check if this is OK or not?!
45945
- chatMessaging.sendPingTimeout&&clearTimeout(chatMessaging.sendPingTimeout);break;}});asyncClient.on('connect',function(newPeerId){asyncGetReadyTime=new Date().getTime();peerId=newPeerId;_events.chatEvents.fireEvent('connect');chatMessaging.ping();});asyncClient.on('disconnect',function(event){oldPeerId=peerId;peerId=undefined;_events.chatEvents.fireEvent('disconnect',event);_events.chatEvents.fireEvent('callEvents',{type:'CALL_ERROR',code:7000,message:'Call Socket is closed!',error:event});});asyncClient.on('reconnect',function(newPeerId){peerId=newPeerId;_events.chatEvents.fireEvent('reconnect');});asyncClient.on('message',function(params,ack){receivedAsyncMessageHandler(params);ack&&ack();});asyncClient.on('error',function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error.errorEvent});});},/**
45966
+ //chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
45967
+ break;}});asyncClient.on('connect',function(newPeerId){asyncGetReadyTime=new Date().getTime();peerId=newPeerId;_events.chatEvents.fireEvent('connect');chatMessaging.ping();});asyncClient.on('disconnect',function(event){oldPeerId=peerId;peerId=undefined;_events.chatEvents.fireEvent('disconnect',event);_events.chatEvents.fireEvent('callEvents',{type:'CALL_ERROR',code:7000,message:'Call Socket is closed!',error:event});});asyncClient.on('reconnect',function(newPeerId){peerId=newPeerId;_events.chatEvents.fireEvent('reconnect');});asyncClient.on('message',function(params,ack){receivedAsyncMessageHandler(params);ack&&ack();});asyncClient.on('error',function(error){_events.chatEvents.fireEvent('error',{code:error.errorCode,message:error.errorMessage,error:error.errorEvent});});},/**
45946
45968
  * Get Device Id With Token
45947
45969
  *
45948
45970
  * If ssoGrantDevicesAddress set as TRUE, chat agent gets Device ID
@@ -48008,7 +48030,10 @@ content:[]};if(params){if(Array.isArray(params.assistants)&&(0,_typeof2["default
48008
48030
  content:[]};if(params){if(Array.isArray(params.assistants)&&(0,_typeof2["default"])(params.assistants[0])==='object'){for(var i=0;i<params.assistants.length;i++){if((0,_typeof2["default"])(params.assistants[i])==='object'&&params.assistants[i].hasOwnProperty('assistant')&&params.assistants[i].assistant.hasOwnProperty('id')&&params.assistants[i].assistant.hasOwnProperty('idType')&&params.assistants[i].assistant.id.length&&_constants.inviteeVOidTypes[params.assistants[i].assistant.idType]>0){sendData.content.push({assistant:{id:params.assistants[i].assistant.id,idType:+_constants.inviteeVOidTypes[params.assistants[i].assistant.idType]}});}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of an assistant!'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of an assistant!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Unblock Assistants!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result;returnData.result=messageContent;}callback&&callback(returnData);}});};publicized.getAssistantsList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.GET_ASSISTANTS,typeCode:generalTypeCode,//params.typeCode,
48009
48031
  content:{},pushMsgType:3,token:token};if(params){if(typeof params.contactType==='string'&&params.contactType.length){sendData.content.contactType=params.contactType;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Enter a ContactType to get all related Assistants!'});return;}sendData.content.count=!!params.count?+params.count:50;sendData.content.offset=!!params.offset?+params.offset:0;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get Assistants list!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getBlockedAssistantsList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCKED_ASSISTANTS,typeCode:generalTypeCode,//params.typeCode,
48010
48032
  content:{},pushMsgType:3,token:token};if(params){if(typeof params.contactType==='string'&&params.contactType.length){sendData.content.contactType=params.contactType;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Enter a ContactType to get all Blocked Assistants!'});return;}sendData.content.count=!!params.count?+params.count:50;sendData.content.offset=!!params.offset?+params.offset:0;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get Blocked Assistants list!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getAssistantsHistory=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ASSISTANT_HISTORY,typeCode:generalTypeCode,//params.typeCode,
48011
- content:{offset:+params.offset>0?+params.offset:0,count:+params.count>0?+params.count:config.getHistoryCount}};if(+params.fromTime>0&&+params.fromTime<9999999999999){sendData.content.fromTime=+params.fromTime;}if(+params.toTime>0&&+params.toTime<9999999999999){sendData.content.toTime=+params.toTime;}if(!!params.actionType&&_constants.assistantActionTypes.hasOwnProperty(params.actionType.toUpperCase())){sendData.content.actionType=_constants.assistantActionTypes[params.actionType.toUpperCase()];}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={participants:formatDataToMakeAssistantHistoryList(messageContent),contentCount:result.contentCount,hasNext:sendData.content.offset+sendData.content.count<result.contentCount&&messageLength>0,nextOffset:sendData.content.offset*1+messageLength*1};returnData.result=resultData;}callback&&callback(returnData);callback=undefined;}});};publicized.mapReverse=mapReverse;publicized.mapSearch=mapSearch;publicized.mapRouting=mapRouting;publicized.mapStaticImage=mapStaticImage;publicized.setAdmin=function(params,callback){setRoleToUser(params,callback);};publicized.removeAdmin=function(params,callback){removeRoleFromUser(params,callback);};publicized.setAuditor=function(params,callback){setRoleToUser(params,callback);};publicized.removeAuditor=function(params,callback){removeRoleFromUser(params,callback);};function requestExportChat(stackArr,wantedCount,stepCount,offset,sendData){sendData.content.offset=offset;sendData.content.count=stepCount;return new Promise(function(resolve,reject){return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){for(var i in result.result){stackArr.push(result.result[i]);}consoleLogging&&console.log("[SDK][exportChat] a step passed...");wantedCount=wantedCount>result.contentCount?result.contentCount:wantedCount;setTimeout(function(){_events.chatEvents.fireEvent('threadEvents',{type:'EXPORT_CHAT',subType:'IN_PROGRESS',threadId:sendData.subjectId,percent:Math.floor(stackArr.length/wantedCount*100)});if(stackArr.length<wantedCount){stepCount=wantedCount-stackArr.length<stepCount?wantedCount-stackArr.length:stepCount;//setTimeout(function () {
48033
+ content:{offset:+params.offset>0?+params.offset:0,count:+params.count>0?+params.count:config.getHistoryCount}};if(+params.fromTime>0&&+params.fromTime<9999999999999){sendData.content.fromTime=+params.fromTime;}if(+params.toTime>0&&+params.toTime<9999999999999){sendData.content.toTime=+params.toTime;}if(!!params.actionType&&_constants.assistantActionTypes.hasOwnProperty(params.actionType.toUpperCase())){sendData.content.actionType=_constants.assistantActionTypes[params.actionType.toUpperCase()];}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={participants:formatDataToMakeAssistantHistoryList(messageContent),contentCount:result.contentCount,hasNext:sendData.content.offset+sendData.content.count<result.contentCount&&messageLength>0,nextOffset:sendData.content.offset*1+messageLength*1};returnData.result=resultData;}callback&&callback(returnData);callback=undefined;}});};publicized.mapReverse=mapReverse;publicized.mapSearch=mapSearch;publicized.mapRouting=mapRouting;publicized.mapStaticImage=mapStaticImage;publicized.setAdmin=function(params,callback){setRoleToUser(params,callback);};publicized.removeAdmin=function(params,callback){removeRoleFromUser(params,callback);};publicized.setAuditor=function(params,callback){setRoleToUser(params,callback);};publicized.removeAuditor=function(params,callback){removeRoleFromUser(params,callback);};function requestExportChat(stackArr,wantedCount,stepCount,offset,sendData){sendData.content.offset=offset;sendData.content.count=stepCount;return new Promise(function(resolve,reject){return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){/* for(var i in result.result) {
48034
+ stackArr.push(result.result[i]);
48035
+ } */stackArr.push.apply(stackArr,(0,_toConsumableArray2["default"])(result.result));consoleLogging&&console.log("[SDK][exportChat] a step passed...");// wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
48036
+ if(result.result.length<stepCount){wantedCount=stackArr.length;}setTimeout(function(){_events.chatEvents.fireEvent('threadEvents',{type:'EXPORT_CHAT',subType:'IN_PROGRESS',threadId:sendData.subjectId,percent:Math.floor(stackArr.length/wantedCount*100)});if(stackArr.length<wantedCount){stepCount=wantedCount-stackArr.length<stepCount?wantedCount-stackArr.length:stepCount;//setTimeout(function () {
48012
48037
  resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));//}, 1000)
48013
48038
  }else{resolve(stackArr);}});}else{if(result.errorCode!==21){consoleLogging&&console.log("[SDK][exportChat] Problem in one step... . Rerunning the request.",wantedCount,stepCount,stackArr.length,sendData,result);setTimeout(function(){resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));},2000);}else{reject(result);}}}});});}publicized.exportChat=function(params,callback){var stackArr=[],wantedCount=10000,stepCount=500,offset=0;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.EXPORT_CHAT,typeCode:generalTypeCode,//params.typeCode,
48014
48039
  content:{offset:+params.offset>0?+params.offset:offset,count:+params.count>0?+params.count:wantedCount//config.getHistoryCount,
@@ -48044,7 +48069,7 @@ content:{count:count,offset:offset}};if(params){if((0,_typeof2["default"])(param
48044
48069
  * + locationPingRequest {object}
48045
48070
  * + content {list} A map of { location: string, locationId: int }
48046
48071
  */var locationPingData={chatMessageVOType:_constants.chatMessageVOTypes.LOCATION_PING,typeCode:generalTypeCode,//params.typeCode,
48047
- pushMsgType:3,token:token},content={};if(params){if(typeof params.location==='string'&&locationPingTypes.hasOwnProperty(params.location.toUpperCase())){content.location=locationPingTypes[params.location.toUpperCase()];if(params.location.toUpperCase()==='THREAD'){if(typeof params.threadId==='number'&&params.threadId>0){content.locationId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'You set the location to be a thread, you have to send a valid ThreadId'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Send a valid location type (CHAT / THREAD / CONTACTS)'});return;}locationPingData.content=JSON.stringify(content);}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to LocationPing!'});return;}return chatMessaging.sendMessage(locationPingData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.clearChatServerCaches=clearChatServerCaches;publicized.deleteCacheDatabases=deleteCacheDatabases;publicized.clearCacheDatabasesOfUser=clearCacheDatabasesOfUser;publicized.getChatState=function(){return chatFullStateObject;};publicized.reconnect=function(){asyncClient.reconnectSocket();};publicized.setToken=function(newToken){if(typeof newToken!=='undefined'){token=newToken;callModule.updateToken(token);chatMessaging.updateToken(token);_events.chatEvents.updateToken(token);}};publicized.generateUUID=_utility["default"].generateUUID;publicized.logout=function(){clearChatServerCaches();_events.chatEvents.clearEventCallbacks();chatMessaging.messagesCallbacks={};chatMessaging.sendMessageCallbacks={};chatMessaging.threadCallbacks={};asyncClient.logout();};publicized.inviteeIdTypes=_constants.inviteeVOidTypes;/**
48072
+ pushMsgType:3,token:token},content={};if(params){if(typeof params.location==='string'&&locationPingTypes.hasOwnProperty(params.location.toUpperCase())){content.location=locationPingTypes[params.location.toUpperCase()];if(params.location.toUpperCase()==='THREAD'){if(typeof params.threadId==='number'&&params.threadId>0){content.locationId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'You set the location to be a thread, you have to send a valid ThreadId'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Send a valid location type (CHAT / THREAD / CONTACTS)'});return;}locationPingData.content=JSON.stringify(content);}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to LocationPing!'});return;}return chatMessaging.sendMessage(locationPingData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.clearChatServerCaches=clearChatServerCaches;publicized.deleteCacheDatabases=deleteCacheDatabases;publicized.clearCacheDatabasesOfUser=clearCacheDatabasesOfUser;publicized.getChatState=function(){return chatFullStateObject;};publicized.reconnect=function(callback){if(!isAsyncReconnecting){asyncClient.reconnectSocket();isAsyncReconnecting=true;callback&&callback({hasError:false,message:"Reconnecting..."});}else{callback&&callback({hasError:true,message:"Socket state is not suitable for reconnecting."});consoleLogging&&console.log("[SDK] Socket state is not suitable for reconnecting.");}};publicized.setToken=function(newToken){if(typeof newToken!=='undefined'){token=newToken;callModule.updateToken(token);chatMessaging.updateToken(token);_events.chatEvents.updateToken(token);}};publicized.generateUUID=_utility["default"].generateUUID;publicized.logout=function(){clearChatServerCaches();_events.chatEvents.clearEventCallbacks();chatMessaging.messagesCallbacks={};chatMessaging.sendMessageCallbacks={};chatMessaging.threadCallbacks={};chatMessaging.stopChatPing();asyncClient.logout();};publicized.inviteeIdTypes=_constants.inviteeVOidTypes;/**
48048
48073
  * Check a turn server availability
48049
48074
  *
48050
48075
  * @param turnIp
@@ -48066,7 +48091,7 @@ token:token,subjectId:threadId};return chatMessaging.sendMessage(sendData,{onRes
48066
48091
  window.PodChat=Chat;}var _default=Chat;// })();
48067
48092
  exports["default"]=_default;
48068
48093
 
48069
- },{"./call.module":266,"./events.module":268,"./lib/call/deviceManager.js":269,"./lib/constants":270,"./messaging.module":272,"./utility/utility":273,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/typeof":10,"dexie":125,"podasync-ws-only":209}],268:[function(require,module,exports){
48094
+ },{"./call.module":266,"./events.module":268,"./lib/call/deviceManager.js":269,"./lib/constants":270,"./messaging.module":273,"./utility/utility":274,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/toConsumableArray":9,"@babel/runtime/helpers/typeof":10,"dexie":125,"podasync-ws-only":209}],268:[function(require,module,exports){
48070
48095
  "use strict";
48071
48096
 
48072
48097
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
@@ -48077,7 +48102,9 @@ Object.defineProperty(exports, "__esModule", {
48077
48102
  exports["default"] = exports.chatEvents = void 0;
48078
48103
  exports.initEventHandler = initEventHandler;
48079
48104
 
48080
- var _utility = _interopRequireDefault(require("./utility/utility")); // import Sentry from "./lib/sentry.js"
48105
+ var _utility = _interopRequireDefault(require("./utility/utility"));
48106
+
48107
+ var _logger = require("./lib/logger"); // import Sentry from "./lib/sentry.js"
48081
48108
 
48082
48109
 
48083
48110
  var chatEvents = null;
@@ -48145,8 +48172,8 @@ function ChatEvents(params) {
48145
48172
  if (eventName === "error" || eventName === "callEvents" && param.type === "CALL_ERROR") {
48146
48173
  try {
48147
48174
  throw new PodChatErrorException(param);
48148
- } catch (err) {
48149
- console.error(err);
48175
+ } catch (err) {//externalLogger(err);
48176
+ // console.error(err);
48150
48177
  }
48151
48178
  }
48152
48179
 
@@ -48192,7 +48219,7 @@ function initEventHandler(params) {
48192
48219
  var _default = ChatEvents;
48193
48220
  exports["default"] = _default;
48194
48221
 
48195
- },{"./utility/utility":273,"@babel/runtime/helpers/interopRequireDefault":5}],269:[function(require,module,exports){
48222
+ },{"./lib/logger":272,"./utility/utility":274,"@babel/runtime/helpers/interopRequireDefault":5}],269:[function(require,module,exports){
48196
48223
  "use strict";
48197
48224
 
48198
48225
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
@@ -48941,6 +48968,43 @@ exports["default"] = _default;
48941
48968
  },{"../events.module":268,"@babel/runtime/helpers/defineProperty":4,"@babel/runtime/helpers/interopRequireDefault":5}],272:[function(require,module,exports){
48942
48969
  "use strict";
48943
48970
 
48971
+ Object.defineProperty(exports, "__esModule", {
48972
+ value: true
48973
+ });
48974
+ exports.externalLogger = externalLogger;
48975
+ exports.init = init;
48976
+ var config = {
48977
+ url: 'http://10.56.34.61:8080/twitter/tweet/1',
48978
+ username: 'chat',
48979
+ password: 'chat123'
48980
+ };
48981
+
48982
+ function externalLogger(message) {
48983
+ var msg;
48984
+ if (typeof message !== "string") msg = JSON.stringify(message);
48985
+ fetch(config.url, {
48986
+ method: 'POST',
48987
+ headers: {
48988
+ 'Authorization': 'Basic ' + btoa("".concat(config.username, ":").concat(config.password)),
48989
+ 'Content-Type': 'application/x-www-form-urlencoded'
48990
+ },
48991
+ body: new URLSearchParams({
48992
+ 'js-browser': msg
48993
+ })
48994
+ })["catch"](function (error) {
48995
+ console.error("[SDK][ExternalLogger] Error while putting log, details: ", error);
48996
+ });
48997
+ }
48998
+
48999
+ function init(externalLogging) {
49000
+ if (externalLogging.url) config.url = externalLogging.url;
49001
+ if (externalLogging.username) config.username = externalLogging.username;
49002
+ if (externalLogging.password) config.password = externalLogging.password;
49003
+ }
49004
+
49005
+ },{}],273:[function(require,module,exports){
49006
+ "use strict";
49007
+
48944
49008
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
48945
49009
 
48946
49010
  Object.defineProperty(exports, "__esModule", {
@@ -48981,10 +49045,25 @@ function ChatMessaging(params) {
48981
49045
  this.threadCallbacks = {};
48982
49046
  this.sendMessageCallbacks = {};
48983
49047
  this.messagesCallbacks = {};
48984
- this.asyncRequestTimeouts = {};
48985
- this.sendPingTimeout = null;
49048
+ this.asyncRequestTimeouts = {}; // this.sendPingTimeout = null;
49049
+
48986
49050
  this.chatState = false;
48987
49051
  this.userInfo = null;
49052
+ /**
49053
+ * sendPingTimeout removed,
49054
+ *
49055
+ * TODO: remove the interval when socket statet changes to closed
49056
+ */
49057
+
49058
+ this.startChatPing = function () {
49059
+ chatPingMessageInterval = setInterval(function () {
49060
+ currentModuleInstance.ping();
49061
+ }, 20000); //TODO: chatPingMessageInterval
49062
+ };
49063
+
49064
+ this.stopChatPing = function () {
49065
+ clearInterval(chatPingMessageInterval);
49066
+ };
48988
49067
 
48989
49068
  this.asyncInitialized = function (client) {
48990
49069
  asyncClient = client;
@@ -49221,11 +49300,12 @@ function ChatMessaging(params) {
49221
49300
  }
49222
49301
  }, asyncRequestTimeout);
49223
49302
  }
49303
+ /* currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
49304
+ currentModuleInstance.sendPingTimeout = setTimeout(function () {
49305
+ currentModuleInstance.ping();
49306
+ }, chatPingMessageInterval); */
49307
+
49224
49308
 
49225
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
49226
- currentModuleInstance.sendPingTimeout = setTimeout(function () {
49227
- currentModuleInstance.ping();
49228
- }, chatPingMessageInterval);
49229
49309
  recursiveCallback && recursiveCallback();
49230
49310
  return {
49231
49311
  uniqueId: uniqueId,
@@ -49257,9 +49337,11 @@ function ChatMessaging(params) {
49257
49337
  chatMessageVOType: _constants.chatMessageVOTypes.PING,
49258
49338
  pushMsgType: 3
49259
49339
  });
49260
- } else {
49261
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
49262
49340
  }
49341
+ /*else {
49342
+ currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
49343
+ }*/
49344
+
49263
49345
  };
49264
49346
  } // if (typeof module !== 'undefined' && typeof module.exports != 'undefined') {
49265
49347
  // module.exports = ChatMessaging;
@@ -49275,7 +49357,7 @@ function ChatMessaging(params) {
49275
49357
  var _default = ChatMessaging;
49276
49358
  exports["default"] = _default;
49277
49359
 
49278
- },{"./lib/constants":270,"./lib/errorHandler":271,"./utility/utility":273,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/typeof":10,"dompurify":131}],273:[function(require,module,exports){
49360
+ },{"./lib/constants":270,"./lib/errorHandler":271,"./utility/utility":274,"@babel/runtime/helpers/interopRequireDefault":5,"@babel/runtime/helpers/typeof":10,"dompurify":131}],274:[function(require,module,exports){
49279
49361
  (function (global){(function (){
49280
49362
  "use strict";
49281
49363
 
@@ -3234,7 +3234,7 @@ Thread: <input type="text" id="threadInput" autocomplete="on" width="500">
3234
3234
  autoStartDownload: true,
3235
3235
  responseType: 'link',
3236
3236
  wantedCount: 10000,
3237
- stepCount: 1000
3237
+ stepCount: 500
3238
3238
  }, result => {
3239
3239
  console.log(result);
3240
3240
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "podchat-browser",
3
- "version": "12.7.2-snapshot.4",
3
+ "version": "12.7.2-snapshot.6",
4
4
  "description": "Javascript SDK to use POD's Chat Service - Browser Only",
5
5
  "main": "./dist/node/chat.js",
6
6
  "scripts": {
@@ -51,7 +51,7 @@
51
51
  "faker": "^5.5.3",
52
52
  "kurento-utils": "^6.16.0",
53
53
  "node-rsa": "^1.1.1",
54
- "podasync-ws-only": "^2.7.10-snapshot.3",
54
+ "podasync-ws-only": "^2.7.10-snapshot.4",
55
55
  "query-string": "^6.8.1",
56
56
  "webrtc-adapter": "^8.0.0"
57
57
  },
package/src/chat.js CHANGED
@@ -6,6 +6,7 @@ import Dexie from "dexie"
6
6
  import ChatCall from "./call.module"
7
7
  import ChatEvents, { initEventHandler, chatEvents } from "./events.module"
8
8
  import ChatMessaging from "./messaging.module"
9
+ // import {externalLogger as externalLog, init as initExternalLogger} from "./lib/logger";
9
10
 
10
11
  import {
11
12
  chatMessageVOTypes,
@@ -20,6 +21,7 @@ import {
20
21
  } from "./lib/constants";
21
22
 
22
23
  import deviceManager from "./lib/call/deviceManager.js";
24
+ import messagingModule from "./messaging.module";
23
25
 
24
26
  function Chat(params) {
25
27
  /*******************************************************
@@ -174,7 +176,14 @@ function Chat(params) {
174
176
  chatSendQueue = [],
175
177
  chatWaitQueue = [],
176
178
  chatUploadQueue = [],
177
- fullResponseObject = params.fullResponseObject || false;
179
+ fullResponseObject = params.fullResponseObject || false,//,
180
+ // externalLogging = {
181
+ // enable: ( params.externalLogging && params.externalLogging.enable !== undefined ? params.externalLogging.enable : true),
182
+ // url: (params.externalLogging && params.externalLogging.url !== undefined ? params.externalLogging.url : null),
183
+ // username: (params.externalLogging && params.externalLogging.username !== undefined ? params.externalLogging.username : null),
184
+ // password: (params.externalLogging && params.externalLogging.password !== undefined ? params.externalLogging.password : null)
185
+ // };
186
+ isAsyncReconnecting = false;
178
187
 
179
188
  if(!consoleLogging) {
180
189
  /**
@@ -187,6 +196,10 @@ function Chat(params) {
187
196
  };
188
197
  }
189
198
 
199
+ // if(externalLogging.enabled) {
200
+ // initExternalLogger(externalLogging);
201
+ // }
202
+
190
203
  initEventHandler(Object.assign(params, {
191
204
  consoleLogging,
192
205
  }));
@@ -279,6 +292,7 @@ function Chat(params) {
279
292
  chatMessaging.asyncInitialized(asyncClient);
280
293
 
281
294
  asyncClient.on('asyncReady', function () {
295
+ chatMessaging.startChatPing();
282
296
  if (actualTimingLog) {
283
297
  Utility.chatStepLogger('Async Connection ', new Date().getTime() - asyncGetReadyTime);
284
298
  }
@@ -403,6 +417,12 @@ function Chat(params) {
403
417
  chatEvents.fireEvent('chatState', state);
404
418
  chatFullStateObject = state;
405
419
 
420
+ if(![0,2].includes(state.socketState)) {
421
+ isAsyncReconnecting = false;
422
+ } else if([0,2].includes(state.socketState)) {
423
+ isAsyncReconnecting = true;
424
+ }
425
+
406
426
  switch (state.socketState) {
407
427
  case 1: // CONNECTED
408
428
  if (state.deviceRegister && state.serverRegister) {
@@ -416,7 +436,7 @@ function Chat(params) {
416
436
  chatMessaging.chatState = false;
417
437
 
418
438
  // TODO: Check if this is OK or not?!
419
- chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
439
+ //chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
420
440
  break;
421
441
  }
422
442
  });
@@ -13728,12 +13748,18 @@ function Chat(params) {
13728
13748
  };
13729
13749
 
13730
13750
  if (!returnData.hasError) {
13731
- for(var i in result.result) {
13751
+ /* for(var i in result.result) {
13732
13752
  stackArr.push(result.result[i]);
13733
- }
13753
+ } */
13754
+
13755
+ stackArr.push(...result.result);
13734
13756
 
13735
13757
  consoleLogging && console.log("[SDK][exportChat] a step passed...");
13736
- wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
13758
+ // wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
13759
+ if(result.result.length < stepCount) {
13760
+ wantedCount = stackArr.length
13761
+ }
13762
+
13737
13763
  setTimeout(function () {
13738
13764
  chatEvents.fireEvent('threadEvents', {
13739
13765
  type: 'EXPORT_CHAT',
@@ -14120,8 +14146,15 @@ function Chat(params) {
14120
14146
  return chatFullStateObject;
14121
14147
  };
14122
14148
 
14123
- publicized.reconnect = function () {
14124
- asyncClient.reconnectSocket();
14149
+ publicized.reconnect = function (callback) {
14150
+ if(!isAsyncReconnecting) {
14151
+ asyncClient.reconnectSocket();
14152
+ isAsyncReconnecting = true;
14153
+ callback && callback({hasError: false, message: "Reconnecting..."});
14154
+ } else {
14155
+ callback && callback({hasError: true, message: "Socket state is not suitable for reconnecting."});
14156
+ consoleLogging && console.log("[SDK] Socket state is not suitable for reconnecting.")
14157
+ }
14125
14158
  };
14126
14159
 
14127
14160
  publicized.setToken = function (newToken) {
@@ -14143,6 +14176,7 @@ function Chat(params) {
14143
14176
  chatMessaging.messagesCallbacks = {};
14144
14177
  chatMessaging.sendMessageCallbacks = {};
14145
14178
  chatMessaging.threadCallbacks = {};
14179
+ chatMessaging.stopChatPing();
14146
14180
 
14147
14181
  asyncClient.logout();
14148
14182
  };
@@ -1,4 +1,5 @@
1
1
  import Utility from "./utility/utility"
2
+ import {externalLogger} from "./lib/logger";
2
3
  // import Sentry from "./lib/sentry.js"
3
4
 
4
5
  let chatEvents = null;
@@ -65,7 +66,8 @@ function ChatEvents(params) {
65
66
  try {
66
67
  throw new PodChatErrorException(param);
67
68
  } catch (err) {
68
- console.error(err);
69
+ //externalLogger(err);
70
+ // console.error(err);
69
71
  }
70
72
  }
71
73
 
@@ -0,0 +1,34 @@
1
+ let config = {
2
+ url: 'http://10.56.34.61:8080/twitter/tweet/1',
3
+ username: 'chat',
4
+ password: 'chat123'
5
+ };
6
+
7
+ function externalLogger(message) {
8
+ let msg;
9
+ if(typeof message !== "string")
10
+ msg = JSON.stringify(message);
11
+ fetch(config.url, {
12
+ method: 'POST',
13
+ headers: {
14
+ 'Authorization': 'Basic ' + btoa(`${config.username}:${config.password}`),
15
+ 'Content-Type': 'application/x-www-form-urlencoded'
16
+ },
17
+ body: new URLSearchParams({
18
+ 'js-browser': msg
19
+ })
20
+ }).catch(error => {
21
+ console.error("[SDK][ExternalLogger] Error while putting log, details: ", error);
22
+ });
23
+ }
24
+
25
+ function init(externalLogging) {
26
+ if(externalLogging.url)
27
+ config.url = externalLogging.url;
28
+ if(externalLogging.username)
29
+ config.username = externalLogging.username;
30
+ if(externalLogging.password)
31
+ config.password = externalLogging.password;
32
+ }
33
+
34
+ export {init, externalLogger};
@@ -27,10 +27,24 @@ import {errorList, raiseError} from "./lib/errorHandler";
27
27
  this.sendMessageCallbacks = {};
28
28
  this.messagesCallbacks = {};
29
29
  this.asyncRequestTimeouts = {};
30
- this.sendPingTimeout = null;
30
+ // this.sendPingTimeout = null;
31
31
  this.chatState = false;
32
32
  this.userInfo = null;
33
33
 
34
+ /**
35
+ * sendPingTimeout removed,
36
+ *
37
+ * TODO: remove the interval when socket statet changes to closed
38
+ */
39
+ this.startChatPing = function () {
40
+ chatPingMessageInterval = setInterval(() => {
41
+ currentModuleInstance.ping();
42
+ }, 20000) ;//TODO: chatPingMessageInterval
43
+ }
44
+ this.stopChatPing = function() {
45
+ clearInterval(chatPingMessageInterval);
46
+ }
47
+
34
48
  this.asyncInitialized = function (client) {
35
49
  asyncClient = client
36
50
  }
@@ -270,10 +284,10 @@ import {errorList, raiseError} from "./lib/errorHandler";
270
284
  }, asyncRequestTimeout);
271
285
  }
272
286
 
273
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
287
+ /* currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
274
288
  currentModuleInstance.sendPingTimeout = setTimeout(function () {
275
289
  currentModuleInstance.ping();
276
- }, chatPingMessageInterval);
290
+ }, chatPingMessageInterval); */
277
291
 
278
292
  recursiveCallback && recursiveCallback();
279
293
 
@@ -306,9 +320,10 @@ import {errorList, raiseError} from "./lib/errorHandler";
306
320
  chatMessageVOType: chatMessageVOTypes.PING,
307
321
  pushMsgType: 3
308
322
  });
309
- } else {
310
- currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
311
323
  }
324
+ /*else {
325
+ currentModuleInstance.sendPingTimeout && clearTimeout(currentModuleInstance.sendPingTimeout);
326
+ }*/
312
327
  };
313
328
 
314
329
  }