podchat
Version:
Javascript SDK to use POD's Chat Service
1,218 lines (1,106 loc) • 373 kB
JavaScript
'use strict';
import {errorList} from './lib/errorHandler';
import {
chatMessageVOTypes,
inviteeVOidTypes,
createThreadTypes,
chatMessageTypes,
systemMessageTypes,
imageMimeTypes,
imageExtentions,
CHAT_ERRORS,
SERVICES_PATH,
chatStickerTypes,
podspace
} from "./lib/constants";
import Async from 'podasync';
import Utility from './utility/utility.js';
import Mime from 'mime';
import App from "./lib/app";
import ChatMessaging from "./lib/messenger";
import buildConfig from "./buildConfig.json"
import ContactsV2 from "./lib/chat/contacts/contactsV2";
/*
* Pod Chat Module
* @module chat
*
* @param {Object} params
*/
function Chat(params) {
const app = new App();
app.contact = new ContactsV2(app);
this.contact = {
add: app.contact.add,
remove: app.contact.remove,
get: app.contact.get,
update: app.contact.update
};
/**
* Defining global variables for Dexie to work in Node ENV
*/
/*******************************************************
* P R I V A T E V A R I A B L E S *
*******************************************************/
function getUserInfoParams(userInfo) {
if (typeof userInfo === 'object') {
if (["id", "name"].every(key => Object.keys(userInfo).includes(key))) {
return userInfo
}
}
if (userInfo != null) {
console.error("[SDK] userInfo params is null or not Valid ");
}
return null
}
app.sdkParams.appId = params.appId || 'PodChat';
app.sdkParams.deviceId = params.deviceId || undefined;
app.sdkParams.token = params.token || "111";
app.sdkParams.mapApiKey = params.mapApiKey || '8b77db18704aa646ee5aaea13e7370f4f88b9e8c';
app.sdkParams.grantDeviceIdFromSSO = (params.grantDeviceIdFromSSO && typeof params.grantDeviceIdFromSSO === 'boolean')
? params.grantDeviceIdFromSSO
: false;
app.sdkParams.seenIntervalPitch = params.seenIntervalPitch || 2000;
app.sdkParams.systemMessageIntervalPitch = params.systemMessageIntervalPitch || 1000;
app.sdkParams.socketAddress = params.socketAddress;
app.sdkParams.serverName = params.serverName || '';
app.sdkParams.wsConnectionWaitTime = params.wsConnectionWaitTime;
app.sdkParams.connectionRetryInterval = params.connectionRetryInterval;
app.sdkParams.msgPriority = params.msgPriority || 1;
app.sdkParams.messageTtl = params.messageTtl || 10000;
app.sdkParams.reconnectOnClose = params.reconnectOnClose;
app.sdkParams.asyncLogging = params.asyncLogging;
app.sdkParams.connectionCheckTimeout = params.connectionCheckTimeout;
app.sdkParams.httpRequestTimeout = (params.httpRequestTimeout >= 0) ? params.httpRequestTimeout : 30000;
app.sdkParams.asyncRequestTimeout = (typeof params.asyncRequestTimeout === 'number' && params.asyncRequestTimeout >= 0) ? params.asyncRequestTimeout : 0;
app.sdkParams.connectionCheckTimeoutThreshold = params.connectionCheckTimeoutThreshold;
app.sdkParams.httpUploadRequestTimeout = (params.httpUploadRequestTimeout >= 0) ? params.httpUploadRequestTimeout : 0;
app.sdkParams.actualTimingLog = (params.asyncLogging.actualTiming && typeof params.asyncLogging.actualTiming === 'boolean')
? params.asyncLogging.actualTiming
: false;
app.sdkParams.consoleLogging = (params.asyncLogging.consoleLogging && typeof params.asyncLogging.consoleLogging === 'boolean')
? params.asyncLogging.consoleLogging
: false;
app.sdkParams.fullResponseObject = params.fullResponseObject || false;
app.sdkParams.webrtcConfig = (params.webrtcConfig ? params.webrtcConfig : null);
app.sdkParams.chatPingMessageInterval = params.chatPingMessageInterval;
app.sdkParams.protocol = params.protocol || 'websocket';
app.sdkParams.callOptions = params.callOptions;
app.sdkParams.generalTypeCode = params.typeCode || 'default';
app.sdkParams.typeCodeOwnerId = params.typeCodeOwnerId || null;
params.ssoHost && (app.sdkParams.SERVICE_ADDRESSES.SSO_ADDRESS = params.ssoHost);
params.platformHost && (app.sdkParams.SERVICE_ADDRESSES.PLATFORM_ADDRESS = params.platformHost);
params.fileServer && (app.sdkParams.SERVICE_ADDRESSES.FILESERVER_ADDRESS = params.fileServer);
params.podSpaceFileServer && (app.sdkParams.SERVICE_ADDRESSES.PODSPACE_FILESERVER_ADDRESS = params.podSpaceFileServer);
params.mapServer && (app.sdkParams.SERVICE_ADDRESSES.MAP_ADDRESS = params.mapServer);
/**
* Minimum value for messageTtl is 2000
*/
if(app.sdkParams.messageTtl < 2000) {
app.sdkParams.messageTtl = 2000;
console.warn("[SDK] messageTtl can not be less than 2000, we changed it to 2000")
}
if(getUserInfoParams(params.userInfo)) {
app.store.user.setUser(getUserInfoParams(params.userInfo))
}
let
asyncClient,
currentModuleInstance = this,
peerId,
oldPeerId,
db,
cacheSecret = '',
isTypingInterval,
queueServers = params.queueServers || [],
queueReceive = params.queueReceive,
queueSend = params.queueSend,
queueConnectionTimeout = params.queueConnectionTimeout,
sendPingTimeout,
getUserInfoTimeout,
config = {
getHistoryCount: 50
},
getUserInfoRetry = 5,
getUserInfoRetryCount = 0,
asyncStateTypes = {
0: 'CONNECTING',
1: 'CONNECTED',
2: 'CLOSING',
3: 'CLOSED'
},
chatState = false,
chatFullStateObject = {},
minIntegerValue = Number.MAX_SAFE_INTEGER * -1,
maxIntegerValue = Number.MAX_SAFE_INTEGER * 1,
chatSendQueue = [],
chatSendQueueHandlerTimeout,
/** call variables */
callTypes = {
'VOICE': 0x0,
'VIDEO': 0x1
},
currentCallParams = {},
currentCallId = null,
newCallId = null,
callClientType = {
WEB: 1,
ANDROID: 2,
DESKTOP: 3,
NODE: 4
},
callRequestController = {
callRequestReceived: false,
callEstablishedInMySide: false,
iCanAcceptTheCall: function () {
return callRequestController.callRequestReceived && callRequestController.callEstablishedInMySide;
}
},
callStopQueue = {
callStarted: false,
},
callNoAnswerTimeout = params.callOptions && params.callOptions.callNoAnswerTimeout ? params.callOptions.callNoAnswerTimeout : 0,
asyncLogCallback = typeof params.asyncLogCallback == "function" ? params.asyncLogCallback : null;
app.messenger = new ChatMessaging(app, Object.assign(params, {
asyncClient: asyncClient
}));
/*******************************************************
* P R I V A T E M E T H O D S *
*******************************************************/
var init = function () {
/**
* Initialize Cache Databases
*/
// startCacheDatabases(function () {
if (app.sdkParams.grantDeviceIdFromSSO) {
var getDeviceIdWithTokenTime = new Date().getTime();
getDeviceIdWithToken(function (retrievedDeviceId) {
if (app.sdkParams.actualTimingLog) {
Utility.chatStepLogger('Get Device ID ', new Date().getTime() - getDeviceIdWithTokenTime);
}
app.sdkParams.deviceId = retrievedDeviceId;
initAsync();
});
} else {
initAsync();
}
// });
},
/**
* Initialize Async
*
* Initializes Async module and sets proper callbacks
*
* @access private
*
* @return {undefined}
* @return {undefined}
*/
initAsync = function () {
if (app.sdkParams.protocol === 'queue' && (!Array.isArray(queueServers) || queueServers.length == 0)) {
console.log('Queue Servers are invalid!', queueServers);
return;
}
var asyncGetReadyTime = new Date().getTime();
if (typeof app.sdkParams.appId == "number") {
app.sdkParams.appId = app.sdkParams.appId.toString()
}
if (typeof app.sdkParams.appId != "string" || app.sdkParams.appId.length > 30) {
app.errorHandler.raiseError(errorList.INVALID_APP_ID, null, true, {});
return;
}
asyncClient = new Async({
appId: app.sdkParams.appId,
protocol: app.sdkParams.protocol,
servers: queueServers,
queueReceive: queueReceive,
queueSend: queueSend,
queueConnectionTimeout: queueConnectionTimeout,
socketAddress: app.sdkParams.socketAddress,
serverName: app.sdkParams.serverName,
deviceId: app.sdkParams.deviceId,
wsConnectionWaitTime: app.sdkParams.wsConnectionWaitTime,
connectionRetryInterval: app.sdkParams.connectionRetryInterval,
connectionCheckTimeout: app.sdkParams.connectionCheckTimeout,
connectionCheckTimeoutThreshold: app.sdkParams.connectionCheckTimeoutThreshold,
messageTtl: app.sdkParams.messageTtl,
reconnectOnClose: app.sdkParams.reconnectOnClose,
asyncLogging: app.sdkParams.asyncLogging,
logLevel: (app.sdkParams.consoleLogging ? 3 : 1),
asyncLogCallback: asyncLogCallback || null,
});
app.messenger.asyncInitialized(asyncClient);
asyncClient.on('asyncReady', function () {
if (app.sdkParams.actualTimingLog) {
Utility.chatStepLogger('Async Connection ', new Date().getTime() - asyncGetReadyTime);
}
peerId = asyncClient.getPeerId();
if (!app.store.user.get()) {
getUserAndUpdateSDKState();
} else if (app.store.user.get().id > 0) {
app.messenger.chatState = true;
app.chatEvents.fireEvent('chatReady');
chatSendQueueHandler();
}
});
asyncClient.on('stateChange', function (state) {
app.chatEvents.fireEvent('chatState', state);
chatFullStateObject = state;
let st = app.sdkParams.protocol == 'queue' ? state.queueState : state.socketState;
switch (st) {
case 1: // CONNECTED
if (
app.sdkParams.protocol != 'websocket'
|| (app.sdkParams.protocol == 'websocket' && state.deviceRegister && state.serverRegister)
) {
app.messenger.chatState = true;
app.messenger.startChatPing();
}
break;
case 0: // CONNECTING
app.messenger.chatState = false;
app.messenger.stopChatPing();
break;
case 2: // CLOSING
case 3: // CLOSED
app.messenger.chatState = false;
app.messenger.stopChatPing();
//chatMessaging.sendPingTimeout && clearTimeout(chatMessaging.sendPingTimeout);
break;
}
});
asyncClient.on('connect', function (newPeerId) {
asyncGetReadyTime = new Date().getTime();
peerId = newPeerId;
app.chatEvents.fireEvent('connect');
ping();
});
asyncClient.on('disconnect', function (event) {
oldPeerId = peerId;
peerId = undefined;
app.chatEvents.fireEvent('disconnect', event);
});
asyncClient.on('reconnect', function (newPeerId) {
peerId = newPeerId;
app.chatEvents.fireEvent('reconnect');
});
asyncClient.on('message', function (params, ack) {
receivedAsyncMessageHandler(params);
ack && ack();
});
asyncClient.on('error', function (error) {
if (error.errorCode) {
app.chatEvents.fireEvent('error', {
code: error.errorCode,
message: error.errorMessage,
error: error.errorEvent
});
} else {
app.chatEvents.fireEvent('error', {
code: 12003,
message: CHAT_ERRORS[12003],
error: error.errorEvent
});
}
});
},
getUserAndUpdateSDKState = function () {
var getUserInfoTime = new Date().getTime();
getUserInfo(function (userInfoResult) {
if (app.sdkParams.actualTimingLog) {
Utility.chatStepLogger('Get User Info ', new Date().getTime() - getUserInfoTime);
}
if (!userInfoResult.hasError) {
// userInfo = userInfoResult.result.user;
app.store.user.setUser(userInfoResult.result.user);
// getAllThreads({
// summary: true,
// cache: false
// });
app.messenger.chatState = true;
app.chatEvents.fireEvent('chatReady');
chatSendQueueHandler();
}
});
},
/**
* Get Device Id With Token
*
* If ssoGrantDevicesAddress set as TRUE, chat agent gets Device ID
* from SSO server and passes it to Async Module
*
* @access private
*
* @param {function} callback The callback function to run after getting Device Id
*
* @return {undefined}
*/
getDeviceIdWithToken = function (callback) {
var deviceId;
var params = {
url: app.sdkParams.SERVICE_ADDRESSES.SSO_ADDRESS + SERVICES_PATH.SSO_DEVICES,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + app.sdkParams.token
}
};
app.httpRequest.httpRequest(params, function (result) {
if (!result.hasError) {
var devices = JSON.parse(result.result.responseText).devices;
if (devices && devices.length > 0) {
for (var i = 0; i < devices.length; i++) {
if (devices[i].current) {
deviceId = devices[i].uid;
break;
}
}
if (!deviceId) {
app.chatEvents.fireEvent('error', {
code: 6000,
message: CHAT_ERRORS[6000],
error: null
});
} else {
callback(deviceId);
}
} else {
app.chatEvents.fireEvent('error', {
code: 6001,
message: CHAT_ERRORS[6001],
error: null
});
}
} else {
app.chatEvents.fireEvent('error', {
code: result.errorCode,
message: result.errorMessage,
error: result
});
}
});
},
/**
* Handshake with SSO to get user's keys
*
* In order to Encrypt and Decrypt cache we need a key.
* We can retrieve encryption keys from SSO, all we
* need to do is to do a handshake with SSO and
* get the keys.
*
* @access private
*
* @param {function} callback The callback function to run after Generating Keys
*
* @return {undefined}
*/
generateEncryptionKey = function (params, callback) {
var data = {
validity: 10 * 365 * 24 * 60 * 60, // 10 Years
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: app.sdkParams.SERVICE_ADDRESSES.SSO_ADDRESS + SERVICES_PATH.SSO_GENERATE_KEY,
method: 'POST',
data: data,
headers: {
'Authorization': 'Bearer ' + app.sdkParams.token
}
};
app.httpRequest.httpRequest(httpRequestParams, function (result) {
if (!result.hasError) {
try {
var response = JSON.parse(result.result.responseText);
} catch (e) {
console.log(e);
}
} else {
app.chatEvents.fireEvent('error', {
code: result.error,
message: result.error_description,
error: result
});
}
});
},
/**
* Get Encryption Keys by KeyId
*
* In order to Encrypt and Decrypt cache we need a key.
* We can retrieve encryption keys from SSO by sending
* KeyId to SSO and get related keys
*
* @access private
*
* @param {function} callback The callback function to run after getting Keys
*
* @return {undefined}
*/
getEncryptionKey = function (params, callback) {
var keyId;
if (params) {
if (params.keyId != 'undefined') {
keyId = params.keyId;
var httpRequestParams = {
url: app.sdkParams.SERVICE_ADDRESSES.SSO_ADDRESS + SERVICES_PATH.SSO_GET_KEY + keyId,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + app.sdkParams.token
}
};
app.httpRequest.httpRequest(httpRequestParams, function (result) {
if (!result.hasError) {
try {
var response = JSON.parse(result.result.responseText);
} catch (e) {
console.log(e);
}
callback && callback({
hasError: false,
secretKey: response.secretKey
});
} else {
callback && callback({
hasError: true,
code: result.errorCode,
message: result.errorMessage
});
app.chatEvents.fireEvent('error', {
code: result.errorCode,
message: result.errorMessage,
error: result
});
}
});
}
}
},
/**
* Get User Info
*
* This functions gets user info from chat serverName.
* If info is not retrived the function will attemp
* 5 more times to get info from erver
*
* @recursive
* @access private
*
* @param {function} callback The callback function to call after
*
* @return {object} Instant function return
*/
getUserInfo = function getUserInfoRecursive(callback) {
getUserInfoRetryCount++;
if (getUserInfoRetryCount > getUserInfoRetry) {
getUserInfoTimeout && clearTimeout(getUserInfoTimeout);
getUserInfoRetryCount = 0;
app.chatEvents.fireEvent('error', {
code: 6101,
message: CHAT_ERRORS[6101],
error: null
});
} else {
getUserInfoTimeout && clearTimeout(getUserInfoTimeout);
getUserInfoTimeout = setTimeout(function () {
getUserInfoRecursive(callback);
}, getUserInfoRetryCount * 10000);
return app.messenger.sendMessage({
chatMessageVOType: chatMessageVOTypes.USER_INFO,
typeCode: params.typeCode
}, {
onResult: function (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);
let resultData = {
user: currentUser
};
returnData.result = resultData;
getUserInfoRetryCount = 0;
callback && callback(returnData);
/**
* Delete callback so if server pushes response
* before cache, cache won't send data again
*/
callback = undefined;
}
}
});
}
},
sendSystemMessage = function (params) {
return app.messenger.sendMessage({
chatMessageVOType: chatMessageVOTypes.SYSTEM_MESSAGE,
subjectId: params.threadId,
content: params.content,
uniqueId: params.uniqueId,
pushMsgType: 3
});
},
/**
* Chat Send Message Queue Handler
*
* Whenever something pushes into cahtSendQueue
* this function invokes and does the message
* sending progress throught async
*
* @access private
*
* @return {undefined}
*/
chatSendQueueHandler = function () {
chatSendQueueHandlerTimeout && clearTimeout(chatSendQueueHandlerTimeout);
if (chatSendQueue.length) {
var messageToBeSend = chatSendQueue[0];
/**
* Getting chatSendQueue from either cache or
* memory and scrolling through the send queue
* to send all the messages which are waiting
* for chatState to become TRUE
*
* There is a small possibility that a Message
* wouldn't make it through network, so it Will
* not reach chat server. To avoid losing those
* messages, we put a clone of every message
* in waitQ, and when ack of the message comes,
* we delete that message from waitQ. otherwise
* we assume that these messages have been failed to
* send and keep them to be either canceled or resent
* by user later. When user calls getHistory(), they
* will have failed messages alongside with typical
* messages history.
*/
if (app.messenger.chatState) {
getChatSendQueue(0, function (chatSendQueue) {
deleteFromChatSentQueue(messageToBeSend,
function () {
app.messenger.sendMessage(messageToBeSend.message, messageToBeSend.callbacks, function () {
if (chatSendQueue.length) {
chatSendQueueHandler();
}
});
});
});
}
}
},
/**
* Ping
*
* This Function sends ping message to keep user connected to
* chat server and updates its status
*
* @access private
*
* @return {undefined}
*/
ping = function () {
if (app.messenger.chatState && app.store.user.get() !== undefined) {
/**
* Ping messages should be sent ASAP, because
* we don't want to wait for send queue, we send them
* right through async from here
*/
app.messenger.sendMessage({
chatMessageVOType: chatMessageVOTypes.PING,
pushMsgType: 3
});
} else {
sendPingTimeout && clearTimeout(sendPingTimeout);
}
},
/**
* Clear Cache
*
* Clears Async queue so that all the remained messages will be
* ignored
*
* @access private
*
* @return {undefined}
*/
clearChatServerCaches = function () {
app.messenger.sendMessage({
chatMessageVOType: chatMessageVOTypes.LOGOUT,
pushMsgType: 3
});
},
/**
* Received Async Message Handler
*
* This functions parses received message from async
*
* @access private
*
* @param {object} asyncMessage Received Message from Async
*
* @return {undefined}
*/
receivedAsyncMessageHandler = function (asyncMessage) {
/**
* + Message Received From Async {object}
* - id {long}
* - senderMessageId {long}
* - senderName {string}
* - senderId {long}
* - type {int}
* - content {string}
*/
var content = JSON.parse(asyncMessage.content);
chatMessageHandler(content);
},
/**
* is Valid Json
*
* This functions checks if a string is valid json or not?
*
* @access private
*
* @param {string} jsonString Json String to be checked
*
* @return {boolean}
*/
isValidJson = function (jsonString) {
try {
JSON.parse(jsonString);
} catch (e) {
return false;
}
return true;
},
/**
* Chat Message Handler
*
* Manages received chat messages and do the job
*
* @access private
*
* @param {object} chatMessage Content of Async Message which is considered as Chat Message
*
* @return {undefined}
*/
chatMessageHandler = function (chatMessage) {
if (chatMessage.typeCode && chatMessage.typeCode !== app.sdkParams.generalTypeCode) {
return;
}
var threadId = chatMessage.subjectId,
type = chatMessage.type,
// TODO Check this again
messageContent = (typeof chatMessage.content === 'string' && isValidJson(chatMessage.content))
? JSON.parse(chatMessage.content)
: chatMessage.content,
contentCount = chatMessage.contentCount,
uniqueId = chatMessage.uniqueId,
time = chatMessage.time;
switch (type) {
/**
* Type 1 Get Threads
*/
case chatMessageVOTypes.CREATE_THREAD:
messageContent.uniqueId = uniqueId;
if (app.store.messagesCallbacks[uniqueId]) {
createThread(messageContent, true, true);
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
} else {
createThread(messageContent, true, false);
}
break;
/**
* Type 2 Message
*/
case chatMessageVOTypes.MESSAGE:
newMessageHandler(threadId, messageContent, chatMessage, uniqueId);
break;
/**
* Type 3 Message Sent
*/
case chatMessageVOTypes.SENT:
if (app.store.sendMessageCallbacks[uniqueId] && app.store.sendMessageCallbacks[uniqueId].onSent) {
app.store.sendMessageCallbacks[uniqueId].onSent({
uniqueId: uniqueId
});
delete (app.store.sendMessageCallbacks[uniqueId].onSent);
app.store.threadCallbacks[threadId][uniqueId].onSent = true;
}
break;
/**
* Type 4 Message Delivery
*/
case chatMessageVOTypes.DELIVERY:
// if (fullResponseObject) {
// getHistory({
// offset: 0,
// threadId: threadId,
// id: messageContent.messageId,
// cache: false
// }, function (result) {
// if (!result.hasError) {
// chatEvents.fireEvent('messageEvents', {
// type: 'MESSAGE_DELIVERY',
// result: {
// message: result.result.history[0],
// threadId: threadId,
// senderId: messageContent.participantId
// }
// });
// }
// });
// } else {
app.chatEvents.fireEvent('messageEvents', {
type: 'MESSAGE_DELIVERY',
result: {
message: messageContent.messageId,
threadId: threadId,
senderId: messageContent.participantId
}
});
// }
sendMessageCallbacksHandler(chatMessageVOTypes.DELIVERY, threadId, uniqueId);
break;
/**
* Type 5 Message Seen
*/
case chatMessageVOTypes.SEEN:
if (app.sdkParams.fullResponseObject) {
getHistory({
offset: 0,
threadId: threadId,
id: messageContent.messageId,
cache: false
}, function (result) {
if (!result.hasError) {
app.chatEvents.fireEvent('messageEvents', {
type: 'MESSAGE_SEEN',
result: {
message: result.result.history[0],
threadId: threadId,
senderId: messageContent.participantId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
});
} else {
app.chatEvents.fireEvent('messageEvents', {
type: 'MESSAGE_SEEN',
result: {
message: messageContent.messageId,
threadId: threadId,
senderId: messageContent.participantId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
sendMessageCallbacksHandler(chatMessageVOTypes.SEEN, threadId, uniqueId);
break;
/**
* Type 6 Chat Ping
*/
case chatMessageVOTypes.PING:
if (app.store.messagesCallbacks[uniqueId]) {
let result = Utility.createReturnData(false, '', 0, messageContent);
result.uniqueId = uniqueId;
app.store.messagesCallbacks[uniqueId](result);
}
break;
/**
* Type 7 Block Contact
*/
case chatMessageVOTypes.BLOCK:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent));
}
break;
/**
* Type 8 Unblock Blocked User
*/
case chatMessageVOTypes.UNBLOCK:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent));
}
break;
/**
* Type 9 Leave Thread
*/
case chatMessageVOTypes.LEAVE_THREAD:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
if (app.sdkParams.fullResponseObject) {
getThreads({
threadIds: [threadId]
}, function (threadsResult) {
if (!threadsResult.cache) {
var threads = threadsResult.result.threads;
if (threads.length > 0) {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LEAVE_PARTICIPANT',
result: {
thread: threads[0],
participant: formatDataToMakeParticipant(messageContent, threadId)
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: threads[0]
},
uniqueId,
typeCode: chatMessage.typeCode
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LEAVE_PARTICIPANT',
result: {
threadId: threadId,
participant: formatDataToMakeParticipant(messageContent, threadId)
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
}
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LEAVE_PARTICIPANT',
result: {
thread: threadId,
participant: formatDataToMakeParticipant(messageContent, threadId)
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
break;
/**
* Type 11 Add Participant to Thread
*/
case chatMessageVOTypes.ADD_PARTICIPANT:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
if (app.sdkParams.fullResponseObject) {
getThreads({
threadIds: [messageContent.id]
}, function (threadsResult) {
var threads = threadsResult.result.threads;
if (!threadsResult.cache) {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_ADD_PARTICIPANTS',
result: {
thread: threads[0]
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: threads[0]
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_ADD_PARTICIPANTS',
result: {
thread: messageContent
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: messageContent
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
break;
/**
* Type 13 Get Contacts List
*/
case chatMessageVOTypes.GET_CONTACTS:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
break;
/**
* Type 14 Get Threads List
*/
case chatMessageVOTypes.GET_THREADS:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
break;
/**
* Type 15 Get Message History of an Thread
*/
case chatMessageVOTypes.GET_HISTORY:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
break;
/**
* Type 17 Remove sb from thread
*/
case chatMessageVOTypes.REMOVED_FROM_THREAD:
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_REMOVED_FROM',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
break;
/**
* Type 18 Remove a participant from Thread
*/
case chatMessageVOTypes.REMOVE_PARTICIPANT:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent, contentCount));
}
if (app.sdkParams.fullResponseObject) {
getThreads({
threadIds: [threadId]
}, function (threadsResult) {
var threads = threadsResult.result.threads;
if (!threadsResult.cache) {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_REMOVE_PARTICIPANTS',
result: {
thread: threads[0]
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: threads[0]
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_REMOVE_PARTICIPANTS',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_LAST_ACTIVITY_TIME',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
break;
/**
* Type 19 Mute Thread
*/
case chatMessageVOTypes.MUTE_THREAD:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent));
}
if (app.sdkParams.fullResponseObject) {
getThreads({
threadIds: [threadId]
}, function (threadsResult) {
var thread = threadsResult.result.threads[0];
thread.mute = true;
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_MUTE',
result: {
thread: thread
},
uniqueId,
typeCode: chatMessage.typeCode
});
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_MUTE',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
break;
/**
* Type 20 Unmute muted Thread
*/
case chatMessageVOTypes.UNMUTE_THREAD:
if (app.store.messagesCallbacks[uniqueId]) {
app.store.messagesCallbacks[uniqueId](Utility.createReturnData(false, '', 0, messageContent));
}
if (app.sdkParams.fullResponseObject) {
getThreads({
threadIds: [threadId]
}, function (threadsResult) {
var thread = threadsResult.result.threads[0];
thread.mute = false;
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_UNMUTE',
result: {
thread: thread
},
uniqueId,
typeCode: chatMessage.typeCode
});
});
} else {
app.chatEvents.fireEvent('threadEvents', {
type: 'THREAD_UNMUTE',
result: {
thread: threadId
},
uniqueId,
typeCode: chatMessage.typeCode
});
}
break;
/**
* Type 21 Update Thread I