podchat-browser 12.8.3 → 12.8.4

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,33 +1,33 @@
1
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 _buildConfig=_interopRequireDefault(require("./buildConfig.json"));var _constants=require("./lib/constants");var _deviceManager=_interopRequireDefault(require("./lib/call/deviceManager.js"));var _store=require("./lib/store");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){/*******************************************************
2
2
  * P R I V A T E V A R I A B L E S *
3
- *******************************************************/var asyncClient,peerId,oldPeerId,token=params.token||"111",generalTypeCode=params.typeCode||'default',typeCodeOwnerId=params.typeCodeOwnerId||null,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
- SSO_DEVICES:'/oauth2/grants/devices',SSO_GENERATE_KEY:'/handshake/users/',SSO_GET_KEY:'/handshake/keys/',// Contacts
5
- ADD_CONTACTS:'/nzh/addContacts',UPDATE_CONTACTS:'/nzh/updateContacts',REMOVE_CONTACTS:'/nzh/removeContacts',SEARCH_CONTACTS:'/nzh/listContacts',// File/Image Upload and Download
6
- UPLOAD_IMAGE:'/nzh/uploadImage',GET_IMAGE:'/nzh/image/',UPLOAD_FILE:'/nzh/uploadFile',GET_FILE:'/nzh/file/',// POD Drive Services
7
- PODSPACE_UPLOAD_FILE_TO_USERGROUP:'/userGroup/uploadFile',//TODO: to be removed
8
- PODSPACE_UPLOAD_FILE_TO_USERGROUP_NEW:'/api/usergroups/{userGroupHash}/files',PODSPACE_UPLOAD_IMAGE_TO_USERGROUP:'/userGroup/uploadImage',//TODO: to be removed
9
- PODSPACE_UPLOAD_IMAGE_TO_USERGROUP_NEW:'/api/usergroups/{userGroupHash}/images',//PODSPACE_UPLOAD_FILE: '/nzh/drive/uploadFile',
10
- //PODSPACE_UPLOAD_FILE_FROM_URL: '/nzh/drive/uploadFileFromUrl',
11
- //TODO: maybe deprecated
12
- PODSPACE_UPLOAD_IMAGE:'/nzh/drive/uploadImage',//TODO: to be removed
13
- PODSPACE_UPLOAD_IMAGE_NEW:'/api/images',PODSPACE_UPLOAD_FILE_NEW:'/api/files',PODSPACE_DOWNLOAD_FILE:'/nzh/drive/downloadFile',//TODO: to be removed
14
- PODSPACE_DOWNLOAD_FILE_NEW:'/api/files/{fileHash}',PODSPACE_DOWNLOAD_IMAGE:'/nzh/drive/downloadImage',//TODO: to be removed
15
- PODSPACE_DOWNLOAD_IMAGE_NEW:'/api/images/{fileHash}',// Neshan Map
16
- REVERSE:'/reverse',SEARCH:'/search',ROUTING:'/routing',STATIC_IMAGE:'/static'},CHAT_ERRORS={// Socket Errors
17
- 6000:'No Active Device found for this Token!',6001:'Invalid Token!',6002:'User not found!',// Get User Info Errors
18
- 6100:'Cant get UserInfo!',6101:'Getting User Info Retry Count exceeded 5 times; Connection Can Not Been Estabilished!',// Http Request Errors
19
- 6200:'Network Error',6201:'URL is not clarified!',// File Uploads Errors
20
- 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
- 6600:'Your Environment doesn\'t have Databse compatibility',6601:'Database is not defined! (missing db)',6602:'Database Error',// Map Errors
22
- 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,
3
+ *******************************************************/var asyncClient,peerId,oldPeerId,token=params.token||"111",generalTypeCode=params.typeCode||'default',typeCodeOwnerId=params.typeCodeOwnerId||null,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
+ SSO_DEVICES:'/oauth2/grants/devices',SSO_GENERATE_KEY:'/handshake/users/',SSO_GET_KEY:'/handshake/keys/',// Contacts
5
+ ADD_CONTACTS:'/nzh/addContacts',UPDATE_CONTACTS:'/nzh/updateContacts',REMOVE_CONTACTS:'/nzh/removeContacts',SEARCH_CONTACTS:'/nzh/listContacts',// File/Image Upload and Download
6
+ UPLOAD_IMAGE:'/nzh/uploadImage',GET_IMAGE:'/nzh/image/',UPLOAD_FILE:'/nzh/uploadFile',GET_FILE:'/nzh/file/',// POD Drive Services
7
+ PODSPACE_UPLOAD_FILE_TO_USERGROUP:'/userGroup/uploadFile',//TODO: to be removed
8
+ PODSPACE_UPLOAD_FILE_TO_USERGROUP_NEW:'/api/usergroups/{userGroupHash}/files',PODSPACE_UPLOAD_IMAGE_TO_USERGROUP:'/userGroup/uploadImage',//TODO: to be removed
9
+ PODSPACE_UPLOAD_IMAGE_TO_USERGROUP_NEW:'/api/usergroups/{userGroupHash}/images',//PODSPACE_UPLOAD_FILE: '/nzh/drive/uploadFile',
10
+ //PODSPACE_UPLOAD_FILE_FROM_URL: '/nzh/drive/uploadFileFromUrl',
11
+ //TODO: maybe deprecated
12
+ PODSPACE_UPLOAD_IMAGE:'/nzh/drive/uploadImage',//TODO: to be removed
13
+ PODSPACE_UPLOAD_IMAGE_NEW:'/api/images',PODSPACE_UPLOAD_FILE_NEW:'/api/files',PODSPACE_DOWNLOAD_FILE:'/nzh/drive/downloadFile',//TODO: to be removed
14
+ PODSPACE_DOWNLOAD_FILE_NEW:'/api/files/{fileHash}',PODSPACE_DOWNLOAD_IMAGE:'/nzh/drive/downloadImage',//TODO: to be removed
15
+ PODSPACE_DOWNLOAD_IMAGE_NEW:'/api/images/{fileHash}',// Neshan Map
16
+ REVERSE:'/reverse',SEARCH:'/search',ROUTING:'/routing',STATIC_IMAGE:'/static'},CHAT_ERRORS={// Socket Errors
17
+ 6000:'No Active Device found for this Token!',6001:'Invalid Token!',6002:'User not found!',// Get User Info Errors
18
+ 6100:'Cant get UserInfo!',6101:'Getting User Info Retry Count exceeded 5 times; Connection Can Not Been Estabilished!',// Http Request Errors
19
+ 6200:'Network Error',6201:'URL is not clarified!',// File Uploads Errors
20
+ 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
+ 6600:'Your Environment doesn\'t have Databse compatibility',6601:'Database is not defined! (missing db)',6602:'Database Error',// Map Errors
22
+ 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
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,webrtcConfig=params.webrtcConfig?params.webrtcConfig:null;if(!consoleLogging){/**
24
24
  * Disable kurento-utils logs
25
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, {
26
26
 
27
27
  //Utility: Utility,
28
28
  consoleLogging,
29
- })),*/chatMessaging=new _messaging["default"](Object.assign(params,{asyncClient:asyncClient,//Utility: Utility,
30
- consoleLogging:consoleLogging,generalTypeCode:generalTypeCode,typeCodeOwnerId:typeCodeOwnerId,chatPingMessageInterval:chatPingMessageInterval,asyncRequestTimeout:asyncRequestTimeout,serverName:serverName,messageTtl:messageTtl,msgPriority:msgPriority})),callModule=new _call["default"](Object.assign(params,{//Utility: Utility,
29
+ })),*/chatMessaging=new _messaging["default"](Object.assign(params,{asyncClient:asyncClient,//Utility: Utility,
30
+ consoleLogging:consoleLogging,generalTypeCode:generalTypeCode,typeCodeOwnerId:typeCodeOwnerId,chatPingMessageInterval:chatPingMessageInterval,asyncRequestTimeout:asyncRequestTimeout,serverName:serverName,messageTtl:messageTtl,msgPriority:msgPriority})),callModule=new _call["default"](Object.assign(params,{//Utility: Utility,
31
31
  consoleLogging:consoleLogging,chatEvents:_events.chatEvents,asyncClient:asyncClient,chatMessaging:chatMessaging}));/*******************************************************
32
32
  * P R I V A T E M E T H O D S *
33
33
  *******************************************************/var init=function init(){/**
@@ -41,19 +41,19 @@ consoleLogging:consoleLogging,chatEvents:_events.chatEvents,asyncClient:asyncCli
41
41
  *
42
42
  * @return {undefined}
43
43
  * @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,webrtcConfig:webrtcConfig});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){getUserAndUpdateSDKState();}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();
45
- });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;switch(state.socketState){case 1:// CONNECTED
46
- if(state.deviceRegister&&state.serverRegister){// chatMessaging.chatState = true;
47
- // chatMessaging.ping();
48
- chatMessaging.startChatPing();}break;case 0:// CONNECTING
49
- chatMessaging.chatState=false;chatMessaging.stopChatPing();break;case 2:// CLOSING
50
- chatMessaging.chatState=false;chatMessaging.stopChatPing();break;case 3:// CLOSED
51
- chatMessaging.chatState=false;chatMessaging.stopChatPing();// TODO: Check if this is OK or not?!
52
- //chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
53
- 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});});},getUserAndUpdateSDKState=function getUserAndUpdateSDKState(){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({
54
- // summary: true,
55
- // cache: false
56
- // });
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,webrtcConfig:webrtcConfig});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){getUserAndUpdateSDKState();}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();
45
+ });asyncClient.on('stateChange',function(state){_events.chatEvents.fireEvent('chatState',state);chatFullStateObject=state;switch(state.socketState){case 1:// CONNECTED
46
+ if(state.deviceRegister&&state.serverRegister){// chatMessaging.chatState = true;
47
+ // chatMessaging.ping();
48
+ chatMessaging.startChatPing();}break;case 0:// CONNECTING
49
+ chatMessaging.chatState=false;chatMessaging.stopChatPing();break;case 2:// CLOSING
50
+ chatMessaging.chatState=false;chatMessaging.stopChatPing();break;case 3:// CLOSED
51
+ chatMessaging.chatState=false;chatMessaging.stopChatPing();// TODO: Check if this is OK or not?!
52
+ //chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
53
+ 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});});},getUserAndUpdateSDKState=function getUserAndUpdateSDKState(){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({
54
+ // summary: true,
55
+ // cache: false
56
+ // });
57
57
  chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQueueHandler();}});},/**
58
58
  * Get Device Id With Token
59
59
  *
@@ -79,7 +79,7 @@ chatMessaging.chatState=true;_events.chatEvents.fireEvent('chatReady');chatSendQ
79
79
  * @param {function} callback The callback function to run after Generating Keys
80
80
  *
81
81
  * @return {undefined}
82
- */generateEncryptionKey=function generateEncryptionKey(params,callback){var data={validity:10*365*24*60*60,// 10 Years
82
+ */generateEncryptionKey=function generateEncryptionKey(params,callback){var data={validity:10*365*24*60*60,// 10 Years
83
83
  renew:false,keyAlgorithm:'aes',keySize:256};if(params){if(params.keyAlgorithm!==undefined){data.keyAlgorithm=params.keyAlgorithm;}if(parseInt(params.keySize)>0){data.keySize=params.keySize;}}var httpRequestParams={url:SERVICE_ADDRESSES.SSO_ADDRESS+SERVICES_PATH.SSO_GENERATE_KEY,method:'POST',data:data,headers:{'Authorization':'Bearer '+token}};httpRequest(httpRequestParams,function(result){if(!result.hasError){try{var response=JSON.parse(result.result.responseText);}catch(e){consoleLogging&&console.log(e);}/**
84
84
  * Save new Key Id in cache and update cacheSecret
85
85
  */if(canUseCache){if(db){db.users.update(chatMessaging.userInfo.id,{keyId:response.keyId}).then(function(){getEncryptionKey({keyId:response.keyId},function(result){if(!result.hasError){cacheSecret=result.secretKey;callback&&callback();}});})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}else{_events.chatEvents.fireEvent('error',{code:result.error,message:result.error_description,error:result});}});},/**
@@ -119,7 +119,7 @@ renew:false,keyAlgorithm:'aes',keySize:256};if(params){if(params.keyAlgorithm!==
119
119
  * @param {function} callback The callback function to call after
120
120
  *
121
121
  * @return {object} Instant function return
122
- */getUserInfo=function getUserInfoRecursive(callback){getUserInfoRetryCount++;if(getUserInfoRetryCount>getUserInfoRetry){getUserInfoTimeout&&clearTimeout(getUserInfoTimeout);getUserInfoRetryCount=0;_events.chatEvents.fireEvent('error',{code:6101,message:CHAT_ERRORS[6101],error:null});}else{getUserInfoTimeout&&clearTimeout(getUserInfoTimeout);getUserInfoTimeout=setTimeout(function(){getUserInfoRecursive(callback);},getUserInfoRetryCount*10000);return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.USER_INFO,typeCode:generalTypeCode//params.typeCode
122
+ */getUserInfo=function getUserInfoRecursive(callback){getUserInfoRetryCount++;if(getUserInfoRetryCount>getUserInfoRetry){getUserInfoTimeout&&clearTimeout(getUserInfoTimeout);getUserInfoRetryCount=0;_events.chatEvents.fireEvent('error',{code:6101,message:CHAT_ERRORS[6101],error:null});}else{getUserInfoTimeout&&clearTimeout(getUserInfoTimeout);getUserInfoTimeout=setTimeout(function(){getUserInfoRecursive(callback);},getUserInfoRetryCount*10000);return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.USER_INFO,typeCode:generalTypeCode//params.typeCode
123
123
  },{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){getUserInfoTimeout&&clearTimeout(getUserInfoTimeout);var messageContent=result.result;var currentUser=formatDataToMakeUser(messageContent);/**
124
124
  * Add current user into cache database #cache
125
125
  */if(canUseCache){if(db){db.users.where('id').equals(parseInt(currentUser.id)).toArray().then(function(users){if(users.length>0&&users[0].id>0){db.users.update(currentUser.id,{cellphoneNumber:currentUser.cellphoneNumber,email:currentUser.email,image:currentUser.image,name:currentUser.name})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{db.users.put(currentUser)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}returnData.result={user:currentUser};getUserInfoRetryCount=0;callback&&callback(returnData);/**
@@ -217,34 +217,34 @@ renew:false,keyAlgorithm:'aes',keySize:256};if(params){if(params.keyAlgorithm!==
217
217
  * Type 3 Message Sent
218
218
  */case _constants.chatMessageVOTypes.SENT:if(chatMessaging.sendMessageCallbacks[uniqueId]&&chatMessaging.sendMessageCallbacks[uniqueId].onSent){chatMessaging.sendMessageCallbacks[uniqueId].onSent({uniqueId:uniqueId,messageId:messageContent});delete chatMessaging.sendMessageCallbacks[uniqueId].onSent;chatMessaging.threadCallbacks[threadId][uniqueId].onSent=true;}break;/**
219
219
  * Type 4 Message Delivery
220
- */case _constants.chatMessageVOTypes.DELIVERY:var threadObject={id:messageContent.conversationId,lastSeenMessageId:messageContent.messageId,lastSeenMessageTime:messageContent.messageTime,lastParticipantId:messageContent.participantId};_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadObject}});// if (fullResponseObject) {
221
- // getHistory({
222
- // offset: 0,
223
- // threadId: threadId,
224
- // id: messageContent.messageId,
225
- // cache: false
226
- // }, function (result) {
227
- // if (!result.hasError) {
228
- // chatEvents.fireEvent('messageEvents', {
229
- // type: 'MESSAGE_DELIVERY',
230
- // result: {
231
- // message: result.result.history[0],
232
- // threadId: threadId,
233
- // senderId: messageContent.participantId
234
- // }
235
- // });
236
- // }
237
- // });
238
- // } else {
239
- // chatEvents.fireEvent('messageEvents', {
240
- // type: 'MESSAGE_DELIVERY',
241
- // result: {
242
- // message: messageContent.messageId,
243
- // threadId: threadId,
244
- // senderId: messageContent.participantId
245
- // }
246
- // });
247
- // }
220
+ */case _constants.chatMessageVOTypes.DELIVERY:var threadObject={id:messageContent.conversationId,lastSeenMessageId:messageContent.messageId,lastSeenMessageTime:messageContent.messageTime,lastParticipantId:messageContent.participantId};_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadObject}});// if (fullResponseObject) {
221
+ // getHistory({
222
+ // offset: 0,
223
+ // threadId: threadId,
224
+ // id: messageContent.messageId,
225
+ // cache: false
226
+ // }, function (result) {
227
+ // if (!result.hasError) {
228
+ // chatEvents.fireEvent('messageEvents', {
229
+ // type: 'MESSAGE_DELIVERY',
230
+ // result: {
231
+ // message: result.result.history[0],
232
+ // threadId: threadId,
233
+ // senderId: messageContent.participantId
234
+ // }
235
+ // });
236
+ // }
237
+ // });
238
+ // } else {
239
+ // chatEvents.fireEvent('messageEvents', {
240
+ // type: 'MESSAGE_DELIVERY',
241
+ // result: {
242
+ // message: messageContent.messageId,
243
+ // threadId: threadId,
244
+ // senderId: messageContent.participantId
245
+ // }
246
+ // });
247
+ // }
248
248
  sendMessageCallbacksHandler(_constants.chatMessageVOTypes.DELIVERY,threadId,uniqueId);break;/**
249
249
  * Type 5 Message Seen
250
250
  */case _constants.chatMessageVOTypes.SEEN:var threadObject={id:messageContent.conversationId,lastSeenMessageId:messageContent.messageId,lastSeenMessageTime:messageContent.messageTime,lastParticipantId:messageContent.participantId};_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadObject}});_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_SEEN',result:{message:messageContent.messageId,threadId:threadId,senderId:messageContent.participantId}});sendMessageCallbacksHandler(_constants.chatMessageVOTypes.SEEN,threadId,uniqueId);break;/**
@@ -321,94 +321,94 @@ sendMessageCallbacksHandler(_constants.chatMessageVOTypes.DELIVERY,threadId,uniq
321
321
  * Remove Message from cache
322
322
  */if(canUseCache&&cacheSecret.length>0){if(db){db.messages.where('id').equals(messageContent).and(function(message){return message.owner===chatMessaging.userInfo.id;})["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}if(fullResponseObject){var time,timeMiliSeconds;if(messageContent.time.toString().length>14){time=messageContent.time;timeMiliSeconds=parseInt(messageContent.time/1000000);}else{time=messageContent.timeNanos?parseInt(parseInt(messageContent.time)/1000)*1000000000+parseInt(messageContent.timeNanos):parseInt(pushMessageVO.time);timeMiliSeconds=parseInt(messageContent.time);}getThreads({threadIds:[threadId]},function(threadsResult){var threads=threadsResult.result.threads;if(!threadsResult.cache){_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_DELETE',result:{message:{id:messageContent.id,pinned:messageContent.pinned,threadId:threadId,time:time,timeMiliSeconds:timeMiliSeconds,timeNanos:messageContent.timeNanos}}});if(messageContent.pinned){_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threads[0]}});}}});}else{_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_DELETE',result:{message:{id:messageContent.id,pinned:messageContent.pinned,threadId:threadId,time:time,timeMiliSeconds:timeMiliSeconds,timeNanos:messageContent.timeNanos}}});if(messageContent.pinned){_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadId}});}}break;/**
323
323
  * Type 30 Thread Info Updated
324
- */case _constants.chatMessageVOTypes.THREAD_INFO_UPDATED:// TODO: Check this line again
325
- // if (!messageContent.conversation && !messageContent.conversation.id) {
326
- // messageContent.conversation.id = threadId;
327
- // }
328
- //
329
- // var thread = formatDataToMakeConversation(messageContent.conversation);
324
+ */case _constants.chatMessageVOTypes.THREAD_INFO_UPDATED:// TODO: Check this line again
325
+ // if (!messageContent.conversation && !messageContent.conversation.id) {
326
+ // messageContent.conversation.id = threadId;
327
+ // }
328
+ //
329
+ // var thread = formatDataToMakeConversation(messageContent.conversation);
330
330
  var thread=formatDataToMakeConversation(messageContent);/**
331
331
  * Add Updated Thread into cache database #cache
332
- */ // if (canUseCache && cacheSecret.length > 0) {
333
- // if (db) {
334
- // var tempData = {};
335
- //
336
- // try {
337
- // var salt = Utility.generateUUID();
338
- //
339
- // tempData.id = thread.id;
340
- // tempData.owner = chatMessaging.userInfo.id;
341
- // tempData.title = Utility.crypt(thread.title, cacheSecret, salt);
342
- // tempData.time = thread.time;
343
- // tempData.data = Utility.crypt(JSON.stringify(unsetNotSeenDuration(thread)), cacheSecret, salt);
344
- // tempData.salt = salt;
345
- // }
346
- // catch (error) {
347
- // chatEvents.fireEvent('error', {
348
- // code: error.code,
349
- // message: error.message,
350
- // error: error
351
- // });
352
- // }
353
- //
354
- // db.threads.put(tempData)
355
- // .catch(function (error) {
356
- // chatEvents.fireEvent('error', {
357
- // code: error.code,
358
- // message: error.message,
359
- // error: error
360
- // });
361
- // });
362
- // }
363
- // else {
364
- // chatEvents.fireEvent('error', {
365
- // code: 6601,
366
- // message: CHAT_ERRORS[6601],
367
- // error: null
368
- // });
369
- // }
370
- // }
332
+ */ // if (canUseCache && cacheSecret.length > 0) {
333
+ // if (db) {
334
+ // var tempData = {};
335
+ //
336
+ // try {
337
+ // var salt = Utility.generateUUID();
338
+ //
339
+ // tempData.id = thread.id;
340
+ // tempData.owner = chatMessaging.userInfo.id;
341
+ // tempData.title = Utility.crypt(thread.title, cacheSecret, salt);
342
+ // tempData.time = thread.time;
343
+ // tempData.data = Utility.crypt(JSON.stringify(unsetNotSeenDuration(thread)), cacheSecret, salt);
344
+ // tempData.salt = salt;
345
+ // }
346
+ // catch (error) {
347
+ // chatEvents.fireEvent('error', {
348
+ // code: error.code,
349
+ // message: error.message,
350
+ // error: error
351
+ // });
352
+ // }
353
+ //
354
+ // db.threads.put(tempData)
355
+ // .catch(function (error) {
356
+ // chatEvents.fireEvent('error', {
357
+ // code: error.code,
358
+ // message: error.message,
359
+ // error: error
360
+ // });
361
+ // });
362
+ // }
363
+ // else {
364
+ // chatEvents.fireEvent('error', {
365
+ // code: 6601,
366
+ // message: CHAT_ERRORS[6601],
367
+ // error: null
368
+ // });
369
+ // }
370
+ // }
371
371
  _events.chatEvents.fireEvent('threadEvents',{type:'THREAD_INFO_UPDATED',result:{thread:thread}});break;/**
372
372
  * Type 31 Thread Last Seen Updated
373
- */case _constants.chatMessageVOTypes.LAST_SEEN_UPDATED:var threadObject=messageContent;threadObject.unreadCount=messageContent.unreadCount?messageContent.unreadCount:0;var localThreadLastSeenUpdated=JSON.parse(JSON.stringify(messageContent));_store.store.threads.save(localThreadLastSeenUpdated);_store.store.threads.get(threadId).unreadCount.set(messageContent.unreadCount);_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_UNREAD_COUNT_UPDATED',result:{thread:threadObject,unreadCount:messageContent.unreadCount?messageContent.unreadCount:0}});_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_SEEN_UPDATED',result:{thread:threadObject,unreadCount:messageContent.unreadCount?messageContent.unreadCount:0}});// if (fullResponseObject) {
374
- // getThreads({
375
- // threadIds: [messageContent.id]
376
- // }, function (threadsResult) {
377
- // var threads = threadsResult.result.threads;
378
- //
379
- // if (!threadsResult.cache) {
380
- // chatEvents.fireEvent('threadEvents', {
381
- // type: 'THREAD_UNREAD_COUNT_UPDATED',
382
- // result: {
383
- // thread: threads[0],
384
- // unreadCount: (messageContent.unreadCount) ? messageContent.unreadCount : 0
385
- // }
386
- // });
387
- //
388
- // chatEvents.fireEvent('threadEvents', {
389
- // type: 'THREAD_LAST_ACTIVITY_TIME',
390
- // result: {
391
- // thread: threads[0]
392
- // }
393
- // });
394
- // }
395
- // });
396
- // } else {
397
- // chatEvents.fireEvent('threadEvents', {
398
- // type: 'THREAD_UNREAD_COUNT_UPDATED',
399
- // result: {
400
- // thread: threadId,
401
- // unreadCount: (messageContent.unreadCount) ? messageContent.unreadCount : 0
402
- // }
403
- // });
404
- //
405
- // chatEvents.fireEvent('threadEvents', {
406
- // type: 'THREAD_LAST_ACTIVITY_TIME',
407
- // result: {
408
- // thread: threadId
409
- // }
410
- // });
411
- // }
373
+ */case _constants.chatMessageVOTypes.LAST_SEEN_UPDATED:var threadObject=messageContent;threadObject.unreadCount=messageContent.unreadCount?messageContent.unreadCount:0;var localThreadLastSeenUpdated=JSON.parse(JSON.stringify(messageContent));_store.store.threads.save(localThreadLastSeenUpdated);_store.store.threads.get(threadId).unreadCount.set(messageContent.unreadCount);_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_UNREAD_COUNT_UPDATED',result:{thread:threadObject,unreadCount:messageContent.unreadCount?messageContent.unreadCount:0}});_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_SEEN_UPDATED',result:{thread:threadObject,unreadCount:messageContent.unreadCount?messageContent.unreadCount:0}});// if (fullResponseObject) {
374
+ // getThreads({
375
+ // threadIds: [messageContent.id]
376
+ // }, function (threadsResult) {
377
+ // var threads = threadsResult.result.threads;
378
+ //
379
+ // if (!threadsResult.cache) {
380
+ // chatEvents.fireEvent('threadEvents', {
381
+ // type: 'THREAD_UNREAD_COUNT_UPDATED',
382
+ // result: {
383
+ // thread: threads[0],
384
+ // unreadCount: (messageContent.unreadCount) ? messageContent.unreadCount : 0
385
+ // }
386
+ // });
387
+ //
388
+ // chatEvents.fireEvent('threadEvents', {
389
+ // type: 'THREAD_LAST_ACTIVITY_TIME',
390
+ // result: {
391
+ // thread: threads[0]
392
+ // }
393
+ // });
394
+ // }
395
+ // });
396
+ // } else {
397
+ // chatEvents.fireEvent('threadEvents', {
398
+ // type: 'THREAD_UNREAD_COUNT_UPDATED',
399
+ // result: {
400
+ // thread: threadId,
401
+ // unreadCount: (messageContent.unreadCount) ? messageContent.unreadCount : 0
402
+ // }
403
+ // });
404
+ //
405
+ // chatEvents.fireEvent('threadEvents', {
406
+ // type: 'THREAD_LAST_ACTIVITY_TIME',
407
+ // result: {
408
+ // thread: threadId
409
+ // }
410
+ // });
411
+ // }
412
412
  break;/**
413
413
  * Type 32 Get Message Delivered List
414
414
  */case _constants.chatMessageVOTypes.GET_MESSAGE_DELIVERY_PARTICIPANTS:if(chatMessaging.messagesCallbacks[uniqueId]){chatMessaging.messagesCallbacks[uniqueId](_utility["default"].createReturnData(false,'',0,messageContent,contentCount));}break;/**
@@ -526,10 +526,10 @@ break;/**
526
526
  */case _constants.chatMessageVOTypes.ERROR:if(chatMessaging.messagesCallbacks[uniqueId]){chatMessaging.messagesCallbacks[uniqueId](_utility["default"].createReturnData(true,messageContent.message,messageContent.code,messageContent,0));}/**
527
527
  * If error code is 21, Token is invalid &
528
528
  * user should logged out
529
- */if(messageContent.code===21){// TODO: Temporarily removed due to unknown side-effects
530
- // chatMessaging.chatState = false;
531
- // asyncClient.logout();
532
- // clearChatServerCaches();
529
+ */if(messageContent.code===21){// TODO: Temporarily removed due to unknown side-effects
530
+ // chatMessaging.chatState = false;
531
+ // asyncClient.logout();
532
+ // clearChatServerCaches();
533
533
  }/* If the error code is 208, so the user
534
534
  * has been blocked cause of spam activity
535
535
  */if(messageContent.code===208){if(chatMessaging.sendMessageCallbacks[uniqueId]){getItemFromChatWaitQueue(uniqueId,function(message){_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_FAILED',cache:false,result:{message:message}});});}}_events.chatEvents.fireEvent('error',{code:messageContent.code,message:messageContent.message,error:messageContent,uniqueId:uniqueId});break;}},/**
@@ -561,51 +561,51 @@ break;/**
561
561
  */newMessageHandler=function newMessageHandler(threadId,messageContent){var message=formatDataToMakeMessage(threadId,messageContent);/*
562
562
  * Send Message delivery for the last message
563
563
  * has been received while being online
564
- */ // putInMessagesDeliveryQueue(threadId, message.id);
564
+ */ // putInMessagesDeliveryQueue(threadId, message.id);
565
565
  /**
566
566
  * Add New Messages into cache database
567
567
  */if(canUseCache&&cacheSecret.length>0){if(db){/**
568
568
  * Insert new messages into cache database
569
569
  * after deleting old messages from cache
570
- */var tempData={};try{var salt=_utility["default"].generateUUID();tempData.id=parseInt(message.id);tempData.owner=parseInt(chatMessaging.userInfo.id);tempData.threadId=parseInt(message.threadId);tempData.time=message.time;tempData.message=_utility["default"].crypt(message.message,cacheSecret,salt);tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(message)),cacheSecret,salt);tempData.salt=salt;tempData.sendStatus='sent';}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}db.messages.put(tempData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_NEW',cache:false,result:{message:message}});var threadObject=message.conversation;var lastMessageVoCopy=Object.assign({},message);lastMessageVoCopy.conversation&&delete lastMessageVoCopy.conversation;threadObject.lastParticipantImage=!!message.participant&&message.participant.hasOwnProperty('image')?message.participant.image:'';threadObject.lastMessageVO=lastMessageVoCopy;threadObject.lastParticipantName=!!message.participant&&message.participant.hasOwnProperty('name')?message.participant.name:'';threadObject.lastMessage=message.hasOwnProperty('message')?message.message:'';_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_UNREAD_COUNT_UPDATED',result:{thread:threadObject,unreadCount:threadObject.unreadCount?threadObject.unreadCount:0}});var storeThread=_store.store.threads.get(threadObject.id);if(!storeThread){_store.store.threads.save(threadObject);storeThread=_store.store.threads.get(threadObject.id);}var unreadCount=message.conversation.unreadCount;// store.threads.get(threadObject.id).unreadCount.set();
571
- if(message.ownerId!=chatMessaging.userInfo.id){if(unreadCount){storeThread.unreadCount.set(unreadCount);}else{if(!storeThread.unreadCount.get())storeThread.unreadCount.set(1);else storeThread.unreadCount.increase();}}else{storeThread.unreadCount.set(0);}_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadObject}});// if (fullResponseObject) {
572
- // getThreads({
573
- // threadIds: [threadId]
574
- // }, function (threadsResult) {
575
- // var threads = threadsResult.result.threads;
576
- //
577
- // chatEvents.fireEvent('threadEvents', {
578
- // type: 'THREAD_UNREAD_COUNT_UPDATED',
579
- // result: {
580
- // thread: threads[0],
581
- // unreadCount: (threads[0].unreadCount) ? threads[0].unreadCount : 0
582
- // }
583
- // });
584
- //
585
- // chatEvents.fireEvent('threadEvents', {
586
- // type: 'THREAD_LAST_ACTIVITY_TIME',
587
- // result: {
588
- // thread: threads[0]
589
- // }
590
- // });
591
- //
592
- // });
593
- // } else {
594
- // chatEvents.fireEvent('threadEvents', {
595
- // type: 'THREAD_LAST_ACTIVITY_TIME',
596
- // result: {
597
- // thread: threadId
598
- // }
599
- // });
600
- //
601
- // chatEvents.fireEvent('threadEvents', {
602
- // type: 'THREAD_UNREAD_COUNT_UPDATED',
603
- // result: {
604
- // thread: messageContent.id,
605
- // unreadCount: (messageContent.conversation.unreadCount) ? messageContent.conversation.unreadCount : 0
606
- // }
607
- // });
608
- // }
570
+ */var tempData={};try{var salt=_utility["default"].generateUUID();tempData.id=parseInt(message.id);tempData.owner=parseInt(chatMessaging.userInfo.id);tempData.threadId=parseInt(message.threadId);tempData.time=message.time;tempData.message=_utility["default"].crypt(message.message,cacheSecret,salt);tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(message)),cacheSecret,salt);tempData.salt=salt;tempData.sendStatus='sent';}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}db.messages.put(tempData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_NEW',cache:false,result:{message:message}});var threadObject=message.conversation;var lastMessageVoCopy=Object.assign({},message);lastMessageVoCopy.conversation&&delete lastMessageVoCopy.conversation;threadObject.lastParticipantImage=!!message.participant&&message.participant.hasOwnProperty('image')?message.participant.image:'';threadObject.lastMessageVO=lastMessageVoCopy;threadObject.lastParticipantName=!!message.participant&&message.participant.hasOwnProperty('name')?message.participant.name:'';threadObject.lastMessage=message.hasOwnProperty('message')?message.message:'';_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_UNREAD_COUNT_UPDATED',result:{thread:threadObject,unreadCount:threadObject.unreadCount?threadObject.unreadCount:0}});var storeThread=_store.store.threads.get(threadObject.id);if(!storeThread){_store.store.threads.save(threadObject);storeThread=_store.store.threads.get(threadObject.id);}var unreadCount=message.conversation.unreadCount;// store.threads.get(threadObject.id).unreadCount.set();
571
+ if(message.ownerId!=chatMessaging.userInfo.id){if(unreadCount){storeThread.unreadCount.set(unreadCount);}else{if(!storeThread.unreadCount.get())storeThread.unreadCount.set(1);else storeThread.unreadCount.increase();}}else{storeThread.unreadCount.set(0);}_events.chatEvents.fireEvent('threadEvents',{type:'THREAD_LAST_ACTIVITY_TIME',result:{thread:threadObject}});// if (fullResponseObject) {
572
+ // getThreads({
573
+ // threadIds: [threadId]
574
+ // }, function (threadsResult) {
575
+ // var threads = threadsResult.result.threads;
576
+ //
577
+ // chatEvents.fireEvent('threadEvents', {
578
+ // type: 'THREAD_UNREAD_COUNT_UPDATED',
579
+ // result: {
580
+ // thread: threads[0],
581
+ // unreadCount: (threads[0].unreadCount) ? threads[0].unreadCount : 0
582
+ // }
583
+ // });
584
+ //
585
+ // chatEvents.fireEvent('threadEvents', {
586
+ // type: 'THREAD_LAST_ACTIVITY_TIME',
587
+ // result: {
588
+ // thread: threads[0]
589
+ // }
590
+ // });
591
+ //
592
+ // });
593
+ // } else {
594
+ // chatEvents.fireEvent('threadEvents', {
595
+ // type: 'THREAD_LAST_ACTIVITY_TIME',
596
+ // result: {
597
+ // thread: threadId
598
+ // }
599
+ // });
600
+ //
601
+ // chatEvents.fireEvent('threadEvents', {
602
+ // type: 'THREAD_UNREAD_COUNT_UPDATED',
603
+ // result: {
604
+ // thread: messageContent.id,
605
+ // unreadCount: (messageContent.conversation.unreadCount) ? messageContent.conversation.unreadCount : 0
606
+ // }
607
+ // });
608
+ // }
609
609
  /**
610
610
  * Update waitQ and remove sent messages from it
611
611
  */deleteFromChatWaitQueue(message,function(){});},/**
@@ -656,7 +656,7 @@ if(message.ownerId!=chatMessaging.userInfo.id){if(unreadCount){storeThread.unrea
656
656
  * - nickname {string}
657
657
  * - name {string}
658
658
  * - image {string}
659
- */var linkedUser={coreUserId:typeof messageContent.coreUserId!=='undefined'?messageContent.coreUserId:messageContent.id,username:messageContent.username,nickname:messageContent.nickname,name:messageContent.name,image:messageContent.image};// return linkedUser;
659
+ */var linkedUser={coreUserId:typeof messageContent.coreUserId!=='undefined'?messageContent.coreUserId:messageContent.id,username:messageContent.username,nickname:messageContent.nickname,name:messageContent.name,image:messageContent.image};// return linkedUser;
660
660
  return JSON.parse(JSON.stringify(linkedUser));},/**
661
661
  * Format Data To Make Contact
662
662
  *
@@ -681,7 +681,7 @@ return JSON.parse(JSON.stringify(linkedUser));},/**
681
681
  * - notSeenDuration {int}
682
682
  * - hasUser {boolean}
683
683
  * - linkedUser {object : RelatedUserVO}
684
- */var contact={id:messageContent.id,blocked:typeof messageContent.blocked!=='undefined'?messageContent.blocked:false,userId:messageContent.userId,firstName:messageContent.firstName,lastName:messageContent.lastName,image:messageContent.profileImage,email:messageContent.email,cellphoneNumber:messageContent.cellphoneNumber,uniqueId:messageContent.uniqueId,notSeenDuration:messageContent.notSeenDuration,hasUser:messageContent.hasUser,linkedUser:undefined};if(typeof messageContent.linkedUser!=='undefined'){contact.linkedUser=formatDataToMakeLinkedUser(messageContent.linkedUser);}// return contact;
684
+ */var contact={id:messageContent.id,blocked:typeof messageContent.blocked!=='undefined'?messageContent.blocked:false,userId:messageContent.userId,firstName:messageContent.firstName,lastName:messageContent.lastName,image:messageContent.profileImage,email:messageContent.email,cellphoneNumber:messageContent.cellphoneNumber,uniqueId:messageContent.uniqueId,notSeenDuration:messageContent.notSeenDuration,hasUser:messageContent.hasUser,linkedUser:undefined};if(typeof messageContent.linkedUser!=='undefined'){contact.linkedUser=formatDataToMakeLinkedUser(messageContent.linkedUser);}// return contact;
685
685
  return JSON.parse(JSON.stringify(contact));},/**
686
686
  * Format Data To Make User
687
687
  *
@@ -704,8 +704,8 @@ return JSON.parse(JSON.stringify(contact));},/**
704
704
  * - receiveEnable {boolean}
705
705
  * - contactSynced {boolean}
706
706
  * - chatProfileVO {object:chatProfileVO}
707
- */var user={id:messageContent.id,coreUserId:messageContent.coreUserId,username:messageContent.username,name:messageContent.name,email:messageContent.email,cellphoneNumber:messageContent.cellphoneNumber,image:messageContent.image,lastSeen:messageContent.lastSeen,sendEnable:messageContent.sendEnable,receiveEnable:messageContent.receiveEnable,contactSynced:messageContent.contactSynced,callCenter:messageContent.callCenter};if(messageContent.contactId){user.contactId=messageContent.contactId;}if(messageContent.contactName){user.contactName=messageContent.contactName;}if(messageContent.contactFirstName){user.contactFirstName=messageContent.contactFirstName;}if(messageContent.contactLastName){user.contactLastName=messageContent.contactLastName;}if(messageContent.blocked){user.blocked=messageContent.blocked;}// Add chatProfileVO if exist
708
- if(messageContent.chatProfileVO){user.chatProfileVO=messageContent.chatProfileVO;}// return user;
707
+ */var user={id:messageContent.id,coreUserId:messageContent.coreUserId,username:messageContent.username,name:messageContent.name,email:messageContent.email,cellphoneNumber:messageContent.cellphoneNumber,image:messageContent.image,lastSeen:messageContent.lastSeen,sendEnable:messageContent.sendEnable,receiveEnable:messageContent.receiveEnable,contactSynced:messageContent.contactSynced,callCenter:messageContent.callCenter};if(messageContent.contactId){user.contactId=messageContent.contactId;}if(messageContent.contactName){user.contactName=messageContent.contactName;}if(messageContent.contactFirstName){user.contactFirstName=messageContent.contactFirstName;}if(messageContent.contactLastName){user.contactLastName=messageContent.contactLastName;}if(messageContent.blocked){user.blocked=messageContent.blocked;}// Add chatProfileVO if exist
708
+ if(messageContent.chatProfileVO){user.chatProfileVO=messageContent.chatProfileVO;}// return user;
709
709
  return JSON.parse(JSON.stringify(user));},/**
710
710
  * Format Data To Make Blocked User
711
711
  *
@@ -725,10 +725,10 @@ return JSON.parse(JSON.stringify(user));},/**
725
725
  * - nickName {string}
726
726
  * - profileImage {string}
727
727
  * - contact {object: contactVO}
728
- */var blockedUser={blockId:messageContent.id,coreUserId:messageContent.coreUserId,firstName:messageContent.firstName,lastName:messageContent.lastName,nickName:messageContent.nickName,profileImage:messageContent.profileImage};// Add contactVO if exist
729
- if(messageContent.contactVO){blockedUser.contact=messageContent.contactVO;}// return blockedUser;
730
- return JSON.parse(JSON.stringify(blockedUser));},formatDataToMakeAssistanthistoryItem=function formatDataToMakeAssistanthistoryItem(messageContent){var assistant={actionType:Object.keys(_constants.assistantActionTypes)[Object.values(_constants.assistantActionTypes).indexOf(messageContent.actionType)],actionTime:messageContent.actionTime};// Add chatProfileVO if exist
731
- if(messageContent.participantVO){assistant.participantVO=messageContent.participantVO;}// return participant;
728
+ */var blockedUser={blockId:messageContent.id,coreUserId:messageContent.coreUserId,firstName:messageContent.firstName,lastName:messageContent.lastName,nickName:messageContent.nickName,profileImage:messageContent.profileImage};// Add contactVO if exist
729
+ if(messageContent.contactVO){blockedUser.contact=messageContent.contactVO;}// return blockedUser;
730
+ return JSON.parse(JSON.stringify(blockedUser));},formatDataToMakeAssistanthistoryItem=function formatDataToMakeAssistanthistoryItem(messageContent){var assistant={actionType:Object.keys(_constants.assistantActionTypes)[Object.values(_constants.assistantActionTypes).indexOf(messageContent.actionType)],actionTime:messageContent.actionTime};// Add chatProfileVO if exist
731
+ if(messageContent.participantVO){assistant.participantVO=messageContent.participantVO;}// return participant;
732
732
  return JSON.parse(JSON.stringify(assistant));},formatDataToMakeAssistantHistoryList=function formatDataToMakeAssistantHistoryList(assistantsList){var returnData=[];for(var i=0;i<assistantsList.length;i++){returnData.push(formatDataToMakeAssistanthistoryItem(assistantsList[i]));}return returnData;},/**
733
733
  * Format Data To Make Invitee
734
734
  *
@@ -781,8 +781,8 @@ return JSON.parse(JSON.stringify(assistant));},formatDataToMakeAssistantHistoryL
781
781
  * - keyId {string}
782
782
  * - roles {list:string}
783
783
  * - username {string}
784
- */var participant={id:messageContent.id,coreUserId:messageContent.coreUserId,threadId:parseInt(threadId),sendEnable:messageContent.sendEnable,receiveEnable:messageContent.receiveEnable,firstName:messageContent.firstName,lastName:messageContent.lastName,name:messageContent.name,cellphoneNumber:messageContent.cellphoneNumber,email:messageContent.email,image:messageContent.image,myFriend:messageContent.myFriend,online:messageContent.online,notSeenDuration:messageContent.notSeenDuration,contactId:messageContent.contactId,contactName:messageContent.contactName,contactFirstName:messageContent.contactFirstName,contactLastName:messageContent.contactLastName,blocked:messageContent.blocked,admin:messageContent.admin,auditor:messageContent.auditor,keyId:messageContent.keyId,roles:messageContent.roles,username:messageContent.username};// Add chatProfileVO if exist
785
- if(messageContent.chatProfileVO){participant.chatProfileVO=messageContent.chatProfileVO;}// return participant;
784
+ */var participant={id:messageContent.id,coreUserId:messageContent.coreUserId,threadId:parseInt(threadId),sendEnable:messageContent.sendEnable,receiveEnable:messageContent.receiveEnable,firstName:messageContent.firstName,lastName:messageContent.lastName,name:messageContent.name,cellphoneNumber:messageContent.cellphoneNumber,email:messageContent.email,image:messageContent.image,myFriend:messageContent.myFriend,online:messageContent.online,notSeenDuration:messageContent.notSeenDuration,contactId:messageContent.contactId,contactName:messageContent.contactName,contactFirstName:messageContent.contactFirstName,contactLastName:messageContent.contactLastName,blocked:messageContent.blocked,admin:messageContent.admin,auditor:messageContent.auditor,keyId:messageContent.keyId,roles:messageContent.roles,username:messageContent.username};// Add chatProfileVO if exist
785
+ if(messageContent.chatProfileVO){participant.chatProfileVO=messageContent.chatProfileVO;}// return participant;
786
786
  return JSON.parse(JSON.stringify(participant));},/**
787
787
  * Format Data To Make Conversation
788
788
  *
@@ -833,11 +833,11 @@ return JSON.parse(JSON.stringify(participant));},/**
833
833
  * - userGroupHash {string}
834
834
  * - leftWithHistory {boolean}
835
835
  * - closed {boolean}
836
- */var conversation={id:messageContent.id,joinDate:messageContent.joinDate,title:messageContent.title,inviter:undefined,participants:undefined,time:messageContent.time,lastMessage:messageContent.lastMessage,lastParticipantName:messageContent.lastParticipantName,group:messageContent.group,partner:messageContent.partner,lastParticipantImage:messageContent.lastParticipantImage,image:messageContent.image,description:messageContent.description,unreadCount:messageContent.unreadCount,lastSeenMessageId:messageContent.lastSeenMessageId,lastSeenMessageTime:messageContent.lastSeenMessageNanos?parseInt(parseInt(messageContent.lastSeenMessageTime)/1000)*1000000000+parseInt(messageContent.lastSeenMessageNanos):parseInt(messageContent.lastSeenMessageTime),lastMessageVO:undefined,pinMessageVO:undefined,partnerLastSeenMessageId:messageContent.partnerLastSeenMessageId,partnerLastSeenMessageTime:messageContent.partnerLastSeenMessageNanos?parseInt(parseInt(messageContent.partnerLastSeenMessageTime)/1000)*1000000000+parseInt(messageContent.partnerLastSeenMessageNanos):parseInt(messageContent.partnerLastSeenMessageTime),partnerLastDeliveredMessageId:messageContent.partnerLastDeliveredMessageId,partnerLastDeliveredMessageTime:messageContent.partnerLastDeliveredMessageNanos?parseInt(parseInt(messageContent.partnerLastDeliveredMessageTime)/1000)*1000000000+parseInt(messageContent.partnerLastDeliveredMessageNanos):parseInt(messageContent.partnerLastDeliveredMessageTime),archiveThread:messageContent.archiveThread,type:messageContent.type,metadata:messageContent.metadata,mute:messageContent.mute,participantCount:messageContent.participantCount,canEditInfo:messageContent.canEditInfo,canSpam:messageContent.canSpam,admin:messageContent.admin,mentioned:messageContent.mentioned,pin:messageContent.pin,uniqueName:messageContent.uniqueName,userGroupHash:messageContent.userGroupHash,leftWithHistory:messageContent.leftWithHistory,closed:messageContent.closed,seenByAnyAssistant:messageContent.seenByAnyAssistant};// Add inviter if exist
837
- if(messageContent.inviter){conversation.inviter=formatDataToMakeParticipant(messageContent.inviter,messageContent.id);}// Add participants list if exist
838
- if(messageContent.participants&&Array.isArray(messageContent.participants)){conversation.participants=[];for(var i=0;i<messageContent.participants.length;i++){var participantData=formatDataToMakeParticipant(messageContent.participants[i],messageContent.id);if(participantData){conversation.participants.push(participantData);}}}// Add lastMessageVO if exist
839
- if(messageContent.lastMessageVO){conversation.lastMessageVO=formatDataToMakeMessage(messageContent.id,messageContent.lastMessageVO);}// Add pinMessageVO if exist
840
- if(messageContent.pinMessageVO){conversation.pinMessageVO=formatDataToMakePinMessage(messageContent.id,messageContent.pinMessageVO);}// return conversation;
836
+ */var conversation={id:messageContent.id,joinDate:messageContent.joinDate,title:messageContent.title,inviter:undefined,participants:undefined,time:messageContent.time,lastMessage:messageContent.lastMessage,lastParticipantName:messageContent.lastParticipantName,group:messageContent.group,partner:messageContent.partner,lastParticipantImage:messageContent.lastParticipantImage,image:messageContent.image,description:messageContent.description,unreadCount:messageContent.unreadCount,lastSeenMessageId:messageContent.lastSeenMessageId,lastSeenMessageTime:messageContent.lastSeenMessageNanos?parseInt(parseInt(messageContent.lastSeenMessageTime)/1000)*1000000000+parseInt(messageContent.lastSeenMessageNanos):parseInt(messageContent.lastSeenMessageTime),lastMessageVO:undefined,pinMessageVO:undefined,partnerLastSeenMessageId:messageContent.partnerLastSeenMessageId,partnerLastSeenMessageTime:messageContent.partnerLastSeenMessageNanos?parseInt(parseInt(messageContent.partnerLastSeenMessageTime)/1000)*1000000000+parseInt(messageContent.partnerLastSeenMessageNanos):parseInt(messageContent.partnerLastSeenMessageTime),partnerLastDeliveredMessageId:messageContent.partnerLastDeliveredMessageId,partnerLastDeliveredMessageTime:messageContent.partnerLastDeliveredMessageNanos?parseInt(parseInt(messageContent.partnerLastDeliveredMessageTime)/1000)*1000000000+parseInt(messageContent.partnerLastDeliveredMessageNanos):parseInt(messageContent.partnerLastDeliveredMessageTime),archiveThread:messageContent.archiveThread,type:messageContent.type,metadata:messageContent.metadata,mute:messageContent.mute,participantCount:messageContent.participantCount,canEditInfo:messageContent.canEditInfo,canSpam:messageContent.canSpam,admin:messageContent.admin,mentioned:messageContent.mentioned,pin:messageContent.pin,uniqueName:messageContent.uniqueName,userGroupHash:messageContent.userGroupHash,leftWithHistory:messageContent.leftWithHistory,closed:messageContent.closed,seenByAnyAssistant:messageContent.seenByAnyAssistant};// Add inviter if exist
837
+ if(messageContent.inviter){conversation.inviter=formatDataToMakeParticipant(messageContent.inviter,messageContent.id);}// Add participants list if exist
838
+ if(messageContent.participants&&Array.isArray(messageContent.participants)){conversation.participants=[];for(var i=0;i<messageContent.participants.length;i++){var participantData=formatDataToMakeParticipant(messageContent.participants[i],messageContent.id);if(participantData){conversation.participants.push(participantData);}}}// Add lastMessageVO if exist
839
+ if(messageContent.lastMessageVO){conversation.lastMessageVO=formatDataToMakeMessage(messageContent.id,messageContent.lastMessageVO);}// Add pinMessageVO if exist
840
+ if(messageContent.pinMessageVO){conversation.pinMessageVO=formatDataToMakePinMessage(messageContent.id,messageContent.pinMessageVO);}// return conversation;
841
841
  return JSON.parse(JSON.stringify(conversation));},/**
842
842
  * Format Data To Make Reply Info
843
843
  *
@@ -860,7 +860,7 @@ return JSON.parse(JSON.stringify(conversation));},/**
860
860
  * - messageType {int}
861
861
  * - metadata {string}
862
862
  * - systemMetadata {string}
863
- */var replyInfo={participant:undefined,repliedToMessageId:messageContent.repliedToMessageId,repliedToMessageTime:messageContent.repliedToMessageNanos?parseInt(parseInt(messageContent.repliedToMessageTime)/1000)*1000000000+parseInt(messageContent.repliedToMessageNanos):parseInt(messageContent.repliedToMessageTime),repliedToMessageTimeMiliSeconds:parseInt(messageContent.repliedToMessageTime),repliedToMessageTimeNanos:parseInt(messageContent.repliedToMessageNanos),message:messageContent.message,deleted:messageContent.deleted,messageType:messageContent.messageType,metadata:messageContent.metadata,systemMetadata:messageContent.systemMetadata};if(messageContent.participant){replyInfo.participant=formatDataToMakeParticipant(messageContent.participant,threadId);}// return replyInfo;
863
+ */var replyInfo={participant:undefined,repliedToMessageId:messageContent.repliedToMessageId,repliedToMessageTime:messageContent.repliedToMessageNanos?parseInt(parseInt(messageContent.repliedToMessageTime)/1000)*1000000000+parseInt(messageContent.repliedToMessageNanos):parseInt(messageContent.repliedToMessageTime),repliedToMessageTimeMiliSeconds:parseInt(messageContent.repliedToMessageTime),repliedToMessageTimeNanos:parseInt(messageContent.repliedToMessageNanos),message:messageContent.message,deleted:messageContent.deleted,messageType:messageContent.messageType,metadata:messageContent.metadata,systemMetadata:messageContent.systemMetadata};if(messageContent.participant){replyInfo.participant=formatDataToMakeParticipant(messageContent.participant,threadId);}// return replyInfo;
864
864
  return JSON.parse(JSON.stringify(replyInfo));},/**
865
865
  * Format Data To Make Forward Info
866
866
  *
@@ -876,7 +876,7 @@ return JSON.parse(JSON.stringify(replyInfo));},/**
876
876
  * + forwardInfo {object : forwardInfoVO}
877
877
  * - participant {object : ParticipantVO}
878
878
  * - conversation {object : ConversationSummary}
879
- */var forwardInfo={participant:undefined,conversation:undefined};if(messageContent.conversation){forwardInfo.conversation=formatDataToMakeConversation(messageContent.conversation);}if(messageContent.participant){forwardInfo.participant=formatDataToMakeParticipant(messageContent.participant,threadId);}// return forwardInfo;
879
+ */var forwardInfo={participant:undefined,conversation:undefined};if(messageContent.conversation){forwardInfo.conversation=formatDataToMakeConversation(messageContent.conversation);}if(messageContent.participant){forwardInfo.participant=formatDataToMakeParticipant(messageContent.participant,threadId);}// return forwardInfo;
880
880
  return JSON.parse(JSON.stringify(forwardInfo));},/**
881
881
  * Format Data To Make Message
882
882
  *
@@ -913,7 +913,7 @@ return JSON.parse(JSON.stringify(forwardInfo));},/**
913
913
  * - systemMetadata {string}
914
914
  * - time {int}
915
915
  * - timeNanos {int}
916
- */if(fromCache||pushMessageVO.time.toString().length>14){var time=pushMessageVO.time,timeMiliSeconds=parseInt(pushMessageVO.time/1000000);}else{var time=pushMessageVO.timeNanos?parseInt(parseInt(pushMessageVO.time)/1000)*1000000000+parseInt(pushMessageVO.timeNanos):parseInt(pushMessageVO.time),timeMiliSeconds=parseInt(pushMessageVO.time);}var message={id:pushMessageVO.id,threadId:threadId,ownerId:pushMessageVO.ownerId?pushMessageVO.ownerId:undefined,uniqueId:pushMessageVO.uniqueId,previousId:pushMessageVO.previousId,message:pushMessageVO.message,messageType:pushMessageVO.messageType,edited:pushMessageVO.edited,editable:pushMessageVO.editable,deletable:pushMessageVO.deletable,delivered:pushMessageVO.delivered,seen:pushMessageVO.seen,mentioned:pushMessageVO.mentioned,pinned:pushMessageVO.pinned,participant:undefined,conversation:undefined,replyInfo:undefined,forwardInfo:undefined,metadata:pushMessageVO.metadata,systemMetadata:pushMessageVO.systemMetadata,time:time,timeMiliSeconds:timeMiliSeconds,timeNanos:parseInt(pushMessageVO.timeNanos),callHistory:pushMessageVO.callHistoryVO};if(pushMessageVO.participant){message.ownerId=pushMessageVO.participant.id;}else if(pushMessageVO.participantVO){message.ownerId=pushMessageVO.participantVO.id;}if(pushMessageVO.conversation){message.conversation=formatDataToMakeConversation(pushMessageVO.conversation);message.threadId=pushMessageVO.conversation.id;}if(pushMessageVO.replyInfoVO||pushMessageVO.replyInfo){message.replyInfo=pushMessageVO.replyInfoVO?formatDataToMakeReplyInfo(pushMessageVO.replyInfoVO,threadId):formatDataToMakeReplyInfo(pushMessageVO.replyInfo,threadId);}if(pushMessageVO.forwardInfo){message.forwardInfo=formatDataToMakeForwardInfo(pushMessageVO.forwardInfo,threadId);}if(pushMessageVO.participant){message.participant=formatDataToMakeParticipant(pushMessageVO.participant,threadId);}// return message;
916
+ */if(fromCache||pushMessageVO.time.toString().length>14){var time=pushMessageVO.time,timeMiliSeconds=parseInt(pushMessageVO.time/1000000);}else{var time=pushMessageVO.timeNanos?parseInt(parseInt(pushMessageVO.time)/1000)*1000000000+parseInt(pushMessageVO.timeNanos):parseInt(pushMessageVO.time),timeMiliSeconds=parseInt(pushMessageVO.time);}var message={id:pushMessageVO.id,threadId:threadId,ownerId:pushMessageVO.ownerId?pushMessageVO.ownerId:undefined,uniqueId:pushMessageVO.uniqueId,previousId:pushMessageVO.previousId,message:pushMessageVO.message,messageType:pushMessageVO.messageType,edited:pushMessageVO.edited,editable:pushMessageVO.editable,deletable:pushMessageVO.deletable,delivered:pushMessageVO.delivered,seen:pushMessageVO.seen,mentioned:pushMessageVO.mentioned,pinned:pushMessageVO.pinned,participant:undefined,conversation:undefined,replyInfo:undefined,forwardInfo:undefined,metadata:pushMessageVO.metadata,systemMetadata:pushMessageVO.systemMetadata,time:time,timeMiliSeconds:timeMiliSeconds,timeNanos:parseInt(pushMessageVO.timeNanos),callHistory:pushMessageVO.callHistoryVO};if(pushMessageVO.participant){message.ownerId=pushMessageVO.participant.id;}else if(pushMessageVO.participantVO){message.ownerId=pushMessageVO.participantVO.id;}if(pushMessageVO.conversation){message.conversation=formatDataToMakeConversation(pushMessageVO.conversation);message.threadId=pushMessageVO.conversation.id;}if(pushMessageVO.replyInfoVO||pushMessageVO.replyInfo){message.replyInfo=pushMessageVO.replyInfoVO?formatDataToMakeReplyInfo(pushMessageVO.replyInfoVO,threadId):formatDataToMakeReplyInfo(pushMessageVO.replyInfo,threadId);}if(pushMessageVO.forwardInfo){message.forwardInfo=formatDataToMakeForwardInfo(pushMessageVO.forwardInfo,threadId);}if(pushMessageVO.participant){message.participant=formatDataToMakeParticipant(pushMessageVO.participant,threadId);}// return message;
917
917
  return JSON.parse(JSON.stringify(message));},/**
918
918
  * Format Data To Make Pin Message
919
919
  *
@@ -931,7 +931,7 @@ return JSON.parse(JSON.stringify(message));},/**
931
931
  * - sender {int}
932
932
  * - text {string}
933
933
  * - notifyAll {boolean}
934
- */var pinMessage={threadId:threadId,time:pushMessageVO.time,sender:pushMessageVO.sender,messageId:pushMessageVO.messageId,text:pushMessageVO.text,metadata:pushMessageVO.metadata,systemMetadata:pushMessageVO.systemMetadata};if(typeof pushMessageVO.notifyAll==='boolean'){pinMessage.notifyAll=pushMessageVO.notifyAll;}// return pinMessage;
934
+ */var pinMessage={threadId:threadId,time:pushMessageVO.time,sender:pushMessageVO.sender,messageId:pushMessageVO.messageId,text:pushMessageVO.text,metadata:pushMessageVO.metadata,systemMetadata:pushMessageVO.systemMetadata};if(typeof pushMessageVO.notifyAll==='boolean'){pinMessage.notifyAll=pushMessageVO.notifyAll;}// return pinMessage;
935
935
  return JSON.parse(JSON.stringify(pinMessage));},/**
936
936
  * Reformat Thread History
937
937
  *
@@ -997,12 +997,12 @@ return JSON.parse(JSON.stringify(pinMessage));},/**
997
997
  * @param {function} callback The callback function to call after
998
998
  *
999
999
  * @return {object} Instant sendMessage result
1000
- */getThreads=function getThreads(params,callback){var count=50,offset=0,content={},whereClause={},returnCache=false;if(params){if(parseInt(params.count)>0){count=params.count;}if(parseInt(params.offset)>0){offset=params.offset;}if(typeof params.threadName==='string'){content.name=whereClause.name=params.threadName;}if(typeof params.username==='string'){content.username=params.username;}if(typeof params.cellphoneNumber==='string'){content.cellphoneNumber=params.cellphoneNumber;}if(Array.isArray(params.threadIds)){content.threadIds=whereClause.threadIds=params.threadIds;}if(typeof params["new"]==='boolean'){content["new"]=params["new"];}if(parseInt(params.creatorCoreUserId)>0){content.creatorCoreUserId=whereClause.creatorCoreUserId=params.creatorCoreUserId;}if(parseInt(params.partnerCoreUserId)>0){content.partnerCoreUserId=whereClause.partnerCoreUserId=params.partnerCoreUserId;}if(parseInt(params.partnerCoreContactId)>0){content.partnerCoreContactId=whereClause.partnerCoreContactId=params.partnerCoreContactId;}if(parseInt(params.fromTime)>0&&parseInt(params.fromTime)<9999999999999){content.fromTime=parseInt(params.fromTime);}if(parseInt(params.toTime)>0&&parseInt(params.toTime)<9999999999999){content.toTime=parseInt(params.toTime);}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;if(typeof params.isGroup==='boolean'){content.isGroup=params.isGroup;}if(typeof params.type==='number'){content.type=params.type;}}content.count=count;content.offset=offset;var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_THREADS,typeCode:generalTypeCode,//params.typeCode,
1000
+ */getThreads=function getThreads(params,callback){var count=50,offset=0,content={},whereClause={},returnCache=false;if(params){if(parseInt(params.count)>0){count=params.count;}if(parseInt(params.offset)>0){offset=params.offset;}if(typeof params.threadName==='string'){content.name=whereClause.name=params.threadName;}if(typeof params.username==='string'){content.username=params.username;}if(typeof params.cellphoneNumber==='string'){content.cellphoneNumber=params.cellphoneNumber;}if(Array.isArray(params.threadIds)){content.threadIds=whereClause.threadIds=params.threadIds;}if(typeof params["new"]==='boolean'){content["new"]=params["new"];}if(parseInt(params.creatorCoreUserId)>0){content.creatorCoreUserId=whereClause.creatorCoreUserId=params.creatorCoreUserId;}if(parseInt(params.partnerCoreUserId)>0){content.partnerCoreUserId=whereClause.partnerCoreUserId=params.partnerCoreUserId;}if(parseInt(params.partnerCoreContactId)>0){content.partnerCoreContactId=whereClause.partnerCoreContactId=params.partnerCoreContactId;}if(parseInt(params.fromTime)>0&&parseInt(params.fromTime)<9999999999999){content.fromTime=parseInt(params.fromTime);}if(parseInt(params.toTime)>0&&parseInt(params.toTime)<9999999999999){content.toTime=parseInt(params.toTime);}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;if(typeof params.isGroup==='boolean'){content.isGroup=params.isGroup;}if(typeof params.type==='number'){content.type=params.type;}}content.count=count;content.offset=offset;var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_THREADS,typeCode:generalTypeCode,//params.typeCode,
1001
1001
  content:content};/**
1002
1002
  * Retrieve threads from cache
1003
1003
  */if(functionLevelCache&&canUseCache&&cacheSecret.length>0){if(db){var thenAble;if(Object.keys(whereClause).length===0){thenAble=db.threads.where('[owner+time]').between([chatMessaging.userInfo.id,minIntegerValue],[chatMessaging.userInfo.id,maxIntegerValue*1000]).reverse();}else{if(whereClause.hasOwnProperty('threadIds')){thenAble=db.threads.where('id').anyOf(whereClause.threadIds).and(function(thread){return thread.owner===chatMessaging.userInfo.id;});}if(whereClause.hasOwnProperty('name')){thenAble=db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).filter(function(thread){var reg=new RegExp(whereClause.name);return reg.test(chatDecrypt(thread.title,cacheSecret,thread.salt));});}if(whereClause.hasOwnProperty('creatorCoreUserId')){thenAble=db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).filter(function(thread){var threadObject=JSON.parse(chatDecrypt(thread.data,cacheSecret,thread.salt),false);return parseInt(threadObject.inviter.coreUserId)===parseInt(whereClause.creatorCoreUserId);});}}thenAble.offset(offset).limit(count).toArray().then(function(threads){db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).count().then(function(threadsCount){var cacheData=[];for(var i=0;i<threads.length;i++){try{cacheData.push(createThread(JSON.parse(chatDecrypt(threads[i].data,cacheSecret,threads[i].salt)),false));}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}var returnData={hasError:false,cache:true,errorCode:0,errorMessage:'',result:{threads:cacheData,contentCount:threadsCount,hasNext:!(threads.length<count),nextOffset:offset*1+threads.length}};if(cacheData.length>0){callback&&callback(returnData);callback=undefined;returnCache=true;}});})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}/**
1004
1004
  * Retrive get threads response from server
1005
- */return chatMessaging.sendMessage(sendMessageParams,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode,uniqueId:result.uniqueId};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={threads:[],contentCount:result.contentCount,hasNext:messageContent&&!(messageLength<count),//(offset + count < result.contentCount && messageLength > 0),
1005
+ */return chatMessaging.sendMessage(sendMessageParams,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode,uniqueId:result.uniqueId};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={threads:[],contentCount:result.contentCount,hasNext:messageContent&&!(messageLength<count),//(offset + count < result.contentCount && messageLength > 0),
1006
1006
  nextOffset:offset*1+messageLength*1},threadData;for(var i=0;i<messageLength;i++){threadData=createThread(messageContent[i],false);if(threadData){resultData.threads.push(threadData);}}_store.store.threads.saveMany(resultData.threads);returnData.result=resultData;/**
1007
1007
  * Updating cache on separated worker to find and
1008
1008
  * delete all messages that have been deleted from
@@ -1017,7 +1017,7 @@ nextOffset:offset*1+messageLength*1},threadData;for(var i=0;i<messageLength;i++)
1017
1017
  */var pinnedThreadsOrderTime=5;for(var i=0;i<resultData.threads.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.threads[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.title=_utility["default"].crypt(resultData.threads[i].title,cacheSecret,salt);tempData.pin=resultData.threads[i].pin;tempData.time=resultData.threads[i].pin?resultData.threads[i].time*pinnedThreadsOrderTime:resultData.threads[i].time;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.threads[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);pinnedThreadsOrderTime--;}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.threads.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);/**
1018
1018
  * Delete callback so if server pushes response before
1019
1019
  * cache, cache won't send data again
1020
- */callback=undefined;if(!returnData.hasError&&returnCache){_events.chatEvents.fireEvent('threadEvents',{type:'THREADS_LIST_CHANGE',result:returnData.result});}}});},getAllThreads=function getAllThreads(params,callback){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_THREADS,typeCode:generalTypeCode,//params.typeCode,
1020
+ */callback=undefined;if(!returnData.hasError&&returnCache){_events.chatEvents.fireEvent('threadEvents',{type:'THREADS_LIST_CHANGE',result:returnData.result});}}});},getAllThreads=function getAllThreads(params,callback){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_THREADS,typeCode:generalTypeCode,//params.typeCode,
1021
1021
  content:{}};sendMessageParams.content.summary=params.summary;return chatMessaging.sendMessage(sendMessageParams,{onResult:function onResult(result){if(!result.hasError){if(canUseCache){if(db){var allThreads=[];for(var m=0;m<result.result.length;m++){allThreads.push(result.result[m].id);}db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).and(function(thread){return allThreads.indexOf(thread.id)<0;})["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(result);}});},/**
1022
1022
  * Get History.
1023
1023
  *
@@ -1043,14 +1043,14 @@ content:{}};sendMessageParams.content.summary=params.summary;return chatMessagin
1043
1043
  * @param {function} callback The callback function to call after
1044
1044
  *
1045
1045
  * @return {object} Instant result of sendMessage
1046
- */getHistory=function getHistory(params,callback){if(parseInt(params.threadId)>0){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_HISTORY,typeCode:generalTypeCode,//params.typeCode,
1046
+ */getHistory=function getHistory(params,callback){if(parseInt(params.threadId)>0){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_HISTORY,typeCode:generalTypeCode,//params.typeCode,
1047
1047
  content:{},subjectId:params.threadId},whereClause={},offset=parseInt(params.offset)>0?parseInt(params.offset):0,count=parseInt(params.count)>0?parseInt(params.count):config.getHistoryCount,order=typeof params.order!='undefined'?params.order.toLowerCase():'desc',functionLevelCache=typeof params.cache=='boolean'?params.cache:true,cacheResult={},serverResult={},cacheFirstMessage,cacheLastMessage,messages,returnCache,cacheReady=false,dynamicHistoryCount=params.dynamicHistoryCount&&typeof params.dynamicHistoryCount==='boolean'?params.dynamicHistoryCount:false,sendingQueue=params.queues&&typeof params.queues.sending==='boolean'?params.queues.sending:true,failedQueue=params.queues&&typeof params.queues.failed==='boolean'?params.queues.failed:true,uploadingQueue=params.queues&&typeof params.queues.uploading==='boolean'?params.queues.uploading:true,sendingQueueMessages=[],failedQueueMessages=[],uploadingQueueMessages=[];if(sendingQueue){getChatSendQueue(parseInt(params.threadId),function(sendQueueMessages){for(var i=0;i<sendQueueMessages.length;i++){var time=new Date().getTime();sendingQueueMessages.push(formatDataToMakeMessage(sendQueueMessages[i].threadId,{uniqueId:sendQueueMessages[i].uniqueId,ownerId:chatMessaging.userInfo.id,message:sendQueueMessages[i].content,metadata:sendQueueMessages[i].metadata,systemMetadata:sendQueueMessages[i].systemMetadata,replyInfo:sendQueueMessages[i].replyInfo,forwardInfo:sendQueueMessages[i].forwardInfo,time:time,timeNanos:time%1000*1000000}));}});}if(uploadingQueue){getChatUploadQueue(parseInt(params.threadId),function(uploadQueueMessages){for(var i=0;i<uploadQueueMessages.length;i++){uploadQueueMessages[i].message.participant=chatMessaging.userInfo;var time=new Date().getTime();uploadQueueMessages[i].message.time=time;uploadQueueMessages[i].message.timeNanos=time%1000*1000000;uploadingQueueMessages.push(formatDataToMakeMessage(params.threadId,uploadQueueMessages[i].message,false));}});}getChatWaitQueue(parseInt(params.threadId),failedQueue,function(waitQueueMessages){if(cacheSecret.length>0){for(var i=0;i<waitQueueMessages.length;i++){var decryptedEnqueuedMessage={};if(cacheInMemory){decryptedEnqueuedMessage=waitQueueMessages[i];}else{decryptedEnqueuedMessage=_utility["default"].jsonParser(chatDecrypt(waitQueueMessages[i].message,cacheSecret));}var time=new Date().getTime();failedQueueMessages[i]=formatDataToMakeMessage(waitQueueMessages[i].threadId,{uniqueId:decryptedEnqueuedMessage.uniqueId,ownerId:chatMessaging.userInfo.id,message:decryptedEnqueuedMessage.content,metadata:decryptedEnqueuedMessage.metadata,systemMetadata:decryptedEnqueuedMessage.systemMetadata,replyInfo:decryptedEnqueuedMessage.replyInfo,forwardInfo:decryptedEnqueuedMessage.forwardInfo,participant:chatMessaging.userInfo,time:time,timeNanos:time%1000*1000000});}}else{failedQueueMessages=[];}if(dynamicHistoryCount){var tempCount=count-(sendingQueueMessages.length+failedQueueMessages.length+uploadingQueueMessages.length);sendMessageParams.content.count=tempCount>0?tempCount:0;}else{sendMessageParams.content.count=count;}sendMessageParams.content.offset=offset;sendMessageParams.content.order=order;if(parseInt(params.messageId)>0){sendMessageParams.content.id=whereClause.id=params.messageId;}if(Array.isArray(params.uniqueIds)){sendMessageParams.content.uniqueIds=params.uniqueIds;}if(parseInt(params.fromTimeFull)>0&&params.fromTimeFull.toString().length===19){sendMessageParams.content.fromTime=whereClause.fromTime=parseInt(params.fromTimeFull.toString().substring(0,13));sendMessageParams.content.fromTimeNanos=whereClause.fromTimeNanos=parseInt(params.fromTimeFull.toString().substring(10,19));}else{if(parseInt(params.fromTime)>0&&parseInt(params.fromTime)<9999999999999){sendMessageParams.content.fromTime=whereClause.fromTime=parseInt(params.fromTime);}if(parseInt(params.fromTimeNanos)>0&&parseInt(params.fromTimeNanos)<999999999){sendMessageParams.content.fromTimeNanos=whereClause.fromTimeNanos=parseInt(params.fromTimeNanos);}}if(parseInt(params.toTimeFull)>0&&params.toTimeFull.toString().length===19){sendMessageParams.content.toTime=whereClause.toTime=parseInt(params.toTimeFull.toString().substring(0,13));sendMessageParams.content.toTimeNanos=whereClause.toTimeNanos=parseInt(params.toTimeFull.toString().substring(10,19));}else{if(parseInt(params.toTime)>0&&parseInt(params.toTime)<9999999999999){sendMessageParams.content.toTime=whereClause.toTime=parseInt(params.toTime);}if(parseInt(params.toTimeNanos)>0&&parseInt(params.toTimeNanos)<999999999){sendMessageParams.content.toTimeNanos=whereClause.toTimeNanos=parseInt(params.toTimeNanos);}}if(typeof params.query!='undefined'){sendMessageParams.content.query=whereClause.query=params.query;}if(params.allMentioned&&typeof params.allMentioned=='boolean'){sendMessageParams.content.allMentioned=whereClause.allMentioned=params.allMentioned;}if(params.unreadMentioned&&typeof params.unreadMentioned=='boolean'){sendMessageParams.content.unreadMentioned=whereClause.unreadMentioned=params.unreadMentioned;}if(params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0){sendMessageParams.content.messageType=whereClause.messageType=_constants.chatMessageTypes[params.messageType.toUpperCase()];}if((0,_typeof2["default"])(params.metadataCriteria)=='object'&&params.metadataCriteria.hasOwnProperty('field')){sendMessageParams.content.metadataCriteria=whereClause.metadataCriteria=params.metadataCriteria;}if(typeof params.onlyNewMessages==="boolean"){sendMessageParams.content.newMessages=params.onlyNewMessages;}/**
1048
1048
  * Get Thread Messages from cache
1049
1049
  *
1050
1050
  * Because we are not applying metadataCriteria search
1051
1051
  * on cached data, if this attribute has been set, we
1052
1052
  * should not return any results from cache
1053
- */ // TODO ASC order?!
1053
+ */ // TODO ASC order?!
1054
1054
  if(functionLevelCache&&canUseCache&&cacheSecret.length>0&&!whereClause.hasOwnProperty('metadataCriteria')&&order.toLowerCase()!=="asc"){if(db){var table=db.messages,collection;returnCache=true;if(whereClause.hasOwnProperty('id')&&whereClause.id>0){collection=table.where('id').equals(parseInt(params.id)).and(function(message){return message.owner===chatMessaging.userInfo.id;}).reverse();}else{collection=table.where('[threadId+owner+time]').between([parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),minIntegerValue],[parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),maxIntegerValue*1000]).reverse();}collection.toArray().then(function(resultMessages){messages=resultMessages.sort(_utility["default"].dynamicSort('time',!(order==='asc')));if(whereClause.hasOwnProperty('fromTime')){var fromTime=whereClause.hasOwnProperty('fromTimeNanos')?Math.floor(whereClause.fromTime/1000)*1000000000+whereClause.fromTimeNanos:whereClause.fromTime*1000000;messages=messages.filter(function(message){return message.time>=fromTime;});}if(whereClause.hasOwnProperty('toTime')){var toTime=whereClause.hasOwnProperty('toTimeNanos')?Math.floor(whereClause.toTime/1000)*1000000000+whereClause.toTimeNanos:whereClause.toTime*1000000;messages=messages.filter(function(message){return message.time<=toTime;});}if(whereClause.hasOwnProperty('query')&&typeof whereClause.query=='string'){messages=messages.filter(function(message){var reg=new RegExp(whereClause.query);return reg.test(chatDecrypt(message.message,cacheSecret,message.salt));});}/**
1055
1055
  * We should check to see if message[offset-1] has
1056
1056
  * GAP on cache or not? if yes, we should not return
@@ -1066,7 +1066,7 @@ if(functionLevelCache&&canUseCache&&cacheSecret.length>0&&!whereClause.hasOwnPro
1066
1066
  * have to do is to check messageGaps table and
1067
1067
  * query it for gaps with time bigger than
1068
1068
  * firstMessage's time
1069
- */if(cacheFirstMessage&&cacheFirstMessage.time>0){db.messageGaps.where('[threadId+owner+time]').between([parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),cacheFirstMessage.time],[parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),maxIntegerValue*1000],true,true).toArray().then(function(gaps){// TODO fill these gaps in a worker
1069
+ */if(cacheFirstMessage&&cacheFirstMessage.time>0){db.messageGaps.where('[threadId+owner+time]').between([parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),cacheFirstMessage.time],[parseInt(params.threadId),parseInt(chatMessaging.userInfo.id),maxIntegerValue*1000],true,true).toArray().then(function(gaps){// TODO fill these gaps in a worker
1070
1070
  if(gaps.length>0){returnCache=false;}})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}if(returnCache){collection.count().then(function(collectionContentCount){var contentCount=0;var cacheData=[];for(var i=0;i<messages.length;i++){/**
1071
1071
  * If any of messages between first and last message of cache response
1072
1072
  * has a GAP before them, we shouldn't return cache's result and
@@ -1253,7 +1253,7 @@ if(gaps.length>0){returnCache=false;}})["catch"](function(error){_events.chatEve
1253
1253
  * thread messages if and only if there are no
1254
1254
  * other conditions applied on getHistory that
1255
1255
  * count and offset
1256
- */if(Object.keys(whereClause).length===0){db.contentCount.put({threadId:parseInt(params.threadId),contentCount:result.contentCount})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}returnData.result={history:history,contentCount:result.contentCount,hasNext:result.result&&!(result.result.length<sendMessageParams.content.count),//(sendMessageParams.content.offset + sendMessageParams.content.count < result.contentCount && messageLength > 0),
1256
+ */if(Object.keys(whereClause).length===0){db.contentCount.put({threadId:parseInt(params.threadId),contentCount:result.contentCount})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}returnData.result={history:history,contentCount:result.contentCount,hasNext:result.result&&!(result.result.length<sendMessageParams.content.count),//(sendMessageParams.content.offset + sendMessageParams.content.count < result.contentCount && messageLength > 0),
1257
1257
  nextOffset:sendMessageParams.content.offset*1+messageLength*1};if(sendingQueue){returnData.result.sending=sendingQueueMessages;}if(uploadingQueue){returnData.result.uploading=uploadingQueueMessages;}if(failedQueue){returnData.result.failed=failedQueueMessages;}/**
1258
1258
  * Check Differences between Cache and Server response
1259
1259
  */if(returnCache&&cacheReady){/**
@@ -1261,16 +1261,16 @@ nextOffset:sendMessageParams.content.offset*1+messageLength*1};if(sendingQueue){
1261
1261
  * are not in server's response, we can assume
1262
1262
  * that they have been removed from server, so
1263
1263
  * we should call MESSAGE_DELETE event for them
1264
- */var batchDeleteMessage=[],batchEditMessage=[],batchNewMessage=[];for(var key in cacheResult){if(!serverResult.hasOwnProperty(key)){batchDeleteMessage.push({id:cacheResult[key].messageId,pinned:cacheResult[key].pinned,threadId:cacheResult[key].threadId});// chatEvents.fireEvent('messageEvents', {
1265
- // type: 'MESSAGE_DELETE',
1266
- // result: {
1267
- // message: {
1268
- // id: cacheResult[key].messageId,
1269
- // pinned: cacheResult[key].pinned,
1270
- // threadId: cacheResult[key].threadId
1271
- // }
1272
- // }
1273
- // });
1264
+ */var batchDeleteMessage=[],batchEditMessage=[],batchNewMessage=[];for(var key in cacheResult){if(!serverResult.hasOwnProperty(key)){batchDeleteMessage.push({id:cacheResult[key].messageId,pinned:cacheResult[key].pinned,threadId:cacheResult[key].threadId});// chatEvents.fireEvent('messageEvents', {
1265
+ // type: 'MESSAGE_DELETE',
1266
+ // result: {
1267
+ // message: {
1268
+ // id: cacheResult[key].messageId,
1269
+ // pinned: cacheResult[key].pinned,
1270
+ // threadId: cacheResult[key].threadId
1271
+ // }
1272
+ // }
1273
+ // });
1274
1274
  }}if(batchDeleteMessage.length){_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_DELETE_BATCH',cache:true,result:batchDeleteMessage});}for(var key in serverResult){if(cacheResult.hasOwnProperty(key)){/**
1275
1275
  * Check digest of cache and server response, if
1276
1276
  * they are not the same, we should emit
@@ -1278,22 +1278,22 @@ nextOffset:sendMessageParams.content.offset*1+messageLength*1};if(sendingQueue){
1278
1278
  * This message is already on cache, but it's
1279
1279
  * content has been changed, so we emit a
1280
1280
  * message edit event to inform client
1281
- */batchEditMessage.push(history[serverResult[key].index]);// chatEvents.fireEvent('messageEvents', {
1282
- // type: 'MESSAGE_EDIT',
1283
- // result: {
1284
- // message: history[serverResult[key].index]
1285
- // }
1286
- // });
1281
+ */batchEditMessage.push(history[serverResult[key].index]);// chatEvents.fireEvent('messageEvents', {
1282
+ // type: 'MESSAGE_EDIT',
1283
+ // result: {
1284
+ // message: history[serverResult[key].index]
1285
+ // }
1286
+ // });
1287
1287
  }}else{/**
1288
1288
  * This Message has not found on cache but it has
1289
1289
  * came from server, so we emit it as a new message
1290
- */batchNewMessage.push(history[serverResult[key].index]);// chatEvents.fireEvent('messageEvents', {
1291
- // type: 'MESSAGE_NEW',
1292
- // cache: true,
1293
- // result: {
1294
- // message: history[serverResult[key].index]
1295
- // }
1296
- // });
1290
+ */batchNewMessage.push(history[serverResult[key].index]);// chatEvents.fireEvent('messageEvents', {
1291
+ // type: 'MESSAGE_NEW',
1292
+ // cache: true,
1293
+ // result: {
1294
+ // message: history[serverResult[key].index]
1295
+ // }
1296
+ // });
1297
1297
  }}if(batchEditMessage.length){_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_EDIT_BATCH',cache:true,result:batchEditMessage});}if(batchNewMessage.length){_events.chatEvents.fireEvent('messageEvents',{type:'MESSAGE_NEW_BATCH',cache:true,result:batchNewMessage});}}else{callback&&callback(returnData);callback=undefined;}}}});});}else{_events.chatEvents.fireEvent('error',{code:999,message:'Thread ID is required for Getting history!'});}},/**
1298
1298
  * Update Thread Info
1299
1299
  *
@@ -1309,10 +1309,10 @@ nextOffset:sendMessageParams.content.offset*1+messageLength*1};if(sendingQueue){
1309
1309
  * @param {function} callback The callback function to call after
1310
1310
  *
1311
1311
  * @return {object} Instant sendMessage result
1312
- */updateThreadInfo=function updateThreadInfo(params,callback){var updateThreadInfoData={chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1313
- content:{},pushMsgType:3,token:token},threadInfoContent={},fileUploadParams={},metadata={file:{}},threadId,fileUniqueId=_utility["default"].generateUUID();if(params){if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}if(parseInt(params.threadId)>0){threadId=parseInt(params.threadId);updateThreadInfoData.subjectId=threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Thread ID is required for Updating thread info!'});}if(typeof params.description=='string'){threadInfoContent.description=params.description;}if(typeof params.title=='string'){threadInfoContent.name=params.title;}if((0,_typeof2["default"])(params.metadata)=='object'){threadInfoContent.metadata=JSON.parse(JSON.stringify(params.metadata));}else if(typeof params.metadata=='string'){try{threadInfoContent.metadata=JSON.parse(params.metadata);}catch(e){threadInfoContent.metadata={};}}else{threadInfoContent.metadata={};}updateThreadInfoData.content=threadInfoContent;if((0,_typeof2["default"])(params.image)=='object'&&params.image.size>0){return chatUploadHandler({threadId:threadId,file:params.image,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);threadInfoContent.metadata=JSON.stringify(Object.assign(threadInfoContent.metadata,uploadHandlerMetadata));putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1314
- subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata,uniqueId:fileUniqueId,pushMsgType:3,token:token},callbacks:callback},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['name']=result.result.name;metadata['fileHash']=result.result.hash;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;metadata['file']['actualHeight']=result.result.actualHeight;metadata['file']['actualWidth']=result.result.actualWidth;metadata['file']['link']="".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true");transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}else{_events.chatEvents.fireEvent('error',{code:999,message:'Thread picture can be a image type only!'});}});});}else if(typeof params.image=='string'&&params.image.length>5){threadInfoContent.metadata=JSON.stringify(Object.assign(threadInfoContent.metadata,{fileHash:params.image}));getImageDownloadLinkFromPodspaceNew({hashCode:params.image},function(result){if(!result.hasError){threadInfoContent.image=result.downloadUrl;}});return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1315
- subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata,uniqueId:fileUniqueId,pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});}else{if(Object.keys(threadInfoContent.metadata).length===0){delete threadInfoContent.metadata;}return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1312
+ */updateThreadInfo=function updateThreadInfo(params,callback){var updateThreadInfoData={chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1313
+ content:{},pushMsgType:3,token:token},threadInfoContent={},fileUploadParams={},metadata={file:{}},threadId,fileUniqueId=_utility["default"].generateUUID();if(params){if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}if(parseInt(params.threadId)>0){threadId=parseInt(params.threadId);updateThreadInfoData.subjectId=threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Thread ID is required for Updating thread info!'});}if(typeof params.description=='string'){threadInfoContent.description=params.description;}if(typeof params.title=='string'){threadInfoContent.name=params.title;}if((0,_typeof2["default"])(params.metadata)=='object'){threadInfoContent.metadata=JSON.parse(JSON.stringify(params.metadata));}else if(typeof params.metadata=='string'){try{threadInfoContent.metadata=JSON.parse(params.metadata);}catch(e){threadInfoContent.metadata={};}}else{threadInfoContent.metadata={};}updateThreadInfoData.content=threadInfoContent;if((0,_typeof2["default"])(params.image)=='object'&&params.image.size>0){return chatUploadHandler({threadId:threadId,file:params.image,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);threadInfoContent.metadata=JSON.stringify(Object.assign(threadInfoContent.metadata,uploadHandlerMetadata));putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1314
+ subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata,uniqueId:fileUniqueId,pushMsgType:3,token:token},callbacks:callback},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['name']=result.result.name;metadata['fileHash']=result.result.hash;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;metadata['file']['actualHeight']=result.result.actualHeight;metadata['file']['actualWidth']=result.result.actualWidth;metadata['file']['link']="".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true");transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}else{_events.chatEvents.fireEvent('error',{code:999,message:'Thread picture can be a image type only!'});}});});}else if(typeof params.image=='string'&&params.image.length>5){threadInfoContent.metadata=JSON.stringify(Object.assign(threadInfoContent.metadata,{fileHash:params.image}));getImageDownloadLinkFromPodspaceNew({hashCode:params.image},function(result){if(!result.hasError){threadInfoContent.image=result.downloadUrl;}});return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1315
+ subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata,uniqueId:fileUniqueId,pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});}else{if(Object.keys(threadInfoContent.metadata).length===0){delete threadInfoContent.metadata;}return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UPDATE_THREAD_INFO,typeCode:generalTypeCode,//params.typeCode,
1316
1316
  subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata,uniqueId:fileUniqueId,pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});}}},/**
1317
1317
  * Update Chat Profile
1318
1318
  *
@@ -1353,7 +1353,7 @@ subjectId:threadId,content:threadInfoContent,metadata:threadInfoContent.metadata
1353
1353
  * @param {string} name Search in Participants list (LIKE in name, contactName, email)
1354
1354
  *
1355
1355
  * @return {object} Instant Response
1356
- */getThreadParticipants=function getThreadParticipants(params,callback){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.THREAD_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1356
+ */getThreadParticipants=function getThreadParticipants(params,callback){var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.THREAD_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1357
1357
  content:{},subjectId:params.threadId},whereClause={},returnCache=false;var offset=parseInt(params.offset)>0?parseInt(params.offset):0,count=parseInt(params.count)>0?parseInt(params.count):config.getHistoryCount;sendMessageParams.content.count=count;sendMessageParams.content.offset=offset;if(typeof params.name==='string'){sendMessageParams.content.name=whereClause.name=params.name;}if(typeof params.username==='string'){sendMessageParams.content.username=whereClause.username=params.username;}if(typeof params.cellphoneNumber==='string'){sendMessageParams.content.cellphoneNumber=whereClause.cellphoneNumber=params.cellphoneNumber;}if(typeof params.admin==='boolean'){sendMessageParams.content.admin=params.admin;}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;/**
1358
1358
  * Retrieve thread participants from cache
1359
1359
  */if(functionLevelCache&&canUseCache&&cacheSecret.length>0){if(db){db.participants.where('expireTime').below(new Date().getTime())["delete"]().then(function(){var thenAble;if(Object.keys(whereClause).length===0){thenAble=db.participants.where('threadId').equals(parseInt(params.threadId)).and(function(participant){return participant.owner===chatMessaging.userInfo.id;});}else{if(whereClause.hasOwnProperty('name')){thenAble=db.participants.where('threadId').equals(parseInt(params.threadId)).and(function(participant){return participant.owner===chatMessaging.userInfo.id;}).filter(function(contact){var reg=new RegExp(whereClause.name);return reg.test(chatDecrypt(contact.contactName,cacheSecret,contact.salt)+' '+chatDecrypt(contact.name,cacheSecret,contact.salt)+' '+chatDecrypt(contact.email,cacheSecret,contact.salt));});}}thenAble.offset(offset).limit(count).reverse().toArray().then(function(participants){db.participants.where('threadId').equals(parseInt(params.threadId)).and(function(participant){return participant.owner===chatMessaging.userInfo.id;}).count().then(function(participantsCount){var cacheData=[];for(var i=0;i<participants.length;i++){try{cacheData.push(formatDataToMakeParticipant(JSON.parse(chatDecrypt(participants[i].data,cacheSecret,participants[i].salt)),participants[i].threadId));}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}var returnData={hasError:false,cache:true,errorCode:0,errorMessage:'',result:{participants:cacheData,contentCount:participantsCount,hasNext:!(participants.length<count),nextOffset:offset*1+participants.length}};if(cacheData.length>0){callback&&callback(returnData);callback=undefined;returnCache=true;}});})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}return chatMessaging.sendMessage(sendMessageParams,{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:reformatThreadParticipants(messageContent,params.threadId),contentCount:result.contentCount,hasNext:sendMessageParams.content.offset+sendMessageParams.content.count<result.contentCount&&messageLength>0,nextOffset:sendMessageParams.content.offset*1+messageLength*1};returnData.result=resultData;/**
@@ -1371,7 +1371,7 @@ content:{},subjectId:params.threadId},whereClause={},returnCache=false;var offse
1371
1371
  * @param {int} messageId Id of Message
1372
1372
  *
1373
1373
  * @return {object} Instant sendMessage result
1374
- */deliver=function deliver(params){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELIVERY,typeCode:generalTypeCode,//params.typeCode,
1374
+ */deliver=function deliver(params){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELIVERY,typeCode:generalTypeCode,//params.typeCode,
1375
1375
  content:params.messageId,pushMsgType:3});},/**
1376
1376
  * Seen
1377
1377
  *
@@ -1382,7 +1382,7 @@ content:params.messageId,pushMsgType:3});},/**
1382
1382
  * @param {int} messageId Id of Message
1383
1383
  *
1384
1384
  * @return {object} Instant sendMessage result
1385
- */seen=function seen(params){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.SEEN,typeCode:generalTypeCode,//params.typeCode,
1385
+ */seen=function seen(params){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.SEEN,typeCode:generalTypeCode,//params.typeCode,
1386
1386
  content:params.messageId,pushMsgType:3});},/**
1387
1387
  * Get Image.
1388
1388
  *
@@ -1425,7 +1425,7 @@ content:params.messageId,pushMsgType:3});},/**
1425
1425
  * @param {string} hashCode HashCode of uploaded file
1426
1426
  *
1427
1427
  * @return {object} File Object
1428
- */getFileFromPodspace=function getFileFromPodspace(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getFileData={};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getFileData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE+"?hash=".concat(params.hashCode,"&_token_=").concat(token,"&_token_issuer_=1");callback({hasError:false,type:'link',result:returnLink});}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE,method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'_token_':token,'_token_issuer_':1// 'Range': 'bytes=100-200'
1428
+ */getFileFromPodspace=function getFileFromPodspace(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getFileData={};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getFileData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE+"?hash=".concat(params.hashCode,"&_token_=").concat(token,"&_token_issuer_=1");callback({hasError:false,type:'link',result:returnLink});}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE,method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'_token_':token,'_token_issuer_':1// 'Range': 'bytes=100-200'
1429
1429
  },data:getFileData},function(result){if(!result.hasError){callback({hasError:result.hasError,result:result.result.response,type:'blob'});}else{callback({hasError:true});}});return{uniqueId:downloadUniqueId,cancel:function cancel(){cancelFileDownload({uniqueId:downloadUniqueId},function(){consoleLogging&&console.log("\"".concat(downloadUniqueId,"\" - File download has been canceled!"));});}};}},/**
1430
1430
  * Get File From PodSpace New
1431
1431
  *
@@ -1437,7 +1437,7 @@ content:params.messageId,pushMsgType:3});},/**
1437
1437
  * @param {string} hashCode HashCode of uploaded file
1438
1438
  *
1439
1439
  * @return {object} File Object
1440
- */getFileFromPodspaceNew=function getFileFromPodspaceNew(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getFileData={};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getFileData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}if(params.checkUserGroupAccess){getFileData.checkUserGroupAccess=true;}}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true";callback({hasError:false,type:'link',result:returnLink});}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true",method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getFileData
1440
+ */getFileFromPodspaceNew=function getFileFromPodspaceNew(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getFileData={};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getFileData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}if(params.checkUserGroupAccess){getFileData.checkUserGroupAccess=true;}}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true";callback({hasError:false,type:'link',result:returnLink});}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_FILE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true",method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getFileData
1441
1441
  },function(result){if(!result.hasError){callback({hasError:result.hasError,result:result.result.response,type:'blob'});}else{callback({hasError:true});}});return{uniqueId:downloadUniqueId,cancel:function cancel(){cancelFileDownload({uniqueId:downloadUniqueId},function(){consoleLogging&&console.log("\"".concat(downloadUniqueId,"\" - File download has been canceled!"));});}};}},/**
1442
1442
  * Deprecated
1443
1443
  *
@@ -1466,9 +1466,9 @@ content:params.messageId,pushMsgType:3});},/**
1466
1466
  * @param {string} quality Image quality betwenn 0.0 anf 1.0
1467
1467
  *
1468
1468
  * @return {object} File Object
1469
- */getImageFromPodspaceNew=function getImageFromPodspaceNew(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getImageData={size:params.size,quality:params.quality,crop:params.crop};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getImageData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop);//+ SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE + `?hash=${params.hashCode}&_token_=${token}&_token_issuer_=1&size=${params.size}&quality=${params.quality}&crop=${params.crop}`;
1470
- callback({hasError:false,type:'link',result:returnLink});}else if(params.responseType==='base64'){httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop),method:'GET',uniqueId:downloadUniqueId,responseType:'blob',headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getImageData
1471
- },function(result){if(!result.hasError){var fr=new FileReader();fr.onloadend=function(){callback({hasError:result.hasError,type:'base64',result:fr.result});};fr.readAsDataURL(result.result.response);}else{callback({hasError:true});}});return{uniqueId:downloadUniqueId,cancel:function cancel(){cancelFileDownload({uniqueId:downloadUniqueId},function(){consoleLogging&&console.log("\"".concat(downloadUniqueId,"\" - Image download has been canceled!"));});}};}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop),method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getImageData
1469
+ */getImageFromPodspaceNew=function getImageFromPodspaceNew(params,callback){var downloadUniqueId=_utility["default"].generateUUID(),getImageData={size:params.size,quality:params.quality,crop:params.crop};if(params){if(params.hashCode&&typeof params.hashCode=='string'){getImageData.hash=params.hashCode;}else{callback({hasError:true,error:'Enter a file hash to get'});return;}if(params.responseType==='link'){var returnLink=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop);//+ SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE + `?hash=${params.hashCode}&_token_=${token}&_token_issuer_=1&size=${params.size}&quality=${params.quality}&crop=${params.crop}`;
1470
+ callback({hasError:false,type:'link',result:returnLink});}else if(params.responseType==='base64'){httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop),method:'GET',uniqueId:downloadUniqueId,responseType:'blob',headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getImageData
1471
+ },function(result){if(!result.hasError){var fr=new FileReader();fr.onloadend=function(){callback({hasError:result.hasError,type:'base64',result:fr.result});};fr.readAsDataURL(result.result.response);}else{callback({hasError:true});}});return{uniqueId:downloadUniqueId,cancel:function cancel(){cancelFileDownload({uniqueId:downloadUniqueId},function(){consoleLogging&&console.log("\"".concat(downloadUniqueId,"\" - Image download has been canceled!"));});}};}else{httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode)+"?checkUserGroupAccess=true&size=".concat(params.size,"&quality=").concat(params.quality,"&crop=").concat(params.crop),method:'GET',responseType:'blob',uniqueId:downloadUniqueId,headers:{'Authorization':'Bearer '+token},enableDownloadProgressEvents:params.enableDownloadProgressEvents,hashCode:params.hashCode//data: getImageData
1472
1472
  },function(result){if(!result.hasError){callback({hasError:result.hasError,type:'blob',result:result.result.response});}else{callback({hasError:true});}});return{uniqueId:downloadUniqueId,cancel:function cancel(){cancelFileDownload({uniqueId:downloadUniqueId},function(){consoleLogging&&console.log("\"".concat(downloadUniqueId,"\" - Image download has been canceled!"));});}};}}},/**
1473
1473
  * Deprecated
1474
1474
  *
@@ -1493,7 +1493,7 @@ callback({hasError:false,type:'link',result:returnLink});}else if(params.respons
1493
1493
  * @param {string} hashCode HashCode of uploaded file
1494
1494
  *
1495
1495
  * @return {string} Image Link
1496
- */getImageDownloadLinkFromPodspaceNew=function getImageDownloadLinkFromPodspaceNew(params,callback){if(params){if(params.hashCode&&typeof params.hashCode=='string'){var downloadUrl=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode);// + '?hash=' + params.hashCode;
1496
+ */getImageDownloadLinkFromPodspaceNew=function getImageDownloadLinkFromPodspaceNew(params,callback){if(params){if(params.hashCode&&typeof params.hashCode=='string'){var downloadUrl=SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_DOWNLOAD_IMAGE_NEW.replace('{fileHash}',params.hashCode);// + '?hash=' + params.hashCode;
1497
1497
  callback&&callback({hasError:false,downloadUrl:downloadUrl});return downloadUrl;}else{callback&&callback({hasError:true,error:'Enter a image hash to get download link!'});}}},/**
1498
1498
  * Get File Download Link From PodSpace
1499
1499
  *
@@ -1536,7 +1536,7 @@ callback&&callback({hasError:false,downloadUrl:downloadUrl});return downloadUrl;
1536
1536
  * @link
1537
1537
  *
1538
1538
  * @return {object} Uploaded File Object
1539
- */uploadFileToPodspace=function uploadFileToPodspace(params,callback){var fileName,fileType,fileSize,fileExtension,uploadUniqueId,uploadThreadId;fileName=params.file.name;fileType=params.file.type;fileSize=params.file.size;fileExtension=params.file.name.split('.').pop();var uploadFileData={};if(params){if(typeof params.file!=='undefined'){uploadFileData.file=params.file;}if(params.randomFileName){uploadFileData.filename=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadFileData.filename=fileName;}uploadFileData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadFileData.threadId=params.threadId;}else{uploadThreadId=0;uploadFileData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadFileData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadFileData.uniqueId=uploadUniqueId;}if(typeof params.userGroupHash=='string'){//userGroupHash = params.userGroupHash;
1539
+ */uploadFileToPodspace=function uploadFileToPodspace(params,callback){var fileName,fileType,fileSize,fileExtension,uploadUniqueId,uploadThreadId;fileName=params.file.name;fileType=params.file.type;fileSize=params.file.size;fileExtension=params.file.name.split('.').pop();var uploadFileData={};if(params){if(typeof params.file!=='undefined'){uploadFileData.file=params.file;}if(params.randomFileName){uploadFileData.filename=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadFileData.filename=fileName;}uploadFileData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadFileData.threadId=params.threadId;}else{uploadThreadId=0;uploadFileData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadFileData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadFileData.uniqueId=uploadUniqueId;}if(typeof params.userGroupHash=='string'){//userGroupHash = params.userGroupHash;
1540
1540
  uploadFileData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to enter a userGroupHash to be able to upload on PodSpace!'});return;}if(typeof params.originalFileName=='string'){uploadFileData.originalFileName=params.originalFileName;}else{uploadFileData.originalFileName=fileName;}}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_FILE_TO_USERGROUP,method:'POST',headers:{'_token_':token,'_token_issuer_':1},data:uploadFileData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;callback({hasError:response.hasError,result:response.result});}catch(e){callback({hasError:true,errorCode:999,errorMessage:'Problem in Parsing result'});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};},uploadFileToPodspaceNew=function uploadFileToPodspaceNew(params,callback){var fileName,fileType,fileSize,fileExtension,uploadUniqueId,uploadThreadId;fileName=params.file.name;fileType=params.file.type;fileSize=params.file.size;fileExtension=params.file.name.split('.').pop();var uploadFileData={};if(params){if(typeof params.file!=='undefined'){uploadFileData.file=params.file;}if(params.randomFileName){uploadFileData.fileName=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadFileData.fileName=fileName;}uploadFileData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadFileData.threadId=params.threadId;}else{uploadThreadId=0;uploadFileData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadFileData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadFileData.uniqueId=uploadUniqueId;}if(typeof params.originalFileName=='string'){uploadFileData.originalFileName=params.originalFileName;}else{uploadFileData.originalFileName=fileName;}}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_FILE_NEW,method:'POST',headers:{'Authorization':'Bearer '+token},data:uploadFileData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;callback({hasError:response.hasError,result:response.result});}catch(e){callback({hasError:true,errorCode:999,errorMessage:'Problem in Parsing result'});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};},/**
1541
1541
  * Upload File To Pod Space
1542
1542
  *
@@ -1552,10 +1552,10 @@ uploadFileData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,
1552
1552
  * @link
1553
1553
  *
1554
1554
  * @return {object} Uploaded File Object
1555
- */uploadFileToPodspaceUserGroupNew=function uploadFileToPodspaceUserGroupNew(params,callback){var fileName,//fileType,
1556
- fileSize,//fileExtension,
1557
- uploadUniqueId,uploadThreadId;fileName=params.file.name;//fileType = params.file.type;
1558
- fileSize=params.file.size;//fileExtension = params.file.name.split('.').pop();
1555
+ */uploadFileToPodspaceUserGroupNew=function uploadFileToPodspaceUserGroupNew(params,callback){var fileName,//fileType,
1556
+ fileSize,//fileExtension,
1557
+ uploadUniqueId,uploadThreadId;fileName=params.file.name;//fileType = params.file.type;
1558
+ fileSize=params.file.size;//fileExtension = params.file.name.split('.').pop();
1559
1559
  var uploadFileData={};if(params){if(typeof params.file!=='undefined'){uploadFileData.file=params.file;}if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadFileData.threadId=params.threadId;}else{uploadThreadId=0;uploadFileData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadFileData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadFileData.uniqueId=uploadUniqueId;}if(typeof params.userGroupHash=='string'){uploadFileData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to enter a userGroupHash to be able to upload on PodSpace!'});return;}if(typeof params.originalFileName=='string'){uploadFileData.originalFileName=params.originalFileName;}else{uploadFileData.originalFileName=fileName;}}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_FILE_TO_USERGROUP_NEW.replace('{userGroupHash}',uploadFileData.userGroupHash),method:'POST',headers:{'Authorization':'Bearer '+token},data:uploadFileData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;callback({hasError:response.hasError,result:response.result});}catch(e){callback({hasError:true,errorCode:999,errorMessage:'Problem in Parsing result'});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};},/**
1560
1560
  * Upload File
1561
1561
  *
@@ -1631,7 +1631,7 @@ var uploadFileData={};if(params){if(typeof params.file!=='undefined'){uploadFile
1631
1631
  * @link https://podspace.pod.ir/apidocs/?srv=/userGroup/uploadImage/
1632
1632
  *
1633
1633
  * @return {object} Uploaded Image Object
1634
- */uploadImageToPodspaceUserGroup=function uploadImageToPodspaceUserGroup(params,callback){var fileName,fileType,fileSize,fileWidth=0,fileHeight=0,fileExtension,uploadUniqueId,uploadThreadId;var continueImageUpload=function continueImageUpload(params){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){var uploadImageData={};if(params){if(typeof params.image!=='undefined'){uploadImageData.file=params.image;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to send a image file!'});return;}if(typeof params.userGroupHash=='string'){// userGroupHash = params.userGroupHash;
1634
+ */uploadImageToPodspaceUserGroup=function uploadImageToPodspaceUserGroup(params,callback){var fileName,fileType,fileSize,fileWidth=0,fileHeight=0,fileExtension,uploadUniqueId,uploadThreadId;var continueImageUpload=function continueImageUpload(params){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){var uploadImageData={};if(params){if(typeof params.image!=='undefined'){uploadImageData.file=params.image;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to send a image file!'});return;}if(typeof params.userGroupHash=='string'){// userGroupHash = params.userGroupHash;
1635
1635
  uploadImageData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to enter a userGroupHash to be able to upload on PodSpace!'});return;}if(params.randomFileName){uploadImageData.fileName=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadImageData.filename=fileName;}uploadImageData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadImageData.threadId=params.threadId;}else{uploadThreadId=0;uploadImageData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadImageData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadImageData.uniqueId=uploadUniqueId;}if(typeof params.originalFileName=='string'){uploadImageData.originalFileName=params.originalFileName;}else{uploadImageData.originalFileName=fileName;}uploadImageData.xC=parseInt(params.xC)||0;uploadImageData.yC=parseInt(params.yC)||0;uploadImageData.hC=parseInt(params.hC)||fileHeight;uploadImageData.wC=parseInt(params.wC)||fileWidth;}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_IMAGE_TO_USERGROUP,method:'POST',headers:{'_token_':token,'_token_issuer_':1},data:uploadImageData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;if(typeof response.hasError!=='undefined'&&!response.hasError){response.result.actualHeight=fileHeight;response.result.actualWidth=fileWidth;callback({hasError:response.hasError,result:response.result});}else{callback({hasError:true,errorCode:response.errorCode,errorMessage:response.message});}}catch(e){consoleLogging&&console.log(e);callback({hasError:true,errorCode:6300,errorMessage:CHAT_ERRORS[6300]});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};}else{callback({hasError:true,errorCode:6301,errorMessage:CHAT_ERRORS[6301]});}};fileName=params.image.name;fileType=params.image.type;fileSize=params.image.size;fileExtension=params.image.name.split('.').pop();var reader=new FileReader();reader.onload=function(e){var image=new Image();image.onload=function(){fileWidth=this.width;fileHeight=this.height;continueImageUpload(params);};image.src=e.target.result;};reader.readAsDataURL(params.image);},/**
1636
1636
  * Upload Image To Podspace User Group
1637
1637
  *
@@ -1653,8 +1653,8 @@ uploadImageData.userGroupHash=params.userGroupHash;}else{callback({hasError:true
1653
1653
  * @link https://podspace.pod.ir/apidocs/?srv=/userGroup/uploadImage/
1654
1654
  *
1655
1655
  * @return {object} Uploaded Image Object
1656
- */uploadImageToPodspaceUserGroupNew=function uploadImageToPodspaceUserGroupNew(params,callback){var fileName,fileType,fileSize,fileWidth=0,fileHeight=0,fileExtension,uploadUniqueId,uploadThreadId;var continueImageUpload=function continueImageUpload(params){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){var uploadImageData={};if(params){if(typeof params.image!=='undefined'){uploadImageData.file=params.image;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to send a image file!'});return;}if(typeof params.userGroupHash=='string'){uploadImageData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to enter a userGroupHash to be able to upload on PodSpace!'});return;}if(params.randomFileName){uploadImageData.fileName=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadImageData.filename=fileName;}uploadImageData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadImageData.threadId=params.threadId;}else{uploadThreadId=0;uploadImageData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadImageData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadImageData.uniqueId=uploadUniqueId;}if(typeof params.originalFileName=='string'){uploadImageData.originalFileName=params.originalFileName;}else{uploadImageData.originalFileName=fileName;}uploadImageData.x=parseInt(params.xC)||0;uploadImageData.y=parseInt(params.yC)||0;uploadImageData.height=parseInt(params.hC)||fileHeight;uploadImageData.weight=parseInt(params.wC)||fileWidth;}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_IMAGE_TO_USERGROUP_NEW.replace('{userGroupHash}',uploadImageData.userGroupHash),method:'POST',headers:{'Authorization':'Bearer '+token},data:uploadImageData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;if(response.status<400){response.result.actualHeight=fileHeight;response.result.actualWidth=fileWidth;callback({hasError:response.hasError,result:response.result});}else{callback({hasError:true,errorCode:response.errorCode,errorMessage:response.message});}}catch(e){consoleLogging&&console.log(e);callback({hasError:true,errorCode:6300,errorMessage:CHAT_ERRORS[6300]});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};}else{callback({hasError:true,errorCode:6301,errorMessage:CHAT_ERRORS[6301]});}};fileName=params.image.name;fileType=params.image.type;fileSize=params.image.size;fileExtension=params.image.name.split('.').pop();var reader=new FileReader();reader.onload=function(e){var image=new Image();image.onload=function(){fileWidth=this.width;fileHeight=this.height;continueImageUpload(params);};image.src=e.target.result;};reader.readAsDataURL(params.image);},sendFileMessage=function sendFileMessage(params,callbacks){var metadata={file:{}},fileUploadParams={},fileUniqueId=typeof params.fileUniqueId=='string'&&params.fileUniqueId.length>0?params.fileUniqueId:_utility["default"].generateUUID();if(params){if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}return chatUploadHandler({threadId:params.threadId,file:params.file,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1657
- messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.content,metadata:JSON.stringify(objectDeepMerger(uploadHandlerMetadata,params.metadata)),systemMetadata:JSON.stringify(params.systemMetadata),uniqueId:fileUniqueId,pushMsgType:3},callbacks:callbacks},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){// Send onFileUpload callback result
1656
+ */uploadImageToPodspaceUserGroupNew=function uploadImageToPodspaceUserGroupNew(params,callback){var fileName,fileType,fileSize,fileWidth=0,fileHeight=0,fileExtension,uploadUniqueId,uploadThreadId;var continueImageUpload=function continueImageUpload(params){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){var uploadImageData={};if(params){if(typeof params.image!=='undefined'){uploadImageData.file=params.image;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to send a image file!'});return;}if(typeof params.userGroupHash=='string'){uploadImageData.userGroupHash=params.userGroupHash;}else{callback({hasError:true,errorCode:999,errorMessage:'You need to enter a userGroupHash to be able to upload on PodSpace!'});return;}if(params.randomFileName){uploadImageData.fileName=_utility["default"].generateUUID()+'.'+fileExtension;}else{uploadImageData.filename=fileName;}uploadImageData.fileSize=fileSize;if(parseInt(params.threadId)>0){uploadThreadId=params.threadId;uploadImageData.threadId=params.threadId;}else{uploadThreadId=0;uploadImageData.threadId=0;}if(typeof params.uniqueId=='string'){uploadUniqueId=params.uniqueId;uploadImageData.uniqueId=params.uniqueId;}else{uploadUniqueId=_utility["default"].generateUUID();uploadImageData.uniqueId=uploadUniqueId;}if(typeof params.originalFileName=='string'){uploadImageData.originalFileName=params.originalFileName;}else{uploadImageData.originalFileName=fileName;}uploadImageData.x=parseInt(params.xC)||0;uploadImageData.y=parseInt(params.yC)||0;uploadImageData.height=parseInt(params.hC)||fileHeight;uploadImageData.weight=parseInt(params.wC)||fileWidth;}httpRequest({url:SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS+SERVICES_PATH.PODSPACE_UPLOAD_IMAGE_TO_USERGROUP_NEW.replace('{userGroupHash}',uploadImageData.userGroupHash),method:'POST',headers:{'Authorization':'Bearer '+token},data:uploadImageData,uniqueId:uploadUniqueId},function(result){if(!result.hasError){try{var response=typeof result.result.responseText=='string'?JSON.parse(result.result.responseText):result.result.responseText;if(response.status<400){response.result.actualHeight=fileHeight;response.result.actualWidth=fileWidth;callback({hasError:response.hasError,result:response.result});}else{callback({hasError:true,errorCode:response.errorCode,errorMessage:response.message});}}catch(e){consoleLogging&&console.log(e);callback({hasError:true,errorCode:6300,errorMessage:CHAT_ERRORS[6300]});}}else{callback({hasError:true,errorCode:result.errorCode,errorMessage:result.errorMessage});}});return{uniqueId:uploadUniqueId,threadId:uploadThreadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:uploadUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};}else{callback({hasError:true,errorCode:6301,errorMessage:CHAT_ERRORS[6301]});}};fileName=params.image.name;fileType=params.image.type;fileSize=params.image.size;fileExtension=params.image.name.split('.').pop();var reader=new FileReader();reader.onload=function(e){var image=new Image();image.onload=function(){fileWidth=this.width;fileHeight=this.height;continueImageUpload(params);};image.src=e.target.result;};reader.readAsDataURL(params.image);},sendFileMessage=function sendFileMessage(params,callbacks){var metadata={file:{}},fileUploadParams={},fileUniqueId=typeof params.fileUniqueId=='string'&&params.fileUniqueId.length>0?params.fileUniqueId:_utility["default"].generateUUID();if(params){if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}return chatUploadHandler({threadId:params.threadId,file:params.file,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1657
+ messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.content,metadata:JSON.stringify(objectDeepMerger(uploadHandlerMetadata,params.metadata)),systemMetadata:JSON.stringify(params.systemMetadata),uniqueId:fileUniqueId,pushMsgType:3},callbacks:callbacks},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){// Send onFileUpload callback result
1658
1658
  if((0,_typeof2["default"])(callbacks)==='object'&&callbacks.hasOwnProperty('onFileUpload')){callbacks.onFileUpload&&callbacks.onFileUpload({name:result.result.name,hashCode:result.result.hash,parentHash:result.result.parentHash,size:result.result.size,actualHeight:result.result.actualHeight,actualWidth:result.result.actualWidth,link:"".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true")});}metadata['name']=result.result.name;metadata['fileHash']=result.result.hash;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;metadata['file']['actualHeight']=result.result.actualHeight;metadata['file']['actualWidth']=result.result.actualWidth;metadata['file']['link']="".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true");transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}else{uploadFileToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['fileHash']=result.result.hash;metadata['name']=result.result.name;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}});});}},/**
1659
1659
  * Delete Cache Database
1660
1660
  *
@@ -1809,18 +1809,18 @@ if((0,_typeof2["default"])(callbacks)==='object'&&callbacks.hasOwnProperty('onFi
1809
1809
  * and is ready. If so, and cache is still not decryptable,
1810
1810
  * there is definitely something wrong with the key; so we are
1811
1811
  * good to go and delete cache databases.
1812
- */if(typeof secret!=='undefined'&&secret!==''){if(db){db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).count().then(function(threadsCount){if(threadsCount>0){clearCacheDatabasesOfUser(function(){consoleLogging&&console.log('All cache databases have been cleared.');});}})["catch"](function(e){consoleLogging&&console.log(e);});}}return'{}';}},objectDeepMerger=function objectDeepMerger(){var target={};var merger=function merger(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){if(Object.prototype.toString.call(obj[prop])==='[object Object]'){target[prop]=objectDeepMerger(target[prop],obj[prop]);}else{target[prop]=obj[prop];}}}};for(var i=0;i<arguments.length;i++){merger(i<0||arguments.length<=i?undefined:arguments[i]);}return target;},setRoleToUser=function setRoleToUser(params,callback){var setRoleData={chatMessageVOType:_constants.chatMessageVOTypes.SET_ROLE_TO_USER,typeCode:generalTypeCode,//params.typeCode,
1813
- content:[],pushMsgType:3,token:token};if(params){if(parseInt(params.threadId)>0){setRoleData.subjectId=params.threadId;}if(params.admins&&Array.isArray(params.admins)){for(var i=0;i<params.admins.length;i++){var temp={};if(parseInt(params.admins[i].userId)>0){temp.userId=params.admins[i].userId;}if(Array.isArray(params.admins[i].roles)){temp.roles=params.admins[i].roles;}setRoleData.content.push(temp);}setRoleData.content=JSON.stringify(setRoleData.content);}}return chatMessaging.sendMessage(setRoleData,{onResult:function onResult(result){callback&&callback(result);}});},removeRoleFromUser=function removeRoleFromUser(params,callback){var setAdminData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_ROLE_FROM_USER,typeCode:generalTypeCode,//params.typeCode,
1814
- content:[],pushMsgType:3,token:token};if(params){if(parseInt(params.threadId)>0){setAdminData.subjectId=params.threadId;}if(params.admins&&Array.isArray(params.admins)){for(var i=0;i<params.admins.length;i++){var temp={};if(parseInt(params.admins[i].userId)>0){temp.userId=params.admins[i].userId;}if(Array.isArray(params.admins[i].roles)){temp.roles=params.admins[i].roles;}setAdminData.content.push(temp);}setAdminData.content=JSON.stringify(setAdminData.content);}}return chatMessaging.sendMessage(setAdminData,{onResult:function onResult(result){callback&&callback(result);}});},unPinMessage=function unPinMessage(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNPIN_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1812
+ */if(typeof secret!=='undefined'&&secret!==''){if(db){db.threads.where('owner').equals(parseInt(chatMessaging.userInfo.id)).count().then(function(threadsCount){if(threadsCount>0){clearCacheDatabasesOfUser(function(){consoleLogging&&console.log('All cache databases have been cleared.');});}})["catch"](function(e){consoleLogging&&console.log(e);});}}return'{}';}},objectDeepMerger=function objectDeepMerger(){var target={};var merger=function merger(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){if(Object.prototype.toString.call(obj[prop])==='[object Object]'){target[prop]=objectDeepMerger(target[prop],obj[prop]);}else{target[prop]=obj[prop];}}}};for(var i=0;i<arguments.length;i++){merger(i<0||arguments.length<=i?undefined:arguments[i]);}return target;},setRoleToUser=function setRoleToUser(params,callback){var setRoleData={chatMessageVOType:_constants.chatMessageVOTypes.SET_ROLE_TO_USER,typeCode:generalTypeCode,//params.typeCode,
1813
+ content:[],pushMsgType:3,token:token};if(params){if(parseInt(params.threadId)>0){setRoleData.subjectId=params.threadId;}if(params.admins&&Array.isArray(params.admins)){for(var i=0;i<params.admins.length;i++){var temp={};if(parseInt(params.admins[i].userId)>0){temp.userId=params.admins[i].userId;}if(Array.isArray(params.admins[i].roles)){temp.roles=params.admins[i].roles;}setRoleData.content.push(temp);}setRoleData.content=JSON.stringify(setRoleData.content);}}return chatMessaging.sendMessage(setRoleData,{onResult:function onResult(result){callback&&callback(result);}});},removeRoleFromUser=function removeRoleFromUser(params,callback){var setAdminData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_ROLE_FROM_USER,typeCode:generalTypeCode,//params.typeCode,
1814
+ content:[],pushMsgType:3,token:token};if(params){if(parseInt(params.threadId)>0){setAdminData.subjectId=params.threadId;}if(params.admins&&Array.isArray(params.admins)){for(var i=0;i<params.admins.length;i++){var temp={};if(parseInt(params.admins[i].userId)>0){temp.userId=params.admins[i].userId;}if(Array.isArray(params.admins[i].roles)){temp.roles=params.admins[i].roles;}setAdminData.content.push(temp);}setAdminData.content=JSON.stringify(setAdminData.content);}}return chatMessaging.sendMessage(setAdminData,{onResult:function onResult(result){callback&&callback(result);}});},unPinMessage=function unPinMessage(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNPIN_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1815
1815
  subjectId:params.messageId,content:JSON.stringify({'notifyAll':typeof params.notifyAll==='boolean'?params.notifyAll:false}),pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});},chatUploadHandler=function chatUploadHandler(params,callbacks){if(typeof params.file!=='undefined'){var fileName,fileType,fileSize,fileExtension,chatUploadHandlerResult={},metadata={file:{}},fileUniqueId=params.fileUniqueId;fileName=params.file.name;fileType=params.file.type;fileSize=params.file.size;fileExtension=params.file.name.split('.').pop();_events.chatEvents.fireEvent('fileUploadEvents',{threadId:params.threadId,uniqueId:fileUniqueId,state:'NOT_STARTED',progress:0,fileInfo:{fileName:fileName,fileSize:fileSize},fileObject:params.file});/**
1816
1816
  * File is a valid Image
1817
1817
  * Should upload to image server
1818
- */if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){chatUploadHandlerResult.image=params.file;if(params.xC>=0){fileUploadParams.xC=params.xC;}if(params.yC>=0){fileUploadParams.yC=params.yC;}if(params.hC>0){fileUploadParams.hC=params.hC;}if(params.wC>0){fileUploadParams.wC=params.wC;}}else{chatUploadHandlerResult.file=params.file;}metadata['file']['originalName']=fileName;metadata['file']['mimeType']=fileType;metadata['file']['size']=fileSize;chatUploadHandlerResult.threadId=params.threadId;chatUploadHandlerResult.uniqueId=fileUniqueId;chatUploadHandlerResult.fileObject=params.file;chatUploadHandlerResult.originalFileName=fileName;callbacks&&callbacks(chatUploadHandlerResult,metadata,fileType,fileExtension);}else{_events.chatEvents.fireEvent('error',{code:6302,message:CHAT_ERRORS[6302]});}return{uniqueId:fileUniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:fileUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};},cancelFileDownload=function cancelFileDownload(params,callback){if(params){if(typeof params.uniqueId=='string'){var uniqueId=params.uniqueId;httpRequestObject[eval('uniqueId')]&&httpRequestObject[eval('uniqueId')].abort();httpRequestObject[eval('uniqueId')]&&delete httpRequestObject[eval('uniqueId')];callback&&callback(uniqueId);}}},cancelFileUpload=function cancelFileUpload(params,callback){if(params){if(typeof params.uniqueId=='string'){var uniqueId=params.uniqueId;httpRequestObject[eval('uniqueId')]&&httpRequestObject[eval('uniqueId')].abort();httpRequestObject[eval('uniqueId')]&&delete httpRequestObject[eval('uniqueId')];deleteFromChatUploadQueue({message:{uniqueId:uniqueId}},callback);}}},cancelMessage=function cancelMessage(uniqueId,callback){deleteFromChatSentQueue({message:{uniqueId:uniqueId}},function(){deleteFromChatWaitQueue({uniqueId:uniqueId},callback);});},mapReverse=function mapReverse(params,callback){var data={};if(params){if(parseFloat(params.lat)>0){data.lat=params.lat;}if(parseFloat(params.lng)>0){data.lng=params.lng;}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.REVERSE,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapSearch=function mapSearch(params,callback){var data={};if(params){if(typeof params.term==='string'){data.term=params.term;}if(parseFloat(params.lat)>0){data.lat=params.lat;}if(parseFloat(params.lng)>0){data.lng=params.lng;}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.SEARCH,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapRouting=function mapRouting(params,callback){var data={};if(params){if(typeof params.alternative==='boolean'){data.alternative=params.alternative;}else{data.alternative=true;}if((0,_typeof2["default"])(params.origin)==='object'){if(parseFloat(params.origin.lat)>0&&parseFloat(params.origin.lng)){data.origin=params.origin.lat+','+parseFloat(params.origin.lng);}else{consoleLogging&&console.log('No origin has been selected!');}}if((0,_typeof2["default"])(params.destination)==='object'){if(parseFloat(params.destination.lat)>0&&parseFloat(params.destination.lng)){data.destination=params.destination.lat+','+parseFloat(params.destination.lng);}else{consoleLogging&&console.log('No destination has been selected!');}}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.ROUTING,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapStaticImage=function mapStaticImage(params,callback){var data={},url=SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.STATIC_IMAGE,hasError=false;if(params){if(typeof params.type==='string'){data.type=params.type;}else{data.type='standard-night';}if(parseInt(params.zoom)>0){data.zoom=params.zoom;}else{data.zoom=15;}if(parseInt(params.width)>0){data.width=params.width;}else{data.width=800;}if(parseInt(params.height)>0){data.height=params.height;}else{data.height=600;}if((0,_typeof2["default"])(params.center)==='object'){if(parseFloat(params.center.lat)>0&&parseFloat(params.center.lng)){data.center=params.center.lat+','+parseFloat(params.center.lng);}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}data.key=mapApiKey;}var keys=Object.keys(data);if(keys.length>0){url+='?';for(var i=0;i<keys.length;i++){var key=keys[i];url+=key+'='+data[key];if(i<keys.length-1){url+='&';}}}var returnData={hasError:hasError,cache:false,errorMessage:hasError?CHAT_ERRORS[6700]:'',errorCode:hasError?6700:undefined,result:{link:!hasError?url:''}};callback&&callback(returnData);},//TODO Change Node Version
1818
+ */if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){chatUploadHandlerResult.image=params.file;if(params.xC>=0){fileUploadParams.xC=params.xC;}if(params.yC>=0){fileUploadParams.yC=params.yC;}if(params.hC>0){fileUploadParams.hC=params.hC;}if(params.wC>0){fileUploadParams.wC=params.wC;}}else{chatUploadHandlerResult.file=params.file;}metadata['file']['originalName']=fileName;metadata['file']['mimeType']=fileType;metadata['file']['size']=fileSize;chatUploadHandlerResult.threadId=params.threadId;chatUploadHandlerResult.uniqueId=fileUniqueId;chatUploadHandlerResult.fileObject=params.file;chatUploadHandlerResult.originalFileName=fileName;callbacks&&callbacks(chatUploadHandlerResult,metadata,fileType,fileExtension);}else{_events.chatEvents.fireEvent('error',{code:6302,message:CHAT_ERRORS[6302]});}return{uniqueId:fileUniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:{caption:params.content,file:{uniqueId:fileUniqueId,fileName:fileName,fileSize:fileSize,fileObject:params.file}}};},cancelFileDownload=function cancelFileDownload(params,callback){if(params){if(typeof params.uniqueId=='string'){var uniqueId=params.uniqueId;httpRequestObject[eval('uniqueId')]&&httpRequestObject[eval('uniqueId')].abort();httpRequestObject[eval('uniqueId')]&&delete httpRequestObject[eval('uniqueId')];callback&&callback(uniqueId);}}},cancelFileUpload=function cancelFileUpload(params,callback){if(params){if(typeof params.uniqueId=='string'){var uniqueId=params.uniqueId;httpRequestObject[eval('uniqueId')]&&httpRequestObject[eval('uniqueId')].abort();httpRequestObject[eval('uniqueId')]&&delete httpRequestObject[eval('uniqueId')];deleteFromChatUploadQueue({message:{uniqueId:uniqueId}},callback);}}},cancelMessage=function cancelMessage(uniqueId,callback){deleteFromChatSentQueue({message:{uniqueId:uniqueId}},function(){deleteFromChatWaitQueue({uniqueId:uniqueId},callback);});},mapReverse=function mapReverse(params,callback){var data={};if(params){if(parseFloat(params.lat)>0){data.lat=params.lat;}if(parseFloat(params.lng)>0){data.lng=params.lng;}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.REVERSE,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapSearch=function mapSearch(params,callback){var data={};if(params){if(typeof params.term==='string'){data.term=params.term;}if(parseFloat(params.lat)>0){data.lat=params.lat;}if(parseFloat(params.lng)>0){data.lng=params.lng;}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.SEARCH,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapRouting=function mapRouting(params,callback){var data={};if(params){if(typeof params.alternative==='boolean'){data.alternative=params.alternative;}else{data.alternative=true;}if((0,_typeof2["default"])(params.origin)==='object'){if(parseFloat(params.origin.lat)>0&&parseFloat(params.origin.lng)){data.origin=params.origin.lat+','+parseFloat(params.origin.lng);}else{consoleLogging&&console.log('No origin has been selected!');}}if((0,_typeof2["default"])(params.destination)==='object'){if(parseFloat(params.destination.lat)>0&&parseFloat(params.destination.lng)){data.destination=params.destination.lat+','+parseFloat(params.destination.lng);}else{consoleLogging&&console.log('No destination has been selected!');}}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.ROUTING,method:'GET',data:data,headers:{'Api-Key':mapApiKey}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:result.hasError,cache:result.cache,errorMessage:result.message,errorCode:result.errorCode,result:responseData};callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});},mapStaticImage=function mapStaticImage(params,callback){var data={},url=SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.STATIC_IMAGE,hasError=false;if(params){if(typeof params.type==='string'){data.type=params.type;}else{data.type='standard-night';}if(parseInt(params.zoom)>0){data.zoom=params.zoom;}else{data.zoom=15;}if(parseInt(params.width)>0){data.width=params.width;}else{data.width=800;}if(parseInt(params.height)>0){data.height=params.height;}else{data.height=600;}if((0,_typeof2["default"])(params.center)==='object'){if(parseFloat(params.center.lat)>0&&parseFloat(params.center.lng)){data.center=params.center.lat+','+parseFloat(params.center.lng);}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}data.key=mapApiKey;}var keys=Object.keys(data);if(keys.length>0){url+='?';for(var i=0;i<keys.length;i++){var key=keys[i];url+=key+'='+data[key];if(i<keys.length-1){url+='&';}}}var returnData={hasError:hasError,cache:false,errorMessage:hasError?CHAT_ERRORS[6700]:'',errorCode:hasError?6700:undefined,result:{link:!hasError?url:''}};callback&&callback(returnData);},//TODO Change Node Version
1819
1819
  getImageFormUrl=function getImageFormUrl(url,uniqueId,callback){getImageFromLinkObjects[uniqueId]=new Image();getImageFromLinkObjects[uniqueId].setAttribute('crossOrigin','anonymous');getImageFromLinkObjects[uniqueId].onload=function(){var canvas=document.createElement("canvas");canvas.width=this.width;canvas.height=this.height;var ctx=canvas.getContext("2d");ctx.drawImage(this,0,0);var dataURI=canvas.toDataURL("image/jpg");var byteString;if(dataURI.split(',')[0].indexOf('base64')>=0)byteString=atob(dataURI.split(',')[1]);else byteString=unescape(dataURI.split(',')[1]);var mimeString=dataURI.split(',')[0].split(':')[1].split(';')[0];var ia=new Uint8Array(byteString.length);for(var i=0;i<byteString.length;i++){ia[i]=byteString.charCodeAt(i);}delete getImageFromLinkObjects[uniqueId];return callback(new Blob([ia],{type:mimeString}));};getImageFromLinkObjects[uniqueId].src=url;};/******************************************************
1820
1820
  * P U B L I C M E T H O D S *
1821
- ******************************************************/var publicized={};publicized.on=_events.chatEvents.on;publicized.off=_events.chatEvents.off;publicized.getPeerId=function(){return peerId;};publicized.getCurrentUser=function(){return chatMessaging.userInfo;};publicized.getUserInfo=function(callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.USER_INFO,typeCode:generalTypeCode},{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result;var currentUser=formatDataToMakeUser(messageContent);returnData.result={user:currentUser};callback&&callback(returnData);}}});};publicized.getThreads=getThreads;publicized.getAllThreads=getAllThreads;publicized.getHistory=getHistory;publicized.getAllMentionedMessages=function(params,callback){return getHistory({threadId:params.threadId,allMentioned:true,typeCode:generalTypeCode,//params.typeCode,
1822
- count:params.count||50,offset:params.offset||0,cache:false,queues:{uploading:false,sending:false}},callback);};publicized.getUnreadMentionedMessages=function(params,callback){return getHistory({threadId:params.threadId,unreadMentioned:true,typeCode:generalTypeCode,//params.typeCode,
1823
- count:params.count||50,offset:params.offset||0,cache:false,queues:{uploading:false,sending:false}},callback);};publicized.getAllUnreadMessagesCount=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.ALL_UNREAD_MESSAGE_COUNT,typeCode:generalTypeCode,//params.typeCode,
1821
+ ******************************************************/var publicized={};publicized.on=_events.chatEvents.on;publicized.off=_events.chatEvents.off;publicized.getPeerId=function(){return peerId;};publicized.getCurrentUser=function(){return chatMessaging.userInfo;};publicized.getUserInfo=function(callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.USER_INFO,typeCode:generalTypeCode},{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result;var currentUser=formatDataToMakeUser(messageContent);returnData.result={user:currentUser};callback&&callback(returnData);}}});};publicized.getThreads=getThreads;publicized.getAllThreads=getAllThreads;publicized.getHistory=getHistory;publicized.getAllMentionedMessages=function(params,callback){return getHistory({threadId:params.threadId,allMentioned:true,typeCode:generalTypeCode,//params.typeCode,
1822
+ count:params.count||50,offset:params.offset||0,cache:false,queues:{uploading:false,sending:false}},callback);};publicized.getUnreadMentionedMessages=function(params,callback){return getHistory({threadId:params.threadId,unreadMentioned:true,typeCode:generalTypeCode,//params.typeCode,
1823
+ count:params.count||50,offset:params.offset||0,cache:false,queues:{uploading:false,sending:false}},callback);};publicized.getAllUnreadMessagesCount=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.ALL_UNREAD_MESSAGE_COUNT,typeCode:generalTypeCode,//params.typeCode,
1824
1824
  content:JSON.stringify({'mute':typeof params.countMuteThreads==='boolean'?params.countMuteThreads:false}),pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};/**
1825
1825
  * Get Contacts
1826
1826
  *
@@ -1833,7 +1833,7 @@ content:JSON.stringify({'mute':typeof params.countMuteThreads==='boolean'?params
1833
1833
  * @param {string} query Search in contacts list to get (search LIKE firstName, lastName, email)
1834
1834
  *
1835
1835
  * @return {object} Instant Response
1836
- */publicized.getContacts=function(params,callback){var count=50,offset=0,content={},whereClause={},returnCache=false;if(params){if(parseInt(params.count)>0){count=parseInt(params.count);}if(parseInt(params.offset)>0){offset=parseInt(params.offset);}if(typeof params.query==='string'){content.query=whereClause.query=params.query;}if(typeof params.email==='string'){content.email=whereClause.email=params.email;}if(typeof params.cellphoneNumber==='string'){content.cellphoneNumber=whereClause.cellphoneNumber=params.cellphoneNumber;}if(parseInt(params.contactId)>0){content.id=whereClause.id=params.contactId;}if(typeof params.uniqueId==='string'){content.uniqueId=whereClause.uniqueId=params.uniqueId;}if(typeof params.username==='string'){content.username=params.username;}if(typeof params.coreUserId!=="undefined"){content.coreUserId=params.coreUserId;}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;}content.size=count;content.offset=offset;var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_CONTACTS,typeCode:generalTypeCode,//params.typeCode,
1836
+ */publicized.getContacts=function(params,callback){var count=50,offset=0,content={},whereClause={},returnCache=false;if(params){if(parseInt(params.count)>0){count=parseInt(params.count);}if(parseInt(params.offset)>0){offset=parseInt(params.offset);}if(typeof params.query==='string'){content.query=whereClause.query=params.query;}if(typeof params.email==='string'){content.email=whereClause.email=params.email;}if(typeof params.cellphoneNumber==='string'){content.cellphoneNumber=whereClause.cellphoneNumber=params.cellphoneNumber;}if(parseInt(params.contactId)>0){content.id=whereClause.id=params.contactId;}if(typeof params.uniqueId==='string'){content.uniqueId=whereClause.uniqueId=params.uniqueId;}if(typeof params.username==='string'){content.username=params.username;}if(typeof params.coreUserId!=="undefined"){content.coreUserId=params.coreUserId;}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;}content.size=count;content.offset=offset;var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.GET_CONTACTS,typeCode:generalTypeCode,//params.typeCode,
1837
1837
  content:content};/**
1838
1838
  * Retrieve contacts from cache #cache
1839
1839
  */if(functionLevelCache&&canUseCache&&cacheSecret.length>0){if(db){/**
@@ -1865,19 +1865,19 @@ content:content};/**
1865
1865
  * - subjectId {int}
1866
1866
  * + content {list} List of CONTACT IDs or inviteeVO Objects
1867
1867
  * - uniqueId {string}
1868
- */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.ADD_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
1868
+ */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.ADD_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
1869
1869
  content:[]};if(params){if(parseInt(params.threadId)>0){sendMessageParams.subjectId=params.threadId;}if(Array.isArray(params.contactIds)){sendMessageParams.content=params.contactIds;}if(Array.isArray(params.usernames)){sendMessageParams.content=[];for(var i=0;i<params.usernames.length;i++){sendMessageParams.content.push({id:params.usernames[i],idType:_constants.inviteeVOidTypes.TO_BE_USER_USERNAME});}}if(Array.isArray(params.coreUserids)){sendMessageParams.content=[];for(var i=0;i<params.coreUserids.length;i++){sendMessageParams.content.push({id:params.coreUserids[i],idType:_constants.inviteeVOidTypes.TO_BE_CORE_USER_ID});}}}return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.removeParticipants=function(params,callback){/**
1870
1870
  * + RemoveParticipantsRequest {object}
1871
1871
  * - subjectId {int}
1872
1872
  * + content {list} List of PARTICIPANT IDs from Thread's Participants object
1873
1873
  * -id {int}
1874
1874
  * - uniqueId {string}
1875
- */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_PARTICIPANT,typeCode:generalTypeCode//params.typeCode
1875
+ */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_PARTICIPANT,typeCode:generalTypeCode//params.typeCode
1876
1876
  };if(params){if(parseInt(params.threadId)>0){sendMessageParams.subjectId=params.threadId;}if(Array.isArray(params.participantIds)){sendMessageParams.content=params.participantIds;}}return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.getCurrentUserRoles=getCurrentUserRoles;publicized.leaveThread=function(params,callback){/**
1877
1877
  * + LeaveThreadRequest {object}
1878
1878
  * - subjectId {int}
1879
1879
  * - uniqueId {string}
1880
- */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.LEAVE_THREAD,typeCode:generalTypeCode//params.typeCode
1880
+ */var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.LEAVE_THREAD,typeCode:generalTypeCode//params.typeCode
1881
1881
  };if(params){if(parseInt(params.threadId)>0){sendMessageParams.subjectId=params.threadId;}if(typeof params.clearHistory==='boolean'){sendMessageParams.content={clearHistory:params.clearHistory};}else{sendMessageParams.content={clearHistory:true};}}return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.createThread=function(params,callback){/**
1882
1882
  * + CreateThreadRequest {object}
1883
1883
  * + invitees {object}
@@ -1898,10 +1898,10 @@ content:[]};if(params){if(parseInt(params.threadId)>0){sendMessageParams.subject
1898
1898
  * -systemMetadata {string}
1899
1899
  * -forwardedMessageIds {string}
1900
1900
  * -forwardedUniqueIds {string}
1901
- */var content={};if(params){if(typeof params.title==='string'){content.title=params.title;}if(typeof params.type==='string'){var threadType=params.type;content.type=_constants.createThreadTypes[threadType];}if(typeof params.uniqueName==='string'){content.uniqueName=params.uniqueName;}if(Array.isArray(params.invitees)){content.invitees=[];for(var i=0;i<params.invitees.length;i++){var tempInvitee=formatDataToMakeInvitee(params.invitees[i]);if(tempInvitee){content.invitees.push(tempInvitee);}}}if(typeof params.image==='string'){content.image=params.image;}if(typeof params.description==='string'){content.description=params.description;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}if((0,_typeof2["default"])(params.message)=='object'){content.message={};if(typeof params.message.text==='string'){content.message.text=params.message.text;}if(typeof params.message.uniqueId==='string'){content.message.uniqueId=params.message.uniqueId;}if(params.message.type>0){content.message.messageType=params.message.type;}if(params.message.repliedTo>0){content.message.repliedTo=params.message.repliedTo;}if(typeof params.message.metadata==='string'){content.message.metadata=params.message.metadata;}else if((0,_typeof2["default"])(params.message.metadata)==='object'){content.message.metadata=JSON.stringify(params.message.metadata);}if(typeof params.message.systemMetadata==='string'){content.message.systemMetadata=params.message.systemMetadata;}else if((0,_typeof2["default"])(params.message.systemMetadata)==='object'){content.message.systemMetadata=JSON.stringify(params.message.systemMetadata);}if(Array.isArray(params.message.forwardedMessageIds)){content.message.forwardedMessageIds=params.message.forwardedMessageIds;content.message.forwardedUniqueIds=[];for(var i=0;i<params.message.forwardedMessageIds.length;i++){content.message.forwardedUniqueIds.push(_utility["default"].generateUUID());}}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1902
- content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.createSelfThread=function(params,callback){var content={type:_constants.createThreadTypes['SELF']};if(params){if(typeof params.description==='string'){content.description=params.description;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}if((0,_typeof2["default"])(params.message)=='object'){content.message={};if(typeof params.message.text==='string'){content.message.text=params.message.text;}if(typeof params.message.uniqueId==='string'){content.message.uniqueId=params.message.uniqueId;}if(params.message.type>0){content.message.messageType=params.message.type;}if(params.message.repliedTo>0){content.message.repliedTo=params.message.repliedTo;}if(typeof params.message.metadata==='string'){content.message.metadata=params.message.metadata;}else if((0,_typeof2["default"])(params.message.metadata)==='object'){content.message.metadata=JSON.stringify(params.message.metadata);}if(typeof params.message.systemMetadata==='string'){content.message.systemMetadata=params.message.systemMetadata;}else if((0,_typeof2["default"])(params.message.systemMetadata)==='object'){content.message.systemMetadata=JSON.stringify(params.message.systemMetadata);}if(Array.isArray(params.message.forwardedMessageIds)){content.message.forwardedMessageIds=params.message.forwardedMessageIds;content.message.forwardedUniqueIds=[];for(var i=0;i<params.message.forwardedMessageIds.length;i++){content.message.forwardedUniqueIds.push(_utility["default"].generateUUID());}}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1903
- content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.sendTextMessage=function(params,callbacks){var metadata={},uniqueId;if(typeof params.uniqueId!=='undefined'){uniqueId=params.uniqueId;}else{uniqueId=_utility["default"].generateUUID();}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1904
- messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:_constants.chatMessageTypes.TEXT,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.textMessage,uniqueId:uniqueId,systemMetadata:JSON.stringify(params.systemMetadata),metadata:JSON.stringify(metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();});return{uniqueId:uniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:params.content};};publicized.sendBotMessage=function(params,callbacks){var metadata={};return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.BOT_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1901
+ */var content={};if(params){if(typeof params.title==='string'){content.title=params.title;}if(typeof params.type==='string'){var threadType=params.type;content.type=_constants.createThreadTypes[threadType];}if(typeof params.uniqueName==='string'){content.uniqueName=params.uniqueName;}if(Array.isArray(params.invitees)){content.invitees=[];for(var i=0;i<params.invitees.length;i++){var tempInvitee=formatDataToMakeInvitee(params.invitees[i]);if(tempInvitee){content.invitees.push(tempInvitee);}}}if(typeof params.image==='string'){content.image=params.image;}if(typeof params.description==='string'){content.description=params.description;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}if((0,_typeof2["default"])(params.message)=='object'){content.message={};if(typeof params.message.text==='string'){content.message.text=params.message.text;}if(typeof params.message.uniqueId==='string'){content.message.uniqueId=params.message.uniqueId;}if(params.message.type>0){content.message.messageType=params.message.type;}if(params.message.repliedTo>0){content.message.repliedTo=params.message.repliedTo;}if(typeof params.message.metadata==='string'){content.message.metadata=params.message.metadata;}else if((0,_typeof2["default"])(params.message.metadata)==='object'){content.message.metadata=JSON.stringify(params.message.metadata);}if(typeof params.message.systemMetadata==='string'){content.message.systemMetadata=params.message.systemMetadata;}else if((0,_typeof2["default"])(params.message.systemMetadata)==='object'){content.message.systemMetadata=JSON.stringify(params.message.systemMetadata);}if(Array.isArray(params.message.forwardedMessageIds)){content.message.forwardedMessageIds=params.message.forwardedMessageIds;content.message.forwardedUniqueIds=[];for(var i=0;i<params.message.forwardedMessageIds.length;i++){content.message.forwardedUniqueIds.push(_utility["default"].generateUUID());}}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1902
+ content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.createSelfThread=function(params,callback){var content={type:_constants.createThreadTypes['SELF']};if(params){if(typeof params.description==='string'){content.description=params.description;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}if((0,_typeof2["default"])(params.message)=='object'){content.message={};if(typeof params.message.text==='string'){content.message.text=params.message.text;}if(typeof params.message.uniqueId==='string'){content.message.uniqueId=params.message.uniqueId;}if(params.message.type>0){content.message.messageType=params.message.type;}if(params.message.repliedTo>0){content.message.repliedTo=params.message.repliedTo;}if(typeof params.message.metadata==='string'){content.message.metadata=params.message.metadata;}else if((0,_typeof2["default"])(params.message.metadata)==='object'){content.message.metadata=JSON.stringify(params.message.metadata);}if(typeof params.message.systemMetadata==='string'){content.message.systemMetadata=params.message.systemMetadata;}else if((0,_typeof2["default"])(params.message.systemMetadata)==='object'){content.message.systemMetadata=JSON.stringify(params.message.systemMetadata);}if(Array.isArray(params.message.forwardedMessageIds)){content.message.forwardedMessageIds=params.message.forwardedMessageIds;content.message.forwardedUniqueIds=[];for(var i=0;i<params.message.forwardedMessageIds.length;i++){content.message.forwardedUniqueIds.push(_utility["default"].generateUUID());}}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1903
+ content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}callback&&callback(returnData);}});};publicized.sendTextMessage=function(params,callbacks){var metadata={},uniqueId;if(typeof params.uniqueId!=='undefined'){uniqueId=params.uniqueId;}else{uniqueId=_utility["default"].generateUUID();}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1904
+ messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:_constants.chatMessageTypes.TEXT,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.textMessage,uniqueId:uniqueId,systemMetadata:JSON.stringify(params.systemMetadata),metadata:JSON.stringify(metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();});return{uniqueId:uniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:params.content};};publicized.sendBotMessage=function(params,callbacks){var metadata={};return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.BOT_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1905
1905
  subjectId:params.messageId,content:params.content,uniqueId:params.uniqueId,metadata:metadata,pushMsgType:3},callbacks);};publicized.sendFileMessage=sendFileMessage;publicized.createThreadWithFileMessage=function(params,createThreadCallback,sendFileMessageCallback){/**
1906
1906
  * + CreateThreadRequest {object}
1907
1907
  * + invitees {object}
@@ -1922,62 +1922,62 @@ subjectId:params.messageId,content:params.content,uniqueId:params.uniqueId,metad
1922
1922
  * -systemMetadata {string}
1923
1923
  * -forwardedMessageIds {string}
1924
1924
  * -forwardedUniqueIds {string}
1925
- */var content={};if(params){if(typeof params.title==='string'){content.title=params.title;}if(typeof params.type==='string'){var threadType=params.type;content.type=_constants.createThreadTypes[threadType];}if(Array.isArray(params.invitees)){content.invitees=[];for(var i=0;i<params.invitees.length;i++){var tempInvitee=formatDataToMakeInvitee(params.invitees[i]);if(tempInvitee){content.invitees.push(tempInvitee);}}}if(typeof params.description==='string'){content.description=params.description;}if(typeof params.content==='string'){content.content=params.content;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1926
- content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}createThreadCallback&&createThreadCallback(returnData);sendFileMessage({threadId:returnData.result.thread.id,file:params.file,content:params.caption,messageType:params.messageType,userGroupHash:returnData.result.thread.userGroupHash},sendFileMessageCallback);}});};publicized.sendLocationMessage=function(params,callbacks){var data={},url=SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.STATIC_IMAGE,hasError=false,fileUniqueId=_utility["default"].generateUUID();if(params){if(typeof params.mapType==='string'){data.type=params.mapType;}else{data.type='standard-night';}if(parseInt(params.mapZoom)>0){data.zoom=params.mapZoom;}else{data.zoom=15;}if(parseInt(params.mapWidth)>0){data.width=params.mapWidth;}else{data.width=800;}if(parseInt(params.mapHeight)>0){data.height=params.mapHeight;}else{data.height=600;}if((0,_typeof2["default"])(params.mapCenter)==='object'){if(parseFloat(params.mapCenter.lat)>0&&parseFloat(params.mapCenter.lng)){data.center=params.mapCenter.lat+','+parseFloat(params.mapCenter.lng);}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}data.key=mapApiKey;data.marker='red';}var keys=Object.keys(data);if(keys.length>0){url+='?';for(var i=0;i<keys.length;i++){var key=keys[i];url+=key+'='+data[key];if(i<keys.length-1){url+='&';}}}if(!hasError){mapReverse({lng:parseFloat(params.mapCenter.lng),lat:parseFloat(params.mapCenter.lat)},function(address){getImageFormUrl(url,fileUniqueId,function(blobImage){sendFileMessage({threadId:params.threadId,fileUniqueId:fileUniqueId,file:new File([blobImage],"location.png",{type:"image/png",lastModified:new Date()}),content:address.result.formatted_address,messageType:'POD_SPACE_PICTURE',userGroupHash:params.userGroupHash,metadata:{mapLink:"https://maps.neshan.org/@".concat(data.center,",").concat(data.zoom,"z"),address:address}},callbacks);});});}return{uniqueId:fileUniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,cancel:function cancel(){if(typeof getImageFromLinkObjects!=='undefined'&&getImageFromLinkObjects.hasOwnProperty(fileUniqueId)){getImageFromLinkObjects[fileUniqueId].onload=function(){};delete getImageFromLinkObjects[fileUniqueId];consoleLogging&&console.log("\"".concat(fileUniqueId,"\" - Downloading Location Map has been canceled!"));}cancelFileUpload({uniqueId:fileUniqueId},function(){consoleLogging&&console.log("\"".concat(fileUniqueId,"\" - Sending Location Message has been canceled!"));});}};};publicized.resendMessage=function(uniqueId,callbacks){if(hasCache&&(0,_typeof2["default"])(queueDb)=='object'&&!forceWaitQueueInMemory){queueDb.waitQ.where('uniqueId').equals(uniqueId).and(function(item){return item.owner===parseInt(chatMessaging.userInfo.id);}).toArray().then(function(messages){if(messages.length){putInChatSendQueue({message:_utility["default"].jsonParser(chatDecrypt(messages[0].message,cacheSecret)),callbacks:callbacks},function(){chatSendQueueHandler();});}})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{for(var i=0;i<chatWaitQueue.length;i++){if(chatWaitQueue[i].uniqueId===uniqueId){putInChatSendQueue({message:chatWaitQueue[i],callbacks:callbacks},function(){chatSendQueueHandler();},true);// break;
1925
+ */var content={};if(params){if(typeof params.title==='string'){content.title=params.title;}if(typeof params.type==='string'){var threadType=params.type;content.type=_constants.createThreadTypes[threadType];}if(Array.isArray(params.invitees)){content.invitees=[];for(var i=0;i<params.invitees.length;i++){var tempInvitee=formatDataToMakeInvitee(params.invitees[i]);if(tempInvitee){content.invitees.push(tempInvitee);}}}if(typeof params.description==='string'){content.description=params.description;}if(typeof params.content==='string'){content.content=params.content;}if(typeof params.metadata==='string'){content.metadata=params.metadata;}else if((0,_typeof2["default"])(params.metadata)==='object'){try{content.metadata=JSON.stringify(params.metadata);}catch(e){consoleLogging&&console.log(e);}}}var sendMessageParams={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1926
+ content:content};return chatMessaging.sendMessage(sendMessageParams,{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={thread:createThread(messageContent)};}createThreadCallback&&createThreadCallback(returnData);sendFileMessage({threadId:returnData.result.thread.id,file:params.file,content:params.caption,messageType:params.messageType,userGroupHash:returnData.result.thread.userGroupHash},sendFileMessageCallback);}});};publicized.sendLocationMessage=function(params,callbacks){var data={},url=SERVICE_ADDRESSES.MAP_ADDRESS+SERVICES_PATH.STATIC_IMAGE,hasError=false,fileUniqueId=_utility["default"].generateUUID();if(params){if(typeof params.mapType==='string'){data.type=params.mapType;}else{data.type='standard-night';}if(parseInt(params.mapZoom)>0){data.zoom=params.mapZoom;}else{data.zoom=15;}if(parseInt(params.mapWidth)>0){data.width=params.mapWidth;}else{data.width=800;}if(parseInt(params.mapHeight)>0){data.height=params.mapHeight;}else{data.height=600;}if((0,_typeof2["default"])(params.mapCenter)==='object'){if(parseFloat(params.mapCenter.lat)>0&&parseFloat(params.mapCenter.lng)){data.center=params.mapCenter.lat+','+parseFloat(params.mapCenter.lng);}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}}else{hasError=true;_events.chatEvents.fireEvent('error',{code:6700,message:CHAT_ERRORS[6700],error:undefined});}data.key=mapApiKey;data.marker='red';}var keys=Object.keys(data);if(keys.length>0){url+='?';for(var i=0;i<keys.length;i++){var key=keys[i];url+=key+'='+data[key];if(i<keys.length-1){url+='&';}}}if(!hasError){mapReverse({lng:parseFloat(params.mapCenter.lng),lat:parseFloat(params.mapCenter.lat)},function(address){getImageFormUrl(url,fileUniqueId,function(blobImage){sendFileMessage({threadId:params.threadId,fileUniqueId:fileUniqueId,file:new File([blobImage],"location.png",{type:"image/png",lastModified:new Date()}),content:address.result.formatted_address,messageType:'POD_SPACE_PICTURE',userGroupHash:params.userGroupHash,metadata:{mapLink:"https://maps.neshan.org/@".concat(data.center,",").concat(data.zoom,"z"),address:address}},callbacks);});});}return{uniqueId:fileUniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,cancel:function cancel(){if(typeof getImageFromLinkObjects!=='undefined'&&getImageFromLinkObjects.hasOwnProperty(fileUniqueId)){getImageFromLinkObjects[fileUniqueId].onload=function(){};delete getImageFromLinkObjects[fileUniqueId];consoleLogging&&console.log("\"".concat(fileUniqueId,"\" - Downloading Location Map has been canceled!"));}cancelFileUpload({uniqueId:fileUniqueId},function(){consoleLogging&&console.log("\"".concat(fileUniqueId,"\" - Sending Location Message has been canceled!"));});}};};publicized.resendMessage=function(uniqueId,callbacks){if(hasCache&&(0,_typeof2["default"])(queueDb)=='object'&&!forceWaitQueueInMemory){queueDb.waitQ.where('uniqueId').equals(uniqueId).and(function(item){return item.owner===parseInt(chatMessaging.userInfo.id);}).toArray().then(function(messages){if(messages.length){putInChatSendQueue({message:_utility["default"].jsonParser(chatDecrypt(messages[0].message,cacheSecret)),callbacks:callbacks},function(){chatSendQueueHandler();});}})["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{for(var i=0;i<chatWaitQueue.length;i++){if(chatWaitQueue[i].uniqueId===uniqueId){putInChatSendQueue({message:chatWaitQueue[i],callbacks:callbacks},function(){chatSendQueueHandler();},true);// break;
1927
1927
  }}}};publicized.cancelMessage=cancelMessage;publicized.clearHistory=function(params,callback){/**
1928
1928
  * + Clear History Request Object {object}
1929
1929
  * - subjectId {int}
1930
- */var clearHistoryParams={chatMessageVOType:_constants.chatMessageVOTypes.CLEAR_HISTORY,typeCode:generalTypeCode//params.typeCode
1930
+ */var clearHistoryParams={chatMessageVOType:_constants.chatMessageVOTypes.CLEAR_HISTORY,typeCode:generalTypeCode//params.typeCode
1931
1931
  };if(params){if(parseInt(params.threadId)>0){clearHistoryParams.subjectId=params.threadId;}}return chatMessaging.sendMessage(clearHistoryParams,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){returnData.result={thread:result.result};/**
1932
1932
  * Delete all messages of this thread from cache
1933
- */if(canUseCache){if(db){db.messages.where('threadId').equals(parseInt(result.result)).and(function(message){return message.owner===chatMessaging.userInfo.id;})["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}});};publicized.getImage=getImage;publicized.getFile=getFile;publicized.getFileFromPodspace=getFileFromPodspaceNew;//getFileFromPodspace;
1934
- publicized.getImageFromPodspace=getImageFromPodspaceNew;//getImageFromPodspace;
1935
- publicized.uploadFile=uploadFile;publicized.uploadImage=uploadImage;publicized.uploadFileToPodspace=uploadFileToPodspaceNew;publicized.uploadImageToPodspace=uploadImageToPodspaceNew;publicized.cancelFileUpload=cancelFileUpload;publicized.cancelFileDownload=cancelFileDownload;publicized.editMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.EDIT_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1933
+ */if(canUseCache){if(db){db.messages.where('threadId').equals(parseInt(result.result)).and(function(message){return message.owner===chatMessaging.userInfo.id;})["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}});};publicized.getImage=getImage;publicized.getFile=getFile;publicized.getFileFromPodspace=getFileFromPodspaceNew;//getFileFromPodspace;
1934
+ publicized.getImageFromPodspace=getImageFromPodspaceNew;//getImageFromPodspace;
1935
+ publicized.uploadFile=uploadFile;publicized.uploadImage=uploadImage;publicized.uploadFileToPodspace=uploadFileToPodspaceNew;publicized.uploadImageToPodspace=uploadImageToPodspaceNew;publicized.cancelFileUpload=cancelFileUpload;publicized.cancelFileDownload=cancelFileDownload;publicized.editMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.EDIT_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1936
1936
  messageType:params.messageType,subjectId:params.messageId,repliedTo:params.repliedTo,content:params.content,uniqueId:params.uniqueId,metadata:params.metadata,systemMetadata:params.systemMetadata,pushMsgType:3},{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){var messageContent=result.result,resultData={editedMessage:formatDataToMakeMessage(undefined,messageContent)};returnData.result=resultData;/**
1937
1937
  * Update Message on cache
1938
1938
  */if(canUseCache&&cacheSecret.length>0){if(db){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=parseInt(resultData.editedMessage.id);tempData.owner=parseInt(chatMessaging.userInfo.id);tempData.threadId=parseInt(resultData.editedMessage.threadId);tempData.time=resultData.editedMessage.time;tempData.message=_utility["default"].crypt(resultData.editedMessage.message,cacheSecret,salt);tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.editedMessage)),cacheSecret,salt);tempData.salt=salt;/**
1939
1939
  * Insert Message into cache database
1940
- */db.messages.put(tempData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}});};publicized.deleteMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1940
+ */db.messages.put(tempData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}});};publicized.deleteMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1941
1941
  subjectId:params.messageId,uniqueId:params.uniqueId,content:JSON.stringify({'deleteForAll':typeof params.deleteForAll==='boolean'?params.deleteForAll:false}),pushMsgType:3},{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){returnData.result={deletedMessage:{id:result.result.id,pinned:result.result.pinned,mentioned:result.result.mentioned,messageType:result.result.messageType,edited:result.result.edited,editable:result.result.editable,deletable:result.result.deletable}};/**
1942
1942
  * Remove Message from cache
1943
1943
  */if(canUseCache){if(db){db.messages.where('id').equals(parseInt(result.result))["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}});};publicized.deleteMultipleMessages=function(params,callback){var messageIdsList=params.messageIds,uniqueIdsList=[];for(var i in messageIdsList){var uniqueId=_utility["default"].generateUUID();uniqueIdsList.push(uniqueId);chatMessaging.messagesCallbacks[uniqueId]=function(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){returnData.result={deletedMessage:{id:result.result.id,pinned:result.result.pinned,mentioned:result.result.mentioned,messageType:result.result.messageType,edited:result.result.edited,editable:result.result.editable,deletable:result.result.deletable}};/**
1944
1944
  * Remove Message from cache
1945
- */if(canUseCache){if(db){db.messages.where('id').equals(parseInt(result.result))["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);};}return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1946
- content:{uniqueIds:uniqueIdsList,ids:messageIdsList,deleteForAll:typeof params.deleteForAll==='boolean'?params.deleteForAll:false},pushMsgType:3});};publicized.replyTextMessage=function(params,callbacks){var uniqueId;if(typeof params.uniqueId!=='undefined'){uniqueId=params.uniqueId;}else{uniqueId=_utility["default"].generateUUID();}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1947
- messageType:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.textMessage,uniqueId:uniqueId,systemMetadata:JSON.stringify(params.systemMetadata),metadata:JSON.stringify(params.metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();});return{uniqueId:uniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:params.content};};publicized.replyFileMessage=function(params,callbacks){var metadata={file:{}},fileUploadParams={},fileUniqueId=_utility["default"].generateUUID();if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}return chatUploadHandler({threadId:params.threadId,file:params.file,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1948
- messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.content,metadata:JSON.stringify(uploadHandlerMetadata),systemMetadata:JSON.stringify(params.systemMetadata),uniqueId:fileUniqueId,pushMsgType:3},callbacks:callbacks},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['name']=result.result.name;metadata['fileHash']=result.result.hash;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['actualHeight']=result.result.actualHeight;metadata['file']['actualWidth']=result.result.actualWidth;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;metadata['file']['link']="".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true");transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}else{uploadFileToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['fileHash']=result.result.hash;metadata['name']=result.result.name;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}});});};publicized.forwardMessage=function(params,callbacks){var threadId=params.threadId,messageIdsList=params.messageIds,uniqueIdsList=[];for(var i in messageIdsList){if(!chatMessaging.threadCallbacks[threadId]){chatMessaging.threadCallbacks[threadId]={};}var uniqueId=_utility["default"].generateUUID();uniqueIdsList.push(uniqueId);chatMessaging.threadCallbacks[threadId][uniqueId]={};chatMessaging.sendMessageCallbacks[uniqueId]={};if(callbacks.onSent){chatMessaging.sendMessageCallbacks[uniqueId].onSent=callbacks.onSent;chatMessaging.threadCallbacks[threadId][uniqueId].onSent=false;chatMessaging.threadCallbacks[threadId][uniqueId].uniqueId=uniqueId;}if(callbacks.onSeen){chatMessaging.sendMessageCallbacks[uniqueId].onSeen=callbacks.onSeen;chatMessaging.threadCallbacks[threadId][uniqueId].onSeen=false;}if(callbacks.onDeliver){chatMessaging.sendMessageCallbacks[uniqueId].onDeliver=callbacks.onDeliver;chatMessaging.threadCallbacks[threadId][uniqueId].onDeliver=false;}}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.FORWARD_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1949
- subjectId:params.threadId,repliedTo:params.repliedTo,content:messageIdsList,uniqueId:uniqueIdsList,metadata:JSON.stringify(params.metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();},true);};publicized.deliver=function(params){return putInMessagesDeliveryQueue(params.threadId,params.messageId);};publicized.seen=function(params){return putInMessagesSeenQueue(params.threadId,params.messageId);};publicized.startTyping=function(params){var uniqueId=_utility["default"].generateUUID();if(parseInt(params.threadId)>0){var threadId=params.threadId;}isTypingInterval&&clearInterval(isTypingInterval);isTypingInterval=setInterval(function(){sendSystemMessage({content:JSON.stringify({type:_constants.systemMessageTypes.IS_TYPING}),threadId:threadId,uniqueId:uniqueId});},systemMessageIntervalPitch);};publicized.stopTyping=function(){isTypingInterval&&clearInterval(isTypingInterval);};publicized.getMessageDeliveredList=function(params,callback){var deliveryListData={chatMessageVOType:_constants.chatMessageVOTypes.GET_MESSAGE_DELIVERY_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1950
- content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.messageId)>0){deliveryListData.content.messageId=params.messageId;}}return chatMessaging.sendMessage(deliveryListData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){for(var i=0;i<result.result.length;i++){result.result[i]=formatDataToMakeUser(result.result[i]);}}callback&&callback(result);}});};publicized.getMessageSeenList=function(params,callback){var seenListData={chatMessageVOType:_constants.chatMessageVOTypes.GET_MESSAGE_SEEN_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1951
- content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.messageId)>0){seenListData.content.messageId=params.messageId;}}return chatMessaging.sendMessage(seenListData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){for(var i=0;i<result.result.length;i++){result.result[i]=formatDataToMakeUser(result.result[i]);}}callback&&callback(result);}});};publicized.updateThreadInfo=updateThreadInfo;publicized.updateChatProfile=updateChatProfile;publicized.muteThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.MUTE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1952
- subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unMuteThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNMUTE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1953
- subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.closeThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.CLOSE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1954
- subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.joinPublicThread=function(params,callback){var joinThreadData={chatMessageVOType:_constants.chatMessageVOTypes.JOIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1955
- content:'',pushMsgType:3,token:token};if(params){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){joinThreadData.content=params.uniqueName;}}return chatMessaging.sendMessage(joinThreadData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.isPublicThreadNameAvailable=function(params,callback){var isNameAvailableData={chatMessageVOType:_constants.chatMessageVOTypes.IS_NAME_AVAILABLE,typeCode:generalTypeCode,//params.typeCode,
1956
- content:'',pushMsgType:3,token:token};if(params){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){isNameAvailableData.content=params.uniqueName;}}return chatMessaging.sendMessage(isNameAvailableData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.changeThreadPrivacy=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.CHANGE_THREAD_PRIVACY,typeCode:generalTypeCode,//params.typeCode,
1957
- pushMsgType:3,content:{},token:token,timeout:params.timeout};if(params){if(parseInt(params.threadId)>0){sendData.subjectId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Thread Id has been sent!"});return;}if(typeof params.threadType==='string'&&_constants.createThreadTypes.hasOwnProperty(params.threadType.toUpperCase())){if(params.threadType.toUpperCase()==='PUBLIC_GROUP'||params.threadType.toUpperCase()==='PUBLIC_CHANNEL'){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){sendData.content.uniqueName=params.uniqueName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"Public Threads need a unique name! One must enter a unique name for this thread."});return;}}sendData.content.type=_constants.createThreadTypes[params.threadType.toUpperCase()];}else{_events.chatEvents.fireEvent('error',{code:999,message:"No thread type has been declared! Possible inputs are (".concat(Object.keys(_constants.createThreadTypes).join(','),")")});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Change thread Privacy!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.pinThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.PIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1958
- subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unPinThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNPIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1959
- subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.deleteThread=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE_THREAD,typeCode:generalTypeCode//params.typeCode
1960
- };if(params){if(+params.threadId>0){sendData.subjectId=+params.threadId;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Delete Thread!'});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.pinMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.PIN_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1961
- subjectId:params.messageId,content:JSON.stringify({'notifyAll':typeof params.notifyAll==='boolean'?params.notifyAll:false}),pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unPinMessage=unPinMessage;publicized.spamPrivateThread=function(params,callback){var spamData={chatMessageVOType:_constants.chatMessageVOTypes.SPAM_PV_THREAD,typeCode:generalTypeCode,//params.typeCode,
1962
- pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.threadId)>0){spamData.subjectId=params.threadId;}}return chatMessaging.sendMessage(spamData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.block=function(params,callback){var blockData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCK,typeCode:generalTypeCode,//params.typeCode,
1963
- content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.contactId)>0){blockData.content.contactId=params.contactId;}if(parseInt(params.threadId)>0){blockData.content.threadId=params.threadId;}if(parseInt(params.userId)>0){blockData.content.userId=params.userId;}}return chatMessaging.sendMessage(blockData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){result.result=formatDataToMakeBlockedUser(result.result);}callback&&callback(result);}});};publicized.unblock=function(params,callback){var unblockData={chatMessageVOType:_constants.chatMessageVOTypes.UNBLOCK,typeCode:generalTypeCode,//params.typeCode,
1964
- pushMsgType:3,token:token,content:{},timeout:params.timeout};if(params){if(parseInt(params.blockId)>0){unblockData.subjectId=params.blockId;}if(parseInt(params.contactId)>0){unblockData.content.contactId=params.contactId;}if(parseInt(params.threadId)>0){unblockData.content.threadId=params.threadId;}if(parseInt(params.userId)>0){unblockData.content.userId=params.userId;}}return chatMessaging.sendMessage(unblockData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){result.result=formatDataToMakeBlockedUser(result.result);}callback&&callback(result);}});};publicized.getBlockedList=function(params,callback){var count=50,offset=0,content={};if(params){if(parseInt(params.count)>0){count=params.count;}if(parseInt(params.offset)>0){offset=params.offset;}}content.count=count;content.offset=offset;var getBlockedData={chatMessageVOType:_constants.chatMessageVOTypes.GET_BLOCKED,typeCode:generalTypeCode,//params.typeCode,
1965
- content:content,pushMsgType:3,token:token,timeout:params.timeout};return chatMessaging.sendMessage(getBlockedData,{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={blockedUsers:[],contentCount:result.contentCount,hasNext:offset+count<result.contentCount&&messageLength>0,nextOffset:offset*1+messageLength*1},blockedUser;for(var i=0;i<messageLength;i++){blockedUser=formatDataToMakeBlockedUser(messageContent[i]);if(blockedUser){resultData.blockedUsers.push(blockedUser);}}returnData.result=resultData;}callback&&callback(returnData);}});};publicized.getUserNotSeenDuration=function(params,callback){var content={};if(params){if(Array.isArray(params.userIds)){content.userIds=params.userIds;}}var getNotSeenDurationData={chatMessageVOType:_constants.chatMessageVOTypes.GET_NOT_SEEN_DURATION,typeCode:generalTypeCode,//params.typeCode,
1945
+ */if(canUseCache){if(db){db.messages.where('id').equals(parseInt(result.result))["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);};}return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1946
+ content:{uniqueIds:uniqueIdsList,ids:messageIdsList,deleteForAll:typeof params.deleteForAll==='boolean'?params.deleteForAll:false},pushMsgType:3});};publicized.replyTextMessage=function(params,callbacks){var uniqueId;if(typeof params.uniqueId!=='undefined'){uniqueId=params.uniqueId;}else{uniqueId=_utility["default"].generateUUID();}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1947
+ messageType:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.textMessage,uniqueId:uniqueId,systemMetadata:JSON.stringify(params.systemMetadata),metadata:JSON.stringify(params.metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();});return{uniqueId:uniqueId,threadId:params.threadId,participant:chatMessaging.userInfo,content:params.content};};publicized.replyFileMessage=function(params,callbacks){var metadata={file:{}},fileUploadParams={},fileUniqueId=_utility["default"].generateUUID();if(!params.userGroupHash||params.userGroupHash.length===0||typeof params.userGroupHash!=='string'){_events.chatEvents.fireEvent('error',{code:6304,message:CHAT_ERRORS[6304]});return;}else{fileUploadParams.userGroupHash=params.userGroupHash;}return chatUploadHandler({threadId:params.threadId,file:params.file,fileUniqueId:fileUniqueId},function(uploadHandlerResult,uploadHandlerMetadata,fileType,fileExtension){fileUploadParams=Object.assign(fileUploadParams,uploadHandlerResult);putInChatUploadQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1948
+ messageType:params.messageType&&typeof params.messageType.toUpperCase()!=='undefined'&&_constants.chatMessageTypes[params.messageType.toUpperCase()]>0?_constants.chatMessageTypes[params.messageType.toUpperCase()]:1,subjectId:params.threadId,repliedTo:params.repliedTo,content:params.content,metadata:JSON.stringify(uploadHandlerMetadata),systemMetadata:JSON.stringify(params.systemMetadata),uniqueId:fileUniqueId,pushMsgType:3},callbacks:callbacks},function(){if(_constants.imageMimeTypes.indexOf(fileType)>=0||_constants.imageExtentions.indexOf(fileExtension)>=0){uploadImageToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['name']=result.result.name;metadata['fileHash']=result.result.hash;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['actualHeight']=result.result.actualHeight;metadata['file']['actualWidth']=result.result.actualWidth;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;metadata['file']['link']="".concat(SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS,"/api/images/").concat(result.result.hash,"?checkUserGroupAccess=true");transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}else{uploadFileToPodspaceUserGroupNew(fileUploadParams,function(result){if(!result.hasError){metadata['fileHash']=result.result.hash;metadata['name']=result.result.name;metadata['file']['name']=result.result.name;metadata['file']['fileHash']=result.result.hash;metadata['file']['hashCode']=result.result.hash;metadata['file']['parentHash']=result.result.parentHash;metadata['file']['size']=result.result.size;transferFromUploadQToSendQ(parseInt(params.threadId),fileUniqueId,JSON.stringify(metadata),function(){chatSendQueueHandler();});}else{deleteFromChatUploadQueue({message:{uniqueId:fileUniqueId}});}});}});});};publicized.forwardMessage=function(params,callbacks){var threadId=params.threadId,messageIdsList=params.messageIds,uniqueIdsList=[];for(var i in messageIdsList){if(!chatMessaging.threadCallbacks[threadId]){chatMessaging.threadCallbacks[threadId]={};}var uniqueId=_utility["default"].generateUUID();uniqueIdsList.push(uniqueId);chatMessaging.threadCallbacks[threadId][uniqueId]={};chatMessaging.sendMessageCallbacks[uniqueId]={};if(callbacks.onSent){chatMessaging.sendMessageCallbacks[uniqueId].onSent=callbacks.onSent;chatMessaging.threadCallbacks[threadId][uniqueId].onSent=false;chatMessaging.threadCallbacks[threadId][uniqueId].uniqueId=uniqueId;}if(callbacks.onSeen){chatMessaging.sendMessageCallbacks[uniqueId].onSeen=callbacks.onSeen;chatMessaging.threadCallbacks[threadId][uniqueId].onSeen=false;}if(callbacks.onDeliver){chatMessaging.sendMessageCallbacks[uniqueId].onDeliver=callbacks.onDeliver;chatMessaging.threadCallbacks[threadId][uniqueId].onDeliver=false;}}putInChatSendQueue({message:{chatMessageVOType:_constants.chatMessageVOTypes.FORWARD_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1949
+ subjectId:params.threadId,repliedTo:params.repliedTo,content:messageIdsList,uniqueId:uniqueIdsList,metadata:JSON.stringify(params.metadata),pushMsgType:3},callbacks:callbacks},function(){chatSendQueueHandler();},true);};publicized.deliver=function(params){return putInMessagesDeliveryQueue(params.threadId,params.messageId);};publicized.seen=function(params){return putInMessagesSeenQueue(params.threadId,params.messageId);};publicized.startTyping=function(params){var uniqueId=_utility["default"].generateUUID();if(parseInt(params.threadId)>0){var threadId=params.threadId;}isTypingInterval&&clearInterval(isTypingInterval);isTypingInterval=setInterval(function(){sendSystemMessage({content:JSON.stringify({type:_constants.systemMessageTypes.IS_TYPING}),threadId:threadId,uniqueId:uniqueId});},systemMessageIntervalPitch);};publicized.stopTyping=function(){isTypingInterval&&clearInterval(isTypingInterval);};publicized.getMessageDeliveredList=function(params,callback){var deliveryListData={chatMessageVOType:_constants.chatMessageVOTypes.GET_MESSAGE_DELIVERY_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1950
+ content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.messageId)>0){deliveryListData.content.messageId=params.messageId;}}return chatMessaging.sendMessage(deliveryListData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){for(var i=0;i<result.result.length;i++){result.result[i]=formatDataToMakeUser(result.result[i]);}}callback&&callback(result);}});};publicized.getMessageSeenList=function(params,callback){var seenListData={chatMessageVOType:_constants.chatMessageVOTypes.GET_MESSAGE_SEEN_PARTICIPANTS,typeCode:generalTypeCode,//params.typeCode,
1951
+ content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.messageId)>0){seenListData.content.messageId=params.messageId;}}return chatMessaging.sendMessage(seenListData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){for(var i=0;i<result.result.length;i++){result.result[i]=formatDataToMakeUser(result.result[i]);}}callback&&callback(result);}});};publicized.updateThreadInfo=updateThreadInfo;publicized.updateChatProfile=updateChatProfile;publicized.muteThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.MUTE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1952
+ subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unMuteThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNMUTE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1953
+ subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.closeThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.CLOSE_THREAD,typeCode:generalTypeCode,//params.typeCode,
1954
+ subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.joinPublicThread=function(params,callback){var joinThreadData={chatMessageVOType:_constants.chatMessageVOTypes.JOIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1955
+ content:'',pushMsgType:3,token:token};if(params){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){joinThreadData.content=params.uniqueName;}}return chatMessaging.sendMessage(joinThreadData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.isPublicThreadNameAvailable=function(params,callback){var isNameAvailableData={chatMessageVOType:_constants.chatMessageVOTypes.IS_NAME_AVAILABLE,typeCode:generalTypeCode,//params.typeCode,
1956
+ content:'',pushMsgType:3,token:token};if(params){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){isNameAvailableData.content=params.uniqueName;}}return chatMessaging.sendMessage(isNameAvailableData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.changeThreadPrivacy=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.CHANGE_THREAD_PRIVACY,typeCode:generalTypeCode,//params.typeCode,
1957
+ pushMsgType:3,content:{},token:token,timeout:params.timeout};if(params){if(parseInt(params.threadId)>0){sendData.subjectId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Thread Id has been sent!"});return;}if(typeof params.threadType==='string'&&_constants.createThreadTypes.hasOwnProperty(params.threadType.toUpperCase())){if(params.threadType.toUpperCase()==='PUBLIC_GROUP'||params.threadType.toUpperCase()==='PUBLIC_CHANNEL'){if(typeof params.uniqueName==='string'&&params.uniqueName.length>0){sendData.content.uniqueName=params.uniqueName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"Public Threads need a unique name! One must enter a unique name for this thread."});return;}}sendData.content.type=_constants.createThreadTypes[params.threadType.toUpperCase()];}else{_events.chatEvents.fireEvent('error',{code:999,message:"No thread type has been declared! Possible inputs are (".concat(Object.keys(_constants.createThreadTypes).join(','),")")});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Change thread Privacy!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.pinThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.PIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1958
+ subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unPinThread=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.UNPIN_THREAD,typeCode:generalTypeCode,//params.typeCode,
1959
+ subjectId:params.threadId,content:{},pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.deleteThread=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DELETE_MESSAGE_THREAD,typeCode:generalTypeCode//params.typeCode
1960
+ };if(params){if(+params.threadId>0){sendData.subjectId=+params.threadId;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Delete Thread!'});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.pinMessage=function(params,callback){return chatMessaging.sendMessage({chatMessageVOType:_constants.chatMessageVOTypes.PIN_MESSAGE,typeCode:generalTypeCode,//params.typeCode,
1961
+ subjectId:params.messageId,content:JSON.stringify({'notifyAll':typeof params.notifyAll==='boolean'?params.notifyAll:false}),pushMsgType:3,token:token},{onResult:function onResult(result){callback&&callback(result);}});};publicized.unPinMessage=unPinMessage;publicized.spamPrivateThread=function(params,callback){var spamData={chatMessageVOType:_constants.chatMessageVOTypes.SPAM_PV_THREAD,typeCode:generalTypeCode,//params.typeCode,
1962
+ pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.threadId)>0){spamData.subjectId=params.threadId;}}return chatMessaging.sendMessage(spamData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.block=function(params,callback){var blockData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCK,typeCode:generalTypeCode,//params.typeCode,
1963
+ content:{},pushMsgType:3,token:token,timeout:params.timeout};if(params){if(parseInt(params.contactId)>0){blockData.content.contactId=params.contactId;}if(parseInt(params.threadId)>0){blockData.content.threadId=params.threadId;}if(parseInt(params.userId)>0){blockData.content.userId=params.userId;}}return chatMessaging.sendMessage(blockData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){result.result=formatDataToMakeBlockedUser(result.result);}callback&&callback(result);}});};publicized.unblock=function(params,callback){var unblockData={chatMessageVOType:_constants.chatMessageVOTypes.UNBLOCK,typeCode:generalTypeCode,//params.typeCode,
1964
+ pushMsgType:3,token:token,content:{},timeout:params.timeout};if(params){if(parseInt(params.blockId)>0){unblockData.subjectId=params.blockId;}if(parseInt(params.contactId)>0){unblockData.content.contactId=params.contactId;}if(parseInt(params.threadId)>0){unblockData.content.threadId=params.threadId;}if(parseInt(params.userId)>0){unblockData.content.userId=params.userId;}}return chatMessaging.sendMessage(unblockData,{onResult:function onResult(result){if((0,_typeof2["default"])(result.result)=='object'){result.result=formatDataToMakeBlockedUser(result.result);}callback&&callback(result);}});};publicized.getBlockedList=function(params,callback){var count=50,offset=0,content={};if(params){if(parseInt(params.count)>0){count=params.count;}if(parseInt(params.offset)>0){offset=params.offset;}}content.count=count;content.offset=offset;var getBlockedData={chatMessageVOType:_constants.chatMessageVOTypes.GET_BLOCKED,typeCode:generalTypeCode,//params.typeCode,
1965
+ content:content,pushMsgType:3,token:token,timeout:params.timeout};return chatMessaging.sendMessage(getBlockedData,{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={blockedUsers:[],contentCount:result.contentCount,hasNext:offset+count<result.contentCount&&messageLength>0,nextOffset:offset*1+messageLength*1},blockedUser;for(var i=0;i<messageLength;i++){blockedUser=formatDataToMakeBlockedUser(messageContent[i]);if(blockedUser){resultData.blockedUsers.push(blockedUser);}}returnData.result=resultData;}callback&&callback(returnData);}});};publicized.getUserNotSeenDuration=function(params,callback){var content={};if(params){if(Array.isArray(params.userIds)){content.userIds=params.userIds;}}var getNotSeenDurationData={chatMessageVOType:_constants.chatMessageVOTypes.GET_NOT_SEEN_DURATION,typeCode:generalTypeCode,//params.typeCode,
1966
1966
  content:content,pushMsgType:3,token:token,timeout:params.timeout};return chatMessaging.sendMessage(getNotSeenDurationData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode};if(!returnData.hasError){returnData.result=result.result;}callback&&callback(returnData);}});};publicized.addContacts=function(params,callback){var data={};if(params){if(typeof params.firstName==='string'){data.firstName=params.firstName;}else{data.firstName='';}if(typeof params.lastName==='string'){data.lastName=params.lastName;}else{data.lastName='';}if(typeof params.typeCode==='string'){data.typeCode=params.typeCode;}else if(generalTypeCode){data.typeCode=generalTypeCode;}data.ownerId=typeCodeOwnerId?typeCodeOwnerId:params.ownerId?params.ownerId:undefined;if(typeof params.cellphoneNumber==='string'){data.cellphoneNumber=params.cellphoneNumber;}else{data.cellphoneNumber='';}if(typeof params.email==='string'){data.email=params.email;}else{data.email='';}if(typeof params.username==='string'){data.username=params.username;}data.uniqueId=_utility["default"].generateUUID();}var requestParams={url:SERVICE_ADDRESSES.PLATFORM_ADDRESS+SERVICES_PATH.ADD_CONTACTS,method:'POST',data:data,headers:{'_token_':token,'_token_issuer_':1}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:responseData.hasError,cache:false,errorMessage:responseData.message,errorCode:responseData.errorCode};if(!responseData.hasError){var messageContent=responseData.result,messageLength=responseData.result.length,resultData={contacts:[],contentCount:messageLength},contactData;for(var i=0;i<messageLength;i++){contactData=formatDataToMakeContact(messageContent[i]);if(contactData){resultData.contacts.push(contactData);}}returnData.result=resultData;/**
1967
1967
  * Add Contacts into cache database #cache
1968
- */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.newAddContacts=function(params,callback){var addContactsData={chatMessageVOType:_constants.chatMessageVOTypes.ADD_CONTACTS,content:{},pushMsgType:3,token:token,typeCode:generalTypeCode},AddContactVO={},firstNameList=[],lastNameList=[],cellPhoneNumberList=[],emailList=[],userNameList=[],uniqueIdList=[];if(params){//for(var item in params.contacts) {
1969
- if(typeof params.firstName==='string'){firstNameList.push(params.firstName);}else{firstNameList.push('');}if(typeof params.lastName==='string'){lastNameList.push(params.lastName);}else{lastNameList.push('');}if(typeof params.cellphoneNumber==='string'){cellPhoneNumberList.push(params.cellphoneNumber);// data.cellphoneNumber = params.cellphoneNumber;
1970
- }else{cellPhoneNumberList.push('');// data.cellphoneNumber = '';
1971
- }if(typeof params.email==='string'){emailList.push(params.email);// data.email = params.email;
1972
- }else{emailList.push('');// data.email = '';
1973
- }if(typeof params.username==='string'){userNameList.push(params.username);// data.username = params.username;
1974
- }uniqueIdList.push(_utility["default"].generateUUID());// data.uniqueId = Utility.generateUUID();
1975
- //}
1976
- AddContactVO={uniqueIdList:uniqueIdList,emailList:emailList,userNameList:userNameList,firstNameList:firstNameList,lastNameList:lastNameList,cellphoneNumberList:cellPhoneNumberList};}addContactsData.content=AddContactVO;return chatMessaging.sendMessage(addContactsData,{onResult:function onResult(result){// var responseData = JSON.parse(result.result.responseText);
1968
+ */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.newAddContacts=function(params,callback){var addContactsData={chatMessageVOType:_constants.chatMessageVOTypes.ADD_CONTACTS,content:{},pushMsgType:3,token:token,typeCode:generalTypeCode},AddContactVO={},firstNameList=[],lastNameList=[],cellPhoneNumberList=[],emailList=[],userNameList=[],uniqueIdList=[];if(params){//for(var item in params.contacts) {
1969
+ if(typeof params.firstName==='string'){firstNameList.push(params.firstName);}else{firstNameList.push('');}if(typeof params.lastName==='string'){lastNameList.push(params.lastName);}else{lastNameList.push('');}if(typeof params.cellphoneNumber==='string'){cellPhoneNumberList.push(params.cellphoneNumber);// data.cellphoneNumber = params.cellphoneNumber;
1970
+ }else{cellPhoneNumberList.push('');// data.cellphoneNumber = '';
1971
+ }if(typeof params.email==='string'){emailList.push(params.email);// data.email = params.email;
1972
+ }else{emailList.push('');// data.email = '';
1973
+ }if(typeof params.username==='string'){userNameList.push(params.username);// data.username = params.username;
1974
+ }uniqueIdList.push(_utility["default"].generateUUID());// data.uniqueId = Utility.generateUUID();
1975
+ //}
1976
+ AddContactVO={uniqueIdList:uniqueIdList,emailList:emailList,userNameList:userNameList,firstNameList:firstNameList,lastNameList:lastNameList,cellphoneNumberList:cellPhoneNumberList};}addContactsData.content=AddContactVO;return chatMessaging.sendMessage(addContactsData,{onResult:function onResult(result){// var responseData = JSON.parse(result.result.responseText);
1977
1977
  var returnData={hasError:result.hasError,cache:false,errorMessage:result.message,errorCode:result.errorCode};if((0,_typeof2["default"])(result.result)=='object'){var _result$result,_result$result2,_result$result2$resul;var messageContent=result===null||result===void 0?void 0:(_result$result=result.result)===null||_result$result===void 0?void 0:_result$result.result,messageLength=result===null||result===void 0?void 0:(_result$result2=result.result)===null||_result$result2===void 0?void 0:(_result$result2$resul=_result$result2.result)===null||_result$result2$resul===void 0?void 0:_result$result2$resul.length,resultData={contacts:[],contentCount:messageLength},contactData;for(var i=0;i<messageLength;i++){contactData=formatDataToMakeContact(messageContent[i]);if(contactData){resultData.contacts.push(contactData);}}returnData.result=resultData;/**
1978
1978
  * Add Contacts into cache database #cache
1979
- */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}// }
1980
- callback&&callback(returnData);}//callback && callback(result);
1979
+ */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}// }
1980
+ callback&&callback(returnData);}//callback && callback(result);
1981
1981
  }});/* var requestParams = {
1982
1982
  url: SERVICE_ADDRESSES.PLATFORM_ADDRESS + SERVICES_PATH.ADD_CONTACTS,
1983
1983
  method: 'POST',
@@ -1997,14 +1997,14 @@ callback&&callback(returnData);}//callback && callback(result);
1997
1997
  errorCode: responseData.errorCode
1998
1998
  };
1999
1999
 
2000
- if (!responseData.hasError) {*/ //} else {
2000
+ if (!responseData.hasError) {*/ //} else {
2001
2001
  /* chatEvents.fireEvent('error', {
2002
2002
  code: result.errorCode,
2003
2003
  message: result.errorMessage,
2004
2004
  error: result
2005
2005
  });
2006
- */ //}
2007
- //});
2006
+ */ //}
2007
+ //});
2008
2008
  };/*
2009
2009
  publicized.removeContacts = function ({id}, callback) {
2010
2010
  var data = {
@@ -2084,7 +2084,7 @@ callback&&callback(returnData);}//callback && callback(result);
2084
2084
  * Add Contacts into cache database #cache
2085
2085
  */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=_utility["default"].crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.removeContacts=function(params,callback){var data={};if(params){if(parseInt(params.id)>0){data.id=parseInt(params.id);}else{_events.chatEvents.fireEvent('error',{code:999,message:'ID is required for Deleting Contact!',error:undefined});}}data.ownerId=typeCodeOwnerId?typeCodeOwnerId:params.ownerId?params.ownerId:undefined;var requestParams={url:SERVICE_ADDRESSES.PLATFORM_ADDRESS+SERVICES_PATH.REMOVE_CONTACTS,method:'POST',data:data,headers:{'_token_':token,'_token_issuer_':1}};httpRequest(requestParams,function(result){if(!result.hasError){var responseData=JSON.parse(result.result.responseText);var returnData={hasError:responseData.hasError,cache:false,errorMessage:responseData.message,errorCode:responseData.errorCode};if(!responseData.hasError){returnData.result=responseData.result;}/**
2086
2086
  * Remove the contact from cache
2087
- */if(canUseCache){if(db){db.contacts.where('id').equals(parseInt(params.id))["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.searchContacts=function(params,callback){var data={size:50,offset:0},whereClause={},returnCache=false;if(params){if(typeof params.firstName==='string'){data.firstName=whereClause.firstName=params.firstName;}if(typeof params.lastName==='string'){data.lastName=whereClause.lastName=params.lastName;}if(parseInt(params.cellphoneNumber)>0){data.cellphoneNumber=whereClause.cellphoneNumber=params.cellphoneNumber;}if(typeof params.email==='string'){data.email=whereClause.email=params.email;}if(typeof params.query==='string'){data.q=whereClause.q=params.query;}if(typeof params.uniqueId==='string'){data.uniqueId=whereClause.uniqueId=params.uniqueId;}if(parseInt(params.id)>0){data.id=whereClause.id=params.id;}if(parseInt(params.typeCode)>0){data.typeCode=whereClause.typeCode=params.typeCode;}// data.typeCode = whereClause.typeCode = generalTypeCode;//params.typeCode;
2087
+ */if(canUseCache){if(db){db.contacts.where('id').equals(parseInt(params.id))["delete"]()["catch"](function(error){_events.chatEvents.fireEvent('error',{code:6602,message:CHAT_ERRORS[6602],error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}callback&&callback(returnData);}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.searchContacts=function(params,callback){var data={size:50,offset:0},whereClause={},returnCache=false;if(params){if(typeof params.firstName==='string'){data.firstName=whereClause.firstName=params.firstName;}if(typeof params.lastName==='string'){data.lastName=whereClause.lastName=params.lastName;}if(parseInt(params.cellphoneNumber)>0){data.cellphoneNumber=whereClause.cellphoneNumber=params.cellphoneNumber;}if(typeof params.email==='string'){data.email=whereClause.email=params.email;}if(typeof params.query==='string'){data.q=whereClause.q=params.query;}if(typeof params.uniqueId==='string'){data.uniqueId=whereClause.uniqueId=params.uniqueId;}if(parseInt(params.id)>0){data.id=whereClause.id=params.id;}if(parseInt(params.typeCode)>0){data.typeCode=whereClause.typeCode=params.typeCode;}// data.typeCode = whereClause.typeCode = generalTypeCode;//params.typeCode;
2088
2088
  if(parseInt(params.size)>0){data.size=params.size;}if(parseInt(params.offset)>0){data.offset=params.offset;}var functionLevelCache=typeof params.cache=='boolean'?params.cache:true;}var requestParams={url:SERVICE_ADDRESSES.PLATFORM_ADDRESS+SERVICES_PATH.SEARCH_CONTACTS,method:'POST',data:data,headers:{'_token_':token,'_token_issuer_':1}};/**
2089
2089
  * Search contacts in cache #cache
2090
2090
  */if(functionLevelCache&&canUseCache&&cacheSecret.length>0){if(db){/**
@@ -2101,42 +2101,42 @@ if(parseInt(params.size)>0){data.size=params.size;}if(parseInt(params.offset)>0)
2101
2101
  */if(canUseCache&&cacheSecret.length>0){if(db){var cacheData=[];for(var i=0;i<resultData.contacts.length;i++){try{var tempData={},salt=_utility["default"].generateUUID();tempData.id=resultData.contacts[i].id;tempData.owner=chatMessaging.userInfo.id;tempData.uniqueId=resultData.contacts[i].uniqueId;tempData.userId=_utility["default"].crypt(resultData.contacts[i].userId,cacheSecret,salt);tempData.cellphoneNumber=_utility["default"].crypt(resultData.contacts[i].cellphoneNumber,cacheSecret,salt);tempData.email=_utility["default"].crypt(resultData.contacts[i].email,cacheSecret,salt);tempData.firstName=_utility["default"].crypt(resultData.contacts[i].firstName,cacheSecret,salt);tempData.lastName=_utility["default"].crypt(resultData.contacts[i].lastName,cacheSecret,salt);tempData.expireTime=new Date().getTime()+cacheExpireTime;tempData.data=crypt(JSON.stringify(unsetNotSeenDuration(resultData.contacts[i])),cacheSecret,salt);tempData.salt=salt;cacheData.push(tempData);}catch(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});}}db.contacts.bulkPut(cacheData)["catch"](function(error){_events.chatEvents.fireEvent('error',{code:error.code,message:error.message,error:error});});}else{_events.chatEvents.fireEvent('error',{code:6601,message:CHAT_ERRORS[6601],error:null});}}}callback&&callback(returnData);/**
2102
2102
  * Delete callback so if server pushes response before
2103
2103
  * cache, cache won't send data again
2104
- */callback=undefined;if(!returnData.hasError&&returnCache){_events.chatEvents.fireEvent('contactEvents',{type:'CONTACTS_SEARCH_RESULT_CHANGE',result:returnData.result});}}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.createBot=function(params,callback){var createBotData={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_BOT,typeCode:generalTypeCode,//params.typeCode,
2105
- content:'',pushMsgType:3,token:token};if(params){if(typeof params.botName==='string'&&params.botName.length>0){if(params.botName.substr(-3)==="BOT"){createBotData.content=params.botName;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Bot name should end in "BOT", ex. "testBOT"'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Insert a bot name to create one!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Insert a bot name to create one!'});return;}return chatMessaging.sendMessage(createBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.defineBotCommand=function(params,callback){var defineBotCommandData={chatMessageVOType:_constants.chatMessageVOTypes.DEFINE_BOT_COMMAND,typeCode:generalTypeCode,//params.typeCode,
2106
- content:{},pushMsgType:3,token:token},commandList=[];if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}if(!Array.isArray(params.commandList)||!params.commandList.length){_events.chatEvents.fireEvent('error',{code:999,message:'Bot Commands List has to be an array of strings.'});return;}else{for(var i=0;i<params.commandList.length;i++){commandList.push('/'+params.commandList[i].trim());}}defineBotCommandData.content={botName:params.botName.trim(),commandList:commandList};}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(defineBotCommandData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.removeBotCommand=function(params,callback){var defineBotCommandData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_BOT_COMMANDS,typeCode:generalTypeCode,//params.typeCode,
2107
- content:{},pushMsgType:3,token:token},commandList=[];if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}if(!Array.isArray(params.commandList)||!params.commandList.length){_events.chatEvents.fireEvent('error',{code:999,message:'Bot Commands List has to be an array of strings.'});return;}else{for(var i=0;i<params.commandList.length;i++){commandList.push('/'+params.commandList[i].trim());}}defineBotCommandData.content={botName:params.botName.trim(),commandList:commandList};}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to remove bot commands'});return;}return chatMessaging.sendMessage(defineBotCommandData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.startBot=function(params,callback){var startBotData={chatMessageVOType:_constants.chatMessageVOTypes.START_BOT,typeCode:generalTypeCode,//params.typeCode,
2108
- content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id for Bot to start in!'});return;}if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}startBotData.subjectId=+params.threadId;startBotData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(startBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.stopBot=function(params,callback){var stopBotData={chatMessageVOType:_constants.chatMessageVOTypes.STOP_BOT,typeCode:generalTypeCode,//params.typeCode,
2109
- content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id for Bot to stop on!'});return;}if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}stopBotData.subjectId=+params.threadId;stopBotData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(stopBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getBotCommandsList=function(params,callback){var getBotCommandsListData={chatMessageVOType:_constants.chatMessageVOTypes.BOT_COMMANDS,typeCode:generalTypeCode,//params.typeCode,
2110
- content:{},pushMsgType:3,token:token};if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}getBotCommandsListData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get bot commands'});return;}return chatMessaging.sendMessage(getBotCommandsListData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getThreadAllBots=function(params,callback){var getThreadBotsData={chatMessageVOType:_constants.chatMessageVOTypes.THREAD_ALL_BOTS,typeCode:generalTypeCode,//params.typeCode,
2111
- content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id to get all Bots List!'});return;}getThreadBotsData.subjectId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get thread\' bots list!'});return;}return chatMessaging.sendMessage(getThreadBotsData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.createTag=function(params,callback){var createTagData={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_TAG,typeCode:generalTypeCode,//params.typeCode,
2112
- content:{},pushMsgType:3,token:token};if(params){if(typeof params.tagName==='string'&&params.tagName.length>0){createTagData.content.name=params.tagName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No tag name has been declared!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Create New Tag!'});return;}return chatMessaging.sendMessage(createTagData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.editTag=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.EDIT_TAG,typeCode:generalTypeCode,//params.typeCode,
2113
- content:{},pushMsgType:3,token:token};if(params){if(parseInt(params.tagId)>0){sendData.subjectId=+params.tagId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Tag Id has been sent!"});return;}if(typeof params.tagName==='string'&&params.tagName.length>0){sendData.content.name=params.tagName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No tag name has been declared!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Edit Tag!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.deleteTag=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DELETE_TAG,typeCode:generalTypeCode,//params.typeCode,
2114
- content:{},pushMsgType:3,token:token};if(params){if(parseInt(params.tagId)>0){sendData.subjectId=+params.tagId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Tag Id has been sent!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Delete Tag!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getTagList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.GET_TAG_LIST,typeCode:generalTypeCode,//params.typeCode,
2115
- content:{},pushMsgType:3,token:token};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.addTagParticipants=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ADD_TAG_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
2116
- content:[]};if(params){if(+params.tagId>0){sendData.subjectId=+params.tagId;}if(Array.isArray(params.threadIds)){sendData.content=params.threadIds;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Add Tag PArticipants!'});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.removeTagParticipants=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_TAG_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
2117
- content:[]};if(params){if(+params.tagId>0){sendData.subjectId=+params.tagId;}if(Array.isArray(params.threadIds)){sendData.content=params.threadIds;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Remove Tag Participants!'});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.registerAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.REGISTER_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2118
- 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('contactType')&&!!params.assistants[i].contactType&&params.assistants[i].hasOwnProperty('roleTypes')&&Array.isArray(params.assistants[i].roleTypes)&&params.assistants[i].roleTypes.length&&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({contactType:params.assistants[i].contactType,roleTypes:params.assistants[i].roleTypes,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 contactType, roleTypes and assistant itself!'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of contactType, roleTypes and assistant itself!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Create 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.deactivateAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DEACTIVATE_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2119
- 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 Deactivate 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.blockAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCK_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2120
- 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 Block 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.unblockAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.UNBLOCK_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2121
- 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,
2122
- 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,
2123
- 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,
2104
+ */callback=undefined;if(!returnData.hasError&&returnCache){_events.chatEvents.fireEvent('contactEvents',{type:'CONTACTS_SEARCH_RESULT_CHANGE',result:returnData.result});}}else{_events.chatEvents.fireEvent('error',{code:result.errorCode,message:result.errorMessage,error:result});}});};publicized.createBot=function(params,callback){var createBotData={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_BOT,typeCode:generalTypeCode,//params.typeCode,
2105
+ content:'',pushMsgType:3,token:token};if(params){if(typeof params.botName==='string'&&params.botName.length>0){if(params.botName.substr(-3)==="BOT"){createBotData.content=params.botName;}else{_events.chatEvents.fireEvent('error',{code:999,message:'Bot name should end in "BOT", ex. "testBOT"'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Insert a bot name to create one!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'Insert a bot name to create one!'});return;}return chatMessaging.sendMessage(createBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.defineBotCommand=function(params,callback){var defineBotCommandData={chatMessageVOType:_constants.chatMessageVOTypes.DEFINE_BOT_COMMAND,typeCode:generalTypeCode,//params.typeCode,
2106
+ content:{},pushMsgType:3,token:token},commandList=[];if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}if(!Array.isArray(params.commandList)||!params.commandList.length){_events.chatEvents.fireEvent('error',{code:999,message:'Bot Commands List has to be an array of strings.'});return;}else{for(var i=0;i<params.commandList.length;i++){commandList.push('/'+params.commandList[i].trim());}}defineBotCommandData.content={botName:params.botName.trim(),commandList:commandList};}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(defineBotCommandData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.removeBotCommand=function(params,callback){var defineBotCommandData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_BOT_COMMANDS,typeCode:generalTypeCode,//params.typeCode,
2107
+ content:{},pushMsgType:3,token:token},commandList=[];if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}if(!Array.isArray(params.commandList)||!params.commandList.length){_events.chatEvents.fireEvent('error',{code:999,message:'Bot Commands List has to be an array of strings.'});return;}else{for(var i=0;i<params.commandList.length;i++){commandList.push('/'+params.commandList[i].trim());}}defineBotCommandData.content={botName:params.botName.trim(),commandList:commandList};}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to remove bot commands'});return;}return chatMessaging.sendMessage(defineBotCommandData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.startBot=function(params,callback){var startBotData={chatMessageVOType:_constants.chatMessageVOTypes.START_BOT,typeCode:generalTypeCode,//params.typeCode,
2108
+ content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id for Bot to start in!'});return;}if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}startBotData.subjectId=+params.threadId;startBotData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(startBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.stopBot=function(params,callback){var stopBotData={chatMessageVOType:_constants.chatMessageVOTypes.STOP_BOT,typeCode:generalTypeCode,//params.typeCode,
2109
+ content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id for Bot to stop on!'});return;}if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}stopBotData.subjectId=+params.threadId;stopBotData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to create bot commands'});return;}return chatMessaging.sendMessage(stopBotData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getBotCommandsList=function(params,callback){var getBotCommandsListData={chatMessageVOType:_constants.chatMessageVOTypes.BOT_COMMANDS,typeCode:generalTypeCode,//params.typeCode,
2110
+ content:{},pushMsgType:3,token:token};if(params){if(typeof params.botName!=='string'||params.botName.length===0){_events.chatEvents.fireEvent('error',{code:999,message:'You need to insert a botName!'});return;}getBotCommandsListData.content=JSON.stringify({botName:params.botName.trim()});}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get bot commands'});return;}return chatMessaging.sendMessage(getBotCommandsListData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getThreadAllBots=function(params,callback){var getThreadBotsData={chatMessageVOType:_constants.chatMessageVOTypes.THREAD_ALL_BOTS,typeCode:generalTypeCode,//params.typeCode,
2111
+ content:{},pushMsgType:3,token:token};if(params){if(typeof+params.threadId!=='number'||params.threadId<0){_events.chatEvents.fireEvent('error',{code:999,message:'Enter a valid Thread Id to get all Bots List!'});return;}getThreadBotsData.subjectId=+params.threadId;}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to get thread\' bots list!'});return;}return chatMessaging.sendMessage(getThreadBotsData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.createTag=function(params,callback){var createTagData={chatMessageVOType:_constants.chatMessageVOTypes.CREATE_TAG,typeCode:generalTypeCode,//params.typeCode,
2112
+ content:{},pushMsgType:3,token:token};if(params){if(typeof params.tagName==='string'&&params.tagName.length>0){createTagData.content.name=params.tagName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No tag name has been declared!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Create New Tag!'});return;}return chatMessaging.sendMessage(createTagData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.editTag=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.EDIT_TAG,typeCode:generalTypeCode,//params.typeCode,
2113
+ content:{},pushMsgType:3,token:token};if(params){if(parseInt(params.tagId)>0){sendData.subjectId=+params.tagId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Tag Id has been sent!"});return;}if(typeof params.tagName==='string'&&params.tagName.length>0){sendData.content.name=params.tagName;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No tag name has been declared!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Edit Tag!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.deleteTag=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DELETE_TAG,typeCode:generalTypeCode,//params.typeCode,
2114
+ content:{},pushMsgType:3,token:token};if(params){if(parseInt(params.tagId)>0){sendData.subjectId=+params.tagId;}else{_events.chatEvents.fireEvent('error',{code:999,message:"No Tag Id has been sent!"});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Delete Tag!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.getTagList=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.GET_TAG_LIST,typeCode:generalTypeCode,//params.typeCode,
2115
+ content:{},pushMsgType:3,token:token};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.addTagParticipants=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ADD_TAG_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
2116
+ content:[]};if(params){if(+params.tagId>0){sendData.subjectId=+params.tagId;}if(Array.isArray(params.threadIds)){sendData.content=params.threadIds;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Add Tag PArticipants!'});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.removeTagParticipants=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.REMOVE_TAG_PARTICIPANT,typeCode:generalTypeCode,//params.typeCode,
2117
+ content:[]};if(params){if(+params.tagId>0){sendData.subjectId=+params.tagId;}if(Array.isArray(params.threadIds)){sendData.content=params.threadIds;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Remove Tag Participants!'});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.registerAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.REGISTER_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2118
+ 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('contactType')&&!!params.assistants[i].contactType&&params.assistants[i].hasOwnProperty('roleTypes')&&Array.isArray(params.assistants[i].roleTypes)&&params.assistants[i].roleTypes.length&&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({contactType:params.assistants[i].contactType,roleTypes:params.assistants[i].roleTypes,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 contactType, roleTypes and assistant itself!'});return;}}}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an array of Assistant Objects each containing of contactType, roleTypes and assistant itself!'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Create 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.deactivateAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.DEACTIVATE_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2119
+ 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 Deactivate 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.blockAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.BLOCK_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2120
+ 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 Block 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.unblockAssistant=function(params,callback){var sendData={chatMessageVOType:_constants.chatMessageVOTypes.UNBLOCK_ASSISTANT,typeCode:generalTypeCode,//params.typeCode,
2121
+ 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,
2122
+ 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,
2123
+ 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,
2124
2124
  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) {
2125
2125
  stackArr.push(result.result[i]);
2126
- } */stackArr.push.apply(stackArr,(0,_toConsumableArray2["default"])(result.result));consoleLogging&&console.log("[SDK][exportChat] a step passed...");// wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
2127
- 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 () {
2128
- resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));//}, 1000)
2129
- }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,
2130
- content:{offset:+params.offset>0?+params.offset:offset,count:+params.count>0?+params.count:wantedCount//config.getHistoryCount,
2131
- },subjectId:params.threadId};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.wantedCount>0){wantedCount=params.wantedCount;}if(+params.stepCount>0){stepCount=params.stepCount;}if(+params.offset>0){offset=params.offset;}// if (params.messageType && typeof params.messageType.toUpperCase() !== 'undefined' && chatMessageTypes[params.messageType.toUpperCase()] > 0) {
2132
- // sendData.content.messageType = chatMessageTypes[params.messageType.toUpperCase()];
2133
- // }
2134
- sendData.content.messageType=1;if(wantedCount<stepCount)stepCount=wantedCount;consoleLogging&&console.log("[SDK][exportChat] Starting...");requestExportChat(stackArr,wantedCount,stepCount,offset,sendData).then(function(result){consoleLogging&&console.log("[SDK][exportChat] Export done..., Now converting...");var exportedFilename=(params.fileName||'export-'+params.threadId)+'.csv',responseType=params.responseType!==null?params.responseType:"blob",autoStartDownload=params.autoStartDownload!==null?params.autoStartDownload:true;var str='',universalBOM="\uFEFF";str+="\u062A\u0627\u0631\u06CC\u062E "+',';//tarikh
2135
- str+=" \u0633\u0627\u0639\u062A "+',';//saat
2136
- str+="\u0646\u0627\u0645 \u0641\u0631\u0633\u062A\u0646\u062F\u0647"+',';//name ferestande
2137
- str+="\u0646\u0627\u0645 \u06A9\u0627\u0631\u0628\u0631\u06CC \u0641\u0631\u0633\u062A\u0646\u062F\u0647"+',';//name karbariye ferestande
2138
- str+="\u0645\u062A\u0646 \u067E\u06CC\u0627\u0645"+',';//matne payam
2139
- str+='\r\n';var line='',radif=1;for(var i=0;i<result.length;i++){line='';if(result[i].messageType!==1){continue;}var sender='';if(result[i].participant.contactName){sender=result[i].participant.contactName+',';}else{if(result[i].participant.firstName){sender=result[i].participant.firstName+' ';}if(result[i].participant.lastName){sender+=result[i].participant.lastName;}sender+=',';}line+=new Date(result[i].time).toLocaleDateString('fa-IR')+',';line+=new Date(result[i].time).toLocaleTimeString('fa-IR')+',';line+=sender;line+=result[i].participant.username+',';line+='"'+result[i].message.replaceAll(",","،").replaceAll('"','”')+'",';// line += result[i].message.replaceAll(",", ".").replace(/(\r\n|\n|\r)/gm, " ") + ',';
2126
+ } */stackArr.push.apply(stackArr,(0,_toConsumableArray2["default"])(result.result));consoleLogging&&console.log("[SDK][exportChat] a step passed...");// wantedCount = wantedCount > result.contentCount ? result.contentCount : wantedCount;
2127
+ 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 () {
2128
+ resolve(requestExportChat(stackArr,wantedCount,stepCount,stackArr.length,sendData));//}, 1000)
2129
+ }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,
2130
+ content:{offset:+params.offset>0?+params.offset:offset,count:+params.count>0?+params.count:wantedCount//config.getHistoryCount,
2131
+ },subjectId:params.threadId};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.wantedCount>0){wantedCount=params.wantedCount;}if(+params.stepCount>0){stepCount=params.stepCount;}if(+params.offset>0){offset=params.offset;}// if (params.messageType && typeof params.messageType.toUpperCase() !== 'undefined' && chatMessageTypes[params.messageType.toUpperCase()] > 0) {
2132
+ // sendData.content.messageType = chatMessageTypes[params.messageType.toUpperCase()];
2133
+ // }
2134
+ sendData.content.messageType=1;if(wantedCount<stepCount)stepCount=wantedCount;consoleLogging&&console.log("[SDK][exportChat] Starting...");requestExportChat(stackArr,wantedCount,stepCount,offset,sendData).then(function(result){consoleLogging&&console.log("[SDK][exportChat] Export done..., Now converting...");var exportedFilename=(params.fileName||'export-'+params.threadId)+'.csv',responseType=params.responseType!==null?params.responseType:"blob",autoStartDownload=params.autoStartDownload!==null?params.autoStartDownload:true;var str='',universalBOM="\uFEFF";str+="\u062A\u0627\u0631\u06CC\u062E "+',';//tarikh
2135
+ str+=" \u0633\u0627\u0639\u062A "+',';//saat
2136
+ str+="\u0646\u0627\u0645 \u0641\u0631\u0633\u062A\u0646\u062F\u0647"+',';//name ferestande
2137
+ str+="\u0646\u0627\u0645 \u06A9\u0627\u0631\u0628\u0631\u06CC \u0641\u0631\u0633\u062A\u0646\u062F\u0647"+',';//name karbariye ferestande
2138
+ str+="\u0645\u062A\u0646 \u067E\u06CC\u0627\u0645"+',';//matne payam
2139
+ str+='\r\n';var line='',radif=1;for(var i=0;i<result.length;i++){line='';if(result[i].messageType!==1){continue;}var sender='';if(result[i].participant.contactName){sender=result[i].participant.contactName+',';}else{if(result[i].participant.firstName){sender=result[i].participant.firstName+' ';}if(result[i].participant.lastName){sender+=result[i].participant.lastName;}sender+=',';}line+=new Date(result[i].time).toLocaleDateString('fa-IR')+',';line+=new Date(result[i].time).toLocaleTimeString('fa-IR')+',';line+=sender;line+=result[i].participant.username+',';line+='"'+result[i].message.replaceAll(",","،").replaceAll('"','”')+'",';// line += result[i].message.replaceAll(",", ".").replace(/(\r\n|\n|\r)/gm, " ") + ',';
2140
2140
  str+=line+'\r\n';radif++;}var blob=new Blob([str],{type:'text/csv;charset=utf-8;'});_events.chatEvents.fireEvent('threadEvents',{type:'EXPORT_CHAT',subType:'DONE',threadId:sendData.subjectId,result:blob});/*if (navigator.msSaveBlob) { // IE 10+
2141
2141
  if(params.autoStartDownload) {
2142
2142
  navigator.msSaveBlob(blob, exportedFilename);
@@ -2146,20 +2146,20 @@ str+=line+'\r\n';radif++;}var blob=new Blob([str],{type:'text/csv;charset=utf-8;
2146
2146
  type: 'blob',
2147
2147
  result: blob
2148
2148
  });
2149
- } else {*/if(responseType==='link'){var link=document.createElement("a"),url=URL.createObjectURL(blob);//if (link.download !== undefined) { // feature detection
2150
- // Browsers that support HTML5 download attribute
2151
- link.setAttribute("href",'data:text/csv; charset=utf-8,'+encodeURIComponent(universalBOM+str));link.setAttribute("download",exportedFilename);if(autoStartDownload){link.style.visibility='hidden';document.body.appendChild(link);link.click();document.body.removeChild(link);}//}
2152
- callback&&callback({hasError:false,type:'link',result:link});}else{callback&&callback({hasError:false,type:'blob',result:blob});}//}
2149
+ } else {*/if(responseType==='link'){var link=document.createElement("a"),url=URL.createObjectURL(blob);//if (link.download !== undefined) { // feature detection
2150
+ // Browsers that support HTML5 download attribute
2151
+ link.setAttribute("href",'data:text/csv; charset=utf-8,'+encodeURIComponent(universalBOM+str));link.setAttribute("download",exportedFilename);if(autoStartDownload){link.style.visibility='hidden';document.body.appendChild(link);link.click();document.body.removeChild(link);}//}
2152
+ callback&&callback({hasError:false,type:'link',result:link});}else{callback&&callback({hasError:false,type:'blob',result:blob});}//}
2153
2153
  callback=undefined;});/*.catch(function (result) {
2154
2154
  consoleLogging && console.log(result);
2155
- });*/};publicized.startCall=callModule.startCall;publicized.startGroupCall=callModule.startGroupCall;publicized.callReceived=callModule.callReceived;publicized.terminateCall=callModule.terminateCall;publicized.acceptCall=callModule.acceptCall;publicized.rejectCall=publicized.cancelCall=callModule.rejectCall;publicized.endCall=callModule.endCall;publicized.startRecordingCall=callModule.startRecordingCall;publicized.stopRecordingCall=callModule.stopRecordingCall;publicized.startScreenShare=callModule.startScreenShare;publicized.resizeScreenShare=callModule.resizeScreenShare;publicized.endScreenShare=callModule.endScreenShare;publicized.getCallsList=callModule.getCallsList;publicized.getCallsToJoin=callModule.getCallsToJoin;publicized.deleteFromCallList=callModule.deleteFromCallList;publicized.getCallParticipants=callModule.getCallParticipants;publicized.addCallParticipants=callModule.addCallParticipants;publicized.removeCallParticipants=callModule.removeCallParticipants;publicized.muteCallParticipants=callModule.muteCallParticipants;publicized.unMuteCallParticipants=callModule.unMuteCallParticipants;publicized.turnOnVideoCall=callModule.turnOnVideoCall;publicized.turnOffVideoCall=callModule.turnOffVideoCall;publicized.disableParticipantsVideoReceive=callModule.disableParticipantsVideoReceive;publicized.enableParticipantsVideoReceive=callModule.enableParticipantsVideoReceive;publicized.pauseCamera=callModule.pauseCamera;publicized.resumeCamera=callModule.resumeCamera;publicized.pauseMice=callModule.pauseMice;publicized.resumeMice=callModule.resumeMice;publicized.resizeCallVideo=callModule.resizeCallVideo;publicized.restartMedia=callModule.restartMedia;publicized.callStop=callModule.callStop;publicized.sendCallMetaData=callModule.sendCallMetaData;publicized.sendCallSticker=callModule.sendCallSticker;publicized.callStickerTypes=_constants.callStickerTypes;publicized.recallThreadParticipant=callModule.recallThreadParticipant;publicized.deviceManager=callModule.deviceManager;publicized.resetCallStream=callModule.resetCallStream;publicized.getMutualGroups=function(params,callback){var count=+params.count?+params.count:50,offset=+params.offset?+params.offset:0;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.MUTUAL_GROUPS,typeCode:generalTypeCode,//params.typeCode,
2155
+ });*/};publicized.startCall=callModule.startCall;publicized.startGroupCall=callModule.startGroupCall;publicized.callReceived=callModule.callReceived;publicized.terminateCall=callModule.terminateCall;publicized.acceptCall=callModule.acceptCall;publicized.rejectCall=publicized.cancelCall=callModule.rejectCall;publicized.endCall=callModule.endCall;publicized.startRecordingCall=callModule.startRecordingCall;publicized.stopRecordingCall=callModule.stopRecordingCall;publicized.startScreenShare=callModule.startScreenShare;publicized.resizeScreenShare=callModule.resizeScreenShare;publicized.endScreenShare=callModule.endScreenShare;publicized.getCallsList=callModule.getCallsList;publicized.getCallsToJoin=callModule.getCallsToJoin;publicized.deleteFromCallList=callModule.deleteFromCallList;publicized.getCallParticipants=callModule.getCallParticipants;publicized.addCallParticipants=callModule.addCallParticipants;publicized.removeCallParticipants=callModule.removeCallParticipants;publicized.muteCallParticipants=callModule.muteCallParticipants;publicized.unMuteCallParticipants=callModule.unMuteCallParticipants;publicized.turnOnVideoCall=callModule.turnOnVideoCall;publicized.turnOffVideoCall=callModule.turnOffVideoCall;publicized.disableParticipantsVideoReceive=callModule.disableParticipantsVideoReceive;publicized.enableParticipantsVideoReceive=callModule.enableParticipantsVideoReceive;publicized.pauseCamera=callModule.pauseCamera;publicized.resumeCamera=callModule.resumeCamera;publicized.pauseMice=callModule.pauseMice;publicized.resumeMice=callModule.resumeMice;publicized.resizeCallVideo=callModule.resizeCallVideo;publicized.restartMedia=callModule.restartMedia;publicized.callStop=callModule.callStop;publicized.sendCallMetaData=callModule.sendCallMetaData;publicized.sendCallSticker=callModule.sendCallSticker;publicized.callStickerTypes=_constants.callStickerTypes;publicized.recallThreadParticipant=callModule.recallThreadParticipant;publicized.deviceManager=callModule.deviceManager;publicized.resetCallStream=callModule.resetCallStream;publicized.getMutualGroups=function(params,callback){var count=+params.count?+params.count:50,offset=+params.offset?+params.offset:0;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.MUTUAL_GROUPS,typeCode:generalTypeCode,//params.typeCode,
2156
2156
  content:{count:count,offset:offset}};if(params){if((0,_typeof2["default"])(params.user)==='object'&&params.user.hasOwnProperty('id')&&params.user.hasOwnProperty('idType')&&params.user.id.length&&_constants.inviteeVOidTypes[params.user.idType]>0){sendData.content.toBeUserVO={id:params.user.id,idType:+_constants.inviteeVOidTypes[params.user.idType]};}else{_events.chatEvents.fireEvent('error',{code:999,message:'You should send an user object like {id: 92, idType: "TO_BE_USER_CONTACT_ID"}'});return;}}else{_events.chatEvents.fireEvent('error',{code:999,message:'No params have been sent to Get Mutual Groups!'});return;}return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){var returnData={hasError:result.hasError,cache:false,errorMessage:result.errorMessage,errorCode:result.errorCode,uniqueId:result.uniqueId};if(!returnData.hasError){var messageContent=result.result,messageLength=messageContent.length,resultData={threads:[],contentCount:result.contentCount,hasNext:offset+count<result.contentCount&&messageLength>0,nextOffset:offset*1+messageLength*1},threadData;for(var i=0;i<messageLength;i++){threadData=createThread(messageContent[i],false);if(threadData){resultData.threads.push(threadData);}}returnData.result=resultData;}callback&&callback(returnData);/**
2157
2157
  * Delete callback so if server pushes response before
2158
2158
  * cache, cache won't send data again
2159
2159
  */callback=undefined;}});};publicized.sendLocationPing=function(params,callback){/**
2160
2160
  * + locationPingRequest {object}
2161
2161
  * + content {list} A map of { location: string, locationId: int }
2162
- */var locationPingData={chatMessageVOType:_constants.chatMessageVOTypes.LOCATION_PING,typeCode:generalTypeCode,//params.typeCode,
2162
+ */var locationPingData={chatMessageVOType:_constants.chatMessageVOTypes.LOCATION_PING,typeCode:generalTypeCode,//params.typeCode,
2163
2163
  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);if(!chatMessaging.userInfo||!chatMessaging.userInfo.id){getUserAndUpdateSDKState();}}};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;/**
2164
2164
  * Check a turn server availability
2165
2165
  *
@@ -2170,14 +2170,14 @@ pushMsgType:3,token:token},content={};if(params){if(typeof params.location==='st
2170
2170
  * @param password
2171
2171
  * @param timeout
2172
2172
  * @return {Promise<boolean>}
2173
- */publicized.checkTURNServer=function(turnIp,port){var useUDP=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var username=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'mkhorrami';var password=arguments.length>4&&arguments[4]!==undefined?arguments[4]:'mkh_123456';var timeout=arguments.length>5?arguments[5]:undefined;var url='turn:'+turnIp+':'+port+'?transport='+(useUDP?'udp':'tcp');var turnConfig={urls:url,username:username,credential:password};if(navigator.userAgent.indexOf('firefox')!==-1&&navigator.userAgent.indexOf('92.0.5')!==-1){alert('Browser version is not suitable for video call. Upgrade or use another browser.');}console.log('turnConfig: ',turnConfig);return new Promise(function(resolve,reject){var promiseResolved;setTimeout(function(){if(promiseResolved)return;resolve(false);promiseResolved=true;},timeout||5000);promiseResolved=false;var myPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection//compatibility for firefox and chrome
2174
- ,pc=new myPeerConnection({iceServers:[turnConfig]}),noop=function noop(){};pc.createDataChannel("");//create a bogus data channel
2175
- pc.createOffer(function(sdp){if(sdp.sdp.indexOf('typ relay')>-1){// sometimes sdp contains the ice candidates...
2176
- promiseResolved=true;resolve(true);}pc.setLocalDescription(sdp,noop,noop);},noop);// create offer and set local description
2177
- pc.onicecandidate=function(ice){//listen for candidate events
2178
- if(promiseResolved||!ice||!ice.candidate||!ice.candidate.candidate||!(ice.candidate.candidate.indexOf('typ relay')>-1))return;promiseResolved=true;resolve(true);};});};publicized.getCustomerInfo=function(params,callback){var userId=params.userId||chatMessaging.userInfo.id,sendData={chatMessageVOType:_constants.chatMessageVOTypes.CUSTOMER_INFO,typeCode:generalTypeCode,//params.typeCode,
2179
- content:[userId],token:token};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.archiveThread=function(_ref,callback){var threadId=_ref.threadId;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ARCHIVE_THREAD,typeCode:generalTypeCode,//params.typeCode,
2180
- token:token,subjectId:threadId};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.unArchiveThread=function(_ref2,callback){var threadId=_ref2.threadId;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.UNARCHIVE_THREAD,typeCode:generalTypeCode,//params.typeCode,
2181
- token:token,subjectId:threadId};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.version=function(){console.log("%c[SDK] Version: podchat-browser@"+_buildConfig["default"].version,"color:green; font-size:13px");console.log("%c[SDK] Build date:"+_buildConfig["default"].date,"color:green;font-size:13px");console.log("%c[SDK] Additional info: "+_buildConfig["default"].VersionInfo,"color:green;font-size:13px");return _buildConfig["default"];};publicized.changeProtocol=function(){var proto=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"websocket";if(["webrtc","websocket"].includes(proto)){if(proto!=protocol){protocol=proto.toLowerCase();asyncClient.logout();initAsync();}else{console.warn("SDK is currently using the ".concat(proto," protocol. Nothing to do."));}}else{console.error("Protocol ".concat(proto," is not supported in SDK. Valid protocols: \"webrtc\", \"websocket\""));}};_store.store.events.on(_store.store.threads.eventsList.UNREAD_COUNT_UPDATED,function(thread){_events.chatEvents.fireEvent('threadEvents',{type:'UNREAD_COUNT_UPDATED',result:{threadId:thread.id,unreadCount:thread.unreadCount||0}});});init();return publicized;}if(window){if(!window.POD){window.POD={};}window.POD.Chat=Chat;//For backward compatibility
2182
- window.PodChat=Chat;}var _default=Chat;// })();
2173
+ */publicized.checkTURNServer=function(turnIp,port){var useUDP=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var username=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'mkhorrami';var password=arguments.length>4&&arguments[4]!==undefined?arguments[4]:'mkh_123456';var timeout=arguments.length>5?arguments[5]:undefined;var url='turn:'+turnIp+':'+port+'?transport='+(useUDP?'udp':'tcp');var turnConfig={urls:url,username:username,credential:password};if(navigator.userAgent.indexOf('firefox')!==-1&&navigator.userAgent.indexOf('92.0.5')!==-1){alert('Browser version is not suitable for video call. Upgrade or use another browser.');}console.log('turnConfig: ',turnConfig);return new Promise(function(resolve,reject){var promiseResolved;setTimeout(function(){if(promiseResolved)return;resolve(false);promiseResolved=true;},timeout||5000);promiseResolved=false;var myPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection//compatibility for firefox and chrome
2174
+ ,pc=new myPeerConnection({iceServers:[turnConfig]}),noop=function noop(){};pc.createDataChannel("");//create a bogus data channel
2175
+ pc.createOffer(function(sdp){if(sdp.sdp.indexOf('typ relay')>-1){// sometimes sdp contains the ice candidates...
2176
+ promiseResolved=true;resolve(true);}pc.setLocalDescription(sdp,noop,noop);},noop);// create offer and set local description
2177
+ pc.onicecandidate=function(ice){//listen for candidate events
2178
+ if(promiseResolved||!ice||!ice.candidate||!ice.candidate.candidate||!(ice.candidate.candidate.indexOf('typ relay')>-1))return;promiseResolved=true;resolve(true);};});};publicized.getCustomerInfo=function(params,callback){var userId=params.userId||chatMessaging.userInfo.id,sendData={chatMessageVOType:_constants.chatMessageVOTypes.CUSTOMER_INFO,typeCode:generalTypeCode,//params.typeCode,
2179
+ content:[userId],token:token};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.archiveThread=function(_ref,callback){var threadId=_ref.threadId;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.ARCHIVE_THREAD,typeCode:generalTypeCode,//params.typeCode,
2180
+ token:token,subjectId:threadId};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.unArchiveThread=function(_ref2,callback){var threadId=_ref2.threadId;var sendData={chatMessageVOType:_constants.chatMessageVOTypes.UNARCHIVE_THREAD,typeCode:generalTypeCode,//params.typeCode,
2181
+ token:token,subjectId:threadId};return chatMessaging.sendMessage(sendData,{onResult:function onResult(result){callback&&callback(result);}});};publicized.version=function(){console.log("%c[SDK] Version: podchat-browser@"+_buildConfig["default"].version,"color:green; font-size:13px");console.log("%c[SDK] Build date:"+_buildConfig["default"].date,"color:green;font-size:13px");console.log("%c[SDK] Additional info: "+_buildConfig["default"].VersionInfo,"color:green;font-size:13px");return _buildConfig["default"];};publicized.changeProtocol=function(){var proto=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"websocket";if(["webrtc","websocket"].includes(proto)){if(proto!=protocol){protocol=proto.toLowerCase();asyncClient.logout();initAsync();}else{console.warn("SDK is currently using the ".concat(proto," protocol. Nothing to do."));}}else{console.error("Protocol ".concat(proto," is not supported in SDK. Valid protocols: \"webrtc\", \"websocket\""));}};_store.store.events.on(_store.store.threads.eventsList.UNREAD_COUNT_UPDATED,function(thread){_events.chatEvents.fireEvent('threadEvents',{type:'UNREAD_COUNT_UPDATED',result:{threadId:thread.id,unreadCount:thread.unreadCount||0}});});init();return publicized;}if(window){if(!window.POD){window.POD={};}window.POD.Chat=Chat;//For backward compatibility
2182
+ window.PodChat=Chat;}var _default=Chat;// })();
2183
2183
  exports["default"]=_default;