Spaces:
Running on Zero
Running on Zero
Upload 9 files
Browse files- static/js/api.js +37 -0
- static/js/chat.js +884 -0
- static/js/chatlist.js +217 -0
- static/js/composer.js +238 -0
- static/js/ripple.js +59 -0
- static/js/sidebar.js +13 -0
- static/js/state.js +55 -0
- static/js/translations.js +190 -0
- static/js/ws.js +107 -0
static/js/api.js
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
async function apiFetch(ep, opts = {}) {
|
| 2 |
+
opts.headers = opts.headers || {};
|
| 3 |
+
opts.headers["Authorization"] = PASS;
|
| 4 |
+
try {
|
| 5 |
+
const r = await fetch(ep, opts);
|
| 6 |
+
if (r.status === 401) {
|
| 7 |
+
// session revoked/expired (e.g. the account was suspended or its
|
| 8 |
+
// password was reset while logged in) — back to the login screen
|
| 9 |
+
if (PASS) { localStorage.removeItem("TG_PASS"); localStorage.removeItem("TG_IS_OWNER"); PASS = ""; location.reload(); }
|
| 10 |
+
return { error: true };
|
| 11 |
+
}
|
| 12 |
+
return await r.json();
|
| 13 |
+
} catch (e) {
|
| 14 |
+
return null;
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// Polling fetch: remembers each URL's ETag and answers {notModified:true} on
|
| 19 |
+
// a 304, so an unchanged chat/list costs no download, parse or diff.
|
| 20 |
+
const _etags = {};
|
| 21 |
+
async function apiFetchCond(ep) {
|
| 22 |
+
const headers = { Authorization: PASS };
|
| 23 |
+
if (_etags[ep]) headers["If-None-Match"] = _etags[ep];
|
| 24 |
+
try {
|
| 25 |
+
const r = await fetch(ep, { headers });
|
| 26 |
+
if (r.status === 304) return { notModified: true };
|
| 27 |
+
if (r.status === 401) {
|
| 28 |
+
if (PASS) { localStorage.removeItem("TG_PASS"); localStorage.removeItem("TG_IS_OWNER"); PASS = ""; location.reload(); }
|
| 29 |
+
return { error: true };
|
| 30 |
+
}
|
| 31 |
+
const et = r.headers.get("ETag");
|
| 32 |
+
if (et) _etags[ep] = et; else delete _etags[ep];
|
| 33 |
+
return await r.json();
|
| 34 |
+
} catch (e) {
|
| 35 |
+
return null;
|
| 36 |
+
}
|
| 37 |
+
}
|
static/js/chat.js
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function murl(fid) { return `/api/media?file_id=${encodeURIComponent(fid)}&auth=${encodeURIComponent(PASS)}`; }
|
| 2 |
+
|
| 3 |
+
function fmtTime(sec) {
|
| 4 |
+
if (!isFinite(sec) || sec < 0) sec = 0;
|
| 5 |
+
const m = Math.floor(sec / 60), s = Math.floor(sec % 60);
|
| 6 |
+
return m + ':' + String(s).padStart(2, '0');
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
// A custom, glass-styled player shared by voice messages and videos —
|
| 10 |
+
// replaces the native <audio controls>/<video controls> widgets, which
|
| 11 |
+
// render as a plain OS-themed bar that clashes with the rest of the UI.
|
| 12 |
+
function mkPlayer(fileId, kind) {
|
| 13 |
+
const el = document.createElement(kind === 'video' ? 'video' : 'audio');
|
| 14 |
+
el.src = murl(fileId);
|
| 15 |
+
el.preload = 'none'; // don't hit the network for every voice/video row just to learn its length
|
| 16 |
+
if (kind === 'video') el.playsInline = true;
|
| 17 |
+
|
| 18 |
+
const wrap = document.createElement('div'); wrap.className = 'mp mp-' + kind;
|
| 19 |
+
const playBtn = document.createElement('button'); playBtn.type = 'button'; playBtn.className = 'mp-play';
|
| 20 |
+
playBtn.innerHTML = '<i class="bi bi-play-fill"></i>';
|
| 21 |
+
|
| 22 |
+
const bar = document.createElement('div'); bar.className = 'mp-bar';
|
| 23 |
+
const barFill = document.createElement('div'); barFill.className = 'mp-bar-fill';
|
| 24 |
+
bar.appendChild(barFill);
|
| 25 |
+
|
| 26 |
+
const time = document.createElement('span'); time.className = 'mp-time'; time.textContent = '0:00';
|
| 27 |
+
const dl = document.createElement('button'); dl.type = 'button'; dl.className = 'mp-dl'; dl.title = 'دانلود';
|
| 28 |
+
dl.innerHTML = '<i class="bi bi-download"></i>';
|
| 29 |
+
dl.onclick = e => { e.stopPropagation(); downloadFile(fileId, kind + (kind === 'video' ? '.mp4' : '.ogg')); };
|
| 30 |
+
|
| 31 |
+
const toggle = () => { if (el.paused) el.play(); else el.pause(); };
|
| 32 |
+
playBtn.onclick = toggle;
|
| 33 |
+
el.addEventListener('play', () => playBtn.innerHTML = '<i class="bi bi-pause-fill"></i>');
|
| 34 |
+
el.addEventListener('pause', () => playBtn.innerHTML = '<i class="bi bi-play-fill"></i>');
|
| 35 |
+
el.addEventListener('timeupdate', () => {
|
| 36 |
+
const pct = el.duration ? (el.currentTime / el.duration) * 100 : 0;
|
| 37 |
+
barFill.style.width = pct + '%';
|
| 38 |
+
time.textContent = fmtTime(el.duration ? el.duration - el.currentTime : el.currentTime);
|
| 39 |
+
});
|
| 40 |
+
el.addEventListener('loadedmetadata', () => { time.textContent = fmtTime(el.duration); });
|
| 41 |
+
el.addEventListener('ended', () => { playBtn.innerHTML = '<i class="bi bi-play-fill"></i>'; });
|
| 42 |
+
bar.addEventListener('click', e => {
|
| 43 |
+
const r = bar.getBoundingClientRect();
|
| 44 |
+
const ratio = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
|
| 45 |
+
if (el.duration) el.currentTime = ratio * el.duration;
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
if (kind === 'voice') {
|
| 49 |
+
wrap.append(playBtn, bar, time, dl);
|
| 50 |
+
wrap.appendChild(el);
|
| 51 |
+
} else {
|
| 52 |
+
// video: the <video> itself (no native controls) sits above a
|
| 53 |
+
// custom control strip; a big center play icon shows while paused.
|
| 54 |
+
const frame = document.createElement('div'); frame.className = 'mp-video-frame';
|
| 55 |
+
const centerPlay = document.createElement('div'); centerPlay.className = 'mp-center-play';
|
| 56 |
+
centerPlay.innerHTML = '<i class="bi bi-play-fill"></i>';
|
| 57 |
+
centerPlay.onclick = toggle;
|
| 58 |
+
el.addEventListener('play', () => centerPlay.classList.add('d-none'));
|
| 59 |
+
el.addEventListener('pause', () => centerPlay.classList.remove('d-none'));
|
| 60 |
+
frame.append(el, centerPlay);
|
| 61 |
+
const strip = document.createElement('div'); strip.className = 'mp-strip';
|
| 62 |
+
strip.append(playBtn, bar, time, dl);
|
| 63 |
+
wrap.append(frame, strip);
|
| 64 |
+
}
|
| 65 |
+
return wrap;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// Stickers can be static WEBP/PNG, animated TGS (gzip-compressed Lottie
|
| 69 |
+
// JSON), or video WEBM — and a plain <img src> with an onerror fallback
|
| 70 |
+
// turned out not to reliably detect "this isn't a static image" for all
|
| 71 |
+
// of those. This fetches the raw bytes up front and sniffs the actual
|
| 72 |
+
// file signature instead, so which renderer to use is a direct decision,
|
| 73 |
+
// not something inferred from whether/when <img> happens to fail.
|
| 74 |
+
async function renderSticker(container, fileId, fallbackEmoji) {
|
| 75 |
+
container.innerHTML = '<div class="sticker-fallback"><div class="spinner-border spinner-border-sm" style="color:var(--md-sys-color-primary)"></div></div>';
|
| 76 |
+
try {
|
| 77 |
+
const res = await fetch(murl(fileId));
|
| 78 |
+
if (!res.ok) throw new Error('fetch failed: ' + res.status);
|
| 79 |
+
const buf = await res.arrayBuffer();
|
| 80 |
+
const b = new Uint8Array(buf);
|
| 81 |
+
container.innerHTML = '';
|
| 82 |
+
|
| 83 |
+
if (b[0] === 0x1f && b[1] === 0x8b) { // gzip → .tgs (Lottie JSON)
|
| 84 |
+
if (typeof pako === 'undefined' || typeof lottie === 'undefined') throw new Error('lottie libs not loaded');
|
| 85 |
+
const animationData = JSON.parse(pako.inflate(b, { to: 'string' }));
|
| 86 |
+
lottie.loadAnimation({ container, renderer: 'svg', loop: true, autoplay: true, animationData });
|
| 87 |
+
return;
|
| 88 |
+
}
|
| 89 |
+
const isWebp = b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46; // "RIFF"
|
| 90 |
+
const isPng = b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47; // \x89PNG
|
| 91 |
+
if (isWebp || isPng) {
|
| 92 |
+
const img = document.createElement('img');
|
| 93 |
+
img.src = URL.createObjectURL(new Blob([b], { type: isWebp ? 'image/webp' : 'image/png' }));
|
| 94 |
+
container.appendChild(img);
|
| 95 |
+
return;
|
| 96 |
+
}
|
| 97 |
+
if (b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) { // EBML → .webm video sticker
|
| 98 |
+
const v = document.createElement('video');
|
| 99 |
+
v.src = URL.createObjectURL(new Blob([b], { type: 'video/webm' }));
|
| 100 |
+
v.autoplay = true; v.loop = true; v.muted = true; v.playsInline = true;
|
| 101 |
+
container.appendChild(v);
|
| 102 |
+
return;
|
| 103 |
+
}
|
| 104 |
+
throw new Error('unrecognized sticker format');
|
| 105 |
+
} catch (e) {
|
| 106 |
+
container.innerHTML = '<div class="sticker-fallback"><span class="emo">' + (fallbackEmoji || '🎭') + '</span><span class="lbl">نمایش این استیکر پشتیبانی نمیشود</span></div>';
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// Runs `fn` when `el` first comes within ~200px of the viewport (immediately
|
| 111 |
+
// if IntersectionObserver is missing). Stickers/GIFs below the fold cost nothing.
|
| 112 |
+
const _lazyIO = ('IntersectionObserver' in window) ? new IntersectionObserver(entries => {
|
| 113 |
+
entries.forEach(en => {
|
| 114 |
+
if (!en.isIntersecting) return;
|
| 115 |
+
_lazyIO.unobserve(en.target);
|
| 116 |
+
const fn = en.target._lazy; en.target._lazy = null; if (fn) fn();
|
| 117 |
+
});
|
| 118 |
+
}, { rootMargin: '200px' }) : null;
|
| 119 |
+
function lazyRender(el, fn) { if (!_lazyIO) { fn(); return; } el._lazy = fn; _lazyIO.observe(el); }
|
| 120 |
+
|
| 121 |
+
function mkMedia(m) {
|
| 122 |
+
if (!m.type || !m.file_id) return null;
|
| 123 |
+
const w = document.createElement('div');
|
| 124 |
+
if (m.type === 'photo') {
|
| 125 |
+
w.className = 'msg-media';
|
| 126 |
+
const i = document.createElement('img');
|
| 127 |
+
i.loading = 'lazy'; i.decoding = 'async';
|
| 128 |
+
i.src = murl(m.file_id);
|
| 129 |
+
i.onclick = () => viewMedia(m.file_id, 'photo');
|
| 130 |
+
const dlBtn = document.createElement('button'); dlBtn.type = 'button'; dlBtn.className = 'media-dl-overlay';
|
| 131 |
+
dlBtn.innerHTML = '<i class="bi bi-download"></i>';
|
| 132 |
+
dlBtn.onclick = e => { e.stopPropagation(); downloadFile(m.file_id, 'photo.jpg'); };
|
| 133 |
+
w.append(i, dlBtn);
|
| 134 |
+
} else if (m.type === 'video') {
|
| 135 |
+
w.appendChild(mkPlayer(m.file_id, 'video'));
|
| 136 |
+
} else if (m.type === 'voice') {
|
| 137 |
+
w.appendChild(mkPlayer(m.file_id, 'voice'));
|
| 138 |
+
} else if (m.type === 'animation') {
|
| 139 |
+
// Telegram GIFs are actually silent looping MP4s under the Bot API —
|
| 140 |
+
// <video> with autoplay/loop/muted reproduces a real GIF exactly.
|
| 141 |
+
w.className = 'msg-media';
|
| 142 |
+
const v = document.createElement('video');
|
| 143 |
+
v.preload = 'none';
|
| 144 |
+
v.autoplay = true; v.loop = true; v.muted = true; v.playsInline = true;
|
| 145 |
+
w.appendChild(v);
|
| 146 |
+
lazyRender(w, () => { v.src = murl(m.file_id); });
|
| 147 |
+
} else if (m.type === 'sticker') {
|
| 148 |
+
w.className = 'msg-sticker';
|
| 149 |
+
lazyRender(w, () => renderSticker(w, m.file_id, m.text)); // fetch + Lottie only once it is on (or near) screen
|
| 150 |
+
} else if (m.type === 'document') {
|
| 151 |
+
w.className = 'msg-doc';
|
| 152 |
+
const a = document.createElement('a');
|
| 153 |
+
a.href = '#'; a.className = 'text-white text-decoration-none';
|
| 154 |
+
a.innerHTML = '<i class="bi bi-file-earmark-arrow-down"></i> دانلود فایل';
|
| 155 |
+
a.onclick = e => { e.preventDefault(); downloadFile(m.file_id, m.text || 'file'); };
|
| 156 |
+
w.appendChild(a);
|
| 157 |
+
} else return null;
|
| 158 |
+
return w;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// Fetches the file as a blob and triggers a same-page download via a
|
| 162 |
+
// temporary object URL — replaces the old <a href=... target="_blank">,
|
| 163 |
+
// which on an installed PWA navigates the whole app shell to the raw file
|
| 164 |
+
// URL; pressing back afterward then exits the app entirely instead of
|
| 165 |
+
// returning to the chat.
|
| 166 |
+
async function downloadFile(fileId, filename) {
|
| 167 |
+
try {
|
| 168 |
+
const res = await fetch(murl(fileId));
|
| 169 |
+
const blob = await res.blob();
|
| 170 |
+
const url = URL.createObjectURL(blob);
|
| 171 |
+
const a = document.createElement('a');
|
| 172 |
+
a.href = url; a.download = filename || 'file';
|
| 173 |
+
document.body.appendChild(a); a.click(); a.remove();
|
| 174 |
+
setTimeout(() => URL.revokeObjectURL(url), 4000);
|
| 175 |
+
} catch (e) {
|
| 176 |
+
showToast('دانلود فایل با خطا مواجه شد.', 'error');
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
// Same reasoning for photos: window.open(..., '_blank') also kicks the
|
| 181 |
+
// PWA out to the system browser. A lightweight in-app lightbox avoids any
|
| 182 |
+
// navigation at all.
|
| 183 |
+
function viewMedia(fileId, type) {
|
| 184 |
+
const img = document.getElementById('mvImg');
|
| 185 |
+
const vid = document.getElementById('mvVideo');
|
| 186 |
+
if (type === 'video') {
|
| 187 |
+
img.classList.add('d-none'); vid.classList.remove('d-none');
|
| 188 |
+
vid.src = murl(fileId);
|
| 189 |
+
} else {
|
| 190 |
+
vid.classList.add('d-none'); img.classList.remove('d-none');
|
| 191 |
+
img.src = murl(fileId);
|
| 192 |
+
}
|
| 193 |
+
pushUiState({ level: 'overlay', chatId: curChatId || null });
|
| 194 |
+
new bootstrap.Modal(document.getElementById('mediaViewerModal')).show();
|
| 195 |
+
document.getElementById('mediaViewerModal').addEventListener('hidden.bs.modal', () => {
|
| 196 |
+
vid.pause(); vid.src = ''; img.src = '';
|
| 197 |
+
}, { once: true });
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// ---- reactions ----
|
| 201 |
+
// Most-used reactions bubble toward the front of both the quick row and
|
| 202 |
+
// the full grid — tracked locally (localStorage), independent of QUICK_REACT
|
| 203 |
+
// /ALL_REACT's original static order.
|
| 204 |
+
const REACT_FREQ_KEY = 'tg_reaction_freq';
|
| 205 |
+
function getReactFreq() {
|
| 206 |
+
try { return JSON.parse(localStorage.getItem(REACT_FREQ_KEY) || '{}'); } catch (e) { return {}; }
|
| 207 |
+
}
|
| 208 |
+
function bumpReactFreq(em) {
|
| 209 |
+
if (!em) return;
|
| 210 |
+
const f = getReactFreq();
|
| 211 |
+
f[em] = (f[em] || 0) + 1;
|
| 212 |
+
localStorage.setItem(REACT_FREQ_KEY, JSON.stringify(f));
|
| 213 |
+
}
|
| 214 |
+
function sortByFreq(list) {
|
| 215 |
+
const f = getReactFreq();
|
| 216 |
+
return [...list].sort((a, b) => (f[b] || 0) - (f[a] || 0));
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
async function doReact(chatId, msgId, emoji) {
|
| 220 |
+
const res = await apiFetch('/api/react', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chatId, msgId, emoji }) });
|
| 221 |
+
if (res?.error) showToast(res.error, 'error'); else { bumpReactFreq(emoji); fetchHistory(chatId, false); }
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
function mkReactBar(chatId, msgId, mine) {
|
| 225 |
+
const wrap = document.createElement('div'); wrap.className = 'react-bar-wrap';
|
| 226 |
+
const bar = document.createElement('div'); bar.className = 'react-bar';
|
| 227 |
+
|
| 228 |
+
const quick = document.createElement('div'); quick.className = 'react-quick';
|
| 229 |
+
sortByFreq(QUICK_REACT).forEach(em => {
|
| 230 |
+
const s = document.createElement('span'); s.textContent = em;
|
| 231 |
+
if (em === mine) s.classList.add('used');
|
| 232 |
+
s.onclick = e => { e.stopPropagation(); const next = em === mine ? null : em; doReact(chatId, msgId, next); bar.classList.remove('show'); };
|
| 233 |
+
quick.appendChild(s);
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
const exp = document.createElement('div'); exp.className = 'react-expand';
|
| 237 |
+
exp.innerHTML = '<i class="bi bi-chevron-down"></i><span style="font-size:.75rem">همه</span>';
|
| 238 |
+
let gridOpen = false;
|
| 239 |
+
const grid = document.createElement('div'); grid.className = 'react-grid';
|
| 240 |
+
sortByFreq(ALL_REACT).forEach(em => {
|
| 241 |
+
const s = document.createElement('span'); s.textContent = em;
|
| 242 |
+
if (em === mine) s.classList.add('used');
|
| 243 |
+
s.onclick = e => { e.stopPropagation(); const next = em === mine ? null : em; doReact(chatId, msgId, next); bar.classList.remove('show'); };
|
| 244 |
+
grid.appendChild(s);
|
| 245 |
+
});
|
| 246 |
+
exp.onclick = e => { e.stopPropagation(); gridOpen = !gridOpen; grid.classList.toggle('open', gridOpen); exp.querySelector('i').style.transform = gridOpen ? 'rotate(180deg)' : ''; };
|
| 247 |
+
|
| 248 |
+
bar.appendChild(quick); bar.appendChild(exp); bar.appendChild(grid);
|
| 249 |
+
wrap.appendChild(bar);
|
| 250 |
+
applyEmojiImages(bar);
|
| 251 |
+
return { wrap, bar };
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
function mkReactionChips(m, isOut) {
|
| 255 |
+
const chips = [];
|
| 256 |
+
if (m.their_reaction) chips.push({ emoji: m.their_reaction, mine: false, label: 'کاربر' });
|
| 257 |
+
if (m.my_reaction) chips.push({ emoji: m.my_reaction, mine: true, label: 'من' });
|
| 258 |
+
if (!chips.length) return null;
|
| 259 |
+
const row = document.createElement('div'); row.className = 'reaction-row' + (isOut ? ' out' : '');
|
| 260 |
+
chips.forEach(c => {
|
| 261 |
+
const chip = document.createElement('span'); chip.className = 'rchip' + (c.mine ? ' mine' : '');
|
| 262 |
+
chip.innerHTML = c.emoji + ' <span class="rl">' + c.label + '</span>';
|
| 263 |
+
if (c.mine) { chip.title = 'برای حذف کلیک کن'; chip.onclick = () => doReact(curChatId, m.msg_id, null); }
|
| 264 |
+
row.appendChild(chip);
|
| 265 |
+
});
|
| 266 |
+
return row;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
function setReply(msgId, prev) {
|
| 270 |
+
replyTarget = { msgId, prev };
|
| 271 |
+
document.getElementById('rstripTxt').textContent = prev;
|
| 272 |
+
document.getElementById('rstrip').classList.add('show');
|
| 273 |
+
document.getElementById('msgIn').focus();
|
| 274 |
+
}
|
| 275 |
+
function cancelReply() { replyTarget = null; document.getElementById('rstrip').classList.remove('show'); }
|
| 276 |
+
|
| 277 |
+
// ---- topbar + chat selection ----
|
| 278 |
+
async function selChat(id, title, biz) {
|
| 279 |
+
curChatId = id; unreadCnt = 0; lastHistHash = ''; cancelReply(); unreadPer[id] = 0; updGlobalUnread();
|
| 280 |
+
if (window.innerWidth <= 768) document.getElementById('sidebar').classList.add('mh');
|
| 281 |
+
document.getElementById('noChat').classList.add('d-none');
|
| 282 |
+
document.getElementById('chatBox').classList.remove('d-none');
|
| 283 |
+
document.getElementById('chatBox').classList.add('d-flex');
|
| 284 |
+
document.getElementById('hdrTitle').innerText = title || id;
|
| 285 |
+
|
| 286 |
+
const av = document.getElementById('hdrAv');
|
| 287 |
+
av.innerHTML = ''; av.style.background = avGrad(id);
|
| 288 |
+
const img = document.createElement('img');
|
| 289 |
+
img.src = `/api/user-photo?id=${encodeURIComponent(id)}&auth=${encodeURIComponent(PASS)}`;
|
| 290 |
+
img.onerror = () => { av.textContent = title ? title[0].toUpperCase() : '?'; };
|
| 291 |
+
av.appendChild(img);
|
| 292 |
+
document.getElementById('hdrSub').textContent = 'شناسه: ' + id;
|
| 293 |
+
|
| 294 |
+
// resolve real capabilities from the chat-list item (falls back to the
|
| 295 |
+
// `biz` argument for a chat just started this session, not yet polled)
|
| 296 |
+
pushUiState({ level: 'chat', chatId: id });
|
| 297 |
+
|
| 298 |
+
const chatObj = allChats.find(x => x.id === id) || {};
|
| 299 |
+
isGroup = chatObj.is_group || false;
|
| 300 |
+
curBizId = chatObj.business_connection_id || biz || null;
|
| 301 |
+
const hasBiz = !!curBizId;
|
| 302 |
+
const hasBotDirect = chatObj.has_bot_chat !== undefined ? !!chatObj.has_bot_chat : !hasBiz;
|
| 303 |
+
|
| 304 |
+
// show/hide the shield icon that opens the group-info modal (Phase 5:
|
| 305 |
+
// the old separate topbar toolbar is gone — showProfileModal() now
|
| 306 |
+
// renders group info + management when isGroup is true)
|
| 307 |
+
document.getElementById('gmodToggleBtn').style.display = isGroup ? 'flex' : 'none';
|
| 308 |
+
gmodChatId = isGroup ? id : null;
|
| 309 |
+
|
| 310 |
+
// sender selector: only offer a real choice when BOTH "بات" and "من" are
|
| 311 |
+
// actually usable for this chat; otherwise pick the one valid mode
|
| 312 |
+
// silently so a message can never be sent through a channel that has
|
| 313 |
+
// no real conversation behind it (that mismatch is what used to throw
|
| 314 |
+
// Telegram's "can't initiate conversation with a user" error).
|
| 315 |
+
const ss = document.getElementById('senderSelector');
|
| 316 |
+
const rBot = document.querySelector('input[name="sender"][value="bot"]');
|
| 317 |
+
const rMe = document.querySelector('input[name="sender"][value="me"]');
|
| 318 |
+
if (hasBiz && hasBotDirect) { ss.style.display = 'flex'; }
|
| 319 |
+
else if (hasBiz) { ss.style.display = 'none'; if (rMe) rMe.checked = true; }
|
| 320 |
+
else { ss.style.display = 'none'; if (rBot) rBot.checked = true; }
|
| 321 |
+
|
| 322 |
+
lastChatsHash = ''; renderChatList(allChats);
|
| 323 |
+
await fetchHistory(id, false);
|
| 324 |
+
await loadChatSP(id);
|
| 325 |
+
scrollBot(false);
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
// ══════════════════════════════════════════════════════════════
|
| 329 |
+
// Unified back-stack: chat list → chat → profile modal → AI panel
|
| 330 |
+
// (and the context menu, parallel to profile/AI, opened from the chat).
|
| 331 |
+
// One history entry per level, so the device/OS back button, a laptop's
|
| 332 |
+
// mouse back button, and every screen's own back control all go through
|
| 333 |
+
// the SAME popstate path and agree on what "back" means — previously
|
| 334 |
+
// each screen (chat, profile, AI panel) handled "back" independently, so
|
| 335 |
+
// e.g. closing the AI panel never actually returned to the profile modal
|
| 336 |
+
// like it was supposed to.
|
| 337 |
+
// ══════════════════════════════════════════════════════════════
|
| 338 |
+
var isApplyingHistoryState = false;
|
| 339 |
+
|
| 340 |
+
function pushUiState(state) {
|
| 341 |
+
if (isApplyingHistoryState) return;
|
| 342 |
+
if (history.state && history.state.level === state.level && history.state.chatId === state.chatId) return;
|
| 343 |
+
history.pushState(state, '', '#' + state.level);
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// DOM-only — no history side effects — so it's safe to call both when
|
| 347 |
+
// replaying a popstate and as a plain helper elsewhere.
|
| 348 |
+
function backList() {
|
| 349 |
+
document.getElementById('sidebar').classList.remove('mh');
|
| 350 |
+
document.getElementById('chatBox').classList.add('d-none');
|
| 351 |
+
document.getElementById('chatBox').classList.remove('d-flex');
|
| 352 |
+
document.getElementById('noChat').classList.remove('d-none');
|
| 353 |
+
curChatId = null;
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
// Makes the DOM match a given history state exactly: closes every overlay
|
| 357 |
+
// first, then reopens whatever that state calls for. Used both when the
|
| 358 |
+
// user actually navigates back/forward AND internally whenever a screen
|
| 359 |
+
// needs to "go back" itself (it just calls history.back() and lets this
|
| 360 |
+
// function do the actual work when popstate fires).
|
| 361 |
+
function applyUiState(state) {
|
| 362 |
+
isApplyingHistoryState = true;
|
| 363 |
+
document.querySelectorAll('.modal.show').forEach(m => { const inst = bootstrap.Modal.getInstance(m); if (inst) inst.hide(); });
|
| 364 |
+
closeMsgContextMenu();
|
| 365 |
+
const level = state && state.level;
|
| 366 |
+
if (level !== 'settings' && level !== 'settings-sub') {
|
| 367 |
+
document.getElementById('settingsPage').classList.remove('show');
|
| 368 |
+
}
|
| 369 |
+
if (!level) {
|
| 370 |
+
if (curChatId) backList();
|
| 371 |
+
} else if (level === 'chat') {
|
| 372 |
+
// chat view DOM is already correct — we never tear it down for
|
| 373 |
+
// shallower overlays, only for leaving the chat entirely.
|
| 374 |
+
} else if (level === 'profile') {
|
| 375 |
+
new bootstrap.Modal(document.getElementById('profileModal')).show();
|
| 376 |
+
} else if (level === 'ai') {
|
| 377 |
+
new bootstrap.Modal(document.getElementById('chatSP')).show();
|
| 378 |
+
} else if (level === 'settings') {
|
| 379 |
+
document.getElementById('settingsPage').classList.add('show');
|
| 380 |
+
showSettingsMain();
|
| 381 |
+
} else if (level === 'settings-sub') {
|
| 382 |
+
document.getElementById('settingsPage').classList.add('show');
|
| 383 |
+
showSettingsSub(state.sub);
|
| 384 |
+
}
|
| 385 |
+
setTimeout(() => { isApplyingHistoryState = false; }, 30);
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
// Every screen's own back control (arrow icon, X, Escape, backdrop click)
|
| 389 |
+
// routes through here instead of closing itself directly — that keeps the
|
| 390 |
+
// browser history in sync with whatever's actually on screen so a later
|
| 391 |
+
// real back-button press doesn't replay a stale state.
|
| 392 |
+
function goBackOneLevel() {
|
| 393 |
+
if (history.state && history.state.level) history.back();
|
| 394 |
+
else backList();
|
| 395 |
+
}
|
| 396 |
+
function handleBackButton() { goBackOneLevel(); }
|
| 397 |
+
|
| 398 |
+
window.addEventListener('popstate', e => applyUiState(e.state));
|
| 399 |
+
|
| 400 |
+
// Bootstrap modals can be dismissed in ways that don't call our own
|
| 401 |
+
// functions (Escape key, clicking the backdrop) — 'hidden.bs.modal' fires
|
| 402 |
+
// regardless of how it closed, so hook history syncing there once per
|
| 403 |
+
// modal instead of duplicating it on every close path.
|
| 404 |
+
function wireModalBackStack(modalId, level) {
|
| 405 |
+
document.getElementById(modalId).addEventListener('hidden.bs.modal', () => {
|
| 406 |
+
if (!isApplyingHistoryState && history.state && history.state.level === level) history.back();
|
| 407 |
+
});
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
// Groups history by real calendar day using the message's `ts` (epoch ms,
|
| 411 |
+
// added server-side). Previously this was a single hardcoded "امروز"
|
| 412 |
+
// label regardless of the actual date — every day looked like today.
|
| 413 |
+
function dateLabel(ts) {
|
| 414 |
+
const d = new Date(ts);
|
| 415 |
+
const now = new Date();
|
| 416 |
+
const startOfDay = x => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
|
| 417 |
+
const diffDays = Math.round((startOfDay(now) - startOfDay(d)) / 86400000);
|
| 418 |
+
if (diffDays === 0) return 'امروز';
|
| 419 |
+
if (diffDays === 1) return 'دیروز';
|
| 420 |
+
try { return d.toLocaleDateString('fa-IR', { year: 'numeric', month: 'long', day: 'numeric' }); }
|
| 421 |
+
catch (e) { return d.toLocaleDateString(); }
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// A message "belongs to the same visual group" as its neighbour when it's
|
| 425 |
+
// the same role+sender, and neither one is a reply/forward (those always
|
| 426 |
+
// start a fresh bubble in the real client too).
|
| 427 |
+
function sameGroup(a, b) {
|
| 428 |
+
return !!a && !!b && a.role === b.role && a.sender === b.sender && !b.reply_to_preview && !b.forwarded_from;
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
// ══════════════════════════════════════════════════════════════
|
| 432 |
+
// History is now paginated (PAGE_SIZE at a time) instead of fetching
|
| 433 |
+
// and fully re-rendering the ENTIRE chat on every single poll. On a
|
| 434 |
+
// long chat that full rebuild was slow enough to look like the panel
|
| 435 |
+
// "stopped loading", and re-running scrollBot() over thousands of
|
| 436 |
+
// freshly-built DOM nodes is exactly what produced the "scrolling in
|
| 437 |
+
// from way above" jump — there was never a real animation, just the
|
| 438 |
+
// browser catching up on a huge layout each time.
|
| 439 |
+
// ══════════════════════════════════════════════════════════════
|
| 440 |
+
const PAGE_SIZE = 100;
|
| 441 |
+
var loadedMsgs = []; // oldest→newest, currently rendered for curChatId
|
| 442 |
+
var oldestLoadedId = null;
|
| 443 |
+
var hasMoreOlder = true;
|
| 444 |
+
var lastDateKeyRendered = null;
|
| 445 |
+
|
| 446 |
+
function buildMsgRow(m, prevM) {
|
| 447 |
+
const isOut = m.role === 'admin' || m.role === 'model' || m.role === 'owner' || m.role === 'bot_auto';
|
| 448 |
+
const contPrev = sameGroup(prevM, m);
|
| 449 |
+
|
| 450 |
+
const frag = document.createDocumentFragment();
|
| 451 |
+
if (m.ts) {
|
| 452 |
+
const dayKey = new Date(m.ts).toDateString();
|
| 453 |
+
if (dayKey !== lastDateKeyRendered) {
|
| 454 |
+
const sep = document.createElement('div'); sep.className = 'date-sep'; sep.textContent = dateLabel(m.ts);
|
| 455 |
+
frag.appendChild(sep);
|
| 456 |
+
lastDateKeyRendered = dayKey;
|
| 457 |
+
}
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
const row = document.createElement('div');
|
| 461 |
+
row.className = 'msg-row ' + (isOut ? 'out' : 'in') + (contPrev ? ' grp' : '');
|
| 462 |
+
row.dataset.mid = m.id;
|
| 463 |
+
|
| 464 |
+
if (m.forwarded_from) {
|
| 465 |
+
const fl = document.createElement('div'); fl.className = 'fwd-lbl';
|
| 466 |
+
fl.innerHTML = '<i class="bi bi-arrow-90deg-left"></i> فوروارد از ' + m.forwarded_from;
|
| 467 |
+
row.appendChild(fl);
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
const bub = document.createElement('div');
|
| 471 |
+
// Color is no longer split by sender_mode ("me" vs "bot") within a
|
| 472 |
+
// panel-sent message — ANY message sent from the panel (role=admin,
|
| 473 |
+
// whichever identity it went out as) is the panel's own voice, so it's
|
| 474 |
+
// always green, labeled "(پنل)". Blue is reserved for role=owner only
|
| 475 |
+
// — a message Telegram itself reports as coming directly from the
|
| 476 |
+
// connected account holder, not something the panel sent.
|
| 477 |
+
let bc = 'b-user';
|
| 478 |
+
if (m.role === 'owner') bc = 'b-me';
|
| 479 |
+
else if (m.role === 'admin' || m.role === 'bot_auto' || m.role === 'model') bc = 'b-bot';
|
| 480 |
+
bub.className = 'bubble ' + bc;
|
| 481 |
+
if (contPrev) bub.classList.add('cont-prev');
|
| 482 |
+
// whether THIS bubble gets a tail depends on whether the NEXT one
|
| 483 |
+
// continues its group — fixed up in fixGroupTail() after the full
|
| 484 |
+
// list (or the newly appended tail) is known, since at render time
|
| 485 |
+
// we don't always have the next message yet (e.g. appending one at
|
| 486 |
+
// a time during polling).
|
| 487 |
+
bub.classList.add('has-tail');
|
| 488 |
+
|
| 489 |
+
if (!contPrev) {
|
| 490 |
+
const sn = document.createElement('div'); sn.className = 'msg-sender';
|
| 491 |
+
let lbl = m.sender || '';
|
| 492 |
+
if (m.role === 'owner') lbl = '🧑 (من)';
|
| 493 |
+
else if (m.role === 'admin') lbl = '🖥 (پنل)';
|
| 494 |
+
else if (m.role === 'model') lbl = '🤖 (هوش مصنوعی)';
|
| 495 |
+
else if (m.role === 'bot_auto') lbl = '🤖 (ربات خودکار)';
|
| 496 |
+
sn.textContent = lbl; bub.appendChild(sn);
|
| 497 |
+
}
|
| 498 |
+
if (m.reply_to_preview) {
|
| 499 |
+
const rq = document.createElement('div'); rq.className = 'rq';
|
| 500 |
+
rq.setAttribute('role', 'button'); rq.tabIndex = 0; rq.title = 'رفتن به پیام اصلی';
|
| 501 |
+
const ri = document.createElement('i'); ri.className = 'bi bi-reply-fill'; ri.style.flexShrink = '0';
|
| 502 |
+
const rs = document.createElement('span'); rs.textContent = m.reply_to_preview; // text, not HTML: the preview carries another person's words
|
| 503 |
+
rq.append(ri, rs);
|
| 504 |
+
const goOriginal = ev => { ev.stopPropagation(); jumpToReplied(m); };
|
| 505 |
+
rq.addEventListener('click', goOriginal);
|
| 506 |
+
rq.addEventListener('keydown', ev => { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); goOriginal(ev); } });
|
| 507 |
+
bub.appendChild(rq);
|
| 508 |
+
}
|
| 509 |
+
if (String(m.text || '').startsWith('/')) {
|
| 510 |
+
const cb = document.createElement('div'); cb.className = 'cmd-badge'; cb.textContent = 'دستور';
|
| 511 |
+
bub.appendChild(cb);
|
| 512 |
+
}
|
| 513 |
+
const med = mkMedia(m); if (med) bub.appendChild(med);
|
| 514 |
+
|
| 515 |
+
const foot = document.createElement('div'); foot.className = 'msg-foot';
|
| 516 |
+
if (m.text) { const td = document.createElement('div'); td.style.whiteSpace = 'pre-wrap'; td.textContent = m.text; foot.appendChild(td); }
|
| 517 |
+
const ts = document.createElement('span'); ts.className = 'msg-time'; ts.textContent = m.time || '';
|
| 518 |
+
foot.appendChild(ts);
|
| 519 |
+
bub.appendChild(foot);
|
| 520 |
+
|
| 521 |
+
row.appendChild(bub);
|
| 522 |
+
|
| 523 |
+
const rc = mkReactionChips(m, isOut);
|
| 524 |
+
if (rc) row.appendChild(rc);
|
| 525 |
+
|
| 526 |
+
if (m.msg_id) {
|
| 527 |
+
const bar = document.createElement('div'); bar.className = 'msg-bar';
|
| 528 |
+
// The reaction picker is ~85 elements. Building it for every message
|
| 529 |
+
// made 93 of each row's 100 DOM nodes (and, on non-Apple phones, ~80
|
| 530 |
+
// emoji <img> per message) — so it is created on first click instead.
|
| 531 |
+
const rbBtn = document.createElement('span'); rbBtn.className = 'tbb'; rbBtn.innerHTML = '<i class="bi bi-emoji-smile"></i>';
|
| 532 |
+
let rb = null;
|
| 533 |
+
rbBtn.onclick = e => {
|
| 534 |
+
e.stopPropagation();
|
| 535 |
+
if (!rb) { const made = mkReactBar(curChatId, m.msg_id, m.my_reaction); rb = made.bar; bar.appendChild(made.wrap); }
|
| 536 |
+
document.querySelectorAll('.react-bar.show').forEach(x => { if (x !== rb) x.classList.remove('show'); });
|
| 537 |
+
rb.classList.toggle('show');
|
| 538 |
+
};
|
| 539 |
+
bar.appendChild(rbBtn);
|
| 540 |
+
|
| 541 |
+
const replyBtn = document.createElement('span'); replyBtn.className = 'tbb'; replyBtn.innerHTML = '<i class="bi bi-reply"></i>'; replyBtn.title = 'ریپلای';
|
| 542 |
+
replyBtn.onclick = () => setReply(m.msg_id, (m.sender || '') + ': ' + (m.text || '[رسانه]'));
|
| 543 |
+
bar.appendChild(replyBtn);
|
| 544 |
+
|
| 545 |
+
if (m.role === 'admin' || m.role === 'owner' || m.role === 'bot_auto' || m.role === 'model') {
|
| 546 |
+
const eb = document.createElement('span'); eb.className = 'tbb'; eb.innerHTML = '<i class="bi bi-pencil"></i>'; eb.title = 'ویرایش';
|
| 547 |
+
eb.onclick = () => editMsg(m.id, m.msg_id || '', m.text);
|
| 548 |
+
bar.appendChild(eb);
|
| 549 |
+
}
|
| 550 |
+
row.appendChild(bar);
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
frag.appendChild(row);
|
| 554 |
+
return frag;
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
// A bubble only gets a tail if the NEXT message doesn't continue its
|
| 558 |
+
// group — walk the currently-loaded list once and fix up the two
|
| 559 |
+
// bubbles around any seam (used after appending/prepending, where a
|
| 560 |
+
// row was built without knowing its new neighbour yet).
|
| 561 |
+
function fixGroupTail(aroundId) {
|
| 562 |
+
const cont = document.getElementById('msgs');
|
| 563 |
+
for (let i = 0; i < loadedMsgs.length; i++) {
|
| 564 |
+
if (aroundId !== undefined && loadedMsgs[i].id !== aroundId) continue;
|
| 565 |
+
const m = loadedMsgs[i], nextM = loadedMsgs[i + 1];
|
| 566 |
+
const row = cont.querySelector(`.msg-row[data-mid="${CSS.escape(String(m.id))}"]`);
|
| 567 |
+
const bub = row && row.querySelector('.bubble');
|
| 568 |
+
if (!bub) continue;
|
| 569 |
+
const contNext = sameGroup(m, nextM);
|
| 570 |
+
bub.classList.toggle('cont-next', contNext);
|
| 571 |
+
bub.classList.toggle('has-tail', !contNext);
|
| 572 |
+
}
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
function renderFullList(list) {
|
| 576 |
+
const cont = document.getElementById('msgs');
|
| 577 |
+
cont.innerHTML = '';
|
| 578 |
+
if (hasMoreOlder && list.length >= PAGE_SIZE) {
|
| 579 |
+
const btn = document.createElement('div'); btn.id = 'loadOlderBtn'; btn.className = 'load-older-btn';
|
| 580 |
+
btn.textContent = 'بارگذاری پیامهای قدیمیتر';
|
| 581 |
+
btn.onclick = loadOlderMessages;
|
| 582 |
+
cont.appendChild(btn);
|
| 583 |
+
}
|
| 584 |
+
lastDateKeyRendered = null;
|
| 585 |
+
const frag = document.createDocumentFragment();
|
| 586 |
+
for (let i = 0; i < list.length; i++) frag.appendChild(buildMsgRow(list[i], list[i - 1]));
|
| 587 |
+
applyEmojiImages(frag);
|
| 588 |
+
cont.appendChild(frag);
|
| 589 |
+
initMsgGestures();
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
function appendRows(newItems) {
|
| 593 |
+
const cont = document.getElementById('msgs');
|
| 594 |
+
const prevLast = loadedMsgs.length ? loadedMsgs[loadedMsgs.length - 1] : null;
|
| 595 |
+
let prev = prevLast;
|
| 596 |
+
for (const m of newItems) {
|
| 597 |
+
const f = buildMsgRow(m, prev); applyEmojiImages(f);
|
| 598 |
+
f.querySelectorAll('.msg-row').forEach(r => r.classList.add('msg-enter')); // live arrivals animate; the first render stays instant
|
| 599 |
+
cont.appendChild(f); prev = m;
|
| 600 |
+
}
|
| 601 |
+
if (prevLast) fixGroupTail(prevLast.id);
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
async function fetchHistory(chatId, silent) {
|
| 605 |
+
if (!chatId) return;
|
| 606 |
+
if (!silent) {
|
| 607 |
+
loadedMsgs = []; oldestLoadedId = null; hasMoreOlder = true; lastHistHash = '';
|
| 608 |
+
delete _etags[`/api/chat?id=${encodeURIComponent(chatId)}&limit=${PAGE_SIZE}`];
|
| 609 |
+
const hist = await apiFetchCond(`/api/chat?id=${encodeURIComponent(chatId)}&limit=${PAGE_SIZE}`);
|
| 610 |
+
if (!hist) return;
|
| 611 |
+
loadedMsgs = hist;
|
| 612 |
+
oldestLoadedId = hist.length ? hist[0].id : null;
|
| 613 |
+
lastHistHash = JSON.stringify(hist);
|
| 614 |
+
renderFullList(loadedMsgs);
|
| 615 |
+
scrollBot(false);
|
| 616 |
+
return;
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
// polling: fetch just the latest page and diff against what's rendered
|
| 620 |
+
const hist = await apiFetchCond(`/api/chat?id=${encodeURIComponent(chatId)}&limit=${PAGE_SIZE}`);
|
| 621 |
+
if (!hist || hist.notModified) return; // 304: nothing changed
|
| 622 |
+
if (hist.error) return;
|
| 623 |
+
const hs = JSON.stringify(hist);
|
| 624 |
+
if (hs === lastHistHash) return;
|
| 625 |
+
lastHistHash = hs;
|
| 626 |
+
const wasBot = atBot();
|
| 627 |
+
|
| 628 |
+
const oldIds = loadedMsgs.map(m => m.id);
|
| 629 |
+
const newIds = hist.map(m => m.id);
|
| 630 |
+
const sameLength = oldIds.length === newIds.length;
|
| 631 |
+
let commonPrefix = 0;
|
| 632 |
+
while (commonPrefix < oldIds.length && commonPrefix < newIds.length && oldIds[commonPrefix] === newIds[commonPrefix]) commonPrefix++;
|
| 633 |
+
|
| 634 |
+
if (commonPrefix === oldIds.length && newIds.length > oldIds.length) {
|
| 635 |
+
// the common case: nothing changed, just new messages at the end —
|
| 636 |
+
// append only those instead of rebuilding the whole list.
|
| 637 |
+
const added = hist.slice(commonPrefix);
|
| 638 |
+
loadedMsgs = hist;
|
| 639 |
+
appendRows(added);
|
| 640 |
+
if (wasBot) scrollBot(true);
|
| 641 |
+
else { unreadCnt += added.length; updUBadge(); document.getElementById('scrollBtn').classList.remove('d-none'); }
|
| 642 |
+
return;
|
| 643 |
+
}
|
| 644 |
+
if (sameLength && commonPrefix === oldIds.length) return; // identical, nothing to do
|
| 645 |
+
|
| 646 |
+
// anything else (edit, reaction, deletion, pagination overlap) — fall
|
| 647 |
+
// back to a full rebuild of just this latest page, not the whole
|
| 648 |
+
// multi-thousand-message history.
|
| 649 |
+
loadedMsgs = hist;
|
| 650 |
+
oldestLoadedId = hist.length ? hist[0].id : oldestLoadedId;
|
| 651 |
+
renderFullList(loadedMsgs);
|
| 652 |
+
if (!wasBot) {
|
| 653 |
+
// can't know exactly how many are "new" after a reshuffle — just
|
| 654 |
+
// surface the scroll-down affordance rather than guessing a count.
|
| 655 |
+
document.getElementById('scrollBtn').classList.remove('d-none');
|
| 656 |
+
} else {
|
| 657 |
+
scrollBot(true);
|
| 658 |
+
}
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
async function loadOlderMessages() {
|
| 662 |
+
if (!hasMoreOlder || !oldestLoadedId || !curChatId) return;
|
| 663 |
+
const btn = document.getElementById('loadOlderBtn');
|
| 664 |
+
if (btn) btn.textContent = 'در حال بارگذاری...';
|
| 665 |
+
const older = await apiFetch(`/api/chat?id=${encodeURIComponent(curChatId)}&limit=${PAGE_SIZE}&before_id=${encodeURIComponent(oldestLoadedId)}`);
|
| 666 |
+
if (!older || !older.length) {
|
| 667 |
+
hasMoreOlder = false;
|
| 668 |
+
if (btn) btn.remove();
|
| 669 |
+
return;
|
| 670 |
+
}
|
| 671 |
+
const cont = document.getElementById('msgs');
|
| 672 |
+
const anchor = cont.firstElementChild;
|
| 673 |
+
const prevScrollHeight = cont.scrollHeight, prevScrollTop = cont.scrollTop;
|
| 674 |
+
|
| 675 |
+
loadedMsgs = older.concat(loadedMsgs);
|
| 676 |
+
oldestLoadedId = older[0].id;
|
| 677 |
+
lastDateKeyRendered = null;
|
| 678 |
+
const frag = document.createDocumentFragment();
|
| 679 |
+
for (let i = 0; i < older.length; i++) frag.appendChild(buildMsgRow(older[i], older[i - 1]));
|
| 680 |
+
applyEmojiImages(frag);
|
| 681 |
+
if (anchor) cont.insertBefore(frag, anchor); else cont.appendChild(frag);
|
| 682 |
+
fixGroupTail(older[older.length - 1].id);
|
| 683 |
+
// keep the viewport pinned to what the user was looking at — prepending
|
| 684 |
+
// content above the fold would otherwise yank the scroll position.
|
| 685 |
+
cont.scrollTop = prevScrollTop + (cont.scrollHeight - prevScrollHeight);
|
| 686 |
+
if (btn) btn.textContent = 'بارگذاری پیامهای قدیمیتر';
|
| 687 |
+
if (older.length < PAGE_SIZE) { hasMoreOlder = false; if (btn) btn.remove(); }
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
// ══════════════════════════════════════════════════════════════
|
| 691 |
+
// Phase 4 — message context menu (right-click / long-press)
|
| 692 |
+
// and swipe-to-reply.
|
| 693 |
+
// ══════════════════════════════════════════════════════════════
|
| 694 |
+
|
| 695 |
+
let _gesturesReady = false;
|
| 696 |
+
// Click on a reply preview → scroll to the message it quotes and flash it. If that message is older than
|
| 697 |
+
// what's loaded, keep paging back until it turns up (or history runs out).
|
| 698 |
+
let _jumping = false;
|
| 699 |
+
async function jumpToReplied(m) {
|
| 700 |
+
if (_jumping) return;
|
| 701 |
+
_jumping = true;
|
| 702 |
+
try {
|
| 703 |
+
// Server preview format is "<telegram first name>: <text or caption or [رسانه]>" cut to 120 chars, so a
|
| 704 |
+
// text fallback (only for old rows saved without reply_to_msg_id) compares just the part after the first
|
| 705 |
+
// colon, as a prefix, and only against messages written BEFORE the reply — nearest one wins.
|
| 706 |
+
const ptxt = (m.reply_to_preview || '').replace(/^[^:]*:\s*/, '');
|
| 707 |
+
const find = () => {
|
| 708 |
+
if (m.reply_to_msg_id != null) {
|
| 709 |
+
return loadedMsgs.find(x => x.msg_id != null && String(x.msg_id) === String(m.reply_to_msg_id)) || null;
|
| 710 |
+
}
|
| 711 |
+
if (!ptxt) return null;
|
| 712 |
+
for (let i = loadedMsgs.indexOf(m) - 1; i >= 0; i--) {
|
| 713 |
+
if (((loadedMsgs[i].text || '[رسانه]')).startsWith(ptxt)) return loadedMsgs[i];
|
| 714 |
+
}
|
| 715 |
+
return null;
|
| 716 |
+
};
|
| 717 |
+
let target = find(), guard = 0;
|
| 718 |
+
while (!target && hasMoreOlder && guard++ < 60) { await loadOlderMessages(); target = find(); }
|
| 719 |
+
const row = target && document.querySelector('#msgs .msg-row[data-mid="' + CSS.escape(String(target.id)) + '"]');
|
| 720 |
+
if (!row) { showToast('پیام اصلی پیدا نشد (ممکن است حذف شده باشد)', 'warn'); return; }
|
| 721 |
+
row.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
| 722 |
+
row.classList.remove('msg-flash'); void row.offsetWidth; row.classList.add('msg-flash');
|
| 723 |
+
setTimeout(() => row.classList.remove('msg-flash'), 1800);
|
| 724 |
+
} finally { _jumping = false; }
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
function msgById(id) { return loadedMsgs.find(m => String(m.id) === String(id)); }
|
| 728 |
+
|
| 729 |
+
// Right-click, long-press and swipe-to-reply — attached once to the list and
|
| 730 |
+
// resolved through event delegation (it used to be six listeners and an extra
|
| 731 |
+
// icon element on every single row).
|
| 732 |
+
function initMsgGestures() {
|
| 733 |
+
if (_gesturesReady) return; _gesturesReady = true;
|
| 734 |
+
const box = document.getElementById('msgs');
|
| 735 |
+
const rowOf = t => (t && t.closest) ? t.closest('.msg-row') : null;
|
| 736 |
+
const open = (row, x, y) => {
|
| 737 |
+
const m = msgById(row.dataset.mid);
|
| 738 |
+
if (m && m.msg_id) openMsgContextMenu(x, y, m, row.classList.contains('out'));
|
| 739 |
+
};
|
| 740 |
+
box.addEventListener('contextmenu', e => {
|
| 741 |
+
const row = rowOf(e.target); if (!row) return;
|
| 742 |
+
e.preventDefault(); open(row, e.clientX, e.clientY);
|
| 743 |
+
});
|
| 744 |
+
let st = null;
|
| 745 |
+
box.addEventListener('touchstart', e => {
|
| 746 |
+
const row = rowOf(e.target); if (!row) { st = null; return; }
|
| 747 |
+
const t = e.touches[0];
|
| 748 |
+
st = { row, x: t.clientX, y: t.clientY, dx: 0, moved: false, swiping: false, icon: null };
|
| 749 |
+
st.timer = setTimeout(() => { if (st && !st.moved) open(st.row, st.x, st.y); }, 450);
|
| 750 |
+
}, { passive: true });
|
| 751 |
+
box.addEventListener('touchmove', e => {
|
| 752 |
+
if (!st) return;
|
| 753 |
+
const t = e.touches[0], dx = t.clientX - st.x, dy = t.clientY - st.y;
|
| 754 |
+
if (Math.abs(dx) > 8 || Math.abs(dy) > 8) { st.moved = true; clearTimeout(st.timer); }
|
| 755 |
+
if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy)) {
|
| 756 |
+
st.swiping = true; st.dx = dx;
|
| 757 |
+
const c = Math.max(-80, Math.min(80, dx));
|
| 758 |
+
st.row.style.transform = `translateX(${c}px)`;
|
| 759 |
+
if (!st.icon) {
|
| 760 |
+
st.row.style.position = 'relative';
|
| 761 |
+
st.icon = document.createElement('i'); st.icon.className = 'bi bi-reply-fill swipe-reply-icon';
|
| 762 |
+
st.row.appendChild(st.icon);
|
| 763 |
+
}
|
| 764 |
+
st.icon.style.opacity = Math.min(1, Math.abs(c) / 60);
|
| 765 |
+
}
|
| 766 |
+
}, { passive: true });
|
| 767 |
+
const end = () => {
|
| 768 |
+
if (!st) return;
|
| 769 |
+
clearTimeout(st.timer);
|
| 770 |
+
if (st.swiping && Math.abs(st.dx) > 60) {
|
| 771 |
+
const m = msgById(st.row.dataset.mid);
|
| 772 |
+
if (m && m.msg_id) setReply(m.msg_id, (m.sender || '') + ': ' + (m.text || '[رسانه]'));
|
| 773 |
+
}
|
| 774 |
+
st.row.style.transform = ''; if (st.icon) st.icon.remove();
|
| 775 |
+
st = null;
|
| 776 |
+
};
|
| 777 |
+
box.addEventListener('touchend', end, { passive: true });
|
| 778 |
+
box.addEventListener('touchcancel', end, { passive: true });
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
function closeMsgContextMenu() {
|
| 782 |
+
const menu = document.getElementById('msgCtxMenu');
|
| 783 |
+
if (!menu.classList.contains('show')) return;
|
| 784 |
+
menu.classList.remove('show');
|
| 785 |
+
if (!isApplyingHistoryState && history.state && history.state.level === 'ctx') history.back();
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
function openMsgContextMenu(x, y, m, isOut) {
|
| 789 |
+
pushUiState({ level: 'ctx', chatId: curChatId });
|
| 790 |
+
const menu = document.getElementById('msgCtxMenu');
|
| 791 |
+
const reactBox = document.getElementById('mcmReact');
|
| 792 |
+
const itemsBox = document.getElementById('mcmItems');
|
| 793 |
+
|
| 794 |
+
reactBox.innerHTML = '';
|
| 795 |
+
sortByFreq(QUICK_REACT).forEach(em => {
|
| 796 |
+
const s = document.createElement('span'); s.textContent = em;
|
| 797 |
+
s.onclick = () => { doReact(curChatId, m.msg_id, em === m.my_reaction ? null : em); closeMsgContextMenu(); };
|
| 798 |
+
reactBox.appendChild(s);
|
| 799 |
+
});
|
| 800 |
+
applyEmojiImages(reactBox);
|
| 801 |
+
|
| 802 |
+
const items = [];
|
| 803 |
+
items.push({ icon: 'bi-reply', label: 'ریپلای', fn: () => setReply(m.msg_id, (m.sender || '') + ': ' + (m.text || '[رسانه]')) });
|
| 804 |
+
if (m.role === 'admin' || m.role === 'owner' || m.role === 'bot_auto' || m.role === 'model') {
|
| 805 |
+
items.push({ icon: 'bi-pencil', label: 'ویرایش', fn: () => editMsg(m.id, m.msg_id || '', m.text) });
|
| 806 |
+
}
|
| 807 |
+
if (m.text) items.push({ icon: 'bi-clipboard', label: 'کپی متن', fn: () => { navigator.clipboard?.writeText(m.text); } });
|
| 808 |
+
if ((m.type === 'sticker' || m.type === 'animation') && m.file_id) {
|
| 809 |
+
items.push({
|
| 810 |
+
icon: 'bi-stickies', label: 'افزودن به پنل استیکر/گیف', fn: () => addToStickerPanel(m.file_id, m.type, m.text),
|
| 811 |
+
});
|
| 812 |
+
}
|
| 813 |
+
items.push({ icon: 'bi-forward', label: 'فوروارد', fn: () => forwardMsg(m.msg_id) });
|
| 814 |
+
if (curIsGroupForCtx()) items.push({ icon: 'bi-pin-angle', label: 'پین پیام', fn: () => pinMsgById(m.msg_id) });
|
| 815 |
+
items.push({ icon: 'bi-trash3', label: 'حذف', danger: true, fn: () => deleteMsgById(m.msg_id) });
|
| 816 |
+
|
| 817 |
+
itemsBox.innerHTML = '';
|
| 818 |
+
items.forEach(it => {
|
| 819 |
+
const d = document.createElement('div'); d.className = 'mcm-item' + (it.danger ? ' danger' : '');
|
| 820 |
+
d.innerHTML = `<i class="bi ${it.icon}"></i><span>${it.label}</span>`;
|
| 821 |
+
d.onclick = () => { it.fn(); closeMsgContextMenu(); };
|
| 822 |
+
itemsBox.appendChild(d);
|
| 823 |
+
});
|
| 824 |
+
|
| 825 |
+
menu.classList.add('show');
|
| 826 |
+
// keep on-screen
|
| 827 |
+
const mw = 260, mh = menu.offsetHeight || 320;
|
| 828 |
+
let left = x, top = y;
|
| 829 |
+
if (left + mw > window.innerWidth) left = window.innerWidth - mw - 10;
|
| 830 |
+
if (top + mh > window.innerHeight) top = window.innerHeight - mh - 10;
|
| 831 |
+
menu.style.left = Math.max(10, left) + 'px';
|
| 832 |
+
menu.style.top = Math.max(10, top) + 'px';
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
function curIsGroupForCtx() { return !!isGroup; }
|
| 836 |
+
|
| 837 |
+
document.addEventListener('click', e => {
|
| 838 |
+
if (!e.target.closest('#msgCtxMenu')) closeMsgContextMenu();
|
| 839 |
+
});
|
| 840 |
+
|
| 841 |
+
async function addToStickerPanel(fileId, type, emoji) {
|
| 842 |
+
const res = await apiFetch('/api/add-recent-media', {
|
| 843 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 844 |
+
body: JSON.stringify({ fileId, type, emoji }),
|
| 845 |
+
});
|
| 846 |
+
if (res?.error) showToast(res.error, 'error');
|
| 847 |
+
else showToast(type === 'sticker' ? 'استیکر به پنل اضافه شد' : 'GIF به پنل اضافه شد', 'success');
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
async function forwardMsg(msgId) {
|
| 851 |
+
const to = prompt('آیدی عددی چت مقصد برای فوروارد:');
|
| 852 |
+
if (!to) return;
|
| 853 |
+
const res = await apiFetch('/api/forward', {
|
| 854 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 855 |
+
body: JSON.stringify({ fromChatId: curChatId, toChatId: to, msgId, businessConnectionId: curBizId }),
|
| 856 |
+
});
|
| 857 |
+
if (res?.error) showToast(res.error, 'error'); else showToast('فوروارد شد', 'success');
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
async function pinMsgById(msgId) {
|
| 861 |
+
const res = await apiFetch('/api/pin-message', {
|
| 862 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 863 |
+
body: JSON.stringify({ chatId: curChatId, msgId, businessConnectionId: curBizId }),
|
| 864 |
+
});
|
| 865 |
+
if (res?.error) showToast(res.error, 'error'); else fetchHistory(curChatId, false);
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
async function deleteMsgById(msgId) {
|
| 869 |
+
if (!confirm('این پیام حذف بشه؟')) return;
|
| 870 |
+
const res = await apiFetch('/api/delete-message', {
|
| 871 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 872 |
+
body: JSON.stringify({ chatId: curChatId, msgId }),
|
| 873 |
+
});
|
| 874 |
+
if (res?.error) showToast(res.error, 'error'); else fetchHistory(curChatId, false);
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
// wire the unified back-stack onto the two modals that participate in it
|
| 878 |
+
// (profile ⇄ AI panel); done here, synchronously, since this script tag
|
| 879 |
+
// loads after their HTML is already in the DOM.
|
| 880 |
+
wireModalBackStack('profileModal', 'profile');
|
| 881 |
+
wireModalBackStack('chatSP', 'ai');
|
| 882 |
+
wireModalBackStack('newChatModal', 'overlay');
|
| 883 |
+
wireModalBackStack('gmodModal', 'overlay');
|
| 884 |
+
wireModalBackStack('mediaViewerModal', 'overlay');
|
static/js/chatlist.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Avatar colours: flat tonal fills (M3 style) picked from the chat id's hash.
|
| 2 |
+
// Mid-lightness + moderate chroma keeps white initials readable.
|
| 3 |
+
function avGrad(id) {
|
| 4 |
+
let h = 0; const s = String(id || "");
|
| 5 |
+
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
|
| 6 |
+
const hue = (h % 12) * 30 + 8;
|
| 7 |
+
return `hsl(${hue} 42% 38%)`;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
async function fetchChats(silent) {
|
| 11 |
+
let chats = await apiFetchCond('/api/chats');
|
| 12 |
+
if (!chats) return;
|
| 13 |
+
const unchanged = !!chats.notModified; // 304: same list as last time — skip the new-message scan
|
| 14 |
+
if (unchanged) chats = allChats;
|
| 15 |
+
else { if (chats.error) return; allChats = chats; }
|
| 16 |
+
let hasNew = false;
|
| 17 |
+
if (!unchanged) chats.forEach(c => {
|
| 18 |
+
if (firstPoll) {
|
| 19 |
+
lastChatText[c.id] = c.last_text;
|
| 20 |
+
} else if (lastChatText[c.id] !== undefined && lastChatText[c.id] !== c.last_text) {
|
| 21 |
+
const self = ['شما', 'پنل', 'شما (من)', 'شما (ربات)', 'ربات', 'دستیار', 'دستیار (AI)'].includes(c.last_sender);
|
| 22 |
+
if (!self && (c.id !== curChatId || document.hidden)) {
|
| 23 |
+
unreadPer[c.id] = (unreadPer[c.id] || 0) + 1;
|
| 24 |
+
if (!c.muted) hasNew = true;
|
| 25 |
+
}
|
| 26 |
+
lastChatText[c.id] = c.last_text;
|
| 27 |
+
} else {
|
| 28 |
+
lastChatText[c.id] = c.last_text;
|
| 29 |
+
}
|
| 30 |
+
});
|
| 31 |
+
if (firstPoll) firstPoll = false;
|
| 32 |
+
if (hasNew && typeof notify === 'function') notify();
|
| 33 |
+
if (typeof updGlobalUnread === 'function') updGlobalUnread();
|
| 34 |
+
|
| 35 |
+
const nh = JSON.stringify(chats) + '|' + JSON.stringify(unreadPer) + '|' + activeTab + '|' + activeView;
|
| 36 |
+
if (nh === lastChatsHash) return;
|
| 37 |
+
lastChatsHash = nh;
|
| 38 |
+
renderChatList(chats);
|
| 39 |
+
|
| 40 |
+
if (curChatId) {
|
| 41 |
+
const c = allChats.find(x => x.id === curChatId);
|
| 42 |
+
const sub = document.getElementById('hdrSub');
|
| 43 |
+
if (sub) {
|
| 44 |
+
if (c?.ai_pending) { sub.textContent = 'در حال آمادهسازی پاسخ...'; sub.className = 'chat-info-subtitle pend'; }
|
| 45 |
+
else { sub.textContent = 'شناسه: ' + curChatId; sub.className = 'chat-info-subtitle'; }
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function filterChats() { renderChatList(allChats); }
|
| 51 |
+
|
| 52 |
+
async function togglePin(id, v) {
|
| 53 |
+
await apiFetch('/api/pin', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chatId: id, pinned: v }) });
|
| 54 |
+
lastChatsHash = ''; fetchChats(false);
|
| 55 |
+
}
|
| 56 |
+
async function toggleMute(id, v) {
|
| 57 |
+
await apiFetch('/api/mute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chatId: id, muted: v }) });
|
| 58 |
+
lastChatsHash = ''; fetchChats(false);
|
| 59 |
+
}
|
| 60 |
+
function togglePinCurrent() { if (!curChatId) return; const c = allChats.find(x => x.id === curChatId); togglePin(curChatId, !(c && c.pinned)); }
|
| 61 |
+
function toggleMuteCurrent() { if (!curChatId) return; const c = allChats.find(x => x.id === curChatId); toggleMute(curChatId, !(c && c.muted)); }
|
| 62 |
+
|
| 63 |
+
// Profile-modal versions: update the button's icon/label IMMEDIATELY
|
| 64 |
+
// (optimistic) instead of waiting for the next poll — previously you had
|
| 65 |
+
// to close and reopen the modal to see the new pin/mute state.
|
| 66 |
+
async function profileTogglePin() {
|
| 67 |
+
if (!curChatId) return;
|
| 68 |
+
const c = allChats.find(x => x.id === curChatId);
|
| 69 |
+
const next = !(c && c.pinned);
|
| 70 |
+
const btn = document.getElementById('paPin');
|
| 71 |
+
btn.querySelector('i').className = 'bi ' + (next ? 'bi-pin-angle-fill' : 'bi-pin-angle');
|
| 72 |
+
btn.querySelector('span').textContent = next ? 'لغو پین' : 'پین گفتگو';
|
| 73 |
+
if (c) c.pinned = next; // keep local cache in sync until the next poll confirms it
|
| 74 |
+
await togglePin(curChatId, next);
|
| 75 |
+
}
|
| 76 |
+
async function profileToggleMute() {
|
| 77 |
+
if (!curChatId) return;
|
| 78 |
+
const c = allChats.find(x => x.id === curChatId);
|
| 79 |
+
const next = !(c && c.muted);
|
| 80 |
+
const btn = document.getElementById('paMute');
|
| 81 |
+
btn.querySelector('i').className = 'bi ' + (next ? 'bi-bell-slash-fill' : 'bi-bell');
|
| 82 |
+
btn.querySelector('span').textContent = next ? 'لغو بیصدا' : 'بیصدا کردن';
|
| 83 |
+
if (c) c.muted = next;
|
| 84 |
+
await toggleMute(curChatId, next);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// li.chatlist-chat > .dialog-avatar + .dialog-subtitle-container(.row-title/.row-subtitle)
|
| 88 |
+
// — real tweb class names, confirmed against _chatlist.scss.
|
| 89 |
+
// Counts CHATS with at least one unread message (not total unread
|
| 90 |
+
// messages) in each view, e.g. one user sent 10 unread messages and
|
| 91 |
+
// another sent 20 → the badge shows "2" (two chats), not "30".
|
| 92 |
+
function updateViewBadges(chats) {
|
| 93 |
+
const botChats = chats.filter(c => !c.business_connection_id || c.has_bot_chat);
|
| 94 |
+
const bizChats = chats.filter(c => c.business_connection_id);
|
| 95 |
+
const botUnread = botChats.filter(c => (unreadPer[c.id] || 0) > 0).length;
|
| 96 |
+
const bizUnread = bizChats.filter(c => (unreadPer[c.id] || 0) > 0).length;
|
| 97 |
+
const botBadge = document.getElementById('vbBotCount');
|
| 98 |
+
const bizBadge = document.getElementById('vbBizCount');
|
| 99 |
+
botBadge.textContent = botUnread > 99 ? '99+' : botUnread;
|
| 100 |
+
botBadge.classList.toggle('d-none', botUnread === 0);
|
| 101 |
+
bizBadge.textContent = bizUnread > 99 ? '99+' : bizUnread;
|
| 102 |
+
bizBadge.classList.toggle('d-none', bizUnread === 0);
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
function renderChatList(chats) {
|
| 106 |
+
updateViewBadges(chats);
|
| 107 |
+
const cont = document.getElementById('chatList');
|
| 108 |
+
const term = (document.getElementById('searchInput').value || '').toLowerCase();
|
| 109 |
+
let base = chats.filter(c => (c.title || '').toLowerCase().includes(term));
|
| 110 |
+
|
| 111 |
+
// view filter: "biz" shows chats with a business connection; "bot" shows
|
| 112 |
+
// everything EXCEPT business-only chats (a chat with both a business
|
| 113 |
+
// connection AND a proven direct bot chat legitimately shows in both).
|
| 114 |
+
if (activeView === 'biz') base = base.filter(c => c.business_connection_id);
|
| 115 |
+
else base = base.filter(c => !c.business_connection_id || c.has_bot_chat);
|
| 116 |
+
|
| 117 |
+
document.getElementById('cntAll').textContent = base.length;
|
| 118 |
+
document.getElementById('cntUnread').textContent = base.filter(c => (unreadPer[c.id] || 0) > 0).length;
|
| 119 |
+
document.getElementById('cntPinned').textContent = base.filter(c => c.pinned).length;
|
| 120 |
+
document.getElementById('cntGroups').textContent = base.filter(c => c.is_group).length;
|
| 121 |
+
|
| 122 |
+
let list = base;
|
| 123 |
+
if (activeTab === 'unread') list = list.filter(c => (unreadPer[c.id] || 0) > 0);
|
| 124 |
+
if (activeTab === 'pinned') list = list.filter(c => c.pinned);
|
| 125 |
+
if (activeTab === 'groups') list = list.filter(c => c.is_group);
|
| 126 |
+
list = [...list].sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0));
|
| 127 |
+
|
| 128 |
+
cont.innerHTML = '';
|
| 129 |
+
list.forEach(c => {
|
| 130 |
+
const li = document.createElement('li');
|
| 131 |
+
li.className = 'chatlist-chat' + (curChatId === c.id ? ' active' : '');
|
| 132 |
+
li.onclick = () => selChat(c.id, c.title, c.business_connection_id);
|
| 133 |
+
|
| 134 |
+
const av = document.createElement('div');
|
| 135 |
+
av.className = 'dialog-avatar';
|
| 136 |
+
av.style.background = avGrad(c.id);
|
| 137 |
+
const img = document.createElement('img');
|
| 138 |
+
img.src = `/api/user-photo?id=${encodeURIComponent(c.id)}&auth=${encodeURIComponent(PASS)}`;
|
| 139 |
+
img.onerror = () => { av.textContent = c.title ? c.title[0].toUpperCase() : '?'; };
|
| 140 |
+
av.appendChild(img);
|
| 141 |
+
|
| 142 |
+
const info = document.createElement('div');
|
| 143 |
+
info.className = 'dialog-subtitle-container';
|
| 144 |
+
|
| 145 |
+
const row = document.createElement('div');
|
| 146 |
+
row.className = 'dialog-row';
|
| 147 |
+
const title = document.createElement('div');
|
| 148 |
+
title.className = 'row-title';
|
| 149 |
+
const strong = document.createElement('strong');
|
| 150 |
+
strong.textContent = c.title || '';
|
| 151 |
+
title.appendChild(strong);
|
| 152 |
+
if (c.business_connection_id) {
|
| 153 |
+
const bi = document.createElement('i');
|
| 154 |
+
bi.className = 'bi bi-briefcase-fill';
|
| 155 |
+
bi.title = 'اتصال بیزینسی';
|
| 156 |
+
bi.style.cssText = 'color:var(--md-sys-color-tertiary);font-size:.9rem';
|
| 157 |
+
title.appendChild(bi);
|
| 158 |
+
}
|
| 159 |
+
if (c.is_group) {
|
| 160 |
+
const gi = document.createElement('i');
|
| 161 |
+
gi.className = 'bi bi-people-fill';
|
| 162 |
+
gi.style.cssText = 'color:var(--md-sys-color-on-surface-variant);font-size:.9rem';
|
| 163 |
+
title.appendChild(gi);
|
| 164 |
+
}
|
| 165 |
+
if (c.muted) {
|
| 166 |
+
const mi = document.createElement('i');
|
| 167 |
+
mi.className = 'bi bi-bell-slash';
|
| 168 |
+
mi.style.cssText = 'color:var(--md-sys-color-on-surface-variant);font-size:1rem';
|
| 169 |
+
title.appendChild(mi);
|
| 170 |
+
}
|
| 171 |
+
if (c.ai_pending) {
|
| 172 |
+
const dot = document.createElement('span');
|
| 173 |
+
dot.className = 'ai-dot';
|
| 174 |
+
dot.title = 'در حال آمادهسازی پاسخ';
|
| 175 |
+
title.appendChild(dot);
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
const meta = document.createElement('div');
|
| 179 |
+
meta.className = 'dialog-meta';
|
| 180 |
+
const pt = document.createElement('i');
|
| 181 |
+
pt.className = 'bi ' + (c.pinned ? 'bi-pin-angle-fill' : 'bi-pin-angle') + ' dialog-pin';
|
| 182 |
+
pt.onclick = e => { e.stopPropagation(); togglePin(c.id, !c.pinned); };
|
| 183 |
+
meta.appendChild(pt);
|
| 184 |
+
const time = document.createElement('span');
|
| 185 |
+
time.className = 'dialog-time';
|
| 186 |
+
time.textContent = c.time || '';
|
| 187 |
+
meta.appendChild(time);
|
| 188 |
+
|
| 189 |
+
row.appendChild(title);
|
| 190 |
+
row.appendChild(meta);
|
| 191 |
+
|
| 192 |
+
const sub = document.createElement('div');
|
| 193 |
+
sub.className = 'row-subtitle';
|
| 194 |
+
const subText = document.createElement('span');
|
| 195 |
+
subText.className = 'dialog-subtitle-inner';
|
| 196 |
+
subText.textContent = (c.last_sender ? c.last_sender + ': ' : '') + (c.last_text || '');
|
| 197 |
+
sub.appendChild(subText);
|
| 198 |
+
const ur = unreadPer[c.id] || 0;
|
| 199 |
+
if (ur > 0) {
|
| 200 |
+
const badge = document.createElement('span');
|
| 201 |
+
badge.className = 'badge dialog-subtitle-badge' + (c.muted ? ' muted' : '');
|
| 202 |
+
badge.textContent = ur > 99 ? '99+' : ur;
|
| 203 |
+
sub.appendChild(badge);
|
| 204 |
+
} else if (c.pinned) {
|
| 205 |
+
const pi = document.createElement('i');
|
| 206 |
+
pi.className = 'bi bi-pin-angle-fill';
|
| 207 |
+
pi.style.cssText = 'color:var(--md-sys-color-on-surface-variant);font-size:1rem';
|
| 208 |
+
sub.appendChild(pi);
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
info.appendChild(row);
|
| 212 |
+
info.appendChild(sub);
|
| 213 |
+
li.appendChild(av);
|
| 214 |
+
li.appendChild(info);
|
| 215 |
+
cont.appendChild(li);
|
| 216 |
+
});
|
| 217 |
+
}
|
static/js/composer.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function syncSendMic() {
|
| 2 |
+
const has = document.getElementById('msgIn').value.trim().length > 0;
|
| 3 |
+
document.getElementById('sendBtn').classList.toggle('d-none', !has);
|
| 4 |
+
document.getElementById('micBtn').classList.toggle('d-none', has);
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
async function sendMsg() {
|
| 8 |
+
const ta = document.getElementById('msgIn');
|
| 9 |
+
const txt = ta.value.trim();
|
| 10 |
+
if (!txt || !curChatId) return;
|
| 11 |
+
ta.value = ''; syncSendMic();
|
| 12 |
+
const selR = document.querySelector('input[name="sender"]:checked');
|
| 13 |
+
const senderMode = (selR && selR.value === 'me') ? 'me' : 'bot';
|
| 14 |
+
const body = { chatId: curChatId, text: txt, senderMode, businessConnectionId: curBizId };
|
| 15 |
+
if (replyTarget) body.replyToMsgId = replyTarget.msgId;
|
| 16 |
+
const res = await apiFetch('/api/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
| 17 |
+
cancelReply();
|
| 18 |
+
if (res?.error) showToast(res.error, 'error'); else { await fetchHistory(curChatId, false); scrollBot(true); }
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
function pickFile(acc, type) {
|
| 22 |
+
document.getElementById('attMenu').classList.remove('show');
|
| 23 |
+
const fi = document.getElementById('fileIn');
|
| 24 |
+
fi.accept = acc === '*' ? '' : acc;
|
| 25 |
+
fi.dataset.kind = type; fi.value = ''; fi.click();
|
| 26 |
+
}
|
| 27 |
+
async function onFilePick(e) {
|
| 28 |
+
const f = e.target.files[0];
|
| 29 |
+
if (!f || !curChatId) return;
|
| 30 |
+
await uploadMedia(f, e.target.dataset.kind, f.name);
|
| 31 |
+
}
|
| 32 |
+
async function uploadMedia(blob, type, name) {
|
| 33 |
+
const fd = new FormData();
|
| 34 |
+
fd.append('chatId', curChatId); fd.append('type', type); fd.append('file', blob, name);
|
| 35 |
+
const selR = document.querySelector('input[name="sender"]:checked');
|
| 36 |
+
const senderMode = (selR && selR.value === 'me') ? 'me' : 'bot';
|
| 37 |
+
fd.append('senderMode', senderMode);
|
| 38 |
+
if (curBizId) fd.append('businessConnectionId', curBizId);
|
| 39 |
+
if (replyTarget) fd.append('replyToMsgId', replyTarget.msgId);
|
| 40 |
+
const res = await apiFetch('/api/send-media', { method: 'POST', body: fd });
|
| 41 |
+
cancelReply();
|
| 42 |
+
if (res?.error) showToast(res.error, 'error'); else { await fetchHistory(curChatId, false); scrollBot(true); }
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// ---- voice recording ----
|
| 46 |
+
// Real tweb layout: cancel(×) — pill(dot + timer) — send(✓), every control
|
| 47 |
+
// live and clickable throughout the recording — not just a "لغو" text link
|
| 48 |
+
// with no way to actually send, which is what this replaces.
|
| 49 |
+
function recTimerText() {
|
| 50 |
+
const mn = Math.floor(recSec / 60), sc = recSec % 60;
|
| 51 |
+
return mn + ':' + String(sc).padStart(2, '0');
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
async function toggleRec() {
|
| 55 |
+
if (mrec && mrec.state === 'recording') { stopRec(true); return; }
|
| 56 |
+
if (!navigator.mediaDevices || !window.MediaRecorder) { showToast('مرورگر از ضبط صدا پشتیبانی نمیکند', 'warn'); return; }
|
| 57 |
+
try {
|
| 58 |
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 59 |
+
rchunks = [];
|
| 60 |
+
mrec = new MediaRecorder(stream, { mimeType: 'audio/webm;codecs=opus' });
|
| 61 |
+
mrec.ondataavailable = e => { if (e.data.size > 0) rchunks.push(e.data); };
|
| 62 |
+
mrec.start();
|
| 63 |
+
document.getElementById('inpRow').style.display = 'none';
|
| 64 |
+
document.getElementById('voiceRecPanel').classList.add('show');
|
| 65 |
+
recSec = 0;
|
| 66 |
+
document.getElementById('voiceRecTimer').textContent = recTimerText();
|
| 67 |
+
recInt = setInterval(() => { recSec++; document.getElementById('voiceRecTimer').textContent = recTimerText(); }, 1000);
|
| 68 |
+
} catch (e) {
|
| 69 |
+
showToast('دسترسی به میکروفون رد شد', 'warn');
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
function cancelRec() { stopRec(false); }
|
| 73 |
+
function stopRec(send) {
|
| 74 |
+
if (!mrec) return;
|
| 75 |
+
const doSend = send;
|
| 76 |
+
mrec.onstop = () => {
|
| 77 |
+
clearInterval(recInt);
|
| 78 |
+
document.getElementById('voiceRecPanel').classList.remove('show');
|
| 79 |
+
document.getElementById('inpRow').style.display = 'flex';
|
| 80 |
+
if (doSend && rchunks.length) {
|
| 81 |
+
const blob = new Blob(rchunks, { type: 'audio/webm' });
|
| 82 |
+
uploadMedia(blob, 'voice', 'voice.webm');
|
| 83 |
+
}
|
| 84 |
+
mrec = null;
|
| 85 |
+
};
|
| 86 |
+
mrec.stream.getTracks().forEach(t => t.stop());
|
| 87 |
+
mrec.stop();
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// ---- emoji picker ----
|
| 91 |
+
// Real tweb source: assets/emoji_test.js category groupings, condensed to
|
| 92 |
+
// the 8 top-level categories the dropdown itself uses.
|
| 93 |
+
const EMOJI_CATS = [
|
| 94 |
+
{ icon: "😊", name: "smileys", emojis: ["😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊","😇","🥰","😍","🤩","😘","😗","☺","😚","😙","🥲","😋","😛","😜","🤪","😝","🤑","🤗","🤭","🤫","🤔","🤐","🤨","😐","😑","😶","😏","😒","🙄","😬","🤥","😌","😔","😪","🤤","😴","😷","🤒","🤕","🤢","🤮","🤧","🥵","🥶","🥴","😵","💫","🤯","🤠","🥳","🥸","😎","🤓","🧐","😕","😟","🙁","☹","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠","���","🤡","👹","👺","👻","👽","👾","🤖","🫨","😵💫","🫠","🫡"] },
|
| 95 |
+
{ icon: "👋", name: "hands", emojis: ["👋","🤚","🖐","✋","🖖","👌","🤌","🤏","✌","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","✍","💅","🤳","💪","🦾","🦵","🦿","🦶","👂","🦻","👃","🫀","🫁","🧠","🦷","🦴","👀","👁","👅","👄","🫦"] },
|
| 96 |
+
{ icon: "🐶", name: "animals", emojis: ["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐻❄️","🐨","🐯","🦁","🐮","🐷","🐽","🐸","🐵","🙈","🙉","🙊","🐒","🐔","🐧","🐦","🐤","🦆","🦅","🦉","🦇","🐺","🐗","🐴","🦄","🐝","🪱","🐛","🦋","🐌","🐞","🐜","🪲","🦟","🦗","🪳","🕷","🦂","🐢","🐍","🦎","🦖","🦕","🐙","🦑","🦐","🦞","🦀","🐡","🐠","🐟","🐬","🐳","🐋","🦈","🦭","🐊","🐅","🐆","🦓","🦍","🦧","🦣","🐘","🦛","🦏","🐪","🐫","🦒","🦘","🦬","🐃","🐂","🐄","🐎","🐖","🐏","🐑","🦙","🐐","🦌","🐕","🐩","🦮","🐕🦺","🐈","🐈⬛","🪶","🐓","🦃","🦤","🦚","🦜","🦢","🦩","🕊","🐇","🦝","🦨","🦡","🦫","🦦","🦥","🐁","🐀","🐿","🦔"] },
|
| 97 |
+
{ icon: "🍕", name: "food", emojis: ["🍏","🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🫐","🍈","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🥬","🥒","🌶","🫑","🧄","🧅","🥔","🌽","🥕","🫛","🧇","🥞","🧈","🍳","🥚","🧆","🥙","🧀","🍖","🍗","🥩","🥓","🌮","🌯","🫔","🧆","🥫","🍱","🍘","🍙","🍚","🍛","🍜","🍝","🍠","🍢","🍣","🍤","🍥","🥮","🍡","🥟","🥠","🥡","🦀","🦞","🦐","🦑","🦪","🍦","🍧","🍨","🍩","🍪","🎂","🍰","🧁","🥧","🍫","🍬","🍭","🍮","🍯","🍼","🥛","☕","🫖","🍵","🧃","🥤","🧋","🍶","🍺","🍻","🥂","🍷","🥃","🍸","🍹","🧉","🍾","🍴","🥄"] },
|
| 98 |
+
{ icon: "🎮", name: "activities", emojis: ["⚽","🏀","🏈","⚾","🥎","🎾","🏐","🏉","🥏","🎱","🪀","🏓","🏸","🏒","🏑","🥍","🏏","🪃","🥅","⛳","🪁","🏹","🎣","🤿","🥊","🥋","🎽","🛹","🛼","🛷","⛸","🥌","🎿","⛷","🏂","🪂","🏋","🤼","🤸","🤺","🏇","⛹","🤾","🏌","🏄","🚣","🧗","🚵","🚴","🏆","🥇","🥈","🥉","🏅","🎖","🏵","🎗","🎫","🎟","🎪","🤹","🎭","🩰","🎨","🎬","🎤","🎧","🎼","🎹","🥁","🪘","🎷","🎺","🎸","🪕","🎻","🎲","♟","🎯","🎳","🎮","🎰","🧩"] },
|
| 99 |
+
{ icon: "🚗", name: "travel", emojis: ["🚗","🚕","🚙","🚌","🚎","🏎","🚓","🚑","🚒","🚐","🛻","🚚","🚛","🚜","🏍","🛵","🛺","🚲","🛴","🛹","🚏","🛣","🛤","⛽","🚦","🚥","🚧","⚓","🛟","⛵","🚤","🛥","🛳","⛴","🚢","✈","🛩","🛫","🛬","🪂","💺","🚁","🚟","🚠","🚡","🛰","🚀","🛸","🪐","💫","⭐","🌟","✨","⚡","☄","🌈","☀","🌤","⛅","🌦","🌧","⛈","🌩","🌨","❄","☃","⛄","🌬","💨","💧","💦","☔","☂","🌊","🌫"] },
|
| 100 |
+
{ icon: "💡", name: "objects", emojis: ["⌚","📱","📲","💻","⌨","🖥","🖨","🖱","🖲","🕹","🗜","💽","💾","💿","📀","📼","📷","📸","📹","🎥","📽","🎞","📞","☎","📟","📠","📺","📻","🧭","⏱","⏲","⏰","🕰","⌛","⏳","📡","🔋","🔌","💡","🔦","🕯","🪔","🧯","🛢","💰","💵","💴","💶","💷","💸","💳","🪙","💎","⚖","🪜","🧰","🪛","🔧","🔨","⚒","🛠","⛏","🪚","🔩","🪤","🧲","🔮","🪄","💈","🛒","🎁","🎀","🪅","🎊","🎉","🎎","🎏","🎐","🎑","🎃","🎄","🎆","🎇","🧧","🎈","🎋","🧨","✉","📩","📨","📧","📥","📤","📦","🏷","📪","📫","📬","📭","📮","📯","📜","📃","📄","📑","🧾","📊","📈","📉","🗒","🗓","📆","📅","🗑","📁","📂","🗂","🗃","🗄","🗑"] },
|
| 101 |
+
{ icon: "#️⃣", name: "symbols", emojis: ["❤","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣","💕","💞","💓","💗","💖","💘","💝","💟","☮","✝","☪","🕉","☸","✡","🔯","🕎","☯","☦","🛐","⛎","♈","♉","♊","♋","♌","♍","♎","♏","♐","♑","♒","♓","🆔","⚛","🉑","☢","☣","📴","📳","🈶","🈚","🈸","🈺","🈷","✴","🆚","💮","🉐","㊙","㊗","🈴","🈵","🈹","🈲","🅰","🅱","🆎","🆑","🅾","🆘","❌","⭕","🛑","⛔","📛","🚫","💯","💢","♨","🚷","🚯","🚳","🚱","🔞","📵","🚭","❗","❕","❓","❔","‼","⁉","🔅","🔆","〽","⚠","🚸","🔱","⚜","🔰","♻","✅","🈯","💹","❎","🌐","💠","Ⓜ","🌀","💤","🏧","🚾","♿","🅿","🛗","🈳","🈹","🈵","🉐","🈴","🉑","🈶","🈚","🎦","📶","🈸","🏬","����","🔁","🔂","▶","⏩","⏭","⏯","◀","⏪","⏮","🔼","⏫","🔽","⏬","⏸","⏹","⏺","⏏","🎵","🎶","➕","➖","➗","✖","♾","💲","💱","™","©","®","〰","➰","➿","🔚","🔙","🔛","🔝","🔜","✔","☑","🔲","🔳","⬛","⬜","◼","◻","◾","◽","▪","▫","🔶","🔷","🔸","🔹","🔺","🔻","💠","🔘","🔵","🟤","⚫","🟣","🟢","🟡","🟠","🔴"] }
|
| 102 |
+
];
|
| 103 |
+
|
| 104 |
+
// ---- most-recently/most-used emoji tracking (localStorage) ----
|
| 105 |
+
// A "🕐 اخیر" category is prepended, sorted by click count descending —
|
| 106 |
+
// the emoji you actually use rise to the top over time.
|
| 107 |
+
const EMOJI_FREQ_KEY = 'tg_emoji_freq';
|
| 108 |
+
function getEmojiFreq() {
|
| 109 |
+
try { return JSON.parse(localStorage.getItem(EMOJI_FREQ_KEY) || '{}'); } catch (e) { return {}; }
|
| 110 |
+
}
|
| 111 |
+
function bumpEmojiFreq(em) {
|
| 112 |
+
const f = getEmojiFreq();
|
| 113 |
+
f[em] = (f[em] || 0) + 1;
|
| 114 |
+
localStorage.setItem(EMOJI_FREQ_KEY, JSON.stringify(f));
|
| 115 |
+
}
|
| 116 |
+
function recentEmojiList() {
|
| 117 |
+
const f = getEmojiFreq();
|
| 118 |
+
return Object.keys(f).sort((a, b) => f[b] - f[a]).slice(0, 40);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function buildEmojiPicker() {
|
| 122 |
+
const cats = document.getElementById('emojiCats');
|
| 123 |
+
cats.innerHTML = '';
|
| 124 |
+
const recent = recentEmojiList();
|
| 125 |
+
const allCats = recent.length ? [{ icon: '🕐', name: 'recent', emojis: recent }, ...EMOJI_CATS] : EMOJI_CATS;
|
| 126 |
+
allCats.forEach((c, i) => {
|
| 127 |
+
const span = document.createElement('span');
|
| 128 |
+
span.className = 'ec' + (i === 0 ? ' active' : '');
|
| 129 |
+
span.textContent = c.icon;
|
| 130 |
+
span.onclick = () => switchEmojiCat(i, allCats);
|
| 131 |
+
cats.appendChild(span);
|
| 132 |
+
});
|
| 133 |
+
applyEmojiImages(cats);
|
| 134 |
+
renderEmojiCat(0, allCats);
|
| 135 |
+
}
|
| 136 |
+
function switchEmojiCat(i, cats) {
|
| 137 |
+
curEmojiCat = i;
|
| 138 |
+
document.querySelectorAll('.ec').forEach((e, j) => e.classList.toggle('active', j === i));
|
| 139 |
+
renderEmojiCat(i, cats || [{ emojis: recentEmojiList() }, ...EMOJI_CATS]);
|
| 140 |
+
}
|
| 141 |
+
function renderEmojiCat(i, cats) {
|
| 142 |
+
const list = (cats || EMOJI_CATS)[i];
|
| 143 |
+
const grid = document.getElementById('emojiGrid');
|
| 144 |
+
grid.innerHTML = '';
|
| 145 |
+
(list.emojis || []).forEach(em => {
|
| 146 |
+
const s = document.createElement('span');
|
| 147 |
+
s.textContent = em;
|
| 148 |
+
s.onclick = () => {
|
| 149 |
+
bumpEmojiFreq(em);
|
| 150 |
+
const ta = document.getElementById('msgIn');
|
| 151 |
+
ta.value += em; ta.dispatchEvent(new Event('input'));
|
| 152 |
+
};
|
| 153 |
+
grid.appendChild(s);
|
| 154 |
+
});
|
| 155 |
+
applyEmojiImages(grid);
|
| 156 |
+
}
|
| 157 |
+
function toggleEmojiPicker() {
|
| 158 |
+
emojiOpen = !emojiOpen;
|
| 159 |
+
if (emojiOpen) buildEmojiPicker(); // ~150 emoji: built on open (also refreshes the "recent" tab), not at page load
|
| 160 |
+
document.getElementById('emojiPicker').classList.toggle('show', emojiOpen);
|
| 161 |
+
if (emojiOpen) { document.getElementById('stickerPicker').classList.remove('show'); stickerOpen = false; }
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
// ---- sticker / GIF panel ----
|
| 165 |
+
// The Bot API has no "search/browse all stickers" call — only a known
|
| 166 |
+
// pack's getStickerSet, plus whatever the admin has actually sent before
|
| 167 |
+
// (tracked server-side as "recent"). Clicking a tile resends it by
|
| 168 |
+
// file_id (no re-upload needed).
|
| 169 |
+
var stickerOpen = false;
|
| 170 |
+
var stickerTab = 'sticker';
|
| 171 |
+
|
| 172 |
+
function toggleStickerPicker() {
|
| 173 |
+
stickerOpen = !stickerOpen;
|
| 174 |
+
document.getElementById('stickerPicker').classList.toggle('show', stickerOpen);
|
| 175 |
+
if (stickerOpen) {
|
| 176 |
+
document.getElementById('emojiPicker').classList.remove('show'); emojiOpen = false;
|
| 177 |
+
loadStickerPanel();
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
function switchStickerTab(tab) {
|
| 181 |
+
stickerTab = tab;
|
| 182 |
+
document.querySelectorAll('.sk-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === tab));
|
| 183 |
+
loadStickerPanel();
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
async function loadStickerPanel() {
|
| 187 |
+
const grid = document.getElementById('stickerGrid');
|
| 188 |
+
grid.innerHTML = '<div class="sk-empty">در حال بارگذاری...</div>';
|
| 189 |
+
const items = [];
|
| 190 |
+
|
| 191 |
+
if (stickerTab === 'sticker') {
|
| 192 |
+
const recent = await apiFetch('/api/recent-media?type=sticker');
|
| 193 |
+
(recent || []).forEach(s => items.push({ file_id: s.file_id, emoji: s.emoji || '🎭', kind: 'sticker' }));
|
| 194 |
+
const gs = await apiFetch('/api/settings');
|
| 195 |
+
const packs = (gs?.sticker_packs || '').split(',').map(s => s.trim()).filter(Boolean);
|
| 196 |
+
for (const packName of packs) {
|
| 197 |
+
const set = await apiFetch('/api/sticker-set?name=' + encodeURIComponent(packName));
|
| 198 |
+
if (set && !set.error) (set.stickers || []).forEach(s => items.push({ file_id: s.file_id, emoji: s.emoji || '🎭', kind: 'sticker' }));
|
| 199 |
+
}
|
| 200 |
+
} else {
|
| 201 |
+
const recent = await apiFetch('/api/recent-media?type=animation');
|
| 202 |
+
(recent || []).forEach(g => items.push({ file_id: g.file_id, kind: 'animation' }));
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
grid.innerHTML = '';
|
| 206 |
+
if (!items.length) {
|
| 207 |
+
grid.innerHTML = '<div class="sk-empty">' + (stickerTab === 'sticker'
|
| 208 |
+
? 'موردی نیست — یا یه استیکر از منوی پیوست بفرست تا اینجا ذخیره بشه، یا توی تنظیمات یه پک ��ستیکر معرفی کن.'
|
| 209 |
+
: 'موردی نیست — یه GIF از منوی پیوست بفرست تا اینجا ذخیره بشه.') + '</div>';
|
| 210 |
+
return;
|
| 211 |
+
}
|
| 212 |
+
items.forEach(it => {
|
| 213 |
+
const tile = document.createElement('div'); tile.className = 'sk-tile';
|
| 214 |
+
if (it.kind === 'sticker') {
|
| 215 |
+
// same byte-sniffing renderer the chat bubbles use — this is
|
| 216 |
+
// what actually makes animated (.tgs) stickers animate in the
|
| 217 |
+
// picker instead of just showing their assigned emoji.
|
| 218 |
+
renderSticker(tile, it.file_id, it.emoji);
|
| 219 |
+
} else {
|
| 220 |
+
const v = document.createElement('video'); v.src = murl(it.file_id);
|
| 221 |
+
v.autoplay = true; v.loop = true; v.muted = true; v.playsInline = true;
|
| 222 |
+
tile.appendChild(v);
|
| 223 |
+
}
|
| 224 |
+
tile.onclick = () => sendStickerFromPanel(it.file_id, it.kind, it.emoji);
|
| 225 |
+
grid.appendChild(tile);
|
| 226 |
+
});
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
async function sendStickerFromPanel(fileId, kind, emoji) {
|
| 230 |
+
if (!curChatId) return;
|
| 231 |
+
const selR = document.querySelector('input[name="sender"]:checked');
|
| 232 |
+
const senderMode = (selR && selR.value === 'me') ? 'me' : 'bot';
|
| 233 |
+
const body = { chatId: curChatId, fileId, type: kind, senderMode, businessConnectionId: curBizId, emoji };
|
| 234 |
+
if (replyTarget) body.replyToMsgId = replyTarget.msgId;
|
| 235 |
+
const res = await apiFetch('/api/send-sticker', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
| 236 |
+
cancelReply();
|
| 237 |
+
if (res?.error) showToast(res.error, 'error'); else { await fetchHistory(curChatId, false); scrollBot(true); }
|
| 238 |
+
}
|
static/js/ripple.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Material Design 3 touch ripple.
|
| 2 |
+
// One delegated pointer listener for the whole app: on press it drops an expanding
|
| 3 |
+
// circle (from the touch point) inside a clipped wrapper in the pressed element and
|
| 4 |
+
// fades it on release. The hover/focus/press "state layer" is pure CSS (base.css).
|
| 5 |
+
(function () {
|
| 6 |
+
const HOSTS = [
|
| 7 |
+
'.icon-btn', '.btn', '.fab', '.chatlist-chat', '.view-btn', '.ftab', '.sp-list-row', '.mcm-item', '.att-menu .opt', '.pa-btn',
|
| 8 |
+
'.u-btn', '.tbb', '.pm-tab', '.pm-media-row', '.ec', '.load-older-btn', '.send-btn', '.scroll-btn', '.voice-rec-cancel',
|
| 9 |
+
'.voice-rec-send', '.react-expand', '.sk-tile', '.gi-member', '.chat-info-container', '.auth-link', '.btn-close', '.mp-play'
|
| 10 |
+
].join(',');
|
| 11 |
+
const MAX_ACTIVE = 4; // never stack unbounded ripples on a slow phone
|
| 12 |
+
|
| 13 |
+
function start(e) {
|
| 14 |
+
if (e.button > 0) return; // primary button / touch only
|
| 15 |
+
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
| 16 |
+
const host = e.target.closest && e.target.closest(HOSTS);
|
| 17 |
+
if (!host || host.disabled || host.classList.contains('disabled')) return;
|
| 18 |
+
|
| 19 |
+
let wrap = host.querySelector(':scope > .md-ripple-wrap');
|
| 20 |
+
if (!wrap) {
|
| 21 |
+
if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
|
| 22 |
+
wrap = document.createElement('span');
|
| 23 |
+
wrap.className = 'md-ripple-wrap';
|
| 24 |
+
host.appendChild(wrap);
|
| 25 |
+
}
|
| 26 |
+
if (wrap.childElementCount >= MAX_ACTIVE) return;
|
| 27 |
+
|
| 28 |
+
const r = host.getBoundingClientRect();
|
| 29 |
+
const centered = host.classList.contains('icon-btn') || host.classList.contains('fab') || host.classList.contains('send-btn') ||
|
| 30 |
+
host.classList.contains('scroll-btn') || host.classList.contains('tbb') || host.classList.contains('btn-close');
|
| 31 |
+
const x = centered ? r.width / 2 : e.clientX - r.left;
|
| 32 |
+
const y = centered ? r.height / 2 : e.clientY - r.top;
|
| 33 |
+
const d = 2 * Math.hypot(Math.max(x, r.width - x), Math.max(y, r.height - y)); // reaches the farthest corner
|
| 34 |
+
|
| 35 |
+
const rip = document.createElement('span');
|
| 36 |
+
rip.className = 'md-ripple';
|
| 37 |
+
rip.style.cssText = `width:${d}px;height:${d}px;left:${x - d / 2}px;top:${y - d / 2}px`;
|
| 38 |
+
wrap.appendChild(rip);
|
| 39 |
+
|
| 40 |
+
let released = false, grown = false;
|
| 41 |
+
const fade = () => {
|
| 42 |
+
if (!released || !grown) return;
|
| 43 |
+
rip.classList.add('release');
|
| 44 |
+
setTimeout(() => rip.remove(), 340);
|
| 45 |
+
};
|
| 46 |
+
rip.addEventListener('animationend', () => { grown = true; fade(); });
|
| 47 |
+
const up = () => {
|
| 48 |
+
released = true; fade();
|
| 49 |
+
window.removeEventListener('pointerup', up, true);
|
| 50 |
+
window.removeEventListener('pointercancel', up, true);
|
| 51 |
+
window.removeEventListener('pointerleave', up, true);
|
| 52 |
+
};
|
| 53 |
+
window.addEventListener('pointerup', up, true);
|
| 54 |
+
window.addEventListener('pointercancel', up, true);
|
| 55 |
+
window.addEventListener('pointerleave', up, true);
|
| 56 |
+
setTimeout(up, 1500); // safety: never leave a ripple stuck
|
| 57 |
+
}
|
| 58 |
+
document.addEventListener('pointerdown', start, { passive: true });
|
| 59 |
+
})();
|
static/js/sidebar.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function switchView(v) {
|
| 2 |
+
activeView = v;
|
| 3 |
+
document.querySelectorAll('.view-btn').forEach(b => b.classList.toggle('active', b.dataset.view === v));
|
| 4 |
+
lastChatsHash = '';
|
| 5 |
+
renderChatList(allChats);
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
function setTab(t) {
|
| 9 |
+
activeTab = t;
|
| 10 |
+
document.querySelectorAll('.ftab').forEach(b => b.classList.toggle('active', b.dataset.tab === t));
|
| 11 |
+
lastChatsHash = '';
|
| 12 |
+
renderChatList(allChats);
|
| 13 |
+
}
|
static/js/state.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Shared mutable state. Every static/js/*.js file (and the remaining inline
|
| 2 |
+
// script in index.html) reads/writes these as plain globals — this file is
|
| 3 |
+
// the single place they're declared, so later phases just add to it instead
|
| 4 |
+
// of each file guessing its own copy.
|
| 5 |
+
var PASS = localStorage.getItem("TG_PASS") || "";
|
| 6 |
+
var curChatId = null, curBizId = null, allChats = [], pollerID = null, pollMs = 3000;
|
| 7 |
+
var lastHistHash = "", unreadCnt = 0, unreadPer = {}, lastChatText = {}, firstPoll = true, lastChatsHash = "";
|
| 8 |
+
var replyTarget = null, activeTab = "all", activeView = "bot";
|
| 9 |
+
var mrec = null, rchunks = [], recInt = null, recSec = 0;
|
| 10 |
+
var isGroup = false;
|
| 11 |
+
var gmodOpen = false;
|
| 12 |
+
var emojiOpen = false;
|
| 13 |
+
var gmodChatId = null;
|
| 14 |
+
var curEmojiCat = 0;
|
| 15 |
+
|
| 16 |
+
// Apple devices already render their own (good) native emoji — the ask was
|
| 17 |
+
// specifically "Telegram/iPhone style, not some other ugly pack", so on
|
| 18 |
+
// Apple platforms we leave native rendering alone entirely and only swap
|
| 19 |
+
// in Twemoji images on platforms whose native emoji font looks worse
|
| 20 |
+
// (Windows, and especially Samsung's own Android font, which was the
|
| 21 |
+
// original complaint).
|
| 22 |
+
var IS_APPLE_PLATFORM = /Mac|iPhone|iPod|iPad/.test(navigator.platform || navigator.userAgent || '');
|
| 23 |
+
function applyEmojiImages(el) {
|
| 24 |
+
if (IS_APPLE_PLATFORM || !window.twemoji) return;
|
| 25 |
+
twemoji.parse(el, { folder: 'svg', ext: '.svg', attributes: () => ({ loading: 'lazy', decoding: 'async' }) });
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
// M3 snackbar — replaces every alert() in the app. type is 'error', 'warn' or
|
| 29 |
+
// 'success'; auto-closes after 2s or on clicking the × button, whichever is first.
|
| 30 |
+
function showToast(msg, type, ms) {
|
| 31 |
+
const host = document.getElementById('toastHost');
|
| 32 |
+
if (!host) { console.log(msg); return; }
|
| 33 |
+
const t = document.createElement('div');
|
| 34 |
+
t.className = 'snackbar ' + (type || 'error');
|
| 35 |
+
const span = document.createElement('span'); span.className = 'sb-msg'; span.textContent = msg;
|
| 36 |
+
const close = document.createElement('button'); close.className = 'sb-close'; close.innerHTML = '<i class="bi bi-x-lg"></i>';
|
| 37 |
+
t.append(span, close);
|
| 38 |
+
host.appendChild(t);
|
| 39 |
+
let done = false;
|
| 40 |
+
const dismiss = () => {
|
| 41 |
+
if (done) return; done = true;
|
| 42 |
+
t.classList.remove('in'); t.classList.add('out');
|
| 43 |
+
setTimeout(() => t.remove(), 160);
|
| 44 |
+
};
|
| 45 |
+
close.onclick = dismiss;
|
| 46 |
+
requestAnimationFrame(() => t.classList.add('in'));
|
| 47 |
+
setTimeout(dismiss, ms || 2000);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// Shorthand for the extremely common "if (res.success) toast success else
|
| 51 |
+
// toast res.error" pattern that most API calls in this app follow.
|
| 52 |
+
function toastResult(res, successMsg) {
|
| 53 |
+
if (res && res.success) showToast(successMsg, 'success');
|
| 54 |
+
else showToast((res && res.error) || 'خطا', 'error');
|
| 55 |
+
}
|
static/js/translations.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const TRANSLATIONS = {
|
| 2 |
+
fa: {
|
| 3 |
+
auth_title: 'پنل مدیریت تلگرام',
|
| 4 |
+
auth_subtitle: 'برای ورود رمز عبور را وارد کن',
|
| 5 |
+
auth_btn: 'ورود',
|
| 6 |
+
auth_error: 'رمز عبور اشتباه است',
|
| 7 |
+
settings_title: 'تنظیمات',
|
| 8 |
+
settings_ai: 'هوش مصنوعی',
|
| 9 |
+
settings_chat: 'تنظیمات چت',
|
| 10 |
+
settings_panel: 'پنل و اعلانها',
|
| 11 |
+
settings_bot: 'پروفایل ربات',
|
| 12 |
+
settings_about: 'درباره',
|
| 13 |
+
settings_ai_toggle: 'فعالسازی کلی AI',
|
| 14 |
+
settings_ai_model: 'مدل زبانی',
|
| 15 |
+
settings_ai_delay: 'تأخیر پاسخ دستهای (ثانیه)',
|
| 16 |
+
settings_ai_prompt: 'پرامپت پیشفرض',
|
| 17 |
+
settings_chat_anim: 'انیمیشن ایموجیها',
|
| 18 |
+
settings_chat_large: 'تک-ایموجی بزرگ و متحرک',
|
| 19 |
+
settings_chat_multi: 'انیمیشن در ایموجیهای چندتایی',
|
| 20 |
+
settings_panel_owner_id: 'آیدی عددی تلگرام شما (برای تشخیص پیامهایتان)',
|
| 21 |
+
settings_panel_stickers: 'پکهای استیکر پنل (نام کوتاه، با کاما جدا کن)',
|
| 22 |
+
settings_panel_poll: 'نرخ بروزرسانی (میلیثانیه)',
|
| 23 |
+
settings_panel_push: 'فعالسازی اعلان پسزمینه',
|
| 24 |
+
settings_bot_name: 'نام ربات',
|
| 25 |
+
settings_bot_short: 'توضیحات کوتاه',
|
| 26 |
+
settings_bot_desc: 'توضیحات کامل',
|
| 27 |
+
settings_save: 'ذخیره',
|
| 28 |
+
about_title: 'Telegram Web Admin',
|
| 29 |
+
about_desc: 'پنل مدیریت ربات/بیزینس تلگرام با ظاهر Telegram Web K',
|
| 30 |
+
about_model: 'مدل زبانی فعال',
|
| 31 |
+
about_ai_state: 'وضعیت AI',
|
| 32 |
+
sidebar_bot: 'ربات',
|
| 33 |
+
sidebar_biz: 'پیامهای من (Business)',
|
| 34 |
+
tab_all: 'همه',
|
| 35 |
+
tab_unread: 'خواندهنشده',
|
| 36 |
+
tab_pinned: 'پینشده',
|
| 37 |
+
tab_groups: 'گروهها',
|
| 38 |
+
no_chat: 'یک گفتگو را برای شروع انتخاب کنید',
|
| 39 |
+
hdr_id: 'شناسه',
|
| 40 |
+
new_chat_title: 'چت جدید',
|
| 41 |
+
new_chat_id: 'آیدی / یوزرنیم',
|
| 42 |
+
new_chat_msg: 'متن اولین پیام',
|
| 43 |
+
new_chat_btn: 'ارسال و شروع چت',
|
| 44 |
+
profile_title: 'پروفایل',
|
| 45 |
+
profile_pin: 'پین گفتگو',
|
| 46 |
+
profile_mute: 'بیصدا کردن',
|
| 47 |
+
profile_ai: 'پنل AI',
|
| 48 |
+
profile_delete: 'حذف گفتگو',
|
| 49 |
+
profile_id: 'شناسه',
|
| 50 |
+
profile_name: 'نام',
|
| 51 |
+
profile_username: 'یوزرنیم',
|
| 52 |
+
profile_bio: 'بیوگرافی',
|
| 53 |
+
profile_photo: 'عکس',
|
| 54 |
+
profile_video: 'ویدیو',
|
| 55 |
+
profile_voice: 'صوتی',
|
| 56 |
+
profile_doc: 'فایل',
|
| 57 |
+
group_title: 'عملیات گروه',
|
| 58 |
+
group_members: 'اعضا (فقط ادمینها — Bot API دسترسی به لیست کامل اعضا نداره)',
|
| 59 |
+
group_mgmt: 'مدیریت گروه',
|
| 60 |
+
group_mute: 'سکوت کاربر',
|
| 61 |
+
group_ban: 'بن کاربر',
|
| 62 |
+
group_unban: 'آنبن کاربر',
|
| 63 |
+
group_del_msg: 'حذف N پیام',
|
| 64 |
+
group_del_user: 'حذف پیامهای یک کاربر',
|
| 65 |
+
group_filter: 'فیلتر محتوا',
|
| 66 |
+
ctx_reply: 'ریپلای',
|
| 67 |
+
ctx_edit: 'ویرایش',
|
| 68 |
+
ctx_copy: 'کپی متن',
|
| 69 |
+
ctx_forward: 'فوروارد',
|
| 70 |
+
ctx_pin: 'پین پیام',
|
| 71 |
+
ctx_add_pack: 'افزودن به پک پنل',
|
| 72 |
+
ctx_delete: 'حذف',
|
| 73 |
+
lang_switch: 'زبان / Language',
|
| 74 |
+
search_placeholder: 'جستجو',
|
| 75 |
+
new_chat_placeholder: '123456789 یا @username',
|
| 76 |
+
first_msg_placeholder: 'سلام...',
|
| 77 |
+
generic_error: 'خطا در عملیات',
|
| 78 |
+
generic_success: 'عملیات با موفقیت انجام شد',
|
| 79 |
+
auth_placeholder: 'رمز عبور',
|
| 80 |
+
save_success: 'تنظیمات ذخیره شد',
|
| 81 |
+
delete_confirm: 'این گفتگو از پنل حذف شود؟',
|
| 82 |
+
edit_prompt: 'ویرایش پیام:',
|
| 83 |
+
user_id_prompt: 'آیدی عددی کاربر را وارد کن:',
|
| 84 |
+
loading: 'در حال بارگذاری...',
|
| 85 |
+
empty: 'موردی نیست',
|
| 86 |
+
ai_on: 'فعال',
|
| 87 |
+
ai_off: 'غیرفعال',
|
| 88 |
+
member_count: ' عضو',
|
| 89 |
+
creator: 'سازنده',
|
| 90 |
+
admin: 'ادمین',
|
| 91 |
+
chat_settings_title: 'تنظیمات AI این چت',
|
| 92 |
+
chat_settings_toggle: 'فعالسازی AI برای این چت',
|
| 93 |
+
chat_settings_prompt_label: 'پرامپت اختصاصی (خالی = پیشfindung)',
|
| 94 |
+
chat_settings_prompt_placeholder: 'دستورالعمل اختصاصی...'
|
| 95 |
+
},
|
| 96 |
+
en: {
|
| 97 |
+
auth_title: 'Telegram Admin Panel',
|
| 98 |
+
auth_subtitle: 'Enter password to login',
|
| 99 |
+
auth_btn: 'Login',
|
| 100 |
+
auth_error: 'Incorrect password',
|
| 101 |
+
settings_title: 'Settings',
|
| 102 |
+
settings_ai: 'AI Settings',
|
| 103 |
+
settings_chat: 'Chat Settings',
|
| 104 |
+
settings_panel: 'Panel & Notifications',
|
| 105 |
+
settings_bot: 'Bot Profile',
|
| 106 |
+
settings_about: 'About',
|
| 107 |
+
settings_ai_toggle: 'Enable Global AI',
|
| 108 |
+
settings_ai_model: 'Language Model',
|
| 109 |
+
settings_ai_delay: 'Batch Response Delay (sec)',
|
| 110 |
+
settings_ai_prompt: 'Default Prompt',
|
| 111 |
+
settings_chat_anim: 'Emoji Animations',
|
| 112 |
+
settings_chat_large: 'Large Animated Single Emoji',
|
| 113 |
+
settings_chat_multi: 'Multi-Emoji Animations',
|
| 114 |
+
settings_panel_owner_id: 'Your Telegram ID (for identification)',
|
| 115 |
+
settings_panel_stickers: 'Panel Sticker Packs (Short name, comma separated)',
|
| 116 |
+
settings_panel_poll: 'Refresh Rate (ms)',
|
| 117 |
+
settings_panel_push: 'Enable Background Notifications',
|
| 118 |
+
settings_bot_name: 'Bot Name',
|
| 119 |
+
settings_bot_short: 'Short Description',
|
| 120 |
+
settings_bot_desc: 'Full Description',
|
| 121 |
+
settings_save: 'Save',
|
| 122 |
+
about_title: 'Telegram Web Admin',
|
| 123 |
+
about_desc: 'Telegram Bot/Business management panel with Telegram Web K look',
|
| 124 |
+
about_model: 'Active Language Model',
|
| 125 |
+
about_ai_state: 'AI Status',
|
| 126 |
+
sidebar_bot: 'Bot',
|
| 127 |
+
sidebar_biz: 'My Messages (Business)',
|
| 128 |
+
tab_all: 'All',
|
| 129 |
+
tab_unread: 'Unread',
|
| 130 |
+
tab_pinned: 'Pinned',
|
| 131 |
+
tab_groups: 'Groups',
|
| 132 |
+
no_chat: 'Select a chat to start',
|
| 133 |
+
hdr_id: 'ID',
|
| 134 |
+
new_chat_title: 'New Chat',
|
| 135 |
+
new_chat_id: 'ID / Username',
|
| 136 |
+
new_chat_msg: 'First message text',
|
| 137 |
+
new_chat_btn: 'Send & Start Chat',
|
| 138 |
+
profile_title: 'Profile',
|
| 139 |
+
profile_pin: 'Pin Chat',
|
| 140 |
+
profile_mute: 'Mute Chat',
|
| 141 |
+
profile_ai: 'AI Panel',
|
| 142 |
+
profile_delete: 'Delete Chat',
|
| 143 |
+
profile_id: 'ID',
|
| 144 |
+
profile_name: 'Name',
|
| 145 |
+
profile_username: 'Username',
|
| 146 |
+
profile_bio: 'Biography',
|
| 147 |
+
profile_photo: 'Photos',
|
| 148 |
+
profile_video: 'Videos',
|
| 149 |
+
profile_voice: 'Voice',
|
| 150 |
+
profile_doc: 'Documents',
|
| 151 |
+
group_title: 'Group Operations',
|
| 152 |
+
group_members: 'Members (Admins only — Bot API limits)',
|
| 153 |
+
group_mgmt: 'Group Management',
|
| 154 |
+
group_mute: 'Mute User',
|
| 155 |
+
group_ban: 'Ban User',
|
| 156 |
+
group_unban: 'Unban User',
|
| 157 |
+
group_del_msg: 'Delete N messages',
|
| 158 |
+
group_del_user: 'Delete user messages',
|
| 159 |
+
group_filter: 'Content Filter',
|
| 160 |
+
ctx_reply: 'Reply',
|
| 161 |
+
ctx_edit: 'Edit',
|
| 162 |
+
ctx_copy: 'Copy Text',
|
| 163 |
+
ctx_forward: 'Forward',
|
| 164 |
+
ctx_pin: 'Pin Message',
|
| 165 |
+
ctx_add_pack: 'Add to Panel Pack',
|
| 166 |
+
ctx_delete: 'Delete',
|
| 167 |
+
lang_switch: 'Language / زبان',
|
| 168 |
+
search_placeholder: 'Search',
|
| 169 |
+
new_chat_placeholder: '123456789 or @username',
|
| 170 |
+
first_msg_placeholder: 'Hello...',
|
| 171 |
+
generic_error: 'Operation failed',
|
| 172 |
+
generic_success: 'Operation successful',
|
| 173 |
+
auth_placeholder: 'Password',
|
| 174 |
+
save_success: 'Settings saved',
|
| 175 |
+
delete_confirm: 'Delete this chat from panel?',
|
| 176 |
+
edit_prompt: 'Edit message:',
|
| 177 |
+
user_id_prompt: 'Enter user numeric ID:',
|
| 178 |
+
loading: 'Loading...',
|
| 179 |
+
empty: 'Nothing found',
|
| 180 |
+
ai_on: 'Enabled',
|
| 181 |
+
ai_off: 'Disabled',
|
| 182 |
+
member_count: ' members',
|
| 183 |
+
creator: 'Creator',
|
| 184 |
+
admin: 'Admin',
|
| 185 |
+
chat_settings_title: 'AI Settings for this chat',
|
| 186 |
+
chat_settings_toggle: 'Enable AI for this chat',
|
| 187 |
+
chat_settings_prompt_label: 'Custom Prompt (empty = default)',
|
| 188 |
+
chat_settings_prompt_placeholder: 'Custom instructions...'
|
| 189 |
+
}
|
| 190 |
+
};
|
static/js/ws.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ══════════════════════════════════════════════════════════════
|
| 2 |
+
// Live updates over WebSocket (server side: class Realtime + /ws in app.py).
|
| 3 |
+
//
|
| 4 |
+
// The socket carries *hints only* ("chat list changed", "chat X changed").
|
| 5 |
+
// On a hint we re-fetch through the normal ETag-cached REST calls, so there
|
| 6 |
+
// is one source of truth and a dropped socket can never leave the UI wrong.
|
| 7 |
+
// While the socket is healthy the old poller drops to a slow safety net
|
| 8 |
+
// (see startPoller in index.html); when it isn't, polling carries on as before.
|
| 9 |
+
//
|
| 10 |
+
// Also drives the Telegram-style connection bar:
|
| 11 |
+
// connecting → socket opening waiting → device has no network
|
| 12 |
+
// updating → connected, catching up on what was missed
|
| 13 |
+
// ══════════════════════════════════════════════════════════════
|
| 14 |
+
var wsLive = false; // true while an authenticated socket is open
|
| 15 |
+
|
| 16 |
+
(function () {
|
| 17 |
+
const STR = {
|
| 18 |
+
fa: { connecting: 'در حال اتصال…', waiting: 'منتظر اتصال به شبکه…', updating: 'در حال بهروزرسانی…' },
|
| 19 |
+
en: { connecting: 'Connecting…', waiting: 'Waiting for network…', updating: 'Updating…' },
|
| 20 |
+
ru: { connecting: 'Подключение…', waiting: 'Ожидание сети…', updating: 'Обновление…' }
|
| 21 |
+
};
|
| 22 |
+
let sock = null, tries = 0, retryTimer = null, watchdog = null, lastRx = 0, wanted = false, state = '';
|
| 23 |
+
|
| 24 |
+
function setState(s) {
|
| 25 |
+
if (s === state) return;
|
| 26 |
+
state = s;
|
| 27 |
+
const bar = document.getElementById('connStatus');
|
| 28 |
+
if (!bar) return;
|
| 29 |
+
const txt = (STR[document.documentElement.lang] || STR.fa)[s];
|
| 30 |
+
if (txt) document.getElementById('connText').textContent = txt;
|
| 31 |
+
bar.classList.toggle('show', !!txt);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function url() { return (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws'; }
|
| 35 |
+
|
| 36 |
+
function scheduleRetry() {
|
| 37 |
+
clearTimeout(retryTimer);
|
| 38 |
+
if (!wanted) return;
|
| 39 |
+
const base = Math.min(15000, 800 * Math.pow(2, tries++));
|
| 40 |
+
retryTimer = setTimeout(open, base + Math.random() * 400);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// Abandon the current socket without waiting for its close handshake — after a network
|
| 44 |
+
// drop a half-open socket can sit in OPEN/CLOSING for a minute and would block reconnecting.
|
| 45 |
+
function drop() {
|
| 46 |
+
const s = sock; sock = null; wsLive = false;
|
| 47 |
+
if (s) { s.onopen = s.onmessage = s.onclose = s.onerror = null; try { s.close(); } catch (e) {} }
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function lost() {
|
| 51 |
+
wsLive = false;
|
| 52 |
+
clearInterval(watchdog);
|
| 53 |
+
setState(navigator.onLine === false ? 'waiting' : 'connecting');
|
| 54 |
+
scheduleRetry();
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
async function catchUp() {
|
| 58 |
+
// anything that happened while we were disconnected
|
| 59 |
+
setState('updating');
|
| 60 |
+
try {
|
| 61 |
+
await Promise.all([fetchChats(true), curChatId ? fetchHistory(curChatId, true) : null]);
|
| 62 |
+
} catch (e) { /* the poller will retry */ }
|
| 63 |
+
if (wsLive) setState('');
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
function open() {
|
| 67 |
+
if (!wanted || !PASS) return;
|
| 68 |
+
if (sock && (sock.readyState === 0 || sock.readyState === 1)) return;
|
| 69 |
+
if (navigator.onLine === false) { setState('waiting'); return; }
|
| 70 |
+
setState('connecting');
|
| 71 |
+
let s;
|
| 72 |
+
try { s = new WebSocket(url()); } catch (e) { return scheduleRetry(); }
|
| 73 |
+
sock = s;
|
| 74 |
+
s.onopen = () => s.send(JSON.stringify({ t: 'auth', token: PASS }));
|
| 75 |
+
s.onmessage = ev => {
|
| 76 |
+
lastRx = Date.now();
|
| 77 |
+
let m; try { m = JSON.parse(ev.data); } catch (e) { return; }
|
| 78 |
+
if (m.t === 'hello') {
|
| 79 |
+
tries = 0; wsLive = true;
|
| 80 |
+
clearInterval(watchdog);
|
| 81 |
+
watchdog = setInterval(() => { if (Date.now() - lastRx > 70000) try { s.close(); } catch (e) {} }, 10000);
|
| 82 |
+
catchUp();
|
| 83 |
+
} else if (m.t === 'dirty') {
|
| 84 |
+
fetchChats(true);
|
| 85 |
+
if (curChatId && (m.chat || []).includes(String(curChatId))) fetchHistory(curChatId, true);
|
| 86 |
+
} else if (m.t === 'ping') {
|
| 87 |
+
try { s.send('{"t":"pong"}'); } catch (e) {}
|
| 88 |
+
} else if (m.t === 'unauthorized') {
|
| 89 |
+
wanted = false; // session is gone: stop retrying, REST 401 handling signs the user out
|
| 90 |
+
wsLive = false; setState('');
|
| 91 |
+
}
|
| 92 |
+
};
|
| 93 |
+
s.onclose = () => { if (sock === s) { sock = null; lost(); } };
|
| 94 |
+
s.onerror = () => { try { s.close(); } catch (e) {} };
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
// called once the user is signed in (startPoller)
|
| 98 |
+
window.wsConnect = function () { wanted = true; open(); };
|
| 99 |
+
|
| 100 |
+
window.addEventListener('online', () => { if (!wanted) return; drop(); clearTimeout(retryTimer); tries = 0; open(); });
|
| 101 |
+
window.addEventListener('offline', () => { if (!wanted) return; drop(); clearInterval(watchdog); clearTimeout(retryTimer); setState('waiting'); });
|
| 102 |
+
document.addEventListener('visibilitychange', () => {
|
| 103 |
+
if (document.hidden || !wanted) return;
|
| 104 |
+
if (wsLive) catchUp(); // coming back to the app: make sure nothing was missed
|
| 105 |
+
else { drop(); clearTimeout(retryTimer); tries = 0; open(); }
|
| 106 |
+
});
|
| 107 |
+
})();
|