You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
198 lines
7.0 KiB
JavaScript
198 lines
7.0 KiB
JavaScript
const chat_ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
|
|
const domain = "192.168.1.106:8000";
|
|
let osichatSocket;
|
|
let isOpen = false;
|
|
let chatLoaded = false;
|
|
|
|
|
|
|
|
|
|
// FUNCTION TO FETCH THE SESSION ID
|
|
async function fetchSessionID() {
|
|
let session_id = 'Unknown';
|
|
while (session_id === 'Unknown') {
|
|
try {
|
|
const response = await fetch('http://192.168.1.106:3000/get-client-session/');
|
|
const data = await response.json();
|
|
if (data.session_id) {
|
|
session_id = data.session_id;
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching session ID:', error);
|
|
}
|
|
}
|
|
return session_id;
|
|
}
|
|
|
|
// FUNCTIONS TO SHOW & HIDE THE LOADER
|
|
function showLoader() {
|
|
const osichatLoader = document.getElementById('osichatLoader');
|
|
if (osichatLoader) {
|
|
osichatLoader.classList.remove('hidden');
|
|
}
|
|
}
|
|
|
|
function hideLoader() {
|
|
const osichatLoader = document.getElementById('osichatLoader');
|
|
if (osichatLoader) {
|
|
osichatLoader.classList.add('hidden');
|
|
}
|
|
}
|
|
|
|
// FUNCTION TO APPEND THE TEXTAREA SCRIPT
|
|
function appendTextAreaScript(domain, chatDiv) {
|
|
const textareaScript = document.createElement('script');
|
|
textareaScript.type = 'text/javascript';
|
|
textareaScript.src = `http://${domain}/static/js/osichat/textarea.js`;
|
|
chatDiv.appendChild(textareaScript);
|
|
}
|
|
|
|
// FUNCTION TO HANDLE FORM SUBMISSION
|
|
function handleFormSubmission(form, eventType, osichatSocket) {
|
|
form.addEventListener('submit', function (event) {
|
|
event.preventDefault();
|
|
|
|
const formData = new FormData(form);
|
|
const eventMessage = { 'event_type': eventType };
|
|
|
|
formData.forEach((value, key) => {
|
|
eventMessage[key] = value;
|
|
});
|
|
osichatSocket.send(JSON.stringify(eventMessage));
|
|
form.reset();
|
|
});
|
|
}
|
|
|
|
// FUNCTION TO HANDLE LOAD CHAT EVENT
|
|
function handleLoadChatEvent(data, osichatSocket) {
|
|
chatLoaded = true;
|
|
hideLoader();
|
|
let chatDiv = document.getElementById('roomContainer'); // CASE WHERE WIDGET IS ALREADY LOADED, DISPLAY THE CHAT PAGES(START/CONVERSATION) IN ROOM CONTAINER
|
|
if (!chatDiv) {
|
|
chatDiv = document.getElementById('osichat'); // CASE WHERE WIDGET IS NOT LOADED, DISPLAY THE WHOLE CHATWIDGET IN OSICHAT
|
|
}
|
|
|
|
chatDiv.innerHTML = data.html;
|
|
|
|
|
|
if (!document.querySelector('script[src="http://' + domain + '/static/js/osichat/chat-toggle.js"]')) {
|
|
const script = document.createElement('script');
|
|
script.type = 'text/javascript';
|
|
script.src = `http://${domain}/static/js/osichat/chat-toggle.js`;
|
|
chatDiv.appendChild(script);
|
|
}
|
|
|
|
const startChatContainer = document.getElementById('startChat');
|
|
if (startChatContainer) {
|
|
handleFormSubmission(startChatContainer, 'start_conversation', osichatSocket);
|
|
}
|
|
|
|
const sendMessageContainer = document.getElementById('sendMessage');
|
|
if (sendMessageContainer) {
|
|
appendTextAreaScript(domain, chatDiv);
|
|
handleFormSubmission(sendMessageContainer, 'send_message', osichatSocket);
|
|
|
|
const uploadScript = document.createElement('script');
|
|
uploadScript.type = 'text/javascript';
|
|
uploadScript.src = `http://${domain}/static/js/osichat/upload-file.js`;
|
|
chatDiv.appendChild(uploadScript);
|
|
}
|
|
}
|
|
|
|
|
|
// FUNCTION TO INITIALIZE WEB SOCKET CONNECTION
|
|
async function initializeChatWebSocket() {
|
|
const session_id = await fetchSessionID();
|
|
let osichatSocketUrl = `${chat_ws_scheme}://${domain}/ws/osichat/${session_id}/`;
|
|
osichatSocket = new WebSocket(osichatSocketUrl);
|
|
|
|
osichatSocket.onopen = () => {
|
|
if(!chatLoaded){
|
|
osichatSocket.send(JSON.stringify({ 'event_type': 'load_chat', 'client_type': 'website_guest', 'reconnecting': 'False'}));
|
|
}else{
|
|
osichatSocket.send(JSON.stringify({ 'event_type': 'load_chat', 'client_type': 'website_guest', 'reconnecting': 'True'}));
|
|
}
|
|
};
|
|
|
|
osichatSocket.onmessage = function (e) {
|
|
const data = JSON.parse(e.data);
|
|
const typingDiv = document.getElementById('typing');
|
|
switch (data.event_type) {
|
|
case 'load_chat':
|
|
handleLoadChatEvent(data, osichatSocket);
|
|
break;
|
|
case 'start_conversation':
|
|
handleLoadChatEvent(data, osichatSocket);
|
|
break;
|
|
case 'typing':
|
|
typingDiv.classList.remove('hidden');
|
|
typingDiv.innerHTML = data.html;
|
|
break;
|
|
case 'stopped_typing':
|
|
typingDiv.classList.add('hidden');
|
|
break;
|
|
case 'send_message':
|
|
if (isOpen) { // If chat widget isOpen (declared in chat-toggle.js) mark all messages as read by guest else just return number of unread messages
|
|
osichatSocket.send(JSON.stringify({ 'event_type': 'update_read_messages', 'chat_state': 'open' }));
|
|
} else {
|
|
osichatSocket.send(JSON.stringify({ 'event_type': 'update_read_messages', 'chat_state': 'closed' }));
|
|
}
|
|
const messagesDiv = document.getElementById('messages');
|
|
messagesDiv.insertAdjacentHTML('beforeend', data.html);
|
|
if (data.user) { // If it is sent by an Osina user play a notification sound for the guest
|
|
const notificationSound = document.getElementById('notification-sound');
|
|
notificationSound.play();
|
|
}
|
|
break;
|
|
case 'uploaded_file':
|
|
const uploadingDiv = document.getElementById(`uploading-${data.file_name}`);
|
|
if (uploadingDiv) {
|
|
uploadingDiv.outerHTML = data.html;
|
|
}
|
|
break;
|
|
case 'update_read_messages':
|
|
const unreadMessages = document.getElementById(`unreadMessages`);
|
|
if (!isOpen) {
|
|
unreadMessages.classList.remove('hidden');
|
|
unreadMessages.innerHTML = data.html;
|
|
const script = document.createElement('script');
|
|
script.src = `http://${domain}/static/js/osichat/chat-toggle.js`;
|
|
document.body.appendChild(script);
|
|
} else {
|
|
unreadMessages.classList.add('hidden');
|
|
}
|
|
break;
|
|
default:
|
|
console.log('Unknown event type:', data.event_type);
|
|
}
|
|
};
|
|
|
|
osichatSocket.onclose = () => {
|
|
console.log('WebSocket connection to osichat closed');
|
|
showLoader();
|
|
setTimeout(() => {
|
|
console.log('Attempting to reconnect to WebSocket...');
|
|
initializeChatWebSocket();
|
|
}, 2000);
|
|
};
|
|
|
|
osichatSocket.onerror = (error) => {
|
|
console.log('WebSocket error:', error);
|
|
showLoader();
|
|
};
|
|
}
|
|
|
|
|
|
window.addEventListener('offline', () => {
|
|
showLoader();
|
|
if (osichatSocket) {
|
|
osichatSocket.close();
|
|
}
|
|
});
|
|
|
|
// INITIALIZE CHAT WEB SOCKET
|
|
initializeChatWebSocket();
|
|
|
|
|
|
|