Convert project to TypeScript; add workflow to build with Vite then publish to GH Pages.
This commit is contained in:
parent
932e63e299
commit
e615234325
30 changed files with 1932 additions and 443 deletions
BIN
web/fonts/selawk.ttf
Normal file
BIN
web/fonts/selawk.ttf
Normal file
Binary file not shown.
BIN
web/fonts/selawkb.ttf
Normal file
BIN
web/fonts/selawkb.ttf
Normal file
Binary file not shown.
BIN
web/fonts/selawkl.ttf
Normal file
BIN
web/fonts/selawkl.ttf
Normal file
Binary file not shown.
BIN
web/fonts/selawksb.ttf
Normal file
BIN
web/fonts/selawksb.ttf
Normal file
Binary file not shown.
BIN
web/fonts/selawksl.ttf
Normal file
BIN
web/fonts/selawksl.ttf
Normal file
Binary file not shown.
174
web/index.html
Normal file
174
web/index.html
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, interactive-widget=resizes-content" />
|
||||
<meta name="HandheldFriendly" content="true" />
|
||||
<title>Pandora</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="loading.css">
|
||||
<link rel="stylesheet" href="metroicons.css">
|
||||
<link rel="manifest" href="./manifest.json">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-container no-active-chat">
|
||||
<aside id="desktop-aside">
|
||||
<button id="profile-sidebar-btn" class="icon-btn mif-person mif-2x" data-page="profile-page"></button>
|
||||
<button id="chats-sidebar-btn" class="icon-btn mif-qa mif-2x" data-page="chat-page"></button>
|
||||
<button id="settings-sidebar-btn" class="icon-btn mif-cog mif-2x" data-page="settings-page"></button>
|
||||
</aside>
|
||||
|
||||
<!-- Sidebar -->
|
||||
<aside class="sidebar">
|
||||
<header class="sidebar-header">
|
||||
<p class="app-name">PANDORA</p>
|
||||
<div class="user-profile">
|
||||
<!-- <div id="pandora-user-icon" class="avatar user-avatar">P</div> -->
|
||||
<div class="user-info">
|
||||
<h3 id="pandora-username" data-content="app-user">Pandora User</h3>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="search-container">
|
||||
<div class="search-wrapper">
|
||||
<input type="text" id="chat-search" placeholder="Search or start new chat...">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-list-container">
|
||||
<div class="loading-chats" id="chats-loader">
|
||||
<div class='loading-animation-wrapper'>
|
||||
<div class="animation">
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="chat-list" id="chat-list">
|
||||
<!-- Chats will be dynamically injected here -->
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="extra-page" id="chat-page">
|
||||
<!-- Main Chat Area -->
|
||||
<main class="chat-area">
|
||||
<!-- No Chat Selected State -->
|
||||
<div class="no-chat-state" id="no-chat-state">
|
||||
<div class="empty-state-content">
|
||||
<div class="empty-state-icon mif-qa mif-3x">
|
||||
</div>
|
||||
<p>Select a contact to view the conversation or start a new chat.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Active Chat State -->
|
||||
<div class="active-chat-container hidden" id="active-chat-container">
|
||||
<header class="chat-header">
|
||||
<div class="active-contact-info">
|
||||
<!-- <button class="icon-btn back-btn mif-arrow-left mif-2x" id="back-to-sidebar" title="Back to chats"></button> -->
|
||||
<div class="avatar active-avatar" id="active-chat-avatar">C</div>
|
||||
<div>
|
||||
<h3 id="active-chat-name">Contact Name</h3>
|
||||
<span class="contact-status" id="active-chat-status"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-actions">
|
||||
<!-- <button class="icon-btn" title="Search in conversation"><i data-lucide="search"></i></button>
|
||||
<button class="icon-btn" title="Call"><i data-lucide="phone"></i></button>
|
||||
<button class="icon-btn" title="Video Call"><i data-lucide="video"></i></button>
|
||||
<button class="icon-btn" title="More Options"><i data-lucide="more-vertical"></i></button> -->
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Messages Area -->
|
||||
<div class="messages-container" id="messages-container">
|
||||
<!-- Messages will be dynamically injected here -->
|
||||
</div>
|
||||
|
||||
<!-- Input Panel -->
|
||||
<footer id="chat-input-panel" class="chat-input-panel">
|
||||
<div class="input-actions-left">
|
||||
<button id="chat-bottom-bar-btn" class="icon-btn mif-expand-less mif-3x" title="Expand"></button>
|
||||
</div>
|
||||
<form class="input-form" id="message-form">
|
||||
<input type="text" id="message-input" placeholder="Type a message..." autocomplete="off">
|
||||
<button type="submit" class="send-btn mif-paper-plane mif-3x" id="send-button">
|
||||
</button>
|
||||
</form>
|
||||
</footer>
|
||||
<!-- Bottom Bar -->
|
||||
<footer id="chat-bottom-bar" class="chat-expanded-panel alternate-panel collapsed">
|
||||
<button id="markread-btn" class="icon-btn send-btn mif-done_all mif-2x" title="Mark read"></button>
|
||||
<input id="attachment-input" style="display: none;" type="file">
|
||||
<button id="attachment-btn" class="icon-btn send-btn mif-attachment mif-2x" title="Attach file"></button>
|
||||
</footer>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<section class="extra-page" id="profile-page">
|
||||
<h2 data-content="app-user">Pandora User</h2>
|
||||
<div class="content">
|
||||
<img id="profile-page-picture" data-resource="app-user-image">
|
||||
<div id="profile-page-user-info">
|
||||
<p id="profile-page-user-number" data-content="app-user-number">Pandora User</p>
|
||||
<input id="profile-page-status-input" placeholder="enter your status" data-value="app-user-status">
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="extra-page" id="settings-page">
|
||||
<div class="modal-content">
|
||||
<header class="modal-header">
|
||||
<h2>SETTINGS</h2>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<h3>server</h3>
|
||||
<div class="form-group">
|
||||
<label for="settings-waha-url">WAHA Server URL</label>
|
||||
<input type="text" id="settings-waha-url" placeholder="http://localhost:3100">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="settings-session">Session ID</label>
|
||||
<input type="text" id="settings-session" placeholder="session_01...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="settings-api-key">API Key (X-API-KEY)</label>
|
||||
<input type="password" id="settings-api-key" placeholder="Enter API Key">
|
||||
</div>
|
||||
<p class="settings-warning">Note: Requests are sent directly from your browser to the WAHA server. Make sure CORS is enabled on your WAHA instance.</p>
|
||||
<h3>chats</h3>
|
||||
<div class="form-group">
|
||||
<label for="settings-background-image">Chat background image</label>
|
||||
<input type="text" id="settings-background-image" placeholder="Enter image URL">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="settings-background-opacity">Chat background opacity</label>
|
||||
<input type="number" min="0" max="1" step="0.1" id="settings-background-opacity" placeholder="Enter opacity value">
|
||||
</div>
|
||||
</div>
|
||||
<footer class="modal-footer">
|
||||
<button class="btn primary-btn" id="save-settings">Save</button>
|
||||
</footer>
|
||||
<div class="sidebar-footer">
|
||||
<div class="api-status-badge">
|
||||
<span class="pulse-dot"></span>
|
||||
<span id="backend-status-text">Backend connected</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- Client-side script loaded as ES Module -->
|
||||
<script type="module" src="./src/app.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
116
web/loading.css
Normal file
116
web/loading.css
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
.loading-animation-wrapper {
|
||||
width: 200px;
|
||||
height: 40px;
|
||||
margin: 10px auto 0 auto;
|
||||
padding-top: 4px;
|
||||
}
|
||||
.loading-animation-wrapper .caption {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
text-align: center;
|
||||
color: #fff;
|
||||
font: 12px/1.4em Arial;
|
||||
}
|
||||
.loading-animation-wrapper .dot {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: #fff;
|
||||
-moz-border-radius: 100%;
|
||||
-webkit-border-radius: 100%;
|
||||
border-radius: 100%;
|
||||
-moz-animation: movingdot 4s infinite;
|
||||
-webkit-animation: movingdot 4s infinite;
|
||||
animation: movingdot 4s infinite;
|
||||
-moz-animation-timing-function: cubic-bezier(0.03, 0.615, 0.995, 0.415);
|
||||
-webkit-animation-timing-function: cubic-bezier(0.03, 0.615, 0.995, 0.415);
|
||||
animation-timing-function: cubic-bezier(0.03, 0.615, 0.995, 0.415);
|
||||
-moz-animation-fill-mode: both;
|
||||
-webkit-animation-fill-mode: both;
|
||||
animation-fill-mode: both;
|
||||
}
|
||||
.loading-animation-wrapper .dot:nth-child(1) {
|
||||
-moz-animation-delay: 1s;
|
||||
-webkit-animation-delay: 1s;
|
||||
animation-delay: 1s;
|
||||
}
|
||||
.loading-animation-wrapper .dot:nth-child(2) {
|
||||
-moz-animation-delay: 0.9s;
|
||||
-webkit-animation-delay: 0.9s;
|
||||
animation-delay: 0.9s;
|
||||
}
|
||||
.loading-animation-wrapper .dot:nth-child(3) {
|
||||
-moz-animation-delay: 0.8s;
|
||||
-webkit-animation-delay: 0.8s;
|
||||
animation-delay: 0.8s;
|
||||
}
|
||||
.loading-animation-wrapper .dot:nth-child(4) {
|
||||
-moz-animation-delay: 0.7s;
|
||||
-webkit-animation-delay: 0.7s;
|
||||
animation-delay: 0.7s;
|
||||
}
|
||||
.loading-animation-wrapper .dot:nth-child(5) {
|
||||
-moz-animation-delay: 0.6s;
|
||||
-webkit-animation-delay: 0.6s;
|
||||
animation-delay: 0.6s;
|
||||
}
|
||||
|
||||
@-moz-keyframes movingdot {
|
||||
0% {
|
||||
-moz-transform: translateX(-30px);
|
||||
transform: translateX(-30px);
|
||||
opacity: 0;
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
-moz-transform: translateX(200px);
|
||||
transform: translateX(200px);
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@-webkit-keyframes movingdot {
|
||||
0% {
|
||||
-webkit-transform: translateX(-30px);
|
||||
transform: translateX(-30px);
|
||||
opacity: 0;
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
-webkit-transform: translateX(200px);
|
||||
transform: translateX(200px);
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@keyframes movingdot {
|
||||
0% {
|
||||
-moz-transform: translateX(-30px);
|
||||
-ms-transform: translateX(-30px);
|
||||
-webkit-transform: translateX(-30px);
|
||||
transform: translateX(-30px);
|
||||
opacity: 0;
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
-moz-transform: translateX(200px);
|
||||
-ms-transform: translateX(200px);
|
||||
-webkit-transform: translateX(200px);
|
||||
transform: translateX(200px);
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
1
web/metroicons.css
Normal file
1
web/metroicons.css
Normal file
File diff suppressed because one or more lines are too long
BIN
web/public/icon-192.png
Normal file
BIN
web/public/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
web/public/icon-512.png
Normal file
BIN
web/public/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
23
web/public/manifest.json
Normal file
23
web/public/manifest.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"name": "PANDORA chat",
|
||||
"short_name": "PANDORA",
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#102457",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"scope": "./",
|
||||
"start_url": "./",
|
||||
"description": "Internet messaging",
|
||||
"icons": [
|
||||
{
|
||||
"src": "icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
}
|
||||
BIN
web/public/message-long.ogg
Normal file
BIN
web/public/message-long.ogg
Normal file
Binary file not shown.
BIN
web/public/message.ogg
Normal file
BIN
web/public/message.ogg
Normal file
Binary file not shown.
476
web/src/app.ts
Normal file
476
web/src/app.ts
Normal file
|
|
@ -0,0 +1,476 @@
|
|||
import { config } from "./config";
|
||||
import { waha } from "./waha";
|
||||
import { ui, elements } from "./ui";
|
||||
import { websocket } from "./websocket";
|
||||
import { compensateMessageOrdering, debounce, formatTime, normalizeId } from "./utils";
|
||||
import { fetchChats, getAppUser, getChatMessages, getChatPicture, getChats, getUser, getUserAbout, markRead, sendStatus, updateOnlineStatus } from "./storage";
|
||||
import { upsertMessages } from "./db";
|
||||
import { showNotification } from "./notification";
|
||||
import type { Chat, Message, WebSocketEvent } from "./types";
|
||||
|
||||
let activeChatState: Chat | null = null;
|
||||
const messageTone = new Audio("./message.ogg");
|
||||
const longPressEvent = new CustomEvent("longpress");
|
||||
export let isLoadingChat = false;
|
||||
export let notificationAuthorization: NotificationPermission = "default";
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
askForNotificationPermission();
|
||||
elements.inputApiKey.value = config.apiKey;
|
||||
elements.inputWahaUrl.value = config.wahaUrl;
|
||||
elements.inputSession.value = config.session;
|
||||
elements.inputBackgroundImage.value = config.bgImg;
|
||||
elements.inputBackgroundOpacity.value = config.bgOpacity;
|
||||
elements.activeChatContainer.style.setProperty('--background-image', `URL("${config.bgImg}")`);
|
||||
elements.activeChatContainer.style.setProperty('--background-opacity', `${config.bgOpacity}`);
|
||||
await updateOnlineStatus();
|
||||
setupEventListeners();
|
||||
try {
|
||||
setupElementsData();
|
||||
loadChats();
|
||||
checkWahaStatus();
|
||||
initWebSocket();
|
||||
} finally {
|
||||
elements.chatsLoader.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
async function askForNotificationPermission() {
|
||||
notificationAuthorization = await Notification.requestPermission();
|
||||
}
|
||||
|
||||
async function setupElementsData() {
|
||||
try {
|
||||
const usr = await getAppUser();
|
||||
const usrPic = (await getChatPicture(usr.id))?.url;
|
||||
const usrInfo = await getUser(usr.id);
|
||||
const usrAbout = (await getUserAbout(usr.id))?.about;
|
||||
elements.contentUserName.forEach(e => {
|
||||
e.innerHTML = usr.pushName || usr.name || '';
|
||||
})
|
||||
elements.contentUserNumber.forEach(async e => {
|
||||
if (usrInfo) e.innerHTML = usrInfo.number;
|
||||
})
|
||||
elements.resourceUserPic.forEach(async e => {
|
||||
if (usrPic) e.src = usrPic;
|
||||
})
|
||||
elements.valueUserStatus.forEach(async e => {
|
||||
if (usrAbout) e.value = usrAbout.trim();
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function loadChats() {
|
||||
elements.chatsLoader.classList.remove('hidden');
|
||||
try {
|
||||
fetchChats().then(async () => {
|
||||
ui.renderChatList(getChats(), activeChatState, selectChat);
|
||||
|
||||
const hash = window.location.hash;
|
||||
if (hash && hash.startsWith('#chat-')) {
|
||||
const chatId = hash.replace('#chat-', '');
|
||||
const chat = getChats().find(c => c.id === chatId);
|
||||
if (chat) {
|
||||
selectChat(chat, true, false);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error: any) {
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
let isScrollingProgrammatically = false;
|
||||
let scrollTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function scrollToChat(smooth = true) {
|
||||
isScrollingProgrammatically = true;
|
||||
elements.appContainer.scrollTo({
|
||||
left: elements.appContainer.clientWidth,
|
||||
behavior: smooth ? 'smooth' : 'auto'
|
||||
});
|
||||
setTimeout(() => { isScrollingProgrammatically = false; }, smooth ? 400 : 50);
|
||||
}
|
||||
|
||||
function scrollToList(smooth = true) {
|
||||
isScrollingProgrammatically = true;
|
||||
elements.appContainer.scrollTo({
|
||||
left: 0,
|
||||
behavior: smooth ? 'smooth' : 'auto'
|
||||
});
|
||||
setTimeout(() => { isScrollingProgrammatically = false; }, smooth ? 400 : 50);
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
if (!window.location.hash) {
|
||||
window.location.hash = '';
|
||||
}
|
||||
|
||||
window.addEventListener('hashchange', () => {
|
||||
const hash = window.location.hash;
|
||||
if (hash && hash.startsWith('#chat-')) {
|
||||
const chatId = hash.replace('#chat-', '');
|
||||
const chat = getChats().find(c => c.id === chatId);
|
||||
if (chat) {
|
||||
selectChat(chat, true);
|
||||
}
|
||||
} else {
|
||||
closeActiveChat(true);
|
||||
}
|
||||
});
|
||||
|
||||
elements.appContainer.addEventListener('scroll', () => {
|
||||
if (window.innerWidth > 768) return;
|
||||
if (isScrollingProgrammatically) return;
|
||||
|
||||
if (scrollTimeout) clearTimeout(scrollTimeout);
|
||||
scrollTimeout = setTimeout(() => {
|
||||
const scrollLeft = elements.appContainer.scrollLeft;
|
||||
const width = elements.appContainer.clientWidth;
|
||||
|
||||
if (scrollLeft < width * 0.2) {
|
||||
// User swiped back to the list view
|
||||
if (activeChatState) {
|
||||
closeActiveChat(false);
|
||||
}
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.code == "Escape") {
|
||||
e.preventDefault();
|
||||
closeActiveChat(false);
|
||||
}
|
||||
});
|
||||
|
||||
elements.chatSearch.addEventListener('input', (e: Event) => {
|
||||
const query = (e.target as HTMLInputElement).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.markreadBtn.addEventListener('click', async () => {
|
||||
if (activeChatState) {
|
||||
const result = await markRead(activeChatState.id);
|
||||
if (result) ui.updateChatInChatList2(result);
|
||||
}
|
||||
})
|
||||
elements.attachmentBtn.addEventListener('click', () => {
|
||||
elements.attachmentInput.click();
|
||||
})
|
||||
elements.attachmentInput.addEventListener('change', function (this: HTMLInputElement) {
|
||||
const firstFile = this.files?.[0];
|
||||
if (firstFile) sendFileMessage(firstFile);
|
||||
})
|
||||
|
||||
elements.backToSidebarBtn.addEventListener('click', () => {
|
||||
closeActiveChat(false);
|
||||
});
|
||||
|
||||
elements.desktopSidebarButtons.forEach(sidebarBtn => {
|
||||
sidebarBtn.addEventListener('click', () => {
|
||||
const page = sidebarBtn.dataset.page;
|
||||
if (page) ui.showExtraPage(page);
|
||||
})
|
||||
})
|
||||
|
||||
elements.saveSettingsBtn.addEventListener('click', saveSettings);
|
||||
|
||||
elements.inputUserStatus.addEventListener('input', debounce(async function() {
|
||||
const result = await sendStatus(elements.inputUserStatus.value);
|
||||
if (result?.success) {
|
||||
showNotification("Status updated successfully!", "", 2000);
|
||||
} else {
|
||||
showNotification("Failed to update status...", "", 2000);
|
||||
}
|
||||
console.log(result);
|
||||
}, 2000))
|
||||
|
||||
elements.selectable.forEach(e => {
|
||||
let timerId: ReturnType<typeof setTimeout>, longPressed: boolean;
|
||||
|
||||
e.addEventListener('mousedown', () => {
|
||||
longPressed = false;
|
||||
|
||||
timerId = setTimeout(() => {
|
||||
longPressed = true;
|
||||
e.dispatchEvent(longPressEvent);
|
||||
}, 500); // 500ms for long press
|
||||
})
|
||||
|
||||
e.addEventListener('click', (event) => {
|
||||
if (longPressed) {
|
||||
event.preventDefault();
|
||||
clearTimeout(timerId);
|
||||
}
|
||||
})
|
||||
|
||||
e.addEventListener('mouseleave', () => {
|
||||
clearTimeout(timerId);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function initWebSocket() {
|
||||
websocket.connect((data: WebSocketEvent) => {
|
||||
const ev = data.event;
|
||||
if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') {
|
||||
handleIncomingMessage(data.payload);
|
||||
upsertMessages([data.payload]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function handleIncomingMessage(msg: Message) {
|
||||
if (!msg) return;
|
||||
|
||||
ui.updateChatInChatList(msg);
|
||||
|
||||
const rawChatId = msg.chatId || (typeof msg.from === 'string' ? msg.from : (msg.from as any)?._serialized) || (msg.chat && msg.chat.id);
|
||||
const msgChatId = normalizeId(rawChatId);
|
||||
if (!msgChatId) {
|
||||
console.warn('[WS] Could not resolve chatId from payload:', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!msg.fromMe) {
|
||||
messageTone.play();
|
||||
}
|
||||
if (notificationAuthorization === "granted") {
|
||||
new Notification("New message", { body: msg.body || msg.text });
|
||||
}
|
||||
|
||||
if (activeChatState && activeChatState.id === msgChatId) {
|
||||
const msgId = normalizeId(msg.id as any) || (msg.id as string);
|
||||
const exists = document.getElementById(msgId);
|
||||
if (!exists) {
|
||||
const container = elements.messagesContainer;
|
||||
const scrolled = container.scrollTop === (container.scrollHeight - container.clientHeight);
|
||||
ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name, (await getAppUser()).id);
|
||||
if (scrolled) {
|
||||
ui.scrollToBottom();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function selectChat(chat: Chat, isPopState = false, smoothScroll = true) {
|
||||
if (isLoadingChat) return;
|
||||
|
||||
isLoadingChat = true;
|
||||
activeChatState = chat;
|
||||
|
||||
chat.unreadCount = 0;
|
||||
|
||||
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-animation-wrapper'>
|
||||
<div class="animation">
|
||||
<p class="animation"></p>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
elements.appContainer.classList.remove('no-active-chat');
|
||||
|
||||
if (window.innerWidth <= 768) {
|
||||
scrollToChat(smoothScroll);
|
||||
}
|
||||
|
||||
if (!isPopState && window.location.hash !== `#chat-${chat.id}`) {
|
||||
window.location.hash = ``;
|
||||
window.location.hash = `chat-${chat.id}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawMessages = await getChatMessages(chat.id);
|
||||
const processedMessages = compensateMessageOrdering(rawMessages);
|
||||
ui.renderMessages(processedMessages, chat.name, (await getAppUser()).id, chat.id);
|
||||
} catch (error) {
|
||||
console.error('Failed to load messages:', error);
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">Error loading messages</div>';
|
||||
}
|
||||
|
||||
isLoadingChat = false;
|
||||
}
|
||||
|
||||
async function closeActiveChat(isPopState = false) {
|
||||
activeChatState = null;
|
||||
|
||||
if (window.innerWidth <= 768) {
|
||||
scrollToList();
|
||||
} else {
|
||||
ui.toggleChatState(false);
|
||||
}
|
||||
|
||||
|
||||
if (!isPopState) {
|
||||
if (window.location.hash.startsWith('#chat-')) {
|
||||
history.back();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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'
|
||||
} as any;
|
||||
|
||||
ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).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: any) {
|
||||
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 = normalizeId(responseData.id as any) || tempBubble.id;
|
||||
}
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
if (meta) meta.innerHTML = `<span>${formatTime(new Date())}</span><span style="width:14px; height:14px;" class="mif-done">`;
|
||||
}
|
||||
|
||||
activeChatState.lastMessage = text;
|
||||
activeChatState.timestamp = new Date().toISOString();
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
const tempBubble = document.getElementById(tempMsg.id);
|
||||
if (tempBubble) {
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
if (meta) meta.innerHTML = `<span style="color: #ef4444;">Failed to send</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function sendFileMessage(file: File) {
|
||||
if (!activeChatState) return;
|
||||
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
|
||||
}
|
||||
} as any;
|
||||
|
||||
ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).id, true);
|
||||
ui.scrollToBottom();
|
||||
|
||||
const result = await waha.sendFileMessage(activeChatState.id, file);
|
||||
ui.removeChatMessage(tempId);
|
||||
ui.appendSingleMessage(result, activeChatState.name, (await getAppUser()).id);
|
||||
} catch (error: any) {
|
||||
console.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function saveSettings() {
|
||||
config.save(
|
||||
elements.inputWahaUrl.value,
|
||||
elements.inputSession.value,
|
||||
elements.inputApiKey.value,
|
||||
elements.inputBackgroundImage.value,
|
||||
elements.inputBackgroundOpacity.value
|
||||
);
|
||||
location.reload();
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
export function getCurrentChat() {
|
||||
return activeChatState;
|
||||
}
|
||||
30
web/src/config.ts
Normal file
30
web/src/config.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
export interface Config {
|
||||
wahaUrl: string;
|
||||
session: string;
|
||||
apiKey: string;
|
||||
bgImg: string;
|
||||
bgOpacity: string;
|
||||
save(url: string, session: string, apiKey: string, bgImg: string, bgOpacity: string): void;
|
||||
}
|
||||
|
||||
export const config: 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') || '',
|
||||
bgImg: localStorage.getItem('background_image') || '',
|
||||
bgOpacity: localStorage.getItem('background_opacity') || '0.4',
|
||||
|
||||
save(url: string, session: string, apiKey: string, bgImg: string, bgOpacity: string): void {
|
||||
this.wahaUrl = url.trim().replace(/\/$/, "");
|
||||
this.session = session.trim();
|
||||
this.apiKey = apiKey.trim();
|
||||
this.bgImg = bgImg.trim();
|
||||
this.bgOpacity = bgOpacity.trim();
|
||||
|
||||
localStorage.setItem('waha_url', this.wahaUrl);
|
||||
localStorage.setItem('waha_session', this.session);
|
||||
localStorage.setItem('waha_api_key', this.apiKey);
|
||||
localStorage.setItem('background_image', this.bgImg);
|
||||
localStorage.setItem('background_opacity', this.bgOpacity);
|
||||
}
|
||||
};
|
||||
245
web/src/db.ts
Normal file
245
web/src/db.ts
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
import { normalizeId } from "./utils";
|
||||
import type { Chat, Message, StoredMedia } from "./types";
|
||||
|
||||
const DB_NAME = "pandora";
|
||||
const DB_VERSION = 6;
|
||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
if (dbPromise) return dbPromise;
|
||||
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
req.onupgradeneeded = () => {
|
||||
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: IDBObjectStore;
|
||||
if (!db.objectStoreNames.contains("messages")) {
|
||||
msgStore = db.createObjectStore("messages", { keyPath: "id" });
|
||||
msgStore.createIndex("from", "from", { unique: false });
|
||||
msgStore.createIndex("fingerprint", ["from", "timestamp"], { unique: false });
|
||||
msgStore.createIndex("cidTimestampId", ["chatId", "timestamp", "id"], { unique: false });
|
||||
} else {
|
||||
msgStore = tx.objectStore("messages");
|
||||
}
|
||||
|
||||
if (!msgStore.indexNames.contains("chatId_timestamp")) {
|
||||
msgStore.createIndex("chatId_timestamp", ["chatId", "timestamp"], { unique: false });
|
||||
}
|
||||
|
||||
// Migration logic
|
||||
msgStore.openCursor().onsuccess = (event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>).result;
|
||||
if (cursor) {
|
||||
const m = cursor.value as Message;
|
||||
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: Chat[]): Promise<void> {
|
||||
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(): Promise<Chat[]> {
|
||||
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: Chat[] = [];
|
||||
idx.openCursor(null, "prev").onsuccess = (e) => {
|
||||
const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).result;
|
||||
if (cursor) {
|
||||
result.push(cursor.value);
|
||||
cursor.continue();
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
};
|
||||
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadChat(chatId: string): Promise<Chat | undefined> {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("chats", "readonly");
|
||||
const store = tx.objectStore("chats");
|
||||
const req = store.get(chatId);
|
||||
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
}
|
||||
|
||||
function mapMessage(m: Message): any {
|
||||
const from = normalizeId(m.from);
|
||||
const to = normalizeId(m.to);
|
||||
const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from);
|
||||
|
||||
return {
|
||||
_data: m._data,
|
||||
id: normalizeId(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: Message[]): Promise<void> {
|
||||
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: string, limit: number = 50): Promise<Message[]> {
|
||||
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: Message[] = [];
|
||||
|
||||
const range = IDBKeyRange.bound([chatId, -Infinity], [chatId, Infinity]);
|
||||
|
||||
idx.openCursor(range, "prev").onsuccess = (e) => {
|
||||
const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).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 loadOlderMessages(chatId: string, oldestTimestamp: any, oldestId: string, limit: number = 50): Promise<Message[]> {
|
||||
const db = await openDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction("messages", "readonly");
|
||||
const store = tx.objectStore("messages");
|
||||
const idx = store.index("cidTimestampId");
|
||||
|
||||
const out: Message[] = [];
|
||||
|
||||
const parsedTimestamp = isNaN(oldestTimestamp) ? oldestTimestamp : Number(oldestTimestamp);
|
||||
|
||||
const range = IDBKeyRange.bound(
|
||||
[chatId, -Infinity, ""],
|
||||
[chatId, parsedTimestamp, oldestId],
|
||||
false,
|
||||
false
|
||||
);
|
||||
|
||||
idx.openCursor(range, "prev").onsuccess = (e) => {
|
||||
const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).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: string, blob: Blob, filename: string): Promise<void> {
|
||||
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: string): Promise<StoredMedia | undefined> {
|
||||
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);
|
||||
});
|
||||
}
|
||||
37
web/src/notification.ts
Normal file
37
web/src/notification.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
export async function showNotification(title: string, subtitle: string, time: number = 5000, _hint?: string): Promise<void> {
|
||||
const notificationBox = document.createElement('div');
|
||||
notificationBox.classList.add('notification-box');
|
||||
|
||||
const notificationTitle = document.createElement('h1');
|
||||
notificationTitle.innerHTML = title;
|
||||
|
||||
const notificationSubtitle = document.createElement('p');
|
||||
notificationSubtitle.innerHTML = subtitle;
|
||||
|
||||
notificationBox.appendChild(notificationTitle);
|
||||
if (subtitle) {
|
||||
notificationBox.appendChild(notificationSubtitle);
|
||||
}
|
||||
document.querySelector('body')!.appendChild(notificationBox);
|
||||
|
||||
let clicked = false;
|
||||
|
||||
notificationBox.addEventListener('click', () => {
|
||||
clicked = true;
|
||||
hideNotification(notificationBox);
|
||||
})
|
||||
|
||||
await new Promise(requestAnimationFrame);
|
||||
notificationBox.classList.add("shown");
|
||||
|
||||
await new Promise<void>(r => setTimeout(r, time));
|
||||
if (!clicked) {
|
||||
hideNotification(notificationBox);
|
||||
}
|
||||
}
|
||||
|
||||
async function hideNotification(notificationBox: HTMLDivElement): Promise<void> {
|
||||
notificationBox.classList.remove('shown');
|
||||
await new Promise<void>(r => setTimeout(r, 1000));
|
||||
notificationBox.remove();
|
||||
}
|
||||
167
web/src/storage.ts
Normal file
167
web/src/storage.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import { loadChat, loadChatsSorted, loadLatestMessages, loadMedia, loadOlderMessages, upsertChats, upsertMedia, upsertMessages } from "./db";
|
||||
import { waha } from "./waha";
|
||||
import type { Chat, Message, AppUser, ContactInfo, UserAboutResponse, ChatPictureResponse, StatusResponse, DownloadedMedia } from "./types";
|
||||
|
||||
let online = false;
|
||||
let chats: Chat[] = [];
|
||||
|
||||
export async function updateOnlineStatus(): Promise<void> {
|
||||
try {
|
||||
await waha.getVersion();
|
||||
online = true;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
online = false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchChats(): Promise<void> {
|
||||
if (online) {
|
||||
await getRemoteChats()
|
||||
}
|
||||
chats = await loadChatsSorted();
|
||||
}
|
||||
|
||||
export async function getRemoteChats(): Promise<void> {
|
||||
const u = await waha.getChats();
|
||||
|
||||
const mapped: Chat[] = 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(): Chat[] {
|
||||
return chats.filter(c => c.id.endsWith("@c.us"));
|
||||
}
|
||||
|
||||
export function getGroups(): Chat[] {
|
||||
return chats.filter(c => c.id.endsWith("@g.us"));
|
||||
}
|
||||
|
||||
export async function getUser(number: string): Promise<ContactInfo | undefined> {
|
||||
if (online) {
|
||||
return await waha.getUser(number);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getUserAbout(userId: string): Promise<UserAboutResponse | undefined> {
|
||||
if (online) {
|
||||
return await waha.getUserAbout(userId);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function getChats(): Chat[] {
|
||||
return chats;
|
||||
}
|
||||
|
||||
export async function getAppUser(): Promise<AppUser> {
|
||||
if (online) {
|
||||
const info = await waha.getMyInfo();
|
||||
localStorage.setItem('pandora-last-username', info.pushName || info.name || '');
|
||||
localStorage.setItem('pandora-last-userid', info.id);
|
||||
return info;
|
||||
} else {
|
||||
return {
|
||||
pushName: localStorage.getItem('pandora-last-username') || 'Unknown',
|
||||
name: localStorage.getItem('pandora-last-username') || 'Unknown',
|
||||
id: localStorage.getItem('pandora-last-userid') || 'Unknown'
|
||||
} as AppUser;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMessage(chatId: string, msgId: string, downloadMedia: boolean): Promise<Message> {
|
||||
if (online) {
|
||||
const newMessage = await waha.getSingleChatMessage(chatId, msgId, downloadMedia);
|
||||
upsertMessages([newMessage]);
|
||||
return newMessage;
|
||||
} else {
|
||||
return {
|
||||
id: `${Date.now()}-temp`,
|
||||
body: "You're offline",
|
||||
from: "system",
|
||||
timestamp: new Date().toISOString()
|
||||
} as Message;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMedia(reqId: string): Promise<DownloadedMedia | undefined> {
|
||||
const cached = await loadMedia(reqId);
|
||||
if (cached) {
|
||||
return { blob: cached.blob, filename: cached.filename };
|
||||
}
|
||||
|
||||
try {
|
||||
if (online) {
|
||||
const media = await waha.downloadMedia(reqId);
|
||||
upsertMedia(reqId, media.blob, media.filename);
|
||||
return media;
|
||||
}
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatMessages(chatId: string): Promise<Message[]> {
|
||||
if (online) {
|
||||
const newMessages = await waha.getChatMessages(chatId);
|
||||
upsertMessages(newMessages);
|
||||
return newMessages;
|
||||
} else {
|
||||
return await loadLatestMessages(chatId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMoreChatMessages(chatId: string, oldestTimestamp: any, oldestId: string): Promise<Message[]> {
|
||||
if (online) {
|
||||
return waha.getChatMessages(chatId, oldestTimestamp);
|
||||
} else {
|
||||
return await loadOlderMessages(chatId, oldestTimestamp, oldestId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatPicture(chatId: string): Promise<ChatPictureResponse> {
|
||||
if (online) {
|
||||
return await waha.getChatPicture(chatId);
|
||||
} else {
|
||||
return { url: "" };
|
||||
}
|
||||
}
|
||||
|
||||
export function isOnline(): boolean {
|
||||
return online;
|
||||
}
|
||||
|
||||
export async function sendStatus(text: string): Promise<StatusResponse> {
|
||||
if (online) {
|
||||
return await waha.setStatus(text);
|
||||
} else {
|
||||
return {
|
||||
success: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function markRead(chatId: string): Promise<Chat | undefined> {
|
||||
if (online) {
|
||||
await waha.readChat(chatId);
|
||||
}
|
||||
|
||||
const chat = await loadChat(chatId);
|
||||
if (chat) {
|
||||
chat.unreadCount = 0;
|
||||
// Note: upsertMessages was called with [chat] in JS, but chat is a Chat object, not Message.
|
||||
// Keeping JS behavior but chat is Chat type here.
|
||||
await upsertChats([chat]);
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
124
web/src/types.ts
Normal file
124
web/src/types.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
/** Represents a chat entry in the sidebar */
|
||||
export interface Chat {
|
||||
id: string;
|
||||
name: string;
|
||||
lastMessage: string;
|
||||
timestamp: number | string | Date;
|
||||
unreadCount: number;
|
||||
}
|
||||
|
||||
/** Raw chat object returned from the WAHA API */
|
||||
export interface WahaChat {
|
||||
id: string | { _serialized?: string; user?: string };
|
||||
chatId?: string;
|
||||
name?: string;
|
||||
unreadCount?: number;
|
||||
lastMessage?: {
|
||||
body?: string;
|
||||
timestamp?: number | string;
|
||||
};
|
||||
lastMessageText?: string;
|
||||
}
|
||||
|
||||
/** Message data sub-object (_data field) */
|
||||
export interface MessageData {
|
||||
notifyName?: string;
|
||||
mimetype?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Media attachment info */
|
||||
export interface MediaInfo {
|
||||
url: string;
|
||||
filename?: string;
|
||||
}
|
||||
|
||||
/** A WhatsApp message */
|
||||
export interface Message {
|
||||
_data?: MessageData;
|
||||
_serialized?: string | { _serialized?: string; user?: string };
|
||||
id: string | { _serialized?: string; user?: string };
|
||||
body?: string;
|
||||
text?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
fromMe?: boolean;
|
||||
sender?: string;
|
||||
timestamp: number | string;
|
||||
status?: string;
|
||||
ack?: number;
|
||||
hasMedia?: boolean;
|
||||
media?: MediaInfo;
|
||||
chatId?: string;
|
||||
chat?: { id: string };
|
||||
participant?: string;
|
||||
}
|
||||
|
||||
/** Temporary message used for optimistic UI updates */
|
||||
export interface TempMessage extends Message {
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** File-sending temporary message */
|
||||
export interface TempFileMessage extends TempMessage {
|
||||
_data: MessageData;
|
||||
hasMedia: true;
|
||||
media: MediaInfo;
|
||||
}
|
||||
|
||||
/** WAHA version response */
|
||||
export interface VersionResponse {
|
||||
version?: string;
|
||||
}
|
||||
|
||||
/** WAHA user info (getMyInfo) */
|
||||
export interface AppUser {
|
||||
id: string;
|
||||
pushName?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/** WAHA contact info */
|
||||
export interface ContactInfo {
|
||||
number: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** WAHA user about response */
|
||||
export interface UserAboutResponse {
|
||||
about?: string;
|
||||
}
|
||||
|
||||
/** Chat picture response */
|
||||
export interface ChatPictureResponse {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
/** Status update response */
|
||||
export interface StatusResponse {
|
||||
success?: boolean;
|
||||
}
|
||||
|
||||
/** WebSocket event payload envelope */
|
||||
export interface WebSocketEvent {
|
||||
event: string;
|
||||
payload: Message;
|
||||
}
|
||||
|
||||
/** IndexedDB stored media record */
|
||||
export interface StoredMedia {
|
||||
reqId: string;
|
||||
blob: Blob;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
/** Downloaded media result */
|
||||
export interface DownloadedMedia {
|
||||
blob: Blob;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
/** Message with _time field used during ordering compensation */
|
||||
export interface MessageWithTime extends Message {
|
||||
_time: number;
|
||||
}
|
||||
439
web/src/ui.ts
Normal file
439
web/src/ui.ts
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
import { formatTime, normalizeId } from "./utils";
|
||||
import { getChatPicture, getMessage, getMedia, getMoreChatMessages } from "./storage";
|
||||
import { getCurrentChat } from "./app";
|
||||
import type { Chat, Message } from "./types";
|
||||
|
||||
export const elements = {
|
||||
chatList: document.getElementById('chat-list') as HTMLUListElement,
|
||||
chatsLoader: document.getElementById('chats-loader') as HTMLDivElement,
|
||||
chatSearch: document.getElementById('chat-search') as HTMLInputElement,
|
||||
backendStatusText: document.getElementById('backend-status-text') as HTMLSpanElement,
|
||||
apiStatusIndicator: document.querySelector('.pulse-dot') as HTMLSpanElement,
|
||||
noChatState: document.getElementById('no-chat-state') as HTMLDivElement,
|
||||
activeChatContainer: document.getElementById('active-chat-container') as HTMLDivElement,
|
||||
activeChatName: document.getElementById('active-chat-name') as HTMLHeadingElement,
|
||||
activeChatAvatar: document.getElementById('active-chat-avatar') as HTMLDivElement,
|
||||
messagesContainer: document.getElementById('messages-container') as HTMLDivElement,
|
||||
messageForm: document.getElementById('message-form') as HTMLFormElement,
|
||||
messageInput: document.getElementById('message-input') as HTMLInputElement,
|
||||
backToSidebarBtn: document.querySelector('.chat-header') as HTMLElement,
|
||||
sidebar: document.querySelector('.sidebar') as HTMLElement,
|
||||
appContainer: document.querySelector('.app-container') as HTMLElement,
|
||||
settingsModal: document.getElementById('settings-page') as HTMLElement,
|
||||
settingsIconBtn: document.getElementById('settings-sidebar-btn') as HTMLButtonElement,
|
||||
saveSettingsBtn: document.getElementById('save-settings') as HTMLButtonElement,
|
||||
inputWahaUrl: document.getElementById('settings-waha-url') as HTMLInputElement,
|
||||
inputSession: document.getElementById('settings-session') as HTMLInputElement,
|
||||
inputApiKey: document.getElementById('settings-api-key') as HTMLInputElement,
|
||||
inputBackgroundImage: document.getElementById('settings-background-image') as HTMLInputElement,
|
||||
inputBackgroundOpacity: document.getElementById('settings-background-opacity') as HTMLInputElement,
|
||||
loggedUserName: document.getElementById('pandora-username') as HTMLHeadingElement,
|
||||
chatBottomBar: document.getElementById('chat-bottom-bar') as HTMLElement,
|
||||
chatBottomBarBtn: document.getElementById('chat-bottom-bar-btn') as HTMLButtonElement,
|
||||
chatInputPanel: document.getElementById('chat-input-panel') as HTMLElement,
|
||||
attachmentInput: document.getElementById('attachment-input') as HTMLInputElement,
|
||||
attachmentBtn: document.getElementById('attachment-btn') as HTMLButtonElement,
|
||||
markreadBtn: document.getElementById('markread-btn') as HTMLButtonElement,
|
||||
extraPages: document.querySelectorAll('.extra-page') as NodeListOf<HTMLElement>,
|
||||
desktopSidebarButtons: document.querySelectorAll("#desktop-aside button") as NodeListOf<HTMLButtonElement>,
|
||||
contentUserName: document.querySelectorAll('[data-content="app-user"]') as NodeListOf<HTMLElement>,
|
||||
contentUserNumber: document.querySelectorAll('[data-content="app-user-number"]') as NodeListOf<HTMLElement>,
|
||||
resourceUserPic: document.querySelectorAll('[data-resource="app-user-image"]') as NodeListOf<HTMLImageElement>,
|
||||
valueUserStatus: document.querySelectorAll('[data-value="app-user-status"]') as NodeListOf<HTMLInputElement>,
|
||||
inputUserStatus: document.getElementById('profile-page-status-input') as HTMLInputElement,
|
||||
selectable: document.querySelectorAll('.selectable') as NodeListOf<HTMLElement>,
|
||||
};
|
||||
|
||||
export const ui = {
|
||||
showExtraPage(pageId: string) {
|
||||
elements.extraPages.forEach(page => {
|
||||
if (page.id != pageId) {
|
||||
page.style.display = "none";
|
||||
} else {
|
||||
page.style.display = "flex";
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* Switch view state when a contact chat is opened or closed
|
||||
*/
|
||||
toggleChatState(hasActive: boolean) {
|
||||
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: boolean, text: string) {
|
||||
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: Chat[], activeChat: Chat | null, onChatSelect: (chat: Chat) => void) {
|
||||
elements.chatList.innerHTML = '';
|
||||
chats.sort((a, b) => {
|
||||
const timeA = new Date(a.timestamp).getTime();
|
||||
const timeB = new Date(b.timestamp).getTime();
|
||||
return timeB - timeA;
|
||||
});
|
||||
|
||||
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 selectable ${activeChat && activeChat.id === chat.id ? 'active' : ''}`;
|
||||
li.dataset.id = 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=""
|
||||
alt="${initials}"
|
||||
data-chat-avatar="${chat.id}"
|
||||
/>
|
||||
</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" data-chatid="${chat.id}">
|
||||
${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 () => {
|
||||
try {
|
||||
const picture = await getChatPicture(chat.id);
|
||||
const img = li.querySelector(`img[data-chat-avatar="${chat.id}"]`) as HTMLImageElement;
|
||||
if (img) img.src = picture.url ? picture.url : '';
|
||||
} catch (e) {
|
||||
}
|
||||
})();
|
||||
}
|
||||
},
|
||||
|
||||
async updateChatInChatList(msg: Message) {
|
||||
const chatNode = document.querySelector(`.chat-item[data-id="${msg.fromMe ? msg.to : msg.from}"]`) as HTMLElement;
|
||||
|
||||
if (chatNode) {
|
||||
const messageItem = chatNode.querySelector('.chat-item-msg') as HTMLElement;
|
||||
const time = chatNode.querySelector('.chat-item-time') as HTMLElement;
|
||||
messageItem.innerText = msg.body || msg.text || 'Media message';
|
||||
time.innerText = msg.timestamp ? formatTime(msg.timestamp) : formatTime(Date.now());
|
||||
|
||||
const activeChatState = getCurrentChat();
|
||||
|
||||
if (!msg.fromMe && (!activeChatState || activeChatState.id !== (msg.fromMe ? msg.to : msg.from))) {
|
||||
const unreadBadge = chatNode.querySelector('.unread-badge') as HTMLElement;
|
||||
if (unreadBadge) {
|
||||
unreadBadge.innerText = (Number(unreadBadge.innerHTML) || 0) + 1 + "";
|
||||
} else {
|
||||
const preview = chatNode.querySelector('.chat-item-preview') as HTMLElement;
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'unread-badge';
|
||||
badge.innerText = '1';
|
||||
preview.appendChild(badge);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async updateChatInChatList2(chat: Chat) {
|
||||
const chatNode = document.querySelector(`.chat-item[data-id="${chat.id}"]`) as HTMLElement;
|
||||
|
||||
if (chatNode) {
|
||||
const messageItem = chatNode.querySelector('.chat-item-msg') as HTMLElement;
|
||||
const time = chatNode.querySelector('.chat-item-time') as HTMLElement;
|
||||
messageItem.innerText = chat.lastMessage || 'Media message';
|
||||
time.innerText = chat.timestamp ? formatTime(chat.timestamp) : formatTime(Date.now());
|
||||
const unreadBadge = chatNode.querySelector('.unread-badge') as HTMLElement;
|
||||
const newCount = (Number(unreadBadge?.innerHTML) || 0);
|
||||
if (unreadBadge && newCount != 0) {
|
||||
unreadBadge.innerText = newCount + "";
|
||||
} else {
|
||||
if (unreadBadge) unreadBadge.remove();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Render chat message log inside chat view container
|
||||
*/
|
||||
async renderMessages(messages: Message[], _activeChatName: string, userID: string, chatId: string) {
|
||||
elements.messagesContainer.innerHTML = '';
|
||||
|
||||
if (messages.length === 0) {
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">No messages. Say hello!</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const loadMore = document.createElement("button");
|
||||
loadMore.classList.add("load-more-btn");
|
||||
loadMore.innerText = "Load more";
|
||||
loadMore.onclick = () => {
|
||||
this.loadMoreMessages(chatId, userID);
|
||||
};
|
||||
elements.messagesContainer.appendChild(loadMore);
|
||||
|
||||
for (const msg of messages) {
|
||||
this.appendSingleMessage(msg, userID, chatId);
|
||||
}
|
||||
|
||||
this.scrollToBottom();
|
||||
},
|
||||
|
||||
async loadMoreMessages(chatId: string, userId: string) {
|
||||
const oldest = document.querySelector('.message-group:first-of-type') as HTMLElement;
|
||||
if (!oldest) return;
|
||||
const oldestTimestamp = oldest.dataset.timestamp;
|
||||
const oldestId = oldest.id;
|
||||
|
||||
const loadMoreButton = document.querySelector('.load-more-btn') as HTMLButtonElement;
|
||||
|
||||
const msgs = await getMoreChatMessages(chatId, oldestTimestamp, oldestId);
|
||||
// JS version had msgs.shift(), probably to avoid duplication of the oldest message
|
||||
msgs.shift();
|
||||
|
||||
msgs.forEach(async msg => {
|
||||
loadMoreButton.after(this.generateMessage(msg, userId, chatId));
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Append a single message (used for optimistic updates immediately upon sending)
|
||||
*/
|
||||
appendSingleMessage(msg: Message, userID: string, chatId: string, isLocal: boolean = false) {
|
||||
elements.messagesContainer.appendChild(this.generateMessage(msg, userID, chatId, isLocal))
|
||||
},
|
||||
|
||||
generateTempMessageLink(msg: Message) {
|
||||
const a = document.createElement('a');
|
||||
a.target = "_blank";
|
||||
if (msg.media) {
|
||||
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 || "file";
|
||||
}
|
||||
}
|
||||
|
||||
return a;
|
||||
},
|
||||
|
||||
generateMessage(msg: Message, userID: string, chatId: string, isLocal: boolean = false) {
|
||||
const isOutgoing = msg.fromMe || msg.sender === 'me';
|
||||
|
||||
function getPrevMessageElem() {
|
||||
return elements.messagesContainer.lastElementChild as HTMLElement | null;
|
||||
}
|
||||
|
||||
const prevMsgEl = getPrevMessageElem();
|
||||
|
||||
const groupDiv = document.createElement('div');
|
||||
groupDiv.className = `message-group selectable ${isOutgoing ? 'outgoing' : 'incoming'}`;
|
||||
groupDiv.id = normalizeId(msg._serialized ? (msg._serialized as any) : msg.id) || "msg-id";
|
||||
groupDiv.dataset.timestamp = msg.timestamp?.toString();
|
||||
groupDiv.dataset.from = msg.participant || (msg.from as string);
|
||||
|
||||
const senderName = isOutgoing ? userID : (msg._data?.notifyName || (msg.from as string));
|
||||
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: string | undefined;
|
||||
|
||||
if (msg.participant) {
|
||||
prevUid = msg.participant;
|
||||
} else {
|
||||
prevUid = msg.from as string;
|
||||
}
|
||||
|
||||
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: HTMLAnchorElement;
|
||||
|
||||
if (isLocal) {
|
||||
a = this.generateTempMessageLink(msg);
|
||||
} else {
|
||||
a = document.createElement('a');
|
||||
a.innerText = `[Request media]`;
|
||||
a.target = "_blank";
|
||||
|
||||
const clickListener = async (e: MouseEvent) => {
|
||||
a.removeEventListener('click', clickListener);
|
||||
a.innerText = `[Downloading]`;
|
||||
const mediaMsg = msg.media ? msg : await getMessage(chatId, normalizeId(msg._serialized ? (msg._serialized as any) : msg.id) || "", true);
|
||||
if (!mediaMsg || !mediaMsg?.media?.url) {
|
||||
a.addEventListener('click', clickListener);
|
||||
a.innerText = `[Error, click to try again]`
|
||||
return;
|
||||
}
|
||||
const url = new URL(mediaMsg.media.url);
|
||||
const reqID = url.pathname.split('/').filter(Boolean).pop();
|
||||
|
||||
if (!reqID) return;
|
||||
const media = await getMedia(reqID);
|
||||
if (!media) return;
|
||||
|
||||
const objectUrl = URL.createObjectURL(media.blob);
|
||||
(e.target as HTMLAnchorElement).href = objectUrl;
|
||||
|
||||
if (media.blob.type.startsWith('image/')) {
|
||||
a.textContent = "";
|
||||
const img = document.createElement('img');
|
||||
img.classList.add('message-image-attachement');
|
||||
img.src = objectUrl;
|
||||
bubble.after(img);
|
||||
const content = bubble.querySelector('.message-content');
|
||||
if (content) content.remove();
|
||||
} else {
|
||||
(e.target as HTMLAnchorElement).textContent = media.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')) {
|
||||
groupDiv.classList.add('same-sender');
|
||||
} else {
|
||||
const indicator = document.createElement('div');
|
||||
indicator.className = 'message-indicator';
|
||||
groupDiv.appendChild(indicator);
|
||||
}
|
||||
} else if (msg.participant) {
|
||||
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
|
||||
const indicator = document.createElement('div');
|
||||
indicator.className = 'message-indicator';
|
||||
groupDiv.appendChild(indicator);
|
||||
} else groupDiv.classList.add('same-sender');
|
||||
} else {
|
||||
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
|
||||
const indicator = document.createElement('div');
|
||||
indicator.className = 'message-indicator';
|
||||
groupDiv.appendChild(indicator);
|
||||
} else groupDiv.classList.add('same-sender');
|
||||
}
|
||||
|
||||
groupDiv.appendChild(bubble);
|
||||
return groupDiv;
|
||||
},
|
||||
|
||||
updateMessage(originalMsgId: string, generatedMsg: HTMLElement) {
|
||||
const originalMsg = document.querySelector(`#${originalMsgId}`);
|
||||
if (originalMsg) {
|
||||
originalMsg.replaceWith(generatedMsg)
|
||||
}
|
||||
},
|
||||
|
||||
updateMessageTick(id: string, status: string) {
|
||||
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>';
|
||||
}
|
||||
|
||||
const msgNode = document.getElementById(id);
|
||||
if (msgNode) {
|
||||
const meta = msgNode.querySelector('.message-meta');
|
||||
if (meta) meta.outerHTML = statusCheck;
|
||||
}
|
||||
},
|
||||
|
||||
toggleChatBottomBar() {
|
||||
elements.chatBottomBar.classList.toggle("collapsed");
|
||||
},
|
||||
|
||||
removeChatMessage(msgId: string) {
|
||||
const message = document.getElementById(msgId);
|
||||
if (message) message.remove();
|
||||
}
|
||||
};
|
||||
121
web/src/utils.ts
Normal file
121
web/src/utils.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import type { Message, MessageWithTime } from "./types";
|
||||
|
||||
/**
|
||||
* 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: string | number | Date): string {
|
||||
if (!dateVal) return '';
|
||||
let date: 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();
|
||||
const minutes = date.getMinutes();
|
||||
const ampm = hours >= 12 ? 'PM' : 'AM';
|
||||
hours = hours % 12;
|
||||
hours = hours ? hours : 12;
|
||||
const minutesStr = minutes < 10 ? '0' + minutes : String(minutes);
|
||||
return `${hours}:${minutesStr} ${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: Message[]): Message[] {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
|
||||
// convert to ms
|
||||
const msgs: MessageWithTime[] = messages.map(m => {
|
||||
let t: number;
|
||||
if (typeof m.timestamp === 'number') {
|
||||
t = m.timestamp < 10000000000 ? m.timestamp * 1000 : m.timestamp;
|
||||
} else {
|
||||
t = new Date(m.timestamp).getTime();
|
||||
}
|
||||
return { ...m, _time: t };
|
||||
});
|
||||
|
||||
msgs.sort((a, b) => a._time - b._time);
|
||||
|
||||
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 outgoing message is sorted before incoming message within 30-sec window
|
||||
if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) {
|
||||
msgs[i] = next;
|
||||
msgs[i + 1] = current;
|
||||
|
||||
// advance the outgoing message timestamp to exactly 1 sec after the incoming
|
||||
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 temp property
|
||||
return msgs.map(({ _time, ...m }) => m);
|
||||
}
|
||||
|
||||
export function getBase64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
resolve((reader.result as string).split(",")[1]);
|
||||
};
|
||||
|
||||
reader.onerror = (e) => {
|
||||
console.error("Error", e);
|
||||
reject(e);
|
||||
};
|
||||
|
||||
reader.onabort = () => {
|
||||
reject(new Error("Aborted"));
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a WhatsApp ID (chatId, messageId, etc.) to its string representation
|
||||
* @param {string|object} raw
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function normalizeId(raw: string | { _serialized?: string; user?: string } | null | undefined): string | null {
|
||||
if (!raw) return null;
|
||||
if (typeof raw === 'object') {
|
||||
return raw._serialized || raw.user || JSON.stringify(raw);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function debounce(func: () => void, delay: number): () => void {
|
||||
let timeoutId: ReturnType<typeof setTimeout>;
|
||||
return function() {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(func, delay);
|
||||
};
|
||||
}
|
||||
184
web/src/waha.ts
Normal file
184
web/src/waha.ts
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
import { config } from "./config";
|
||||
import { showNotification } from "./notification";
|
||||
import { getBase64 } from "./utils";
|
||||
import type { Message, VersionResponse, AppUser, ContactInfo, UserAboutResponse, ChatPictureResponse, StatusResponse } from "./types";
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const url = `${config.wahaUrl}${path}`;
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': '*/*',
|
||||
...(options.headers as Record<string, string>)
|
||||
};
|
||||
if (config.apiKey) {
|
||||
headers['X-Api-Key'] = config.apiKey;
|
||||
}
|
||||
|
||||
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(() => '');
|
||||
}
|
||||
|
||||
showNotification("API Error", `WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`, 4000);
|
||||
throw new Error(`WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function downloadFile(path: string, options: RequestInit = {}): Promise<{ blob: Blob, filename: string }> {
|
||||
const url = `${config.wahaUrl}${path}`;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': (options.headers as Record<string, string> | undefined)?.['Content-Type'] ?? 'application/json',
|
||||
'accept': '*/*',
|
||||
...(options.headers as Record<string, string>)
|
||||
};
|
||||
|
||||
if (config.apiKey) headers['X-Api-Key'] = config.apiKey;
|
||||
|
||||
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(): Promise<VersionResponse> {
|
||||
return await request<VersionResponse>('/api/version');
|
||||
},
|
||||
|
||||
async getChats(): Promise<any[]> {
|
||||
const data = await request<any[]>(`/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: string, beforeTimestamp?: any): Promise<Message[]> {
|
||||
return request<Message[]>(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40${beforeTimestamp ? `&filter.timestamp.lte=${beforeTimestamp}` : "" }`);
|
||||
},
|
||||
|
||||
async getSingleChatMessage(chatId: string, messageId: string, downloadMedia: boolean): Promise<Message> {
|
||||
return request<Message>(`/api/${config.session}/chats/${chatId}/messages/${messageId}?downloadMedia=${downloadMedia}`);
|
||||
},
|
||||
|
||||
async getChatPicture(chatId: string): Promise<ChatPictureResponse> {
|
||||
return request<ChatPictureResponse>(`/api/${config.session}/chats/${chatId}/picture`);
|
||||
},
|
||||
|
||||
async getUser(chatId: string): Promise<ContactInfo> {
|
||||
return request<ContactInfo>(`/api/${config.session}/contacts/${chatId}`);
|
||||
},
|
||||
|
||||
async getUserAbout(chatId: string): Promise<UserAboutResponse> {
|
||||
return request<UserAboutResponse>(`/api/contacts/about?contactId=${chatId}&session=${config.session}`);
|
||||
},
|
||||
|
||||
async readChat(chatId: string): Promise<any> {
|
||||
return request('/api/sendSeen', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async downloadMedia(file: string): Promise<{ blob: Blob, filename: string }> {
|
||||
const { blob, filename } = await downloadFile(`/api/files/${config.session}/${file}`);
|
||||
return { blob, filename };
|
||||
},
|
||||
|
||||
async getMyInfo(): Promise<AppUser> {
|
||||
return request<AppUser>(`/api/sessions/${config.session}/me`);
|
||||
},
|
||||
|
||||
async startTyping(chatId: string): Promise<any> {
|
||||
return request('/api/startTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async stopTyping(chatId: string): Promise<any> {
|
||||
return request('/api/stopTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async sendTextMessage(chatId: string, text: string): Promise<Message> {
|
||||
return request<Message>('/api/sendText', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
chatId,
|
||||
text,
|
||||
session: config.session
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async setStatus(text: string): Promise<StatusResponse> {
|
||||
return request<StatusResponse>(`/api/${config.session}/profile/status`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
status: text
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async sendFileMessage(chatId: string, file: File): Promise<Message> {
|
||||
const fileBase64 = await getBase64(file);
|
||||
const body: RequestInit = {
|
||||
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<Message>(endpoint, body);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
100
web/src/websocket.ts
Normal file
100
web/src/websocket.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { config } from "./config";
|
||||
import { isOnline, updateOnlineStatus } from "./storage";
|
||||
import type { WebSocketEvent } from "./types";
|
||||
|
||||
let socket: WebSocket | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let currentOnMessageCallback: ((data: WebSocketEvent) => void) | null = null;
|
||||
|
||||
export const websocket = {
|
||||
connect(onMessageCallback: (data: WebSocketEvent) => void) {
|
||||
if (!isOnline()) return;
|
||||
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.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) as WebSocketEvent;
|
||||
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(() => {
|
||||
updateOnlineStatus().then(() => {
|
||||
if (currentOnMessageCallback) {
|
||||
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');
|
||||
}
|
||||
}
|
||||
};
|
||||
1100
web/style.css
Normal file
1100
web/style.css
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue