SmartIT_Extensions/BMC/smart-it-full-helix/components/chat/chat-model.js

767 lines
43 KiB
JavaScript

"use strict";
(function () {
'use strict';
angular.module('myitsmApp')
.factory('chatModel', ['$http', '$timeout', '$filter', '$q', 'chatService', 'chatSwarm', 'userModel', 'systemAlertService', 'ticketModel', 'assetModel',
function ($http, $timeout, $filter, $q, chatService, chatSwarm, userModel, systemAlertService, ticketModel, assetModel) {
var chatModel = {
Client: {},
connectInProgress: false,
connected: false,
cachedProfiles: {},
pendingProfileRequests: {},
currentUser: { available: EntityVO.CHAT_STATUS_OFFLINE },
activeChatRooms: [],
pendingChatRoomMessages: {}
};
var checkAvailabilityList = [], requestedProfiles = [], profileRequestPromise;
chatModel.openChatConnection = function () {
if (chatModel.connectInProgress) {
return;
}
chatModel.connectInProgress = true;
userModel.getFullCurrentUserData()
.then(function () {
return chatService.openChatConnection({ userCallbacks: chatModel.chatEventHandlers });
})
.then(function (Client) {
chatModel.Client = Client;
chatModel.Client.pendingPromises.connectionState.promise.then(function () {
chatModel.currentUser = userModel.userFullData;
chatModel.currentUser.available = EntityVO.CHAT_STATUS_ONLINE;
if (!chatModel.currentUser.jid) {
chatModel.currentUser.jid = Strophe.getNodeFromJid(chatModel.Client.conn.jid);
}
chatModel.connected = true;
chatModel.Client.pendingPromises.disconnect.promise.then(function () {
chatModel.connected = true;
chatModel.currentUser.available = EntityVO.CHAT_STATUS_ONLINE;
});
});
})
.finally(function () {
chatModel.connectInProgress = false;
});
};
chatModel.getUserProfileByJID = function (jid) {
var userProfilesToRequest = _.uniq([].concat(jid));
if (userProfilesToRequest && requestedProfiles.length > 0) {
userProfilesToRequest = _.difference(userProfilesToRequest, requestedProfiles);
}
if (userProfilesToRequest.length == 0) {
return profileRequestPromise;
}
else {
requestedProfiles = angular.copy(userProfilesToRequest);
}
profileRequestPromise = chatModel.Client.getUserProfileByJID(requestedProfiles)
.then(function (resp) {
_.each(resp, function (profile) {
chatModel.cachedProfiles[profile.jid] ? angular.extend(chatModel.cachedProfiles[profile.jid], profile) : chatModel.cachedProfiles[profile.jid] = profile;
});
return resp;
})
.finally(function () {
requestedProfiles = [];
});
return profileRequestPromise;
};
var availabilityCheckDebounced = _.debounce(function (users) {
var request = (users.length == 1) ? users[0] : users;
return chatModel.Client.checkPresence(request)
.then(function (response) {
var availabilityData = {};
if (response.available) {
availabilityData[request] = response.available;
}
else {
availabilityData = response.availability;
}
_.each(availabilityData, function (status, userJID) {
status = status.toLowerCase();
if (chatModel.cachedProfiles[userJID]) {
chatModel.cachedProfiles[userJID].available = status;
}
else {
chatModel.cachedProfiles[userJID] = { available: status };
}
});
checkAvailabilityList = [];
return (response.available || response.availability);
});
}, 400);
chatModel.checkUserAvailability = function (user) {
checkAvailabilityList = _.uniq(checkAvailabilityList.concat(user));
availabilityCheckDebounced(_.compact(checkAvailabilityList));
};
chatModel.generateUserJID = function (loginId) {
if (!loginId)
return "";
var systeUserJID = chatModel.currentUser.jid, systemUserId = chatModel.currentUser.loginId;
var systemTenant = systeUserJID.split(systemUserId.toLowerCase()).pop();
return loginId.toLowerCase() + systemTenant;
};
chatModel.updateCachedProfiles = function (profiles) {
if (profiles && profiles.length) {
_.each(profiles, function (profile) {
if (profile.jid) {
chatModel.cachedProfiles[profile.jid] = profile;
}
});
}
};
chatModel.setUserAvailability = function (availability) {
chatModel.currentUser.available = availability;
chatModel.currentUser.manualStatus = availability;
return chatModel.Client.setUserPresence(availability);
};
chatModel.createChatRoom = function (invitee) {
var chatWindow = chatModel.createChatWindowInstance({ isOpened: true, messages: [] });
chatModel.activeChatRooms.push(chatWindow);
return chatModel.Client.createChatRoom(invitee)
.then(function (room) {
var chatRoom = chatModel.Client.conn['muc'].rooms[room.name];
var userJid = chatModel.Client.conn.jid, message = chatModel.createChatMessageInstance({ eventType: 'enter', author: { jid: userJid }, type: 'system' }, chatRoom.name);
chatWindow.build({ id: chatRoom.name, room: chatRoom, isLoading: false, participants: chatRoom.roster, messages: [message] });
return chatWindow;
})
.finally(function () {
chatWindow.isLoading = false;
});
};
chatModel.createChatWindowInstance = function (config) {
var activeChatWindow = config.room ? _.find(chatModel.activeChatRooms, { id: config.room.name }) : angular.noop();
if (activeChatWindow)
return activeChatWindow;
var chatWindow = new ChatWindowVO();
if (config) {
chatWindow.build(config);
}
return chatWindow;
};
chatModel.createChatMessageInstance = function (message, roomName) {
var chatWindow = _.find(chatModel.activeChatRooms, { id: roomName }), author = message.author, authorProfile, authorUserId, newMessage;
var mucRoom = chatModel.Client.conn['muc'].rooms[roomName], currentUserNick = mucRoom.nick;
if (author.nick && chatWindow) {
author.jid = chatWindow.participants[author.nick] ? chatWindow.participants[author.nick].jid : '';
if (!author.jid && currentUserNick == author.nick) {
author.jid = chatModel.currentUser.jid;
}
}
else if (author.nick && !chatWindow) {
var authorInfo = mucRoom.roster ? mucRoom.roster[author.nick] : angular.noop();
if (!authorInfo) {
if (currentUserNick == author.nick) {
authorInfo = chatModel.currentUser;
}
else
return { message: message, roomName: roomName, skipped: true };
}
author.jid = authorInfo.jid;
}
authorUserId = author.jid ? author.jid.split("@")[0] : angular.noop();
authorProfile = (authorUserId == chatModel.currentUser.jid) ? chatModel.currentUser : chatModel.cachedProfiles[authorUserId];
if (!authorProfile || (authorProfile && !authorProfile.firstName)) {
chatModel.getUserProfileByJID([authorUserId]).then(function () {
newMessage.author = chatModel.cachedProfiles[authorUserId];
(chatWindow && chatWindow.roster && !chatWindow.roster[authorUserId]) ? chatWindow.roster[authorUserId] = newMessage.author : angular.noop();
});
}
else {
(chatWindow && chatWindow.roster && !chatWindow.roster[authorUserId]) ? chatWindow.roster[authorUserId] = authorProfile : angular.noop();
}
if (chatSwarm.checkIfChatOpsMessage(message.text)) {
newMessage = chatSwarm.formatChatMessage(newMessage, message, chatWindow, authorProfile, false);
}
else if (message.hasOwnProperty("text") && message.text != (EntityVO.CHATOPS_SWARM) && message.text.startsWith(EntityVO.CHATOPS_SWARM)) {
try {
var messageText = message.text.substring(6);
if (!chatSwarm.checkIfJson(messageText)) {
newMessage = new ChatMessageVO()
.build({
text: message.text, author: authorProfile, chatWindow: chatWindow, type: message.type || 'chat',
created: message.created || "", eventType: message.eventType
});
}
else {
var fullData = JSON.parse(messageText);
var json = JSON.parse(fullData.participants);
for (var i = 0; i < json.length; i++) {
var personDetailsSelf = json[i];
if (authorProfile != null && authorProfile.hasOwnProperty("fullName") && personDetailsSelf[0].fullName == authorProfile.fullName) {
json.splice(i, 1);
break;
}
}
for (var p = 0; p < json.length; p++) {
var personDetails = json[p];
chatModel.checkUserAvailability(personDetails[0].jid);
try {
json[p].available = chatModel.cachedProfiles[personDetails[0].jid].available;
}
catch (e) {
json[p].available = "offline";
}
}
fullData.participants = json;
newMessage = new ChatMessageDataVO()
.build({
created: message.created,
data: fullData,
author: authorProfile,
type: message.type || 'swarmPeopleDetails',
chatWindow: chatWindow
});
}
}
catch (e) {
newMessage = new ChatMessageDataVO()
.build({
created: message.created,
data: [],
author: authorProfile,
type: message.type || 'swarmPeopleDetails',
chatWindow: chatWindow
});
}
}
else {
newMessage = new ChatMessageVO()
.build({
text: message.text, author: authorProfile, chatWindow: chatWindow, type: message.type || 'chat',
created: message.created || "", eventType: message.eventType
});
}
return newMessage;
};
chatModel.assignChatRoom = function (room, assignInfo) {
return chatModel.Client.assignChatRoom(room, assignInfo);
};
chatModel.createAssignedChatRoom = function (parent, user) {
return chatModel.createChatRoom(user).then(function (chatWindow) {
// var chatRoom = _.findWhere(chatModel.activeChatRooms,{id: room.name});
chatWindow.parent = parent;
return chatModel.assignChatRoom(chatWindow.room, parent);
});
};
chatModel.createAssignedChatRoomWithUser = function (user, parent) {
return chatModel.createAssignedChatRoom(parent, user);
};
chatModel.removeChatAssignment = function (room) {
return chatModel.Client.removeChatAssignment(room);
};
chatModel.inviteUserToChat = function (user, chatWindow) {
chatModel.Client.inviteUserToChatRoom(user, chatWindow.room);
if (!chatWindow.roster[user.jid]) {
chatWindow.roster[user.jid] = user;
}
};
chatModel.processChatMessage = function (messageText, chatWindow) {
if (messageText == EntityVO.CHATOPS_DETAILS || messageText == EntityVO.CHATOPS_KNOWLEDGE
|| messageText == EntityVO.CHATOPS_SIMILARINCIDENTS || messageText == EntityVO.CHATOPS_SWARM || messageText == EntityVO.CHATOPS_TOOLS) {
chatSwarm.processChatMessage(messageText, chatWindow).then(function (response) {
chatModel.sendChatMessage(response, chatWindow.room);
}, function (result) {
chatModel.sendChatMessage(EntityVO.CHATOPS_ERROR, chatWindow.room);
});
}
else {
chatModel.sendChatMessage(messageText, chatWindow.room);
}
};
chatModel.generateChatWindowByRoomId = function (id) {
if (!id)
return $q.when(1);
return chatModel.Client.joinChat(id).then(function (room) {
var chatConfig = { room: room, roster: {}, isLoading: true }, chatWindow = chatModel.createChatWindowInstance(chatConfig);
var participantPromise = chatModel.getParticipantsProfiles(chatWindow), parentPromise = chatModel.getRoomAdditionalInfo(chatWindow);
$q.all([participantPromise, parentPromise]).finally(function () {
chatWindow.isLoading = false;
if (!chatWindow.parent && chatWindow.assignedTo) {
var parent = ticketModel.cache[chatWindow.assignedTo.objectId];
if (parent) {
chatWindow.parent = parent;
}
}
});
chatModel.activeChatRooms.push(chatWindow);
return chatWindow;
});
};
chatModel.sendChatMessage = function (message, room) {
var nickname = room.client.nick;
room.message(nickname, message, null, 'groupchat');
};
chatModel.getParticipantsProfiles = function (chatWindow) {
var room = chatWindow.room, requestProfiles = [];
_.each(room.roster, function (user) {
var userJID = Strophe.getNodeFromJid(user.jid), cachedProfile = chatModel.cachedProfiles[userJID];
if (userJID == chatModel.currentUser.jid) {
chatWindow.roster[userJID] = chatModel.currentUser;
return;
}
if (cachedProfile && (cachedProfile.fullName || cachedProfile.displayName)) {
chatWindow.roster[userJID] = chatModel.cachedProfiles[userJID];
}
else {
requestProfiles.push(userJID);
}
});
if (requestProfiles.length > 0) {
chatModel.getUserProfileByJID(requestProfiles).then(function () {
$timeout(function () {
_.each(requestProfiles, function (profileJID) {
chatWindow.roster[profileJID] = chatModel.cachedProfiles[profileJID];
});
});
});
}
};
chatModel.getRoomAdditionalInfo = function (chatWindow) {
var room = chatWindow.room, chatHistory = chatModel.pendingChatRoomMessages[chatWindow.id];
if (chatHistory) {
!chatWindow.messages ? chatWindow.messages = [] : angular.noop();
_.each(chatHistory, function (historyItem) {
if (historyItem.skipped) {
var message = chatModel.createChatMessageInstance(historyItem.message, historyItem.roomName);
}
chatWindow.messages.push(message || historyItem);
});
chatModel.pendingChatRoomMessages[chatWindow.id] = null;
}
chatWindow.loadingAssignments = true;
chatModel.Client.getRoomAssignments(room)
.then(function (resp) {
if (resp.assignmentData && !_.isEmpty(resp.assignmentData)) {
chatWindow.assignedTo = resp.assignmentData;
return chatModel.fillRoomParentData(chatWindow, resp.assignmentData);
}
else
chatWindow.loadingAssignments = false;
return $q.when(1);
})
.catch(function () {
chatWindow.loadingAssignments = false;
});
//No need to show spinner while conversation assignment is loading
return $q.when(1);
};
chatModel.fillRoomParentData = function (chatWindow, parentInfo) {
var assignmentPromise;
if (parentInfo.objectType == EntityVO.TYPE_ASSET) {
assignmentPromise = assetModel.getAssetDetailsByID(parentInfo.objectId, parentInfo.classId)
.then(function () {
chatWindow.parent = assetModel.assetDetails;
return assetModel.assetDetails;
});
}
else {
parentInfo.chatWindow = chatWindow;
assignmentPromise = ticketModel.getTicket(parentInfo.objectId, parentInfo.objectType)
.then(function () {
if (chatWindow) {
chatWindow.parent = ticketModel.cache[parentInfo.objectId];
}
return ticketModel.cache[parentInfo.objectId];
});
}
return assignmentPromise.finally(function () { chatWindow.loadingAssignments = false; });
};
chatModel.showNotification = function (chatWindow) {
var senderJID = chatWindow.inviterJID, senderProfile = chatModel.cachedProfiles[senderJID] || {};
if (senderProfile.fullName || senderProfile.displayName) {
var inviterName = senderProfile.fullName || senderProfile.displayName, text = $filter('i18n')('chat.invitationMessage', inviterName);
}
else {
var inviter = _.find(chatWindow.participants, function (user) {
var userJID = Strophe.getNodeFromJid(user.jid);
return (userJID == senderJID);
}), inviterNick = inviter.nick.split("_").join(" ");
text = $filter('i18n')('chat.invitationMessage', inviterNick);
}
systemAlertService.success({ text: text, icon: "icon-comments", clear: true, hide: 10000, click: (function () { this.isOpened = true; }).bind(chatWindow) });
};
chatModel.getCurrentStateTicketData = function (stateId) {
return ticketModel.cache[stateId];
};
chatModel.saveChatLogToTicketWorknote = function (chatWindow, parentTicket) {
// if(chatWindow.parent && (parentTicket.id == chatWindow.parent.id)){
if (parentTicket.reconciliationId) {
return chatModel.Client.saveChatLogToTicketWorknote(chatWindow.room, parentTicket.reconciliationId, parentTicket.ticketType, parentTicket.classId);
}
return chatModel.Client.saveChatLogToTicketWorknote(chatWindow.room, parentTicket.id, parentTicket.type);
};
chatModel.openChatWindow = function (chatWindow) {
if (chatWindow.hasOwnProperty('isOpened')) {
chatWindow.isOpened = true;
}
return chatWindow;
};
chatModel.leaveRoomAndDestroyChatWindow = function (chatWindow) {
chatModel.Client.destroyChatRoom(chatWindow.room);
chatModel.removeChatFromActiveList(chatWindow);
chatModel.Client.removeRoosterItemByJID(chatWindow.room.name);
};
chatModel.leaveConversation = function (chatWindow) {
chatModel.Client.leaveChatRoom(chatWindow.room);
chatModel.removeChatFromActiveList(chatWindow);
chatModel.Client.removeRoosterItemByJID(chatWindow.room.name);
};
chatModel.removeChatFromActiveList = function (chatWindow) {
var index = chatModel.activeChatRooms.indexOf(chatWindow);
if (index >= 0) {
chatModel.activeChatRooms.splice(index, 1);
}
};
/**
* These Callbacks are being triggered from chat-service
* */
chatModel.chatEventHandlers = {
connectionState: function (status) {
chatModel.connected = status == 'connected' ? true : false;
},
presence: function (jid, status, manualStatus) {
$timeout(function () {
var userId = jid.split("@")[0];
if (userId == chatModel.Client.conn.authcid && (jid != chatModel.Client.conn.jid)) {
if (manualStatus && (manualStatus != chatModel.currentUser.manualStatus)) {
chatModel.currentUser.available = status;
chatModel.currentUser.manualStatus = manualStatus;
chatModel.Client.setUserPresence(status);
}
return;
}
if (chatModel.cachedProfiles[userId]) {
chatModel.cachedProfiles[userId].available = status;
}
else {
chatModel.cachedProfiles[userId] = { available: status };
}
});
},
invite: function (invite) {
var from = invite.from, inviterJID = from.split("@")[0];
chatModel.Client.joinChat(invite.roomId).then(function (room) {
var chatConfig = { room: room, roster: {}, inviterJID: inviterJID, isLoading: true }, chatWindow = chatModel.createChatWindowInstance(chatConfig);
var participantsPromise = chatModel.getParticipantsProfiles(chatWindow), parentPromise = chatModel.getRoomAdditionalInfo(chatWindow);
$q.all([participantsPromise, parentPromise])
.finally(function () {
chatWindow.isLoading = false;
$timeout(function () {
chatModel.showNotification(chatWindow);
chatModel.activeChatRooms.push(chatWindow);
});
chatModel.Client.addToRoster(room.name);
});
});
},
message: function (messageData, roomName) {
var newMessage = chatModel.createChatMessageInstance(messageData, roomName), chatWindow = newMessage ? newMessage.chatWindow : null;
if (!chatWindow) {
chatModel.pendingChatRoomMessages[roomName] ? chatModel.pendingChatRoomMessages[roomName].push(newMessage) : chatModel.pendingChatRoomMessages[roomName] = [newMessage];
return true;
}
$timeout(function () {
chatWindow.messages ? chatWindow.messages.push(newMessage) : chatWindow.messages = [newMessage];
});
},
history: function (message, roomName) {
var newMessage = chatModel.createChatMessageInstance(message, roomName), chatWindow = newMessage.chatWindow;
if (!chatWindow) {
chatModel.pendingChatRoomMessages[roomName] ? chatModel.pendingChatRoomMessages[roomName].push(newMessage) : chatModel.pendingChatRoomMessages[roomName] = [newMessage];
}
else {
$timeout(function () {
chatWindow.messages ? chatWindow.messages.push(newMessage) : chatWindow.messages = [newMessage];
});
}
},
roomAutoJoin: function (room) {
var chatConfig = { room: room, roster: {}, isLoading: true }, chatWindow = chatModel.createChatWindowInstance(chatConfig);
var participantPromise = chatModel.getParticipantsProfiles(chatWindow);
var parentPromise = chatModel.getRoomAdditionalInfo(chatWindow);
$q.all([participantPromise, parentPromise]).finally(function () {
chatWindow.isLoading = false;
});
chatModel.activeChatRooms.push(chatWindow);
},
roomAutoLeave: function (room) {
var text = $filter('i18n')('chat.popup.systemMessage.leaveChatRoom.self');
var chatWindow = _.find(chatModel.activeChatRooms, { id: room.name });
if (window.opener) {
chatWindow.inactiveRoom = true;
}
if (chatWindow) {
chatWindow.inactiveRoomReason = text;
var index = chatModel.activeChatRooms.indexOf(chatWindow);
if (index >= 0) {
chatModel.activeChatRooms.splice(index, 1);
}
}
return room.name;
},
chatRoomChanges: function (room, changes) {
if (changes) {
var chatWindow = _.find(chatModel.activeChatRooms, { id: (room ? room.name : changes.data.roomId) });
if (changes.type == 'connection') {
chatWindow.loadingAssignments = true;
chatModel.fillRoomParentData(chatWindow, changes.data)
.then(function () {
var msg = generateAssignmentUpdatesMessage(chatWindow, changes);
$timeout(function () {
chatWindow.messages.push(msg);
});
});
}
else if (changes.type == 'disconnection') {
changes.parent = _.clone(chatWindow.parent);
var msg = generateAssignmentUpdatesMessage(chatWindow, changes);
$timeout(function () {
chatWindow.messages.push(msg);
});
if (chatWindow.parent) {
chatWindow.parent = null;
}
}
else if (changes.type == 'roster') {
var userJid = Strophe.getBareJidFromJid(changes.data.jid), message = chatModel.createChatMessageInstance({ eventType: changes.data.eventType, author: { jid: userJid },
type: 'system' }, changes.data.roomId);
if (!chatWindow) {
if (chatModel.pendingChatRoomMessages[changes.data.roomId]) {
chatModel.pendingChatRoomMessages[changes.data.roomId].push(message);
}
else {
chatModel.pendingChatRoomMessages[changes.data.roomId] = [message];
}
}
else {
$timeout(function () {
if (changes.data.eventType == 'enter') {
chatWindow.participants = _.clone(chatWindow.room.roster);
}
chatWindow.messages ? chatWindow.messages.push(message) : chatWindow.messages = [message];
});
}
}
else if (changes.type == 'destroy' && chatWindow) {
if (room) {
var chatOwner = chatWindow.roomOwner || _.find(chatWindow.participants, { affiliation: 'owner' }), chatOwnerId = chatOwner.jid.split("@")[0], chatOwnerProfile = chatWindow.roster[chatOwnerId], ownerName = chatOwnerProfile ? "" + (chatOwnerProfile.displayName || chatOwnerProfile.firstName + " " + chatOwnerProfile.lastName) : chatOwner.nick.replace("_", " "), text = $filter('i18n')("chat.ownerLeave.notification", ownerName);
systemAlertService.success({ text: text, icon: "icon-comments", clear: true, hide: 10000 });
chatWindow.inactiveRoomReason = text;
}
$timeout(function () {
chatWindow.inactiveRoom = true;
chatWindow.isOpened = false;
var index = chatModel.activeChatRooms.indexOf(chatWindow);
(index >= 0) ? chatModel.activeChatRooms.splice(index, 1) : angular.noop();
if (window.opener)
window.close();
});
}
}
},
rosterUpdates: function (updates) {
var deletedItems = updates.removed;
deletedItems.length && handleItemsDeletedFromRoster(deletedItems);
}
};
chatModel.generateRosterSummary = function (chatWindow) {
if (chatWindow.generateRosterSummary) {
return chatWindow.generateRosterSummary();
}
};
chatModel.getArchivedConversationDetails = function (conv) {
var roomId = conv.mucJid;
return chatModel.Client.getArchivedConversationById(conv.id)
.then(function (resp) {
var conversationJSON, conversationMessages = [];
try {
conversationJSON = JSON.parse(resp);
}
catch (e) {
conversationJSON = {};
}
if (resp) {
var conversation = conversationJSON.messages || [];
_.each(conversation, function (msg, index, context) {
if (index > 0) {
var prevMsg = context[index - 1];
if (prevMsg && ((prevMsg.sentDate == msg.sentDate || prevMsg.body == msg.body) && prevMsg.fromJid == msg.fromJid && prevMsg.event && msg.event))
return;
}
if (msg.event || (roomId == msg.fromJid && roomId == msg.toJid)) {
msg.type = 'system';
if (msg.body.indexOf("disconnection") >= 0) {
msg.eventType = 'disconnected';
msg.parent = msg.body.match(/[^{}]+(?=\})/g);
}
else if (msg.body.indexOf("connection") >= 0) {
msg.eventType = 'connected';
msg.parent = msg.body.match(/[^{}]+(?=\})/g);
}
else {
msg.eventType = "other";
msg.text = msg.body;
}
if (msg.parent) {
msg.parent = JSON.parse("{" + msg.parent + "}");
if (msg.parent.connectorsJid == chatModel.currentUser.jid)
msg.senderProfile = chatModel.currentUser;
else
msg.senderProfile = chatModel.cachedProfiles[msg.parent.connectorsJid];
}
}
else {
if (msg.fromJid != chatModel.currentUser.jid)
msg.senderProfile = chatModel.cachedProfiles[msg.fromJid];
else
msg.senderProfile = chatModel.currentUser;
}
var message = convertArchiveItemToChatMessage(msg);
if (msg.parent)
chatModel.fillRoomParentData(message, msg.parent);
conversationMessages.push(message);
});
conversationMessages = _.sortBy(conversationMessages, 'created');
}
return conversationMessages;
});
};
chatModel.getConversationsHistory = function (start, limit) {
var params = { start: (start || 0), limit: (limit || 100) };
return chatModel.Client.requestConversationsHistoryForCurrentUser(params)
.then(function (history) {
if (!history) {
return $q.when(1);
}
return processConversationHistory(history);
});
};
function generateAssignmentUpdatesMessage(chatWindow, assignInfo) {
var type = (assignInfo.type == 'connection') ? 'connected' : 'disconnected', userJid = assignInfo.data ? assignInfo.data.connectorsJid : '', userProfile = (userJid == chatModel.currentUser.jid) ? chatModel.currentUser : chatModel.cachedProfiles[userJid], parent = chatWindow.parent ? _.clone(chatWindow.parent) : assignInfo.parent;
var settings = { author: userProfile, type: 'system', created: new Date().getTime(), eventType: type, parent: parent };
return new ChatMessageVO().build(settings);
}
function processConversationHistory(historyItems) {
console.log("Processing History: ", historyItems);
var chatHistory = { requestProfiles: [], requestTickets: [], pendingTicketDetails: [] }, chatHistoryArr = [];
_.map(historyItems, function (item) {
if (item.conversation.messagesCount == 0 || item.conversation.participants.length < 2) {
return;
}
var id = item.conversation.id, buildData = angular.extend(item.conversation, { connection: item.connection });
buildData.participants = _.without(buildData.participants, chatModel.currentUser.jid);
chatHistory[id] = new ChatHistoryItemVO().build(buildData);
chatHistoryArr.push(chatHistory[id]);
if (item.connection) {
chatHistory[id].parent = item.connection;
if (item.connection.objectType == EntityVO.TYPE_SERVICEREQUEST || item.connection.objectType == EntityVO.TYPE_ASSET) {
chatModel.fillRoomParentData(chatHistory[id], item.connection).then(function (parentData) {
chatHistory[id].parent = parentData;
});
}
else {
chatHistory.requestTickets = _.union(chatHistory.requestTickets, [{ uuid: item.connection.objectId, type: item.connection.objectType }]);
chatHistory.pendingTicketDetails.push(chatHistory[id]);
}
}
chatHistory.requestProfiles = _.union(chatHistory.requestProfiles, chatHistory[id].participants);
});
if (chatHistory.requestProfiles.length > 0) {
chatModel.getUserProfileByJID(chatHistory.requestProfiles, true).then(function () {
chatHistory.requestProfiles = null;
_.each(chatHistoryArr, function (chatHistoryItem) {
chatHistoryItem.fillRoster(chatModel.cachedProfiles);
});
});
}
if (chatHistory.requestTickets.length > 0) {
chatModel.Client.getTicketDetailsBulk(chatHistory.requestTickets)
.then(function (ticketDetails) {
chatHistory.requestTickets = null;
_.each(chatHistory.pendingTicketDetails, function (chatHistoryItem) {
var parentTicket = ticketDetails[chatHistoryItem.parent.objectId][0];
parentTicket ? chatHistoryItem.parent = parentTicket : angular.noop();
ticketModel.cache[chatHistoryItem.parent.objectId] = parentTicket;
});
chatHistory.pendingTicketDetails = [];
});
}
return { obj: chatHistory, arr: chatHistoryArr };
}
function convertArchiveItemToChatMessage(data) {
var newMessage = "";
if (chatSwarm.checkIfChatOpsMessage(data.body)) {
var message = { "text": data.body, "created": data.sentDate };
newMessage = chatSwarm.formatChatMessage(newMessage, message, null, data.senderProfile, true);
}
else if (data.body != (EntityVO.CHATOPS_SWARM) && data.body.startsWith(EntityVO.CHATOPS_SWARM) && chatSwarm.checkIfJson(data.body.substring(6))) {
try {
var messageText = data.body.substring(6);
var fullData = JSON.parse(messageText);
var json = JSON.parse(fullData.participants);
for (var i = 0; i < json.length; i++) {
var personDetailsSelf = json[i];
if (data.senderProfile != null && data.senderProfile.hasOwnProperty("fullName") && personDetailsSelf[0].fullName == data.senderProfile.fullName) {
json.splice(i, 1);
break;
}
}
for (var p = 0; p < json.length; p++) {
var personDetails = json[p];
chatModel.checkUserAvailability(personDetails[0].jid);
try {
json[p].available = chatModel.cachedProfiles[personDetails[0].jid].available;
}
catch (e) {
json[p].available = "offline";
}
}
fullData.participants = json;
newMessage = new ChatMessageDataVO()
.build({
created: data.sentDate,
data: fullData,
author: data.senderProfile,
type: 'swarmPeopleDetails',
fromHistory: true,
chatWindow: null
});
}
catch (e) {
newMessage = new ChatMessageDataVO()
.build({
created: data.sentDate,
data: [],
author: data.senderProfile,
type: 'swarmPeopleDetails',
fromHistory: true,
chatWindow: null
});
}
}
else {
var messageSettings = { text: data.text || data.body, author: data.senderProfile, type: data.type || 'chat', created: data.sentDate, eventType: data.eventType };
data.parent ? messageSettings.parent = data.parent : angular.noop();
newMessage = new ChatMessageVO().build(messageSettings);
}
return newMessage;
}
function handleItemsDeletedFromRoster(items) {
_.each(items, function (jid) {
var chatWindow = _.find(chatModel.activeChatRooms, { id: jid });
if (chatWindow) {
var index = chatModel.activeChatRooms.indexOf(chatWindow);
if (index >= 0) {
$timeout(function () {
chatModel.activeChatRooms.splice(index, 1);
});
}
}
});
}
return chatModel;
}
]);
}());