File size: 8,022 Bytes
9da4125 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
// Функция для автоматического обновления сообщений в чате
function initChatUpdater(contactId) {
// Если нет активного контакта, не запускаем обновление
if (!contactId || contactId === 0) return;
// Последний ID сообщения, которое мы видели
let lastMessageId = getLastMessageId();
// Функция для получения ID последнего сообщения в чате
function getLastMessageId() {
const messages = document.querySelectorAll('.message');
if (messages.length > 0) {
const lastMessage = messages[messages.length - 1];
return lastMessage.dataset.messageId || 0;
}
return 0;
}
// Функция для добавления новых сообщений в чат
function addNewMessages(messages, userId) {
const chatMessages = document.getElementById('chatMessages');
const wasScrolledToBottom = isScrolledToBottom(chatMessages);
// Добавляем каждое новое сообщение
messages.forEach(message => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${message.sender_id == userId ? 'message-sent' : 'message-received'} mb-3`;
messageDiv.dataset.messageId = message.id;
// Базовое содержимое сообщения
let messageContent = `
<div class="message-content p-3 rounded ${message.sender_id == userId ? 'bg-primary text-white' : 'bg-light'}">
${message.content}
`;
// Добавляем вложение, если оно есть
if (message.attachment) {
const attachment = message.attachment;
messageContent += `
<div class="message-attachment mt-2">
<div class="attachment-info">
<i class="fas ${getAttachmentIcon(attachment.file_type)}"></i>
<a href="/download/${attachment.id}" class="attachment-link">
${attachment.original_filename}
</a>
<span class="attachment-size">${attachment.size_formatted}</span>
</div>
`;
// Добавляем предпросмотр в зависимости от типа файла
if (attachment.file_type === 'image') {
messageContent += `
<div class="attachment-preview mt-2">
<a href="/download/${attachment.id}" target="_blank">
<img src="/download/${attachment.id}" class="img-thumbnail" style="max-width: 200px; max-height: 200px;">
</a>
</div>
`;
} else if (attachment.file_type === 'video') {
messageContent += `
<div class="attachment-preview mt-2">
<video controls class="img-thumbnail" style="max-width: 250px; max-height: 250px;">
<source src="/download/${attachment.id}" type="video/mp4">
Ваш браузер не поддерживает видео.
</video>
</div>
`;
} else if (attachment.file_type === 'audio') {
messageContent += `
<div class="attachment-preview mt-2">
<audio controls style="max-width: 250px;">
<source src="/download/${attachment.id}">
Ваш браузер не поддерживает аудио.
</audio>
</div>
`;
}
messageContent += `
</div>
`;
}
// Добавляем время и статус прочтения
messageContent += `
<div class="message-time text-end">
<small class="${message.sender_id == userId ? 'text-white-50' : 'text-muted'}">
${message.created_at}
${message.sender_id == userId ?
(message.is_read ? '<i class="fas fa-check-double"></i>' : '<i class="fas fa-check"></i>') :
''}
</small>
</div>
</div>
`;
messageDiv.innerHTML = messageContent;
chatMessages.appendChild(messageDiv);
});
// Функция для получения иконки в зависимости от типа файла
function getAttachmentIcon(fileType) {
switch(fileType) {
case 'image': return 'fa-image';
case 'video': return 'fa-video';
case 'audio': return 'fa-music';
case 'text': return 'fa-file-alt';
default: return 'fa-file';
}
}
// Если пользователь был прокручен вниз, прокручиваем к новым сообщениям
if (wasScrolledToBottom) {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Обновляем последний ID сообщения
if (messages.length > 0) {
lastMessageId = messages[messages.length - 1].id;
}
}
// Проверка, прокручен ли чат до конца
function isScrolledToBottom(element) {
return element.scrollHeight - element.clientHeight <= element.scrollTop + 1;
}
// Функция для получения новых сообщений
function fetchNewMessages() {
fetch(`/get_new_messages/${contactId}?last_id=${lastMessageId}`)
.then(response => response.json())
.then(data => {
if (data.messages && data.messages.length > 0) {
addNewMessages(data.messages, data.user_id);
}
})
.catch(error => console.error('Ошибка при получении новых сообщений:', error));
}
// Запускаем периодическое обновление каждые 5 секунд
const intervalId = setInterval(fetchNewMessages, 5000);
// Сохраняем ID интервала, чтобы можно было его остановить при необходимости
window.chatUpdateInterval = intervalId;
// Обработчик отправки формы сообщения
const messageForm = document.getElementById('messageForm');
if (messageForm) {
messageForm.addEventListener('submit', function(e) {
// Стандартная отправка формы происходит, но после успешной отправки
// мы сразу запрашиваем новые сообщения, чтобы не ждать интервала
setTimeout(fetchNewMessages, 500);
});
}
}
// Остановка обновления чата при переходе на другую страницу
function stopChatUpdater() {
if (window.chatUpdateInterval) {
clearInterval(window.chatUpdateInterval);
window.chatUpdateInterval = null;
}
} |