Files
eveAI/static/js/eveai-chat-widget.js

203 lines
6.3 KiB
JavaScript

class EveAIChatWidget extends HTMLElement {
static get observedAttributes() {
return ['tenant-id', 'api-key', 'domain'];
}
constructor() {
super();
this.socket = null; // Initialize socket to null
this.attributesSet = false; // Flag to check if all attributes are set
this.jwtToken = null; // Initialize jwtToken to null
console.log('EveAIChatWidget constructor called');
}
connectedCallback() {
console.log('connectedCallback called');
this.innerHTML = this.getTemplate();
this.messagesArea = this.querySelector('.messages-area');
this.questionInput = this.querySelector('.question-area input');
this.querySelector('.question-area button').addEventListener('click', () => this.handleSendMessage());
if (this.areAllAttributesSet() && !this.socket) {
console.log('Attributes already set in connectedCallback, initializing socket');
this.initializeSocket();
}
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`attributeChangedCallback called: ${name} changed from ${oldValue} to ${newValue}`);
this.updateAttributes();
console.log('Current attributes:', {
tenantId: this.getAttribute('tenant-id'),
apiKey: this.getAttribute('api-key'),
domain: this.getAttribute('domain')
});
if (this.areAllAttributesSet() && !this.socket) {
console.log('All attributes set in attributeChangedCallback, initializing socket');
this.attributesSet = true;
this.initializeSocket();
}
}
updateAttributes() {
console.log('Updating attributes:');
this.tenantId = this.getAttribute('tenant-id');
this.apiKey = this.getAttribute('api-key');
this.domain = this.getAttribute('domain');
console.log('Updated attributes:', {
tenantId: this.tenantId,
apiKey: this.apiKey,
domain: this.domain
});
}
areAllAttributesSet() {
const tenantId = this.getAttribute('tenant-id');
const apiKey = this.getAttribute('api-key');
const domain = this.getAttribute('domain');
console.log('Checking if all attributes are set:', {
tenantId,
apiKey,
domain
});
return tenantId && apiKey && domain;
}
initializeSocket() {
if (this.socket) {
console.log('Socket already initialized');
return;
}
if (!this.domain || this.domain === 'null') {
console.error('Domain attribute is missing or invalid');
return;
}
console.log(`Initializing socket connection to ${this.domain}`);
// Ensure apiKey is passed in the query parameters
this.socket = io(this.domain, {
path: '/chat/socket.io/',
transports: ['websocket', 'polling'],
query: {
tenantId: this.tenantId,
apiKey: this.apiKey // Ensure apiKey is included here
},
auth: {
token: 'Bearer ' + this.apiKey // Ensure token is included here
}
});
this.socket.on('connect', (data) => {
console.log('Socket connected');
});
this.socket.on('authenticated', (data) => {
console.log('Authenticated event received: ', data);
if (data.token) {
this.jwtToken = data.token; // Store the JWT token received from the server
}
});
this.socket.on('connect_error', (err) => {
console.error('Socket connection error:', err);
});
this.socket.on('connect_timeout', () => {
console.error('Socket connection timeout');
});
this.socket.on('disconnect', () => {
console.log('Socket disconnected');
});
this.socket.on('bot_response', (data) => {
if (data.tenantId === this.tenantId) {
console.log('Bot response received:', data)
console.log('Task ID received:', data.taskId)
this.addMessage(data.message, 'bot', data.messageId, data.algorithm);
this.checkTaskStatus(data.taskId)
}
});
this.socket.on('task_status', (data) => {
console.log('Task status received:', data)
console.log('Task ID received:', data.taskId)
if (data.status === 'SUCCESS') {
this.addMessage(data.result, 'bot');
} else if (data.status === 'FAILURE') {
this.addMessage('Failed to process message.', 'bot');
} else if (data.status === 'pending') {
console.log('Task is pending')
setTimeout(() => this.checkTaskStatus(data.taskId), 1000); // Poll every second
console.log('New check sent')
}
});
}
checkTaskStatus(taskId) {
this.socket.emit('check_task_status', { task_id: taskId });
}
getTemplate() {
return `
<div class="chat-container">
<div class="messages-area"></div>
<div class="question-area">
<input type="text" placeholder="Type your message here..." />
<button>Send</button>
</div>
</div>
`;
}
addMessage(text, type = 'user', id = null, algorithm = 'default') {
const message = document.createElement('div');
message.classList.add('message', type);
message.innerHTML = `
<p>${text}</p>
${type === 'bot' ? `
<div class="message-icons">
<span class="algorithm-indicator" style="background-color: var(--algorithm-color-${algorithm});"></span>
<i class="material-icons" onclick="handleFeedback('${id}', 'up')">thumb_up</i>
<i class="material-icons" onclick="handleFeedback('${id}', 'down')">thumb_down</i>
</div>` : ''}
`;
this.messagesArea.appendChild(message);
this.messagesArea.scrollTop = this.messagesArea.scrollHeight;
}
handleSendMessage() {
console.log('handleSendMessage called');
const message = this.questionInput.value.trim();
if (message) {
this.addMessage(message, 'user');
this.questionInput.value = '';
this.sendMessageToBackend(message);
}
}
sendMessageToBackend(message) {
console.log('sendMessageToBackend called');
if (!this.socket) {
console.error('Socket is not initialized');
return;
}
if (!this.jwtToken) {
console.error('JWT token is not available');
return;
}
console.log('Sending message to backend');
this.socket.emit('user_message', { tenantId: this.tenantId, token: this.jwtToken, message });
}
}
customElements.define('eveai-chat-widget', EveAIChatWidget);
function handleFeedback(messageId, feedback) {
// Send feedback to the backend
console.log(`Feedback for ${messageId}: ${feedback}`);
// Implement the actual feedback mechanism
}