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.

158 lines
6.1 KiB
JavaScript

const chat_ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
const domain = "192.168.1.111:8000";
let osichatSocket;
let isOpen = 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.111: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;
}
// 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) {
const osichatLoader = document.getElementById('osichatLoader');
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 = () => {
console.log('WebSocket connection to osichat established');
osichatSocket.send(JSON.stringify({ 'event_type': 'load_chat', 'client_type': 'website_guest' }));
};
osichatSocket.onmessage = function (e) {
const data = JSON.parse(e.data);
switch (data.event_type) {
case 'load_chat':
handleLoadChatEvent(data, osichatSocket);
break;
case 'start_conversation':
handleLoadChatEvent(data, osichatSocket);
break;
case 'send_message':
console.log('h')
console.log(isOpen)
if (isOpen) { // Id 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' }));
console.log(isOpen)
} 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');
console.log(notificationSound)
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')
console.log(unreadMessages)
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');
// osichatLoader.classList.remove('hidden');
};
osichatSocket.onerror = (error) => {
console.log('WebSocket error:', error);
// osichatLoader.classList.remove('hidden');
};
}
initializeChatWebSocket();