Save chats, messages and media to IndexedDB
This commit is contained in:
parent
819c16d02f
commit
3a1ed0903c
9 changed files with 348 additions and 67 deletions
323
js/app.js
Normal file
323
js/app.js
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
import { config } from "./config.js";
|
||||
import { waha } from "./waha.js";
|
||||
import { ui, elements } from "./ui.js";
|
||||
import { websocket } from "./websocket.js";
|
||||
import { compensateMessageOrdering, formatTime } from "./utils.js";
|
||||
import { fetchChats, getAppUser, getChatMessages, getChats } from "./storage.js";
|
||||
import { upsertMessages } from "./db.js";
|
||||
|
||||
let activeChatState = null;
|
||||
let userInfo;
|
||||
const messageTone = new Audio("./message.ogg");
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
setupEventListeners();
|
||||
try {
|
||||
elements.loggedUserName.textContent = await getAppUser().pushName;
|
||||
loadChats();
|
||||
checkWahaStatus();
|
||||
initWebSocket();
|
||||
} finally {
|
||||
elements.chatsLoader.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
function loadChats() {
|
||||
try {
|
||||
elements.chatsLoader.classList.remove('hidden');
|
||||
fetchChats().then(() => {
|
||||
ui.renderChatList(getChats(), activeChatState, selectChat);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to load chats:', error);
|
||||
elements.chatList.innerHTML = `
|
||||
<li class="loading-chats" style="color: var(--text-primary); text-align: center; padding: 20px;">
|
||||
<p>Connection to WAHA failed.</p>
|
||||
<p style="font-size: 0.75rem; color: var(--text-primary); margin-top: 8px;">
|
||||
Ensure WAHA server is running and CORS is enabled, or click Settings to configure.
|
||||
</p>
|
||||
<p style="font-size: 0.75rem; color: var(--text-muted); margin-top: 8px;">${error.message}</p>
|
||||
</li>
|
||||
`;
|
||||
} finally {
|
||||
elements.chatsLoader.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.code == "Escape") {
|
||||
e.preventDefault();
|
||||
ui.toggleChatState();
|
||||
}
|
||||
});
|
||||
|
||||
elements.refreshChatsBtn.addEventListener('click', () => {
|
||||
elements.refreshChatsBtn.classList.add('spinning');
|
||||
loadChats()
|
||||
setTimeout(() => {
|
||||
elements.refreshChatsBtn.classList.remove('spinning');
|
||||
}, 600);
|
||||
});
|
||||
|
||||
elements.chatSearch.addEventListener('input', (e) => {
|
||||
const query = e.target.value.toLowerCase();
|
||||
const filtered = getChats().filter(chat =>
|
||||
chat.name.toLowerCase().includes(query)
|
||||
);
|
||||
ui.renderChatList(filtered, activeChatState, selectChat);
|
||||
});
|
||||
|
||||
elements.messageForm.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
});
|
||||
|
||||
elements.chatBottomBar.style.height = `${elements.chatInputPanel.offsetHeight}px`;
|
||||
const observer = new ResizeObserver(() => {
|
||||
elements.chatBottomBar.style.height =
|
||||
`${elements.chatInputPanel.offsetHeight}px`;
|
||||
});
|
||||
|
||||
observer.observe(elements.chatInputPanel);
|
||||
elements.chatBottomBarBtn.addEventListener('click', ui.toggleChatBottomBar);
|
||||
elements.chatBottomBar.addEventListener('click', (e) => {
|
||||
if (e.target == e.currentTarget) ui.toggleChatBottomBar();
|
||||
});
|
||||
|
||||
elements.attachmentBtn.addEventListener('click', () => {
|
||||
elements.attachmentInput.click();
|
||||
})
|
||||
elements.attachmentInput.addEventListener('change', function () {
|
||||
const firstFile = this.files[0];
|
||||
sendFileMessage(firstFile);
|
||||
})
|
||||
|
||||
elements.backToSidebarBtn.addEventListener('click', () => {
|
||||
elements.sidebar.classList.remove('hidden');
|
||||
elements.activeChatContainer.classList.add('hidden');
|
||||
});
|
||||
|
||||
elements.settingsIconBtn.addEventListener('click', openSettings);
|
||||
elements.cancelSettingsBtn.addEventListener('click', () => ui.toggleModal(false));
|
||||
elements.saveSettingsBtn.addEventListener('click', saveSettings);
|
||||
}
|
||||
|
||||
function initWebSocket() {
|
||||
websocket.connect((data) => {
|
||||
// console.log('[WS] Received event:', data.event, data);
|
||||
const ev = data.event;
|
||||
if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') {
|
||||
handleIncomingMessage(data.payload);
|
||||
upsertMessages([data.payload]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeChatId(raw) {
|
||||
if (!raw) return null;
|
||||
if (typeof raw === 'object') {
|
||||
return raw._serialized || raw.user || JSON.stringify(raw);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function handleIncomingMessage(msg) {
|
||||
if (!msg) return;
|
||||
|
||||
// console.log('[WS] handleIncomingMessage payload:', msg);
|
||||
|
||||
ui.updateChatInChatList(msg);
|
||||
|
||||
const rawChatId = msg.chatId || msg.from || (msg.chat && msg.chat.id);
|
||||
const msgChatId = normalizeChatId(rawChatId);
|
||||
if (!msgChatId) {
|
||||
console.warn('[WS] Could not resolve chatId from payload:', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// console.log('[WS] Resolved msgChatId:', msgChatId, '| activeChatState:', activeChatState?.id);
|
||||
if (msg.fromMe) {
|
||||
messageTone.play();
|
||||
}
|
||||
|
||||
if (activeChatState && activeChatState.id === msgChatId) {
|
||||
const msgId = normalizeChatId(msg.id) || msg.id;
|
||||
const exists = document.getElementById(msgId);
|
||||
if (!exists) {
|
||||
ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name, userInfo.id);
|
||||
ui.scrollToBottom();
|
||||
}
|
||||
}
|
||||
|
||||
const chatIndex = getChats().findIndex(c => c.id === msgChatId);
|
||||
if (chatIndex !== -1) {
|
||||
const chat = getChats()[chatIndex];
|
||||
chat.lastMessage = msg.body || msg.text || 'Media message';
|
||||
chat.timestamp = msg.timestamp ? (msg.timestamp * 1000) : Date.now();
|
||||
|
||||
if (!msg.fromMe && (!activeChatState || activeChatState.id !== msgChatId)) {
|
||||
chat.unreadCount = (chat.unreadCount || 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function selectChat(chat) {
|
||||
activeChatState = chat;
|
||||
|
||||
chat.unreadCount = 0;
|
||||
|
||||
// ui.renderChatList(chatsState, activeChatState, selectChat);
|
||||
|
||||
ui.toggleChatState(true);
|
||||
elements.activeChatName.textContent = chat.name.toUpperCase();
|
||||
elements.activeChatAvatar.textContent = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?';
|
||||
|
||||
elements.messagesContainer.innerHTML = `
|
||||
<div class="loading-chats">
|
||||
<div class='dots'>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</div>
|
||||
<span>Loading messages...
|
||||
</span>
|
||||
</div>`;
|
||||
|
||||
if (window.innerWidth <= 768) {
|
||||
elements.sidebar.classList.add('hidden');
|
||||
}
|
||||
|
||||
try {
|
||||
const rawMessages = await getChatMessages(chat.id);
|
||||
const processedMessages = compensateMessageOrdering(rawMessages);
|
||||
ui.renderMessages(processedMessages, chat.name, getAppUser().id, chat.id);
|
||||
} catch (error) {
|
||||
console.error('Failed to load messages:', error);
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">Error loading messages</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const text = elements.messageInput.value.trim();
|
||||
if (!text || !activeChatState) return;
|
||||
|
||||
elements.messageInput.value = '';
|
||||
|
||||
const tempMsg = {
|
||||
id: 'temp-' + Date.now(),
|
||||
body: text,
|
||||
fromMe: true,
|
||||
sender: 'me',
|
||||
timestamp: new Date().toISOString(),
|
||||
status: 'sending'
|
||||
};
|
||||
|
||||
ui.appendSingleMessage(tempMsg, activeChatState.name, userInfo.id);
|
||||
ui.scrollToBottom();
|
||||
|
||||
try {
|
||||
try {
|
||||
await waha.startTyping(activeChatState.id);
|
||||
const delay = Math.min(4000, Math.max(1000, text.length * 50));
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
} catch (e) {
|
||||
console.warn('Presence start failed:', e);
|
||||
}
|
||||
|
||||
try {
|
||||
await waha.stopTyping(activeChatState.id);
|
||||
} catch (e) {
|
||||
console.warn('Presence stop failed:', e);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!activeChatState.id.endsWith('@lid')) {
|
||||
await waha.readChat(activeChatState.id);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('readChat failed (non-fatal):', e.message);
|
||||
}
|
||||
|
||||
const responseData = await waha.sendTextMessage(activeChatState.id, text);
|
||||
|
||||
const tempBubble = document.getElementById(tempMsg.id);
|
||||
if (tempBubble) {
|
||||
if (responseData && responseData.id) {
|
||||
tempBubble.id = responseData.id;
|
||||
}
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
meta.innerHTML = `<span>${formatTime(new Date())}</span><span style="width:14px; height:14px;" class="mif-done">`;
|
||||
}
|
||||
|
||||
activeChatState.lastMessage = text;
|
||||
activeChatState.timestamp = new Date();
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
const tempBubble = document.getElementById(tempMsg.id);
|
||||
if (tempBubble) {
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
meta.innerHTML = `<span style="color: #ef4444;">Failed to send</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function sendFileMessage(file) {
|
||||
try {
|
||||
const tempId = 'temp-' + Date.now();
|
||||
const tempMsg = {
|
||||
_data: {
|
||||
mimetype: file.type
|
||||
},
|
||||
id: tempId,
|
||||
body: "",
|
||||
fromMe: true,
|
||||
sender: 'me',
|
||||
timestamp: new Date().toISOString(),
|
||||
status: 'sending',
|
||||
hasMedia: true,
|
||||
media: {
|
||||
url: URL.createObjectURL(file),
|
||||
filename: file.name
|
||||
}
|
||||
};
|
||||
|
||||
ui.appendSingleMessage(tempMsg, activeChatState.name, userInfo.id, activeChatState.id, true);
|
||||
ui.scrollToBottom();
|
||||
|
||||
const result = await waha.sendFileMessage(activeChatState.id, file);
|
||||
ui.updateMessageTick(tempId, result.status);
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
elements.inputWahaUrl.value = config.wahaUrl;
|
||||
elements.inputSession.value = config.session;
|
||||
elements.inputApiKey.value = config.apiKey;
|
||||
ui.toggleModal(true);
|
||||
}
|
||||
|
||||
function saveSettings() {
|
||||
config.save(
|
||||
elements.inputWahaUrl.value,
|
||||
elements.inputSession.value,
|
||||
elements.inputApiKey.value
|
||||
);
|
||||
ui.toggleModal(false);
|
||||
loadChats();
|
||||
checkWahaStatus();
|
||||
initWebSocket();
|
||||
}
|
||||
|
||||
async function checkWahaStatus() {
|
||||
try {
|
||||
const data = await waha.getVersion();
|
||||
ui.updateConnectionStatus(true, `WAHA Connected: v${data.version || 'OK'}`);
|
||||
} catch (e) {
|
||||
ui.updateConnectionStatus(false, 'WAHA Server Offline');
|
||||
}
|
||||
}
|
||||
17
js/config.js
Normal file
17
js/config.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Client Configuration State & Storage Manager
|
||||
|
||||
export const config = {
|
||||
wahaUrl: localStorage.getItem('waha_url') || 'http://inspiran.beetal-castor.ts.net:3100',
|
||||
session: localStorage.getItem('waha_session') || 'session_01kxc62bk5fs8vh4v127k88a7j',
|
||||
apiKey: localStorage.getItem('waha_api_key') || '',
|
||||
|
||||
save(url, session, apiKey) {
|
||||
this.wahaUrl = url.trim().replace(/\/$/, "");
|
||||
this.session = session.trim();
|
||||
this.apiKey = apiKey.trim();
|
||||
|
||||
localStorage.setItem('waha_url', this.wahaUrl);
|
||||
localStorage.setItem('waha_session', this.session);
|
||||
localStorage.setItem('waha_api_key', this.apiKey);
|
||||
}
|
||||
};
|
||||
204
js/db.js
Normal file
204
js/db.js
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
const DB_NAME = "pandora";
|
||||
const DB_VERSION = 6;
|
||||
let dbPromise = null;
|
||||
|
||||
function normalizeId(raw) {
|
||||
if (!raw) return null;
|
||||
if (typeof raw === 'object') {
|
||||
return raw._serialized || raw.user || JSON.stringify(raw);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function openDb() {
|
||||
if (dbPromise) return dbPromise;
|
||||
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
req.onupgradeneeded = (e) => {
|
||||
const db = req.result;
|
||||
const tx = req.transaction;
|
||||
|
||||
if (!db.objectStoreNames.contains("chats")) {
|
||||
const store = db.createObjectStore("chats", { keyPath: "id" });
|
||||
store.createIndex("timestamp", "timestamp", { unique: false });
|
||||
}
|
||||
|
||||
let msgStore;
|
||||
if (!db.objectStoreNames.contains("messages")) {
|
||||
msgStore = db.createObjectStore("messages", { keyPath: "id" });
|
||||
msgStore.createIndex("from", "from", { unique: false });
|
||||
msgStore.createIndex("fingerprint", ["from", "timestamp"], { unique: false });
|
||||
} else {
|
||||
msgStore = tx.objectStore("messages");
|
||||
}
|
||||
|
||||
if (!msgStore.indexNames.contains("chatId_timestamp")) {
|
||||
msgStore.createIndex("chatId_timestamp", ["chatId", "timestamp"], { unique: false });
|
||||
}
|
||||
|
||||
if (db.objectStoreNames.contains("messages")) {
|
||||
msgStore.openCursor().onsuccess = (event) => {
|
||||
const cursor = event.target.result;
|
||||
if (cursor) {
|
||||
const m = cursor.value;
|
||||
const from = normalizeId(m.from);
|
||||
const to = normalizeId(m.to);
|
||||
const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from);
|
||||
if (!m.chatId && chatId) {
|
||||
m.chatId = chatId;
|
||||
cursor.update(m);
|
||||
}
|
||||
cursor.continue();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (!db.objectStoreNames.contains("media")) {
|
||||
db.createObjectStore("media", { keyPath: "reqId" });
|
||||
}
|
||||
};
|
||||
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
export async function upsertChats(chats) {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("chats", "readwrite");
|
||||
const store = tx.objectStore("chats");
|
||||
|
||||
for (const c of chats) {
|
||||
store.put({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
lastMessage: c.lastMessage,
|
||||
timestamp: c.timestamp,
|
||||
unreadCount: c.unreadCount ?? 0
|
||||
});
|
||||
}
|
||||
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadChatsSorted() {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("chats", "readonly");
|
||||
const store = tx.objectStore("chats");
|
||||
const idx = store.index("timestamp");
|
||||
|
||||
const result = [];
|
||||
idx.openCursor(null, "prev").onsuccess = (e) => {
|
||||
const cursor = e.target.result;
|
||||
if (cursor) {
|
||||
result.push(cursor.value);
|
||||
cursor.continue();
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
};
|
||||
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
function mapMessage(m) {
|
||||
const from = normalizeId(m.from);
|
||||
const to = normalizeId(m.to);
|
||||
const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from);
|
||||
|
||||
return {
|
||||
_data: m._data,
|
||||
id: m.id,
|
||||
timestamp: m.timestamp,
|
||||
body: m.body,
|
||||
from: from,
|
||||
fromMe: m.fromMe,
|
||||
ack: m.ack,
|
||||
hasMedia: m.hasMedia,
|
||||
media: m.media,
|
||||
chatId: chatId,
|
||||
}
|
||||
}
|
||||
|
||||
export async function upsertMessages(messages) {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("messages", "readwrite");
|
||||
const store = tx.objectStore("messages");
|
||||
|
||||
for (const m of messages) {
|
||||
store.put(mapMessage(m));
|
||||
}
|
||||
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadLatestMessages(chatId, limit = 50) {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("messages", "readonly");
|
||||
const store = tx.objectStore("messages");
|
||||
const idx = store.index("chatId_timestamp");
|
||||
|
||||
const out = [];
|
||||
|
||||
const range = IDBKeyRange.bound([chatId, -Infinity], [chatId, Infinity]);
|
||||
|
||||
idx.openCursor(range, "prev").onsuccess = (e) => {
|
||||
const cursor = e.target.result;
|
||||
if (!cursor) return resolve(out);
|
||||
|
||||
out.push(cursor.value);
|
||||
if (out.length >= limit) resolve(out);
|
||||
else cursor.continue();
|
||||
};
|
||||
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertMedia(reqId, blob, filename) {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("media", "readwrite");
|
||||
const store = tx.objectStore("media");
|
||||
|
||||
store.put({
|
||||
reqId: reqId,
|
||||
blob: blob,
|
||||
filename: filename
|
||||
});
|
||||
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadMedia(reqId) {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("media", "readonly");
|
||||
const store = tx.objectStore("media");
|
||||
const req = store.get(reqId);
|
||||
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
}
|
||||
108
js/storage.js
Normal file
108
js/storage.js
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { loadChatsSorted, loadLatestMessages, loadMedia, upsertChats, upsertMedia, upsertMessages } from "./db.js";
|
||||
import { waha } from "./waha.js";
|
||||
|
||||
let user;
|
||||
let chats = [];
|
||||
|
||||
export async function fetchChats() {
|
||||
try {
|
||||
await getRemoteChats()
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
|
||||
chats = await loadChatsSorted();
|
||||
}
|
||||
|
||||
export async function getRemoteChats() {
|
||||
const u = await waha.getChats();
|
||||
|
||||
const mapped = u.map(chat => ({
|
||||
id: chat.id,
|
||||
name: chat.name,
|
||||
lastMessage: chat.lastMessage,
|
||||
timestamp: chat.timestamp,
|
||||
unreadCount: chat.unreadCount ?? 0
|
||||
}));
|
||||
|
||||
await upsertChats(mapped);
|
||||
}
|
||||
|
||||
export function getUsers() {
|
||||
return chats.filter(c => c.id.endsWith("@c.us"));
|
||||
}
|
||||
|
||||
export function getGroups() {
|
||||
return chats.filter(c => c.id.endsWith("@g.us"));
|
||||
}
|
||||
|
||||
export function getUser(number) {
|
||||
return users.find(user => user.id === number);
|
||||
}
|
||||
|
||||
export function getChats() {
|
||||
return chats;
|
||||
}
|
||||
|
||||
export async function getAppUser() {
|
||||
if (user) {
|
||||
return user;
|
||||
} else {
|
||||
try {
|
||||
return await waha.getMyInfo();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return {
|
||||
pushName: "Unknown",
|
||||
id: "Unknown"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMessage(chatId, msgId, downloadMedia) {
|
||||
try {
|
||||
const newMessage = await waha.getSingleChatMessage(chatId, msgId, downloadMedia);
|
||||
upsertMessages([newMessage]);
|
||||
return newMessage;
|
||||
} catch (error) {
|
||||
return {
|
||||
id: `${Date.now()}-temp`,
|
||||
body: "You're offline",
|
||||
from: "system",
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMedia(reqId) {
|
||||
try {
|
||||
const media = await waha.downloadMedia(reqId);
|
||||
upsertMedia(reqId, media.blob, media.filename);
|
||||
return media;
|
||||
} catch (error) {
|
||||
const cached = await loadMedia(reqId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatMessages(chatId) {
|
||||
try {
|
||||
const newMessages = await waha.getChatMessages(chatId);
|
||||
upsertMessages(newMessages);
|
||||
return newMessages;
|
||||
} catch (error) {
|
||||
return await loadLatestMessages(chatId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatPicture(chatId) {
|
||||
try {
|
||||
return await waha.getChatPicture(chatId);
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
323
js/ui.js
Normal file
323
js/ui.js
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
import { formatTime } from "./utils.js";
|
||||
import { waha } from "./waha.js";
|
||||
import { config } from "./config.js";
|
||||
import { getChatPicture, getMessage, getMedia } from "./storage.js";
|
||||
|
||||
// DOM Selector Cache
|
||||
export const elements = {
|
||||
chatList: document.getElementById('chat-list'),
|
||||
chatsLoader: document.getElementById('chats-loader'),
|
||||
chatSearch: document.getElementById('chat-search'),
|
||||
refreshChatsBtn: document.getElementById('refresh-chats-btn'),
|
||||
backendStatusText: document.getElementById('backend-status-text'),
|
||||
apiStatusIndicator: document.querySelector('.pulse-dot'),
|
||||
noChatState: document.getElementById('no-chat-state'),
|
||||
activeChatContainer: document.getElementById('active-chat-container'),
|
||||
activeChatName: document.getElementById('active-chat-name'),
|
||||
activeChatAvatar: document.getElementById('active-chat-avatar'),
|
||||
messagesContainer: document.getElementById('messages-container'),
|
||||
messageForm: document.getElementById('message-form'),
|
||||
messageInput: document.getElementById('message-input'),
|
||||
// backToSidebarBtn: document.getElementById('back-to-sidebar'),
|
||||
backToSidebarBtn: document.querySelector('.chat-header'),
|
||||
sidebar: document.querySelector('.sidebar'),
|
||||
settingsModal: document.getElementById('settings-modal'),
|
||||
settingsIconBtn: document.querySelector('.header-actions button[title="Settings"]'),
|
||||
cancelSettingsBtn: document.getElementById('cancel-settings'),
|
||||
saveSettingsBtn: document.getElementById('save-settings'),
|
||||
inputWahaUrl: document.getElementById('settings-waha-url'),
|
||||
inputSession: document.getElementById('settings-session'),
|
||||
inputApiKey: document.getElementById('settings-api-key'),
|
||||
loggedUserName: document.getElementById('pandora-username'),
|
||||
chatBottomBar: document.getElementById('chat-bottom-bar'),
|
||||
chatBottomBarBtn: document.getElementById('chat-bottom-bar-btn'),
|
||||
chatInputPanel: document.getElementById('chat-input-panel'),
|
||||
attachmentInput: document.getElementById('attachment-input'),
|
||||
attachmentBtn: document.getElementById('attachment-btn'),
|
||||
};
|
||||
|
||||
export const ui = {
|
||||
/**
|
||||
* Show or hide Settings connection modal
|
||||
*/
|
||||
toggleModal(show) {
|
||||
if (show) {
|
||||
elements.settingsModal.classList.remove('hidden');
|
||||
} else {
|
||||
elements.settingsModal.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Switch view state when a contact chat is opened or closed
|
||||
*/
|
||||
toggleChatState(hasActive) {
|
||||
if (hasActive) {
|
||||
elements.noChatState.classList.add('hidden');
|
||||
elements.activeChatContainer.classList.remove('hidden');
|
||||
} else {
|
||||
elements.noChatState.classList.remove('hidden');
|
||||
elements.activeChatContainer.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Scroll message list automatically to bottom
|
||||
*/
|
||||
scrollToBottom() {
|
||||
elements.messagesContainer.scrollTop = elements.messagesContainer.scrollHeight;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update connection status badge in sidebar footer
|
||||
*/
|
||||
updateConnectionStatus(isConnected, text) {
|
||||
elements.backendStatusText.textContent = text;
|
||||
if (isConnected) {
|
||||
elements.apiStatusIndicator.style.backgroundColor = 'var(--online-color)';
|
||||
elements.apiStatusIndicator.style.animation = 'pulse 1.8s infinite';
|
||||
} else {
|
||||
elements.apiStatusIndicator.style.backgroundColor = '#ef4444';
|
||||
elements.apiStatusIndicator.style.animation = 'none';
|
||||
}
|
||||
},
|
||||
|
||||
async renderChatList(chats, activeChat, onChatSelect) {
|
||||
elements.chatList.innerHTML = '';
|
||||
|
||||
chats.sort((a, b) => b.timestamp - a.timestamp);
|
||||
|
||||
if (chats.length === 0) {
|
||||
elements.chatList.innerHTML = `<li class="loading-chats">No chats found</li>`;
|
||||
return;
|
||||
}
|
||||
|
||||
for (const chat of chats) {
|
||||
const li = document.createElement('li');
|
||||
li.className = `chat-item ${activeChat && activeChat.id === chat.id ? 'active' : ''}`;
|
||||
li.dataset.id = chat.id;
|
||||
|
||||
const picture = await getChatPicture(chat.id);
|
||||
const initials = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?';
|
||||
const hasUnread = chat.unreadCount && chat.unreadCount > 0;
|
||||
const timeStr = formatTime(chat.timestamp || new Date());
|
||||
|
||||
li.innerHTML = `
|
||||
<div class="avatar"><img src="${picture.url ? picture.url : ""}" alt="${initials}"></div>
|
||||
<div class="chat-item-info">
|
||||
<div class="chat-item-meta">
|
||||
<span class="chat-item-name">${chat.name}</span>
|
||||
<span class="chat-item-time">${timeStr}</span>
|
||||
</div>
|
||||
<div class="chat-item-preview">
|
||||
<span class="chat-item-msg">${chat.lastMessage || 'No messages yet'}</span>
|
||||
${hasUnread ? `<span class="unread-badge">${chat.unreadCount}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
li.addEventListener('click', () => onChatSelect(chat));
|
||||
elements.chatList.appendChild(li);
|
||||
}
|
||||
},
|
||||
|
||||
async updateChatInChatList(msg) {
|
||||
const li = document.getElementById(msg.from);
|
||||
li.querySelector(".chat-item-msg").innerText = msg.body;
|
||||
},
|
||||
|
||||
/**
|
||||
* Render chat message log inside chat view container
|
||||
*/
|
||||
async renderMessages(messages, activeChatName, userID, chatId) {
|
||||
elements.messagesContainer.innerHTML = '';
|
||||
|
||||
if (messages.length === 0) {
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">No messages. Say hello!</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
for (const msg of messages) {
|
||||
this.appendSingleMessage(msg, activeChatName, userID, chatId);
|
||||
}
|
||||
|
||||
this.scrollToBottom();
|
||||
},
|
||||
|
||||
/**
|
||||
* Append a single message (used for optimistic updates immediately upon sending)
|
||||
*/
|
||||
appendSingleMessage(msg, activeChatName, userID, chatId, isLocal = false) {
|
||||
elements.messagesContainer.appendChild(this.generateMessage(msg, activeChatName, userID, chatId, isLocal))
|
||||
},
|
||||
|
||||
generateTempMessageLink(msg) {
|
||||
const a = document.createElement('a');
|
||||
a.target = "_blank";
|
||||
a.href = msg.media.url;
|
||||
|
||||
if (msg._data?.mimetype?.startsWith('image/')) {
|
||||
const img = document.createElement('img');
|
||||
img.classList.add('message-image-attachement');
|
||||
img.src = msg.media.url;
|
||||
a.appendChild(img);
|
||||
} else {
|
||||
a.textContent = msg.media.filename || "Download file";
|
||||
a.download = msg.media.filename;
|
||||
}
|
||||
|
||||
return a;
|
||||
},
|
||||
|
||||
generateMessage(msg, activeChatName, userID, chatId, isLocal = false) {
|
||||
console.log(msg);
|
||||
const isOutgoing = msg.fromMe || msg.sender === 'me';
|
||||
|
||||
function getPrevMessageElem() {
|
||||
return elements.messagesContainer.lastElementChild;
|
||||
}
|
||||
|
||||
const prevMsgEl = getPrevMessageElem();
|
||||
|
||||
const groupDiv = document.createElement('div');
|
||||
groupDiv.className = `message-group ${isOutgoing ? 'outgoing' : 'incoming'}`;
|
||||
groupDiv.id = msg.id;
|
||||
groupDiv.dataset.from = msg.participant || msg.from;
|
||||
|
||||
const senderName = isOutgoing ? userID : (msg._data.notifyName || msg.from);
|
||||
const timeStr = formatTime(msg.timestamp || new Date());
|
||||
|
||||
let statusCheck = '';
|
||||
if (isOutgoing) {
|
||||
if (msg.status === 'read') {
|
||||
statusCheck = '<span class="mif-done_all" style="color: var(--online-color); width:14px; height:14px;"></span>';
|
||||
} else if (msg.status === 'delivered') {
|
||||
statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>';
|
||||
} else if (msg.status === 'sending') {
|
||||
statusCheck = '<span class="mif-earth" style="width:14px; height:14px;"></span>';
|
||||
} else {
|
||||
statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>';
|
||||
}
|
||||
}
|
||||
|
||||
const bubble = document.createElement('div');
|
||||
bubble.className = 'message-bubble';
|
||||
|
||||
let prevUid;
|
||||
|
||||
if (msg.participant) {
|
||||
prevUid = msg.participant;
|
||||
} else {
|
||||
prevUid = msg.from;
|
||||
}
|
||||
|
||||
if (!isOutgoing && (!prevMsgEl || prevUid !== prevMsgEl.dataset.from)) {
|
||||
const senderEl = document.createElement('span');
|
||||
senderEl.className = 'message-sender';
|
||||
senderEl.textContent = senderName;
|
||||
bubble.appendChild(senderEl);
|
||||
}
|
||||
|
||||
const contentEl = document.createElement('div');
|
||||
contentEl.classList.add('message-content');
|
||||
const textEl = document.createElement('div');
|
||||
textEl.innerHTML = msg.body || msg.text || "";
|
||||
contentEl.appendChild(textEl);
|
||||
bubble.appendChild(contentEl);
|
||||
|
||||
if (msg.hasMedia) {
|
||||
let a;
|
||||
|
||||
if (isLocal) {
|
||||
a = this.generateTempMessageLink(msg);
|
||||
} else {
|
||||
a = document.createElement('a');
|
||||
a.innerText = `[Request media]`;
|
||||
a.target = "_blank";
|
||||
|
||||
const clickListener = async (e) => {
|
||||
a.removeEventListener('click', clickListener);
|
||||
a.innerText = `[Downloading]`;
|
||||
const mediaMsg = msg.media ? msg : await getMessage(chatId, msg.id, true);
|
||||
const url = new URL(mediaMsg.media.url);
|
||||
const reqID = url.pathname.split('/').filter(Boolean).pop();
|
||||
|
||||
const { blob, filename } = await getMedia(reqID);
|
||||
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
e.target.href = objectUrl;
|
||||
|
||||
if (blob.type.startsWith('image/')) {
|
||||
a.textContent = "";
|
||||
const img = document.createElement('img');
|
||||
img.classList.add('message-image-attachement');
|
||||
img.src = objectUrl;
|
||||
bubble.after(img);
|
||||
bubble.querySelector('.message-content').remove();
|
||||
} else {
|
||||
e.target.textContent = filename || `Download ${mediaMsg.media.filename}`;
|
||||
}
|
||||
}
|
||||
|
||||
a.addEventListener('click', clickListener);
|
||||
}
|
||||
|
||||
contentEl.appendChild(a);
|
||||
|
||||
if (!isLocal && msg._data?.mimetype?.startsWith('image/')) {
|
||||
a.click();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'message-meta';
|
||||
meta.innerHTML = `<span>${timeStr}</span>${statusCheck}`;
|
||||
|
||||
bubble.appendChild(meta);
|
||||
|
||||
if (isOutgoing) {
|
||||
if (prevMsgEl && prevMsgEl.classList.contains('outgoing')) {
|
||||
} else {
|
||||
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator';
|
||||
}
|
||||
} else if (msg.participant) {
|
||||
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
|
||||
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator';
|
||||
}
|
||||
} else {
|
||||
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
|
||||
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator';
|
||||
}
|
||||
}
|
||||
|
||||
groupDiv.appendChild(bubble);
|
||||
return groupDiv;
|
||||
},
|
||||
|
||||
updateMessage(originalMsgId, generatedMsg) {
|
||||
const originalMsg = document.querySelector(`#${originalMsgId}`);
|
||||
if (originalMsg) {
|
||||
originalMsg.replaceWith(generatedMsg)
|
||||
}
|
||||
},
|
||||
|
||||
updateMessageTick(id, status) {
|
||||
let statusCheck;
|
||||
if (status === 'read') {
|
||||
statusCheck = '<span class="mif-done_all" style="color: var(--online-color); width:14px; height:14px;"></span>';
|
||||
} else if (status === 'delivered') {
|
||||
statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>';
|
||||
} else if (status === 'sending') {
|
||||
statusCheck = '<span class="mif-earth" style="width:14px; height:14px;"></span>';
|
||||
} else {
|
||||
statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>';
|
||||
}
|
||||
|
||||
document.getElementById(id).querySelector('.message-meta').outerHTML = statusCheck;
|
||||
},
|
||||
|
||||
toggleChatBottomBar() {
|
||||
elements.chatBottomBar.classList.toggle("collapsed");
|
||||
}
|
||||
};
|
||||
102
js/utils.js
Normal file
102
js/utils.js
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// Helper utilities and algorithms
|
||||
|
||||
/**
|
||||
* Format timestamps (supports Unix epoch seconds/ms, strings and ISO dates)
|
||||
* @param {string|number|Date} dateVal
|
||||
* @returns {string} Formatted HH:MM AM/PM string
|
||||
*/
|
||||
export function formatTime(dateVal) {
|
||||
if (!dateVal) return '';
|
||||
let date;
|
||||
if (typeof dateVal === 'number') {
|
||||
date = new Date(dateVal < 10000000000 ? dateVal * 1000 : dateVal);
|
||||
} else if (typeof dateVal === 'string' && /^\d+$/.test(dateVal)) {
|
||||
const num = parseInt(dateVal, 10);
|
||||
date = new Date(num < 10000000000 ? num * 1000 : num);
|
||||
} else {
|
||||
date = new Date(dateVal);
|
||||
}
|
||||
|
||||
let hours = date.getHours();
|
||||
let minutes = date.getMinutes();
|
||||
const ampm = hours >= 12 ? 'PM' : 'AM';
|
||||
hours = hours % 12;
|
||||
hours = hours ? hours : 12;
|
||||
minutes = minutes < 10 ? '0' + minutes : minutes;
|
||||
return `${hours}:${minutes} ${ampm}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust outgoing messages backdated behind incoming messages due to clock drift.
|
||||
* Uses a 30-second sliding bubble-sort window.
|
||||
* @param {Array} messages List of raw messages from WAHA
|
||||
* @returns {Array} Compensated chronological message array
|
||||
*/
|
||||
export function compensateMessageOrdering(messages) {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
|
||||
// Convert timestamps to numeric milliseconds for stable comparison
|
||||
const msgs = messages.map(m => {
|
||||
let t = m.timestamp;
|
||||
if (typeof t === 'number') {
|
||||
if (t < 10000000000) t = t * 1000;
|
||||
} else {
|
||||
t = new Date(t).getTime();
|
||||
}
|
||||
return { ...m, _time: t };
|
||||
});
|
||||
|
||||
// Initial chronological sort
|
||||
msgs.sort((a, b) => a._time - b._time);
|
||||
|
||||
// Apply drift bubble adjustments
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (let i = 0; i < msgs.length - 1; i++) {
|
||||
const current = msgs[i];
|
||||
const next = msgs[i + 1];
|
||||
const timeDiff = next._time - current._time;
|
||||
|
||||
// Swap if an outgoing message is sorted before an incoming message within a 30-sec window
|
||||
if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) {
|
||||
msgs[i] = next;
|
||||
msgs[i + 1] = current;
|
||||
|
||||
// Advance the outgoing message's timestamp to be exactly 1 second after the incoming one
|
||||
current._time = next._time + 1000;
|
||||
if (typeof current.timestamp === 'number') {
|
||||
current.timestamp = Math.floor(current._time / 1000);
|
||||
} else {
|
||||
current.timestamp = new Date(current._time).toISOString();
|
||||
}
|
||||
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up temporary property
|
||||
return msgs.map(({ _time, ...m }) => m);
|
||||
}
|
||||
|
||||
export function getBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
resolve(reader.result.split(",")[1]);
|
||||
};
|
||||
|
||||
reader.onerror = (e) => {
|
||||
console.error("Error", e);
|
||||
reject(e);
|
||||
};
|
||||
|
||||
reader.onabort = () => {
|
||||
reject(new Error("Aborted"));
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
168
js/waha.js
Normal file
168
js/waha.js
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import { config } from "./config.js";
|
||||
import { getBase64 } from "./utils.js";
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const url = `${config.wahaUrl}${path}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': '*/*',
|
||||
...options.headers
|
||||
};
|
||||
if (config.apiKey) {
|
||||
headers['X-Api-Key'] = config.apiKey;
|
||||
}
|
||||
|
||||
// console.log(`[WAHA] ${options.method || 'GET'} ${url}`, options.body ? JSON.parse(options.body) : '');
|
||||
|
||||
const response = await fetch(url, { ...options, headers });
|
||||
if (!response.ok) {
|
||||
let errorDetail = '';
|
||||
try {
|
||||
const errBody = await response.json();
|
||||
errorDetail = JSON.stringify(errBody);
|
||||
console.error(`[WAHA] Error response body:`, errBody);
|
||||
} catch (_) {
|
||||
errorDetail = await response.text().catch(() => '');
|
||||
}
|
||||
throw new Error(`WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function downloadFile(path, options = {}) {
|
||||
const url = `${config.wahaUrl}${path}`;
|
||||
|
||||
const headers = {
|
||||
'Content-Type': options.headers?.['Content-Type'] ?? 'application/json',
|
||||
'accept': '*/*',
|
||||
...options.headers
|
||||
};
|
||||
|
||||
if (config.apiKey) headers['X-Api-Key'] = config.apiKey;
|
||||
|
||||
// console.log(`[WAHA] ${options.method || 'GET'} ${url}`);
|
||||
|
||||
const response = await fetch(url, { ...options, headers });
|
||||
|
||||
if (!response.ok) {
|
||||
let errorDetail = '';
|
||||
try {
|
||||
errorDetail = JSON.stringify(await response.json());
|
||||
} catch (_) {
|
||||
errorDetail = await response.text().catch(() => '');
|
||||
}
|
||||
throw new Error(`WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
|
||||
let filename = 'download';
|
||||
const cd = response.headers.get('content-disposition');
|
||||
if (cd) {
|
||||
const m = cd.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
filename = decodeURIComponent(m?.[1] || m?.[2] || filename);
|
||||
}
|
||||
|
||||
return { blob, filename };
|
||||
}
|
||||
|
||||
|
||||
export const waha = {
|
||||
async getVersion() {
|
||||
return request('/api/version');
|
||||
},
|
||||
|
||||
async getChats() {
|
||||
const data = await request(`/api/${config.session}/chats`);
|
||||
return data.map(chat => {
|
||||
let chatId = chat.id;
|
||||
if (chatId && typeof chatId === "object") {
|
||||
chatId = chatId._serialized || chatId.user || JSON.stringify(chatId);
|
||||
}
|
||||
return {
|
||||
id: chatId || chat.chatId || chat.name,
|
||||
name: chat.name || "Unknown Contact",
|
||||
unreadCount: chat.unreadCount || 0,
|
||||
lastMessage: chat.lastMessage?.body || chat.lastMessageText || "Click to open chat",
|
||||
timestamp: chat.lastMessage?.timestamp || new Date()
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async getChatMessages(chatId) {
|
||||
return request(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40`);
|
||||
},
|
||||
|
||||
async getSingleChatMessage(chatId, messageId, downladMedia) {
|
||||
return request(`/api/${config.session}/chats/${chatId}/messages/${messageId}?downloadMedia=${downladMedia}`);
|
||||
},
|
||||
|
||||
async getChatPicture(chatId) {
|
||||
return request(`/api/${config.session}/chats/${chatId}/picture`);
|
||||
},
|
||||
|
||||
async readChat(chatId) {
|
||||
return request('/api/sendSeen', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async downloadMedia(file) {
|
||||
const { blob, filename } = await downloadFile(`/api/files/${config.session}/${file}`);
|
||||
return { blob, filename };
|
||||
},
|
||||
|
||||
async getMyInfo() {
|
||||
return request(`/api/sessions/${config.session}/me`);
|
||||
},
|
||||
|
||||
async startTyping(chatId) {
|
||||
return request('/api/startTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async stopTyping(chatId) {
|
||||
return request('/api/stopTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async sendTextMessage(chatId, text) {
|
||||
return request('/api/sendText', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
chatId,
|
||||
text,
|
||||
session: config.session
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async sendFileMessage(chatId, file) {
|
||||
const fileBase64 = await getBase64(file);
|
||||
const body = {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
chatId,
|
||||
file: {
|
||||
mimetype: file.type,
|
||||
filename: file.name,
|
||||
data: fileBase64
|
||||
},
|
||||
session: config.session
|
||||
})
|
||||
};
|
||||
|
||||
let endpoint = "/api/sendFile";
|
||||
|
||||
if (file.type.startsWith('image/')) endpoint = '/api/sendImage';
|
||||
if (file.type.startsWith('video/')) endpoint = '/api/sendVideo';
|
||||
|
||||
const result = await request(endpoint, body);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
93
js/websocket.js
Normal file
93
js/websocket.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { config } from "./config.js";
|
||||
|
||||
let socket = null;
|
||||
let reconnectTimer = null;
|
||||
let currentOnMessageCallback = null;
|
||||
|
||||
export const websocket = {
|
||||
connect(onMessageCallback) {
|
||||
currentOnMessageCallback = onMessageCallback;
|
||||
|
||||
this.disconnect(false);
|
||||
|
||||
const httpUrl = config.wahaUrl;
|
||||
if (!httpUrl) {
|
||||
console.warn('[WS] Config wahaUrl is empty. Cannot connect.');
|
||||
return;
|
||||
}
|
||||
|
||||
let wsUrl = httpUrl.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:');
|
||||
wsUrl = wsUrl.replace(/\/$/, '') + '/ws';
|
||||
|
||||
const apiKey = config.apiKey;
|
||||
const session = config.session;
|
||||
const events = ['session.status', 'message', 'message.any'];
|
||||
|
||||
const queryParams = new URLSearchParams();
|
||||
if (apiKey) {
|
||||
queryParams.append('x-api-key', apiKey);
|
||||
}
|
||||
queryParams.append('session', session);
|
||||
events.forEach(event => queryParams.append('events', event));
|
||||
|
||||
const fullWsUrl = `${wsUrl}?${queryParams.toString()}`;
|
||||
console.log('[WS] Connecting to:', fullWsUrl);
|
||||
|
||||
try {
|
||||
socket = new WebSocket(fullWsUrl);
|
||||
|
||||
socket.onopen = () => {
|
||||
console.log('[WS] Connection successfully established');
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (currentOnMessageCallback) {
|
||||
currentOnMessageCallback(data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[WS] Failed to parse message JSON:', e);
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = (error) => {
|
||||
console.error('[WS] WebSocket Error occurred:', error);
|
||||
};
|
||||
|
||||
socket.onclose = (event) => {
|
||||
console.log(`[WS] Connection closed (code: ${event.code}). Reconnecting in 5 seconds...`);
|
||||
socket = null;
|
||||
|
||||
reconnectTimer = setTimeout(() => {
|
||||
this.connect(currentOnMessageCallback);
|
||||
}, 5000);
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('[WS] Failed to initialize WebSocket client:', e);
|
||||
}
|
||||
},
|
||||
|
||||
disconnect(clearCallback = true) {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (clearCallback) {
|
||||
currentOnMessageCallback = null;
|
||||
}
|
||||
if (socket) {
|
||||
socket.onclose = null;
|
||||
socket.onerror = null;
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.close();
|
||||
socket = null;
|
||||
console.log('[WS] Connection closed explicitly');
|
||||
}
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue