`use strict`;
let rocketChatSocket = null;
let activeChannelClass = 'active';
let groupChannelClass = 'group';
let defaultZIndex = 99999;
let dateTimeOptions = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timezone: 'UTC',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
let timeOptions = {
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
let dateOptions = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timezone: 'UTC'
};
let userNamesArray = [];
let loadNewPage = false;
let channelsTimes = {};
let lastCreatedChannelName = null;
let lastCreatedChannelId = null;
let needLoadDefaultChannelMessages = false;
$(window).on("load", function () {
$.ajax({
url: '/ajax/chat/getAgencyUserNames.php',
success: function (data) {
userNamesArray = JSON.parse(data);
if ($('#session_user_chat_username').length > 0) {
let logo = findLogoByUsername($('#session_user_chat_username').val());
if (logo) {
$('.chat-block__top_left-icon img').attr('src', logo);
$('.chat-block__top_left-icon').show();
} else {
$('.chat-block__top_left-icon').hide();
}
}
setupChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
}
});
}
);
$(document).ready(function () {
$('.chat-main-block .chat-block__top_left-burger').on('click', function () {
$(this).toggleClass('active');
$('.chat-main-block .chat-block__left').toggleClass('show');
//$('.chat-block__right').toggleClass('hide');
});
$('.chat-main-block .dots-modal__add-remove_title').on('click', function () {
$(this).next().slideToggle();
});
$('.chat-main-block .chat-block__top_right-icons .closed').on('click', function () {
document.getElementById("chat-content").removeEventListener("scroll", onScrollMessagesPart);
$(".chat-main-block").hide(50);
});
$('.chat-main-block .group-data__top_icon').on('click', function () {
let userAmin = $('.chat-main-block .chat-block__left_item.active').length > 0 ? $('.chat-main-block .chat-block__left_item.active').attr('data-admin') : '';
let type = $('.chat-main-block .chat-block__left_item.active').length > 0 ? $('.chat-main-block .chat-block__left_item.active').attr('data-type') : '';
if (type === 'g' && $('#session_user_chat_username').val() === userAmin) {
$('#changeGroupAvatarBlock').show();
}
});
$('.chat-main-block .dots-modal-show').on('click', function () {
$('.chat-main-block .dots-modal__btn2').hide();
$('.chat-main-block .dots-modal__btn3').hide();
$('.chat-main-block .dots-modal__btn4').hide();
$('.chat-main-block .dots-modal').css('height', '58px');
$('.chat-main-block .dots-modal').css('bottom', '-45px');
let userAmin = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-admin') : '';
let type = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-type') : '';
if (type === 'd') {
$('.chat-main-block .dots-modal__btn3').show();
$('.chat-main-block .dots-modal').css('height', '85px');
$('.chat-main-block .dots-modal').css('bottom', '-75px');
} else {
if (userAmin) {
if ($('#session_user_chat_username').val() === userAmin) {
$('.chat-main-block .dots-modal__btn3').show();
$('.chat-main-block .dots-modal__btn2').show();
$('.chat-main-block .dots-modal').css('height', '122px');
$('.chat-main-block .dots-modal').css('bottom', '-105px');
} else {
$('.chat-main-block .dots-modal__btn4').show();
$('.chat-main-block .dots-modal').css('height', '85px');
$('.chat-main-block .dots-modal').css('bottom', '-75px');
}
} else {
$('.chat-main-block .dots-modal__btn4').show();
$('.chat-main-block .dots-modal').css('height', '85px');
$('.chat-main-block .dots-modal').css('bottom', '-75px');
}
}
$('.chat-main-block .dots-modal').fadeIn();
});
$("body").on('click', '.new-message__top_closed', function(){
$(this).parents('.new-message').remove();
return false;
});
$("body").on('click', '.new-message', function(){
let channelId = $(this).attr('data-channel');
if (channelId) {
let messageChannelDiv = $("div[data-id='" + channelId + "']");
if (messageChannelDiv && messageChannelDiv.length > 0) {
messageChannelDiv.click();
openChat();
}
}
$(this).remove();
});
$("body").on('click', '.chat-main-block .chat-block__left_item', function(e){
if($(e.target).closest('.chat-block_cian__left_list').length == 0){
$('.chat-main-block .chat-block__left_item').each(function (index, element) {
$(element).removeClass("active");
});
$(this).addClass('active');
//удаляем счетчик
if ($(this).find('.chat-block__left_item-quantity').length > 0) {
$(this).find('.chat-block__left_item-quantity').remove();
}
recalculateTopCounter();
$('.chat-main-block .chat-block__right_wrapper').show(100);
$('.chat-main-block .group-data').hide(10);
// получаем инфу о канале для вывода в заголовке
getChannelInfo();
// получаем сообщения с канала
getChannelMessages($(this).attr('data-id'));
}
});
$("body").on('click', '.group-data__center_item-remove', function() {
if (confirm("Удалить пользователя из беседы?")) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
let userId = $(this).attr('data-id');
blockChat();
$.ajax({
url: '/ajax/chat/removeUserFromChannel.php',
method: "post",
data: {
"groupId": channelId,
"userId": userId
},
success: function (data) {
$('.chat-block__right_wrapper').show(100);
$('.group-data').hide(10);
getChannelInfo();
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
});
$('.chat-main-block .modal-add__one_btn').on('click', function () {
$('.chat-main-block .modal-add__one').fadeOut(100);
$('.chat-main-block .modal-add__two').fadeIn(100);
if (this.id === 'otherChatCreate') {
$(".chat-main-block .modal-add").css('height', '300px');
let htmlUsersList = '';
//делаем наполнение списка пользователей
userNamesArray.forEach(function (element, index, array) {
//текущего пользователя не добавляем в список. Он будет владельцем канала
if (element.id !== $('#session_user_id').val()) {
let userFio = element.last_name + ' ' + element.first_name;
if (element.middle_name) {
userFio = element.last_name + ' ' + element.first_name + ' ' + element.middle_name;
}
htmlUsersList = htmlUsersList + '
' + userFio + '
'
}
});
$(".chat-main-block .modal-add__two_list").html(htmlUsersList);
$(".chat-main-block .modal-add__two_list").show();
}
if (this.id === 'agencyChatCreate') {
$(".chat-main-block .modal-add__two_list").hide();
$(".chat-main-block .modal-add").css('height', '123px');
}
});
$('.chat-main-block .cancel-add').on('click', function () {
$('.chat-main-block .modal-add__one').fadeIn(100);
$('.chat-main-block .modal-add__two').fadeOut(100);
$(".chat-main-block .modal-add__two_list").hide();
$(".chat-main-block .modal-add").css('height', '123px');
});
$('#chat-message-input').on('keypress', function(e) {
if((e.which === 13 || e.originalEvent.code === 'Enter')) {
if (!e.ctrlKey) {
sendChatMesasge();
e.preventDefault();
e.stopPropagation();
return false;
} else {
var position = this.selectionEnd;
if (this.value.length === position) {
$(this).val(function(i,val){
return val + "\n";
});
$(this).scrollTop($(this).prop('scrollHeight'));
} else {
this.value = this.value.substring(0, position) + '\n' + this.value.substring(position);
this.selectionEnd = position;
}
}
}
});
$('.create-agency-channel').on('click', function () {
let name = $('#chatGroupName').val();
let isUsersSelect = $('.modal-add__two_list').is(':visible');
if (isUsersSelect) {
let users = '';
let usersCount = 0;
$(".modal-add__two_list").find('input[type="checkbox"]').each(function (index, element) {
if ($(element).prop('checked')) {
if (users) {
users = users + ',';
}
users = users + $(element).attr('data-id');
usersCount++;
}
})
if (usersCount === 0) {
alert("Необходимо выбрать пользователей");
} else {
if (usersCount > 1 && !name) {
alert("Необходимо ввести название группы");
} else {
if (usersCount === 1) {
let username = '';
userNamesArray.forEach(function (element, index, array) {
if (element.id === users) {
username = element.chat_login;
}
});
if (username) {
createDirect(username);
}
} else {
blockChat();
$.ajax({
url: '/ajax/chat/createChannel.php',
method: "post",
data: {
"name": name,
"users": users
},
success: function (data) {
if (data) {
alert(data);
} else {
$('.modal-add__two').fadeOut(100);
$('.modal-add__one').fadeIn(100);
$('.modal-add').fadeOut(100);
$(".modal-add").css('height', '123px');
lastCreatedChannelName = name;
getChannels();
}
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
}
} else {
if (!name) {
alert("Необходимо ввести название группы");
} else {
blockChat();
$.ajax({
url: '/ajax/chat/createAgencyChannel.php',
method: "post",
data: {
"name": name
},
success: function (data) {
if (data) {
alert(data);
} else {
$('.modal-add__two').fadeOut(100);
$('.modal-add__one').fadeIn(100);
$('.modal-add').fadeOut(100);
$(".modal-add").css('height', '123px');
$('.chat-main-block .chat-block__top_left-add').hide();
if (confirm("Страница будет перезагружена для применения настроек чата")) {
location.reload();
}
}
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
});
$('.chat-block__top_left-add').on('click', function () {
if ($('#session_agency_id').val() === '93') {
$('.chat-main-block .modal-add__one_input').show();
let htmlUsersList = '';
$('.modal-add__one_list').html('');
//делаем наполнение списка пользователей
userNamesArray.forEach(function (element, index, array) {
let logoUrl = '/images/chat/one.png';
let userFio = element.last_name + ' ' + element.first_name;
if (element.middle_name) {
userFio = element.last_name + ' ' + element.first_name + ' ' + element.middle_name;
}
if (element.user_logo) {
logoUrl = '/photos/agency/' + element.user_logo;
}
htmlUsersList = htmlUsersList + '';
});
$('.chat-main-block .modal-add__one_list').html(htmlUsersList);
$('.chat-main-block .modal-add__one_list').show();
$(".chat-main-block .modal-add").css('height', '297px');
}
$('.chat-main-block .modal-add').fadeIn(100);
});
$('.dots-modal__btn2').on('click', function () {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
blockChat();
$.ajax({
url: '/ajax/chat/getGroupUsers.php',
method: "post",
data: {
"groupId": channelId
},
success: function (data) {
let result = JSON.parse(data);
$('.dots-modal__add_list').html('');
let html = '';
if (result.success) {
let found = false;
userNamesArray.forEach(function (element, index, array) {
found = false;
result.members.forEach(function(member, index, array) {
if (element.chat_login === member.username) {
found = true;
}
});
if (!found) {
let userFio = element.last_name + ' ' + element.first_name;
if (element.middle_name) {
userFio = element.last_name + ' ' + element.first_name + ' ' + element.middle_name;
}
html = html + '' + userFio + '
'
}
});
$('.dots-modal__add_list').html(html);
}
if (html) {
$('.chat-main-block .dots-modal').fadeOut(100);
$('.chat-main-block .dots-modal__add').fadeIn(100);
} else {
$('.chat-main-block .dots-modal').fadeOut(100);
alert("Все агенты уже в беседе.");
}
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
});
$('.group-data__top_text-add').on('click', function () {
$('.dots-modal__add').fadeIn(100);
});
$('.group-data__top_rename').on('click', function () {
$(this).fadeOut(1);
let name = $('.group-data__top_text-name .name');
$(name).fadeOut(1);
$('.rename-input').fadeIn(100);
});
$('.dots-modal__btn1').on('click', function () {
getExtChannelInfo();
});
$('.dots-modal__btn3').on('click', function () {
clearChat();
});
$('.dots-modal__btn4').on('click', function () {
leaveChat();
});
$('.group-data__top_close').on('click', function () {
$('.chat-block__right_wrapper').show(100);
$('.group-data').hide(10);
});
$(document).mouseup(function (e) {
var div = $(".dots-modal, .modal-add, .dots-modal__add ");
if (!div.is(e.target) && div.has(e.target).length === 0) {
$(div).fadeOut();
}
});
});
function changeAvatarForGroup() {
let url = $('#chatGroupAvatarInput').val();
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
let renameGroup = {
"msg": "method",
"method": "saveRoomSettings",
"id": "saveRoomSettingsAvatar",
"params": [
channelId, "roomDescription", url
]
};
rocketChatSocket.send(JSON.stringify(renameGroup));
}
}
}
function renameChatGroup() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
if (!$('#chatGroupNameInput').val()) {
alert("Необходимо указать имя");
} else {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
let renameGroup = {
"msg": "method",
"method": "saveRoomSettings",
"id": "saveRoomSettingsId",
"params": [
channelId, "roomName", $('#chatGroupNameInput').val()
]
};
rocketChatSocket.send(JSON.stringify(renameGroup));
}
}
}
}
/**
* inits a websocket by a given url, returned promise resolves with initialized websocket, rejects after failure/timeout.
*
* @param url the websocket url to init
* @param existingWebsocket if passed and this passed websocket is already open, this existingWebsocket is resolved, no additional websocket is opened
* @param timeoutMs the timeout in milliseconds for opening the websocket
* @param numberOfRetries the number of times initializing the socket should be retried, if not specified or 0, no retries are made
* and a failure/timeout causes rejection of the returned promise
* @return {Promise}
*/
function initWebsocket(url, existingWebsocket, timeoutMs, numberOfRetries) {
timeoutMs = timeoutMs ? timeoutMs : 1500;
numberOfRetries = numberOfRetries ? numberOfRetries : 0;
var hasReturned = false;
var promise = new Promise((resolve, reject) => {
setTimeout(function () {
if(!hasReturned) {
console.info('opening websocket timed out: ' + url);
rejectInternal();
}
}, timeoutMs);
if (!existingWebsocket || existingWebsocket.readyState !== existingWebsocket.OPEN) {
if (existingWebsocket) {
existingWebsocket.close();
}
var websocket = new WebSocket(url);
websocket.onopen = function () {
if(hasReturned) {
websocket.close();
} else {
console.info('websocket to opened! url: ' + url);
let connectRequest = {
"msg": "connect",
"version": "1",
"support": ["1", "pre2", "pre1"]
};
websocket.send(JSON.stringify(connectRequest));
let loginRequest = {
"msg": "method",
"method": "login",
"id": "login",
"params": [
{"resume": $('#session_user_chat_token').val()}
]
};
websocket.send(JSON.stringify(loginRequest));
websocket.onmessage = function (event) {
let response = JSON.parse(event.data);
if ($('#session_agency_id').val() === '93') {
console.log('response', response);
}
// you have to pong back if you need to keep the connection alive
// each ping from server need a 'pong' back
if (response.msg === 'ping') {
websocket.send(JSON.stringify({
msg: 'pong'
}));
return;
}
if (response.msg === 'result') {
if (response.id === 'login') {
//подписываемся на изменения
subscribeToChannelChanged();
//получаем список каналов и список сообщений в дефолтном
getChannels();
}
//получили список чатов - обновляем данные по нужной комнате
if (response.id === 'roomInfo') {
if (response.result && response.result.length > 0) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
response.result.forEach(function(element, index, array) {
if (element._id === channelId) {
if (element.t && element.t === 'd') {
let channelName = '';
element.usernames.forEach(function(element, index, array) {
if (element !== $('#session_user_chat_username').val()) {
channelName = findUserByUsername(element);
}
});
$('.name-chat').html(channelName).show();
} else {
$('.name-chat').html(element.fname).show();
}
$('.quantity-participant').html('Участников: ' + element.usersCount).show();
}
});
}
}
}
if (response.id === 'saveRoomSettingsId') {
if (response.result && response.result.result) {
let newName = $('#chatGroupNameInput').val();
$('.rename-input').hide();
$('#chatExtInfoName').html(newName);
$('.name-chat').html(newName);
$('.chat-block__left_item.active').find('.chat-block__left_item-text').find('.name').html(newName);
$('.group-data__top_rename').show();
$('#chatExtInfoName').show();
}
}
if (response.id === 'saveRoomSettingsAvatar') {
if (response.result && response.result.result) {
let newAvatar = $('#chatGroupAvatarInput').val();
$('#changeGroupAvatarBlock').hide();
if (newAvatar) {
$('#chatGroupImage').attr('src', newAvatar);
$('.chat-block__left_item.active').find('.chat-block__left_item-icon').find('img').attr('src', newAvatar);
} else {
$('#chatGroupImage').attr('src', '/images/chat/group.png');
$('.chat-block__left_item.active').find('.chat-block__left_item-icon').find('img').attr('src', '/images/chat/group.png');
}
}
}
if (response.id === 'extRoomInfo') {
if (response.result && response.result.length > 0) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
response.result.forEach(function(element, index, array) {
if (element._id === channelId) {
if (element.t && element.t === 'd') {
$('.group-data__top_rename').hide();
$('.group-data__bottom').show();
$('.group-data__center_list').css('height', '213px');
let channelName = '';
let channelLogo = '/images/chat/one.png';
element.usernames.forEach(function(element, index, array) {
if (element !== $('#session_user_chat_username').val()) {
channelName = findUserByUsername(element);
let logo = findLogoByUsername(element);
if (logo) {
channelLogo = logo;
}
}
});
$('#chatGroupImage').attr('src', channelLogo);
$('#chatExtInfoName').html(channelName);
$('#chatExtInfoDate').html('Создана: ' + new Date(element.ts.$date).toLocaleString("ru", dateTimeOptions).replace(',',''));
let html = '';
element.usernames.forEach(function(member, index, array) {
let name = findUserByUsername(member);
let logo = findLogoByUsername(member);
let logoHtml = '';
if (logo) {
logoHtml = ''
}
html = html + '\n' + logoHtml +
'
\n' + name +
'
\n' +
'
'
});
$('.group-data__center_list').html(html);
$('.chat-block__right_wrapper, .dots-modal').fadeOut(1);
$('.group-data').fadeIn(100);
} else {
$('#chatGroupAvatarInput').val(element.description);
$('#changeGroupAvatarBlock').hide();
if (element.description) {
$('#chatGroupImage').attr('src', element.description);
} else {
$('#chatGroupImage').attr('src', '/images/chat/group.png');
}
$('#chatExtInfoName').html(element.fname);
$('#chatGroupNameInput').val(element.fname);
$('#chatExtInfoDate').html('Создана: ' + new Date(element.ts.$date).toLocaleString("ru", dateTimeOptions).replace(',',''));
blockChat();
$.ajax({
url: '/ajax/chat/getGroupUsers.php',
method: "post",
data: {
"groupId": channelId
},
success: function (data) {
let result = JSON.parse(data);
$('.group-data__center_list').html('');
let html = '';
if (result.success) {
result.members.forEach(function(member, index, array) {
let name = findUserByUsername(member.username);
let logo = findLogoByUsername(member.username);
let logoHtml = '';
if (logo) {
logoHtml = ''
}
let deleteUserHtml = '';
if ($('#session_user_chat_username').val() === element.u.username && element.u.username !== member.username) {
$('.group-data__top_rename').show();
deleteUserHtml = ' \n' +
' \n' +
'\n' +
' \n' +
' \n' +
' \n' +
' \n' +
' \n' +
' \n' +
' \n'
} else {
$('.group-data__top_rename').hide();
}
html = html + '\n' + logoHtml +
'
\n' + name +
'
\n' + deleteUserHtml +
'
'
});
}
$('.group-data__center_list').html(html);
if ($('#session_user_chat_username').val() === element.u.username && element._id !== $('#session_agency_channel_id').val()) {
$('.group-data__bottom').show();
$('.group-data__center_list').css('height', '213px');
} else {
$('.group-data__bottom').hide();
$('.group-data__center_list').css('height', '281px');
}
$('.chat-block__right_wrapper, .dots-modal').fadeOut(1);
$('.group-data').fadeIn(100);
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
});
}
}
}
//получили список чатов - обновляем
if (response.id === 'rooms') {
if (response.result && response.result.length > 0) {
let currentDate = new Date();
let yesterday = new Date(currentDate);
yesterday.setDate(yesterday.getDate() - 1);
//очищаем
let html = '';
let active = '';
let group = '';
$('.chat-block__left_list').html('');
response.result.forEach(function(element, index, array) {
if (lastCreatedChannelName !== null) {
if (element.fname === lastCreatedChannelName) {
active = activeChannelClass;
lastCreatedChannelId = element._id;
$('.name-chat').html(element.fname).show();
$('.quantity-participant').html('Участников: ' + element.usersCount).show();
} else {
active = '';
}
} else {
if (index === 0) {
active = activeChannelClass;
$('.name-chat').html(element.fname).show();
$('.quantity-participant').html('Участников: ' + element.usersCount).show();
} else {
active = '';
}
}
if (element.t && element.t === 'd') {
group = '';
} else {
group = groupChannelClass;
}
let lastMessage = ' ';
if (element.lastMessage) {
let date = new Date(element.lastMessage.ts.$date);
lastMessage = '' + element.lastMessage.msg +
' ' + getDateFill(currentDate, yesterday, date) + ' ';
}
if (element.t && element.t === 'd') {
let channelName = '';
let channelLogo = '';
element.usernames.forEach(function(element, index, array) {
if (element !== $('#session_user_chat_username').val()) {
channelName = findUserByUsername(element);
let logo = findLogoByUsername(element);
if (logo) {
channelLogo = '';
}
}
});
$('.name-chat').html(channelName).show();
html += '' + channelLogo + '
' + channelName + ' ' + lastMessage + '
';
} else {
let channelLogo = '';
if (element.description) {
channelLogo = '';
}
html += '' + channelLogo +'
' + element.fname + ' ' + lastMessage + '
';
}
//подписываемся на канал для получения сообщений
subscribeToChannelMessages(element._id);
});
if (lastCreatedChannelId !== null) {
getChannelMessages(lastCreatedChannelId);
}
lastCreatedChannelId = null;
lastCreatedChannelName = null;
$('.chat-block__left_list').html(html);
//список каналов
$('.chat-block__left_list').show();
if (needLoadDefaultChannelMessages) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
getChannelMessages(channelId);
}
needLoadDefaultChannelMessages = false;
}
//строка отпарвки в чат
$('.chat-block__right_bottom').show();
getSubscriptions();
}
return;
}
if(response.id === 'createDirectMessageNew') {
let rid = response.result.rid;
$('.modal-add__two').fadeOut(100);
$('.modal-add__one').fadeIn(100);
$('.modal-add').fadeOut(100);
$(".modal-add").css('height', '123px');
let messageChannelDiv = $("div[data-id='" + rid + "']");
if (messageChannelDiv && messageChannelDiv.length > 0) {
messageChannelDiv.click();
} else {
let channelName = '';
let channelLogo = '';
response.result.usernames.forEach(function(element, index, array) {
if (element !== $('#session_user_chat_username').val()) {
channelName = findUserByUsername(element);
let logo = findLogoByUsername(element);
if (logo) {
channelLogo = '';
}
}
});
let html = '' + channelLogo +'
' + channelName + '
';
//подписываемся на канал для получения сообщений
subscribeToChannelMessages(rid);
$('.chat-block__left_list').html($('.chat-block__left_list').html() + html);
messageChannelDiv = $("div[data-id='" + rid + "']");
if (messageChannelDiv && messageChannelDiv.length > 0) {
messageChannelDiv.click();
}
}
}
if (response.id === 'subscriptions') {
if (response.result && response.result.length > 0) {
let count = 0;
response.result.forEach(function(element, index, array) {
if (element && element.unread) {
count = count + element.unread;
updateCounters(element, element.unread);
}
});
$(".open-chat .quantity-message").html(count);
if (count) {
$(".open-chat .quantity-message").show();
}
}
return;
}
if (response.id === 'messages') {
if (response.result && response.result.messages.length > 0) {
let result = printMessages('', response.result.messages, true);
$('#chat-content').html(result[0]);
loadNewPage = true;
$('#chat-content').animate({scrollTop: $('#chat-content').prop('scrollHeight')}, 1000);
loadNewPage = false;
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
readChannelMessages(channelId);
}
} else {
if (response.result.messages.length === 0) {
$('#chat-content').html('');
}
}
setupScrollEvents();
return;
}
if (response.id === 'prevMessages') {
if (response.result && response.result.messages.length > 0) {
//формируем HTML
let res = printMessages('', response.result.messages, false);
let timeArr = res[1];
let prevHtml = $('#chat-content').html();
timeArr.forEach(function (element, index, array) {
if (prevHtml.includes(element)) {
prevHtml = prevHtml.replace(element, "");
}
});
//объединяем
let result = res[0] + prevHtml;
//выводим
$('#chat-content').html(result);
//перематываем наверх
loadNewPage = true;
$('#chat-content').animate({scrollTop: 10}, 1000);
loadNewPage = false;
}
loadNewPage = false;
return;
}
if (response.id === 'message') {
$('#chat-message-input').val('');
$('#chat-message-input').focus();
return;
}
if (response.id === 'deleteRoom') {
$('.chat-block__right_wrapper').show(100);
$('.group-data').hide(10);
getChannels();
}
if (response.id === 'leaveRoom') {
$('.chat-block__right_wrapper').show(100);
$('.dots-modal').fadeOut(100);
$('.group-data').hide(10);
needLoadDefaultChannelMessages = true;
getChannels();
}
}
if (response.msg === 'changed') {
if (response.collection === 'stream-room-messages') {
if (response.fields && response.fields.args && response.fields.args.length > 0) {
//если чат открыт - выводим сообщения
if ($(".chat-main-block").is(":visible")) {
//будем проверять тут наличие отметок по датам
let prevHtml = $('#chat-content').html();
//формируем HTML
let res = printMessages(prevHtml, response.fields.args, true);
//объединяем
let result = prevHtml + res[0];
//показываем
$('#chat-content').html(result);
//скроллим вниз
loadNewPage = true;
$('#chat-content').animate({scrollTop: $('#chat-content').prop('scrollHeight')}, 1000);
loadNewPage = false;
} else {
//иначе просто обновляем общий счетчик
let count = $(".open-chat .quantity-message").html();
if (count) {
$(".open-chat .quantity-message").html(+count + response.fields.args.length);
} else {
$(".open-chat .quantity-message").html(response.fields.args.length);
}
$(".open-chat .quantity-message").show();
//и счетчики каналов
response.fields.args.forEach(function (element, index, array) {
updateCounters(element, 1);
showBottomMessage(element);
});
}
}
}
if (response.collection === 'stream-notify-user') {
if (response.fields && response.fields.args && response.fields.args.length > 0) {
if (response.fields.args[0] === 'inserted') {
let channelInfo = response.fields.args[1];
if (channelInfo.u.username !== $('#session_user_chat_username').val()) {
if (element.t && element.t === 'd') {
let channelName = '';
let channelLogo = '';
element.usernames.forEach(function(element, index, array) {
if (element !== $('#session_user_chat_username').val()) {
channelName = findUserByUsername(element);
let logo = findLogoByUsername(element);
if (logo) {
channelLogo = '';
}
}
});
let html = '' + channelLogo +'
' + channelName + '
';
} else {
let channelLogo = '';
let html = '' + channelLogo + '
' + channelInfo.fname + '
';
}
//подписываемся на канал для получения сообщений
subscribeToChannelMessages(channelInfo.rid);
$('.chat-block__left_list').html($('.chat-block__left_list').html() + html);
}
}
}
}
}
}
resolve(websocket);
}
};
websocket.onclose = function () {
console.info('websocket closed! url: ' + url);
rejectInternal();
};
websocket.onerror = function () {
console.info('websocket error! url: ' + url);
if (websocket && websocket.readyState === WebSocket.CLOSED) {
$('#chat-content').html('Произошла ошибка, обратитесь к администратору.
');
}
rejectInternal();
};
} else {
resolve(existingWebsocket);
}
function rejectInternal() {
if(numberOfRetries <= 0) {
reject();
} else if(!hasReturned) {
hasReturned = true;
console.info('retrying connection to websocket! url: ' + url + ', remaining retries: ' + (numberOfRetries-1));
initWebsocket(url, null, timeoutMs, numberOfRetries-1).then(resolve, reject);
}
}
});
promise.then(function () {hasReturned = true;}, function () {hasReturned = true;});
return promise;
}
function setupChat() {
if($('#session_user_chat_token').length || $('#session_user_chat_user_id').length) {
initWebsocket("wss://rocket.joywork.ru/websocket", null, 10000, 5).then(function(socket){
console.log('socket initialized!');
rocketChatSocket = socket;
}, function(){
console.log('init of socket failed!');
});
}
}
function isFeedAtTop() {
return 0 === document.getElementById("chat-content").scrollTop;
}
function setupScrollEvents() {
document.getElementById("chat-content").addEventListener("scroll", onScrollMessagesPart);
}
function onScrollMessagesPart() {
if (isFeedAtTop() && !loadNewPage) {
loadNewPage = true;
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
loadPrevPage(channelId);
} else {
loadNewPage = false;
}
}
}
function loadPrevPage(channelId) {
let time = null;
if (channelsTimes && channelsTimes[channelId]) {
time = channelsTimes[channelId];
}
getChannelMessages(channelId, time);
}
function printMessages(prevHtml, messages, updateChatLine) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
let html = '';
let currentDate = new Date();
let yesterday = new Date(currentDate);
yesterday.setDate(yesterday.getDate() - 1);
let lastDate = null;
//массив для хранения строк с выводом даты, чтобы потом удалить
let dateLines = [];
messages.reverse().forEach(function (element, index, array) {
let date = new Date(element.ts.$date);
if (updateChatLine) {
let messageChannelDiv = $("div[data-id='" + element.rid + "']");
if (messageChannelDiv && messageChannelDiv.length > 0) {
let text = element.msg;
if (element.t) {
if (element.t === 'au') {
text = 'Пользователь ' + findUserByUsername(element.msg) + ' добавлен в группу';
}
if (element.t === 'ru') {
text = 'Пользователь ' + findUserByUsername(element.msg) + ' удален из группы';
}
if (element.t === 'r') {
text = 'Группа переименована, новое наименование ' + element.msg;
}
if (element.t === 'room_changed_description') {
text = 'Изменен аватар группы на ' + element.msg;
}
}
if (text.length > 30) {
text = text.slice(0, 30) + '...';
}
messageChannelDiv.find('.letter').html(text);
messageChannelDiv.find('.when').html(getDateFill(currentDate, yesterday, date));
}
}
//если сообщение в текущий канал - пишем и показываем
if (channelId === element.rid) {
if (channelsTimes && channelsTimes[channelId]) {
let time = channelsTimes[channelId];
if (time > element.ts.$date) {
channelsTimes[channelId] = element.ts.$date
}
} else {
channelsTimes[channelId] = element.ts.$date;
}
let dateLine = '' + getDateFill(currentDate, yesterday, date) + '
';
dateLines.push(dateLine);
if (lastDate === null) {
let result = dateLine;
if (!prevHtml.includes(result) && !html.includes(result)) {
html += result;
}
lastDate = date;
} else {
if (!isSameDate(lastDate, date)) {
html += dateLine;
}
lastDate = date;
}
if (element.t && element.t === 'au') {
html += 'Администратор Пользователь ' + findUserByUsername(element.msg) + ' добавлен в группу ' + date.toLocaleString("ru", dateTimeOptions).replace(',', '') + '
';
} else {
if (element.t && element.t === 'ru') {
html += '' + findUserByUsername(element.u.username) + ' Пользователь ' + findUserByUsername(element.msg) + ' исключен из группы ' + date.toLocaleString("ru", dateTimeOptions).replace(',', '') + '
';
} else {
if (element.t && element.t === 'r') {
html += '' + findUserByUsername(element.u.username) + ' Группа переименована, новое наименование ' + element.msg + ' ' + date.toLocaleString("ru", dateTimeOptions).replace(',', '') + '
';
} else {
if (element.t && element.t === 'room_changed_description') {
html += '' + findUserByUsername(element.u.username) + ' Изменен аватар группы на ' + element.msg + ' ' + date.toLocaleString("ru", dateTimeOptions).replace(',', '') + '
';
} else {
let imgBlock = '';
let logo = findLogoByUsername(element.u.username);
if (logo) {
imgBlock = '';
}
let message = element.msg;
//формируем перенос строки
message = message.replace(/\n/g, " ");
html += '' + imgBlock + '
' + findUserByUsername(element.u.username) + ' ' + message + ' ' + date.toLocaleString("ru", dateTimeOptions).replace(',', '') + '
';
}
}
}
}
} else {
//меняем количество в счетчиках
updateCounters(element, 1);
}
});
return [html, dateLines];
}
function showBottomMessage(element) {
if (element.u.username !== $('#session_user_chat_username').val() && !element.t) {
let id = element._id;
let newZIndex = defaultZIndex + $('.new-message').length;
let html = '';
html = html + '
';
html = html + '
Новое сообщение ';
html = html + '
';
html = html + '
';
html = html + '
';
let logo = findLogoByUsername(element.u.username);
if (logo) {
html = html + '
';
html = html + '
';
html = html + '
';
}
html = html + '
';
html = html + findUserByUsername(element.u.username);
html = html + '';
html = html + '';
if (element.msg.length > 30) {
html = html + element.msg.slice(0, 30) + '...';
} else {
html = html + element.msg;
}
html = html + ' ';
html = html + '';
html = html + new Date(element.ts.$date).toLocaleTimeString("ru", timeOptions).replace(',','');
html = html + ' ';
html = html + '
';
html = html + '
';
html = html + '
';
if ($('.new-message').length > 0) {
//будет показан поверх всех
$('.new-message').first().before(html);
} else {
$('.chat-main-block').after(html);
}
/*setTimeout(function() {
$('#' + id).remove();
}, 3000);*/
}
}
function updateCounters(element, newMessagesCnt = 1) {
if (!newMessagesCnt) {
newMessagesCnt = element.unread;
}
let messageChannelDiv = $("div[data-id='" + element.rid + "']");
if (messageChannelDiv && messageChannelDiv.length > 0) {
if ($(messageChannelDiv).find('.chat-block__left_item-quantity').length === 0) {
$(messageChannelDiv).html($(messageChannelDiv).html() + '
');
}
let count = $(messageChannelDiv).find('.chat-block__left_item-quantity').html();
if (count) {
$(messageChannelDiv).find('.chat-block__left_item-quantity').html(+count + newMessagesCnt);
} else {
$(messageChannelDiv).find('.chat-block__left_item-quantity').html(newMessagesCnt);
}
}
}
function sendChatMesasge() {
let message = $('#chat-message-input').val();
if (message && $('.chat-block__left_item.active').length > 0 && rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let channelId = $('.chat-block__left_item.active').attr('data-id');
let mesageSendRequest = {
"msg": "method",
"method": "sendMessage",
"id": "message",
"params": [
{
"_id": String(generateHash(17)),
"rid": channelId,
"msg": message
}
]
};
rocketChatSocket.send(JSON.stringify(mesageSendRequest));
}
}
function getDateFill(currentDate, yesterday, fromDate) {
if (isSameDate(currentDate, fromDate)) {
return 'Сегодня';
}
if (isSameDate(yesterday, fromDate)) {
return 'Вчера';
}
return fromDate.toLocaleString("ru", dateOptions).replace(',','');
}
function isSameDate(currentDate, fromDate) {
return currentDate.getDate() === fromDate.getDate() && currentDate.getMonth() === fromDate.getMonth() &&
currentDate.getFullYear() === fromDate.getFullYear();
}
function findUserByUsername(username) {
let userFio = username;
userNamesArray.forEach(function (element, index, array) {
if (element.chat_login === username) {
if (element.middle_name) {
userFio = element.last_name + ' ' + element.first_name + ' ' + element.middle_name;
} else {
userFio = element.last_name + ' ' + element.first_name;
}
}
});
return userFio;
}
function findLogoByUsername(username) {
let userLogo = '';
userNamesArray.forEach(function (element, index, array) {
if (element.chat_login === username) {
if (element.user_logo) {
userLogo = '/photos/agency/' + element.user_logo;
}
}
});
return userLogo;
}
function deleteGroup() {
if ($('.chat-block__left_item.active').length > 0) {
let channelId = $('.chat-block__left_item.active').attr('data-id');
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let roomDeleteRequest = {
"msg": "method",
"method": "eraseRoom",
"id": "deleteRoom",
"params": [ channelId ]
};
rocketChatSocket.send(JSON.stringify(roomDeleteRequest));
}
}
}
function generateHash(targetLength) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < targetLength; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function openChat() {
if(!$('#session_user_chat_token').length || !$('#session_user_chat_user_id').length) {
if ($('#session_admin_rights').val() === "1") {
$('#chat-content').html('Необходимо создать Общий чат агентства. Нажмите на зеленый + вверху и введите название общего чата. Все сотрудники будут добавлены в него автоматически.
');
} else {
$('#chat-content').html('Необходимо создать Общий чат агентства. Обратитесь к своему руководителю.
');
}
$('.chat-main-block .chat-block__top_left-icon').hide();
} else {
$('#chat-content').html('Идет процесс получения данных...
');
}
if(!$('#session_agency_channel_id').length) {
if ($('#session_admin_rights').val() === "1") {
$('.chat-main-block .chat-main-block .chat-block__top_left-add').show();
$('#agencyChatCreate').show();
$('#otherChatCreate').hide();
} else {
$('.chat-main-block .chat-block__top_left-add').hide();
}
} else {
$('.chat-main-block .chat-block__top_left-add').show();
$('#agencyChatCreate').hide();
$('#otherChatCreate').show();
}
if ($('.chat-block__left_item.active').length > 0) {
let channelId = $('.chat-block__left_item.active').attr('data-id');
getChannelMessages(channelId, null);
//удаляем счетчик
if ($('.chat-block__left_item.active').find('.chat-block__left_item-quantity').length > 0) {
$('.chat-block__left_item.active').find('.chat-block__left_item-quantity').remove();
}
recalculateTopCounter();
}
$('.chat-main-block .dots-modal-show').show();
//$('.chat-block__top_left-burger').click();
loadNewPage = true;
$(".chat-main-block").fadeIn(500);
loadNewPage = false;
}
function recalculateTopCounter() {
let sum = 0;
$('.chat-block__left_item').each(function (index, element) {
if($(element).closest('.chat-cian').length == 0) {
if ($(element).find('.chat-block__left_item-quantity').length > 0) {
let html = $(element).find('.chat-block__left_item-quantity').html();
if (html) {
sum = +html + sum;
}
}
}
});
if (sum) {
$(".open-chat .quantity-message").html(sum);
$(".open-chat .quantity-message").show();
} else {
$(".open-chat .quantity-message").html('');
$(".open-chat .quantity-message").hide();
}
}
function getChannels() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let roomsRequest = {
"msg": "method",
"method": "rooms/get",
"id": "rooms",
"params": [
{"date": 0}
]
};
rocketChatSocket.send(JSON.stringify(roomsRequest));
}
}
function getChannelInfo() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let roomsRequest = {
"msg": "method",
"method": "rooms/get",
"id": "roomInfo",
"params": [
{"date": 0}
]
};
rocketChatSocket.send(JSON.stringify(roomsRequest));
}
}
function getExtChannelInfo() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let roomsRequest = {
"msg": "method",
"method": "rooms/get",
"id": "extRoomInfo",
"params": [
{"date": 0}
]
};
rocketChatSocket.send(JSON.stringify(roomsRequest));
}
}
function createDirect(username) {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let directRequest = {
"msg": "method",
"method": "createDirectMessage",
"id": "createDirectMessageNew",
"params": [username]
};
rocketChatSocket.send(JSON.stringify(directRequest));
}
}
function leaveChat() {
if (confirm("Покинуть беседу?")) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let leaveRoomRequest = {
"msg": "method",
"method": "leaveRoom",
"id": "leaveRoom",
"params": [ channelId ]
};
rocketChatSocket.send(JSON.stringify(leaveRoomRequest));
}
}
}
}
function clearChat() {
if (confirm("Удалить все сообщения в беседе?")) {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
blockChat();
$.ajax({
url: '/ajax/chat/clearChannel.php',
method: "post",
data: {
"groupId": channelId
},
success: function (data) {
if (data) {
console.log(data);
}
$('.chat-block__left_item.active').find('.letter').html('');
$('.chat-block__left_item.active').find('.when').html('');
$('#chat-content').html('');
$('.dots-modal').fadeOut(100);
unBlockChat();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
}
function getSubscriptions() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let getSubscriptionsRequest = {
"msg": "method",
"method": "subscriptions/get",
"id": "subscriptions",
"params": [
{"date": 0}
]
};
rocketChatSocket.send(JSON.stringify(getSubscriptionsRequest));
}
}
function getChannelMessages(channelId, time) {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let timeParam = null;
let id = "messages";
if (time) {
timeParam = { "$date": time };
id = "prevMessages";
} else {
channelsTimes[channelId] = 0;
}
let messagesRequest = {
"msg": "method",
"method": "loadHistory",
"id": id,
"params": [ channelId, timeParam, 20, { "$date": new Date().getTime() }]
};
rocketChatSocket.send(JSON.stringify(messagesRequest));
}
}
function readChannelMessages(channelId) {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let messagesRequest = {
"msg": "method",
"method": "readMessages",
"id": "readChannelMessages",
"params": [ channelId]
};
rocketChatSocket.send(JSON.stringify(messagesRequest));
}
}
function subscribeToChannelMessages(channelId) {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let channelMessagesUnsub = {
"msg": "unsub",
"id": channelId
};
rocketChatSocket.send(JSON.stringify(channelMessagesUnsub));
let channelMessagesSub = {
"msg": "sub",
"id": channelId,
"name": "stream-room-messages",
"params":[ channelId, false ]
};
rocketChatSocket.send(JSON.stringify(channelMessagesSub));
}
}
function subscribeToChannelChanged() {
if (rocketChatSocket && rocketChatSocket.readyState === WebSocket.OPEN) {
let channelMessagesUnsub = {
"msg": "unsub",
"id": "streamNotifyUser"
};
rocketChatSocket.send(JSON.stringify(channelMessagesUnsub));
let channelMessagesSub = {
"msg": "sub",
"id": "streamNotifyUser",
"name": "stream-notify-user",
"params":[ $('#session_user_chat_user_id').val() + '/subscriptions-changed', false ]
};
rocketChatSocket.send(JSON.stringify(channelMessagesSub));
}
}
function addUsersToChannel() {
let channelId = $('.chat-block__left_item.active').length > 0 ? $('.chat-block__left_item.active').attr('data-id') : '';
if (channelId) {
let users = '';
$(".dots-modal__add_list").find('input[type="checkbox"]').each(function (index, element) {
if ($(element).prop('checked')) {
if (users) {
users = users + ',';
}
users = users + $(element).attr('data-id');
}
})
if (!users) {
alert("Необходимо выбрать пользователей");
} else {
blockChat();
$.ajax({
url: '/ajax/chat/addUsersToChannel.php',
method: "post",
data: {
"channelId": channelId,
"users": users
},
success: function (data) {
if (data) {
alert(data);
} else {
$('.modal-add__two').fadeOut(100);
$('.modal-add__one').fadeIn(100);
$('.modal-add').fadeOut(100);
$('.dots-modal__add').fadeOut(100);
$(".modal-add").css('height', '123px');
getChannelInfo();
unBlockChat();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("eRROR: " + errorThrown + "; status:" + textStatus);
unBlockChat();
}
});
}
}
}
function blockChat() {
$('#chat-spinner').show();
}
function unBlockChat() {
$('#chat-spinner').hide();
}
(function () {
const cropElement = document.querySelectorAll('.letter'), // выбор элементов
size = 27 // кол-во символов
endCharacter = '...'; // окончание
cropElement.forEach(el => {
let text = el.innerHTML;
if (el.innerHTML.length > size) {
text = text.substr(0, size);
el.innerHTML = text + endCharacter;
}
});
}());
(function () {
const cropElement = document.querySelectorAll('.new-message__bottom_text'), // выбор элементов
size = 47 // кол-во символов
endCharacter = '...'; // окончание
cropElement.forEach(el => {
let text = el.innerHTML;
if (el.innerHTML.length > size) {
text = text.substr(0, size);
el.innerHTML = text + endCharacter;
}
});
}());
(function () {
const cropElement = document.querySelectorAll('.modal-add__one_list span'), // выбор элементов
size = 24 // кол-во символов
endCharacter = '...'; // окончание
cropElement.forEach(el => {
let text = el.innerHTML;
if (el.innerHTML.length > size) {
text = text.substr(0, size);
el.innerHTML = text + endCharacter;
}
});
}());
//var objDiv = document.getElementById("chat");
//objDiv.scrollTop = objDiv.scrollHeight;