levix-bot 4.9.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -1,1981 +0,0 @@
1
- /* Levix dashboard — plain browser JS, no framework, no build step.
2
- *
3
- * Everything it shows comes from /dashboard/api/*, which sits behind the same
4
- * session as this page. Every value rendered here started life as a WhatsApp
5
- * message (a note, a warning reason, a group subject), so it goes through
6
- * esc() before it touches innerHTML.
7
- */
8
-
9
- (() => {
10
- "use strict";
11
-
12
- // --- tiny helpers -------------------------------------------------------
13
-
14
- const $ = (selector, root = document) => root.querySelector(selector);
15
- const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
16
-
17
- const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
18
- const esc = (value) =>
19
- String(value ?? "").replace(/[&<>"']/g, (char) => ESCAPES[char]);
20
-
21
- const shortJid = (jid) => String(jid ?? "").split("@")[0];
22
-
23
- function timeAgo(ms) {
24
- if (!ms) return "—";
25
- const seconds = Math.max(0, (Date.now() - ms) / 1000);
26
- if (seconds < 60) return "just now";
27
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
28
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
29
- return `${Math.floor(seconds / 86400)}d ago`;
30
- }
31
-
32
- function humanUptime(seconds) {
33
- const days = Math.floor(seconds / 86400);
34
- const hours = Math.floor((seconds % 86400) / 3600);
35
- const minutes = Math.floor((seconds % 3600) / 60);
36
- if (days) return `${days}d ${hours}h`;
37
- if (hours) return `${hours}h ${minutes}m`;
38
- return `${minutes}m`;
39
- }
40
-
41
- function toast(message, kind = "") {
42
- const box = $("#toasts");
43
- const node = document.createElement("div");
44
- node.className = `toast ${kind}`;
45
- node.textContent = message;
46
- box.appendChild(node);
47
- setTimeout(() => node.remove(), 4200);
48
- }
49
-
50
- /**
51
- * Every call goes through here so an expired session sends the operator back
52
- * to the login page instead of leaving a dashboard that silently stops
53
- * updating.
54
- */
55
- async function api(path, options = {}) {
56
- const response = await fetch(`/dashboard/api${path}`, {
57
- headers: { "Content-Type": "application/json" },
58
- ...options,
59
- body: options.body ? JSON.stringify(options.body) : undefined,
60
- });
61
-
62
- if (response.status === 401) {
63
- window.location.assign("/");
64
- throw new Error("Session expired");
65
- }
66
-
67
- const data = await response.json().catch(() => ({}));
68
- if (!response.ok || data.success === false) {
69
- throw new Error(data.error || `Request failed (${response.status})`);
70
- }
71
- return data;
72
- }
73
-
74
- /** Wrap an action so a failure lands in a toast instead of the console. */
75
- function guard(fn) {
76
- return async (...args) => {
77
- try {
78
- await fn(...args);
79
- } catch (error) {
80
- toast(error.message, "error");
81
- }
82
- };
83
- }
84
-
85
- // --- theme --------------------------------------------------------------
86
-
87
- const THEME_KEY = "levix.theme";
88
-
89
- function applyTheme(theme) {
90
- document.documentElement.setAttribute("data-theme", theme);
91
- const button = $("#theme-btn");
92
- button.setAttribute(
93
- "aria-label",
94
- theme === "light" ? "Switch to dark theme" : "Switch to light theme"
95
- );
96
- button.setAttribute(
97
- "title",
98
- theme === "light" ? "Switch to dark theme" : "Switch to light theme"
99
- );
100
- try {
101
- localStorage.setItem(THEME_KEY, theme);
102
- } catch {
103
- /* private mode — the choice just won't stick */
104
- }
105
- }
106
-
107
- function initTheme() {
108
- let saved = "dark";
109
- try {
110
- saved = localStorage.getItem(THEME_KEY) || "dark";
111
- } catch {
112
- /* ignore */
113
- }
114
- applyTheme(saved);
115
- $("#theme-btn").addEventListener("click", () => {
116
- const next =
117
- document.documentElement.getAttribute("data-theme") === "light"
118
- ? "dark"
119
- : "light";
120
- applyTheme(next);
121
- });
122
- }
123
-
124
- // --- i18n -----------------------------------------------------------------
125
-
126
- const LANG_KEY = "levix_lang";
127
- let currentLang = "en";
128
-
129
- const I18N = {
130
- en: {
131
- overview: "Overview",
132
- connection: "Connection",
133
- commands: "Commands",
134
- ai: "AI & memory",
135
- groups: "Groups",
136
- roles: "Roles",
137
- data: "Tables",
138
- data_label: "Data",
139
- control: "Control",
140
- settings: "Settings",
141
- workspace: "Workspace",
142
- settings_sub: "Configure your bot options and AI models. Changes take effect immediately.",
143
- settings_tab_ai: "AI Assistant",
144
- settings_tab_general: "General",
145
- settings_tab_security: "Security",
146
- settings_tab_whatsapp: "WhatsApp Proxy",
147
- settings_tab_media: "Media & Storage",
148
- pw_heading: "Control panel password",
149
- pw_current: "Current password",
150
- pw_next: "New password",
151
- pw_change_btn: "Change password",
152
- pw_hint: "This password protects your dashboard. It is stored securely as a hash.",
153
- ai_wizard_title: "AI Provider Setup",
154
- ai_wizard_sub: "Choose which provider powers your assistant's chat responses.",
155
- provider_gemini: "Google Gemini",
156
- provider_gemini_desc: "Free key, native multimodal vision, and Google Search grounding.",
157
- provider_groq: "Groq",
158
- provider_groq_desc: "Ultra-fast Llama 3 & Whisper STT inference.",
159
- provider_openai: "OpenAI / Compatible",
160
- provider_openai_desc: "GPT-4o, OpenRouter, Together AI, or any compatible endpoint.",
161
- provider_ollama: "Ollama (Local)",
162
- provider_ollama_desc: "Self-hosted models running locally on your hardware.",
163
- provider_anthropic: "Anthropic Claude",
164
- provider_anthropic_desc: "Claude 3.5 & Sonnet reasoning models.",
165
- apply_preset: "Apply Preset",
166
- active_provider: "Active Provider",
167
- api_key: "API Key",
168
- base_url: "Base URL",
169
- model_name: "Model Name",
170
- capabilities_title: "Model Capabilities & Media",
171
- capabilities_sub: "Configure vision inspection and voice speech-to-text.",
172
- vision_toggle: "Vision & Image Analysis",
173
- vision_toggle_hint: "Allows the AI to inspect and understand photos sent in messages.",
174
- stt_title: "Voice Transcription (STT)",
175
- stt_hint: "Which engine transcribes voice messages when using !stt.",
176
- agent_mode_toggle: "Autonomous Agent Mode",
177
- agent_mode_hint: "Enables multi-turn tool calling (web search, memory, bot actions).",
178
- google_search_toggle: "Google Search Grounding",
179
- google_search_hint: "Allows Gemini to look up current live web data.",
180
- advanced_btn: "Advanced AI Settings…",
181
- ai_advanced_title: "Advanced AI Settings",
182
- save: "Save",
183
- saved: "Saved",
184
- saved_here: "saved here",
185
- default_val: "default",
186
- restart_to_apply: "restart to apply",
187
- not_set: "not set",
188
- cleared: "Cleared",
189
- clear: "Clear",
190
- done: "Done",
191
- close: "Close",
192
- supports_vision_badge: "Vision Supported",
193
- supports_audio_badge: "Audio/STT Ready",
194
- recommended: "Recommended",
195
- detected: "Detected",
196
- connected: "Connected",
197
- disconnected: "Disconnected",
198
- idle: "Idle",
199
- starting: "Starting…",
200
- linking: "Linking…",
201
- reconnecting: "Reconnecting…",
202
- unlink: "Unlink",
203
- start_bot: "Start",
204
- stop_bot: "Stop",
205
- reconnect_bot: "Reconnect to apply",
206
- },
207
- ar: {
208
- overview: "نظرة عامة",
209
- connection: "الاتصال",
210
- commands: "الأوامر",
211
- ai: "الذكاء الاصطناعي والذاكرة",
212
- groups: "المجموعات",
213
- roles: "الصلاحيات",
214
- data: "الجداول والبيانات",
215
- data_label: "البيانات",
216
- control: "التحكم",
217
- settings: "الإعدادات",
218
- workspace: "مساحة العمل",
219
- settings_sub: "لوحة التحكم المركزية لضبط إعدادات البوت والذكاء الاصطناعي. تُطبق التغييرات فوراً.",
220
- settings_tab_ai: "الذكاء الاصطناعي",
221
- settings_tab_general: "عام",
222
- settings_tab_security: "الأمان",
223
- settings_tab_whatsapp: "بروكسي واتساب",
224
- settings_tab_media: "الوسائط والتخزين",
225
- pw_heading: "كلمة مرور لوحة التحكم",
226
- pw_current: "كلمة المرور الحالية",
227
- pw_next: "كلمة المرور الجديدة",
228
- pw_change_btn: "تغيير كلمة المرور",
229
- pw_hint: "هذه الكلمة تحمي حساب واتساب المربوط. تُحفظ بشكل مشفر تماماً.",
230
- ai_wizard_title: "إعداد مزود الذكاء الاصطناعي",
231
- ai_wizard_sub: "اختر المزود والموديل الذي يشغّل محادثات المساعد الخاص بك.",
232
- provider_gemini: "جوجل جيميني",
233
- provider_gemini_desc: "مفتاح مجاني مع دعم فائق لقراءة الصور والبحث المباشر.",
234
- provider_groq: "جروك (Groq)",
235
- provider_groq_desc: "سرعة خارقة في الرد وتفريغ الصوت بموديلات Llama و Whisper.",
236
- provider_openai: "OpenAI / متوافق",
237
- provider_openai_desc: "موديلات GPT-4o أو OpenRouter أو Together ومختلف المزودات.",
238
- provider_ollama: "أولاما (محلي)",
239
- provider_ollama_desc: "موديلات تعمل محلياً على جهازك دون اتصال خارجي.",
240
- provider_anthropic: "أنثروبيك كلود",
241
- provider_anthropic_desc: "موديلات Claude 3.5 & Sonnet لقدرات تحليلية متقدمة.",
242
- apply_preset: "تطبيق الإعداد الجاهز",
243
- active_provider: "المزود النشط",
244
- api_key: "مفتاح API",
245
- base_url: "رابط الخدمة (Base URL)",
246
- model_name: "اسم الموديل",
247
- capabilities_title: "قدرات الموديل ومعالجة الوسائط",
248
- capabilities_sub: "تحديد ما إذا كان الموديل سيتعامل مع الصور والتسجيلات الصوتية.",
249
- vision_toggle: "تحليل وقراءة الصور (Vision)",
250
- vision_toggle_hint: "يسمح للذكاء الاصطناعي برؤية وفهم الصور والمستندات المرسلة في الشات.",
251
- stt_title: "تفريغ الصوتيات إلى نص (STT)",
252
- stt_hint: "المحرك المستخدم في تحويل الرسائل الصوتية لنصوص عند طلب !stt.",
253
- agent_mode_toggle: "وضع الوكيل الذكي (Agent Mode)",
254
- agent_mode_hint: "تفعيل البحث بالإنترنت، تسجيل الملاحظات في الذاكرة، وأدوات المجموعات.",
255
- google_search_toggle: "البحث الحي عبر جوجل",
256
- google_search_hint: "يتيح لموديل جيميني جلب أحدث المعلومات والأخبار الحية من محرك بحث جوجل.",
257
- advanced_btn: "إعدادات متقدمة للذكاء الاصطناعي…",
258
- ai_advanced_title: "إعدادات متقدمة للذكاء الاصطناعي",
259
- save: "حفظ",
260
- saved: "تم الحفظ بنجاح",
261
- saved_here: "محفوظ هنا",
262
- default_val: "افتراضي",
263
- restart_to_apply: "إعادة التشغيل للتطبيق",
264
- not_set: "غير محدد",
265
- cleared: "تم الحذف",
266
- clear: "مسح",
267
- done: "تم",
268
- close: "إغلاق",
269
- supports_vision_badge: "يدعم تحليل الصور",
270
- supports_audio_badge: "يدعم تفريغ الصوتيات",
271
- recommended: "موصى به",
272
- detected: "تم اكتشافه",
273
- connected: "متصل",
274
- disconnected: "غير متصل",
275
- idle: "خامل",
276
- starting: "جاري البدء…",
277
- linking: "جاري الربط…",
278
- reconnecting: "جاري إعادة الاتصال…",
279
- unlink: "إلغاء الربط",
280
- start_bot: "تشغيل",
281
- stop_bot: "إيقاف",
282
- reconnect_bot: "إعادة الاتصال لتطبيق التغييرات",
283
- },
284
- };
285
-
286
- function t(key) {
287
- return I18N[currentLang]?.[key] || I18N.en[key] || key;
288
- }
289
-
290
- function applyLang(lang) {
291
- currentLang = lang === "ar" ? "ar" : "en";
292
- document.documentElement.setAttribute("lang", currentLang);
293
- document.documentElement.setAttribute("dir", currentLang === "ar" ? "rtl" : "ltr");
294
- if (currentLang === "ar") {
295
- document.documentElement.classList.add("lang-ar");
296
- } else {
297
- document.documentElement.classList.remove("lang-ar");
298
- }
299
-
300
- const langTag = $("#lang-tag");
301
- if (langTag) {
302
- langTag.textContent = currentLang === "ar" ? "EN" : "عربي";
303
- }
304
- const langBtn = $("#lang-btn");
305
- if (langBtn) {
306
- const title = currentLang === "ar" ? "Switch to English" : "التبديل إلى العربية";
307
- langBtn.setAttribute("title", title);
308
- langBtn.setAttribute("aria-label", title);
309
- }
310
-
311
- try {
312
- localStorage.setItem(LANG_KEY, currentLang);
313
- } catch {}
314
-
315
- document.querySelectorAll("[data-i18n]").forEach((el) => {
316
- const key = el.getAttribute("data-i18n");
317
- const val = t(key);
318
- if (val) el.textContent = val;
319
- });
320
-
321
- document.querySelectorAll("[data-i18n-title]").forEach((el) => {
322
- const key = el.getAttribute("data-i18n-title");
323
- const val = t(key);
324
- if (val) el.setAttribute("title", val);
325
- });
326
-
327
- if (currentView && VIEWS[currentView]) {
328
- $("#page-title").textContent = t(currentView) || VIEWS[currentView].title;
329
- }
330
- }
331
-
332
- function initLang() {
333
- let chosen = "en";
334
- try {
335
- const saved = localStorage.getItem(LANG_KEY);
336
- if (saved === "ar" || saved === "en") chosen = saved;
337
- else {
338
- const nav = (navigator.languages && navigator.languages[0]) || navigator.language || "";
339
- if (nav.toLowerCase().startsWith("ar")) chosen = "ar";
340
- }
341
- } catch {}
342
- applyLang(chosen);
343
-
344
- $("#lang-btn")?.addEventListener("click", () => {
345
- applyLang(currentLang === "ar" ? "en" : "ar");
346
- if (currentView && VIEWS[currentView]?.load) {
347
- VIEWS[currentView].load().catch(() => {});
348
- }
349
- });
350
- }
351
-
352
- // --- routing ------------------------------------------------------------
353
-
354
- const VIEWS = {};
355
- let currentView = null;
356
-
357
- function setSidebar(open) {
358
- $(".sidebar").classList.toggle("open", open);
359
- $("#sidebar-backdrop").classList.toggle("open", open);
360
- $("#menu-btn").setAttribute("aria-expanded", String(open));
361
- $("#menu-btn").setAttribute(
362
- "aria-label",
363
- open ? "Close navigation" : "Open navigation"
364
- );
365
- }
366
-
367
- function show(name) {
368
- const target = VIEWS[name] ? name : "overview";
369
- currentView = target;
370
-
371
- $$(".view").forEach((view) =>
372
- view.classList.toggle("active", view.id === `view-${target}`)
373
- );
374
- $$(".nav a").forEach((link) => {
375
- const active = link.dataset.view === target;
376
- link.classList.toggle("active", active);
377
- if (active) link.setAttribute("aria-current", "page");
378
- else link.removeAttribute("aria-current");
379
- });
380
- $("#page-title").textContent = I18N[currentLang]?.[target] || VIEWS[target].title;
381
- setSidebar(false);
382
-
383
- VIEWS[target].load();
384
- }
385
-
386
- function initRouting() {
387
- $$(".nav a").forEach((link) => {
388
- link.addEventListener("click", (event) => {
389
- event.preventDefault();
390
- window.location.hash = link.dataset.view;
391
- });
392
- });
393
-
394
- window.addEventListener("hashchange", () =>
395
- show(window.location.hash.slice(1))
396
- );
397
- $("#menu-btn").addEventListener("click", () =>
398
- setSidebar(!$(".sidebar").classList.contains("open"))
399
- );
400
- $("#sidebar-backdrop").addEventListener("click", () => setSidebar(false));
401
- window.addEventListener("keydown", (event) => {
402
- if (event.key === "Escape") setSidebar(false);
403
- });
404
- $("#refresh-btn").addEventListener("click", () => {
405
- VIEWS[currentView].load();
406
- loadStats();
407
- });
408
- }
409
-
410
- // --- connection status --------------------------------------------------
411
- //
412
- // The backend owns the session (src/core/session.js); this file only draws
413
- // what it reports. Nothing here starts, stops or retries a connection on its
414
- // own, and closing this tab does not touch the bot.
415
-
416
- // What each backend state looks like: the pill class, the label, and the
417
- // sentence under the Connection card's heading.
418
- const SESSION_LABELS = {
419
- idle: { tone: "off", label: "Not started", tag: "danger", tagText: "Not started" },
420
- starting: { tone: "warn", label: "Connecting", tag: "warn", tagText: "Connecting" },
421
- waiting_for_qr: { tone: "warn", label: "Waiting to link", tag: "warn", tagText: "Waiting to link" },
422
- linking: { tone: "warn", label: "Linking", tag: "warn", tagText: "Linking" },
423
- connected: { tone: "on", label: "Connected", tag: "ok", tagText: "Linked" },
424
- reconnecting: { tone: "warn", label: "Reconnecting", tag: "warn", tagText: "Reconnecting" },
425
- disconnected: { tone: "off", label: "Disconnected", tag: "danger", tagText: "Disconnected" },
426
- retry_exhausted: { tone: "off", label: "Disconnected", tag: "danger", tagText: "Gave up reconnecting" },
427
- logged_out: { tone: "off", label: "Not linked", tag: "danger", tagText: "Not linked" },
428
- error: { tone: "off", label: "Error", tag: "danger", tagText: "Error" },
429
- };
430
-
431
- const describeSession = (state) =>
432
- SESSION_LABELS[state] || { tone: "off", label: "Disconnected", tag: "danger", tagText: "Disconnected" };
433
-
434
- // The last snapshot the backend sent. Every renderer reads this rather than
435
- // its own idea of what is going on, so the pill and the Connection card can
436
- // never disagree.
437
- let sessionSnapshot = null;
438
-
439
- function setStatus(snapshot) {
440
- if (!snapshot) return;
441
- sessionSnapshot = snapshot;
442
- const look = describeSession(snapshot.state);
443
- const pill = $("#status-pill");
444
- pill.className = `pill ${look.tone}`;
445
- pill.innerHTML = `<span class="dot"></span>${esc(look.label)}`;
446
- // Outside the `currentView` check: leaving the Connection screen while a
447
- // reconnect was pending used to leave the ticker running for the life of
448
- // the page, because only renderConnection() could ever stop it.
449
- syncRetryTicker(snapshot);
450
- if (currentView === "connection") renderConnection();
451
- }
452
-
453
- // --- overview -----------------------------------------------------------
454
-
455
- async function loadStats() {
456
- const { stats } = await api("/stats");
457
-
458
- // /stats carries the same session snapshot the socket pushes, so the poll
459
- // that runs every 15s refreshes the pill instead of flattening whatever the
460
- // last live event put there.
461
- setStatus(stats.connection);
462
-
463
- const cards = [
464
- ["Groups", stats.totalGroups, "Communities", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>'],
465
- ["Commands", stats.commandCount, "Available", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/></svg>'],
466
- ["Open debts", stats.totalDebts, "Unsettled", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" x2="12" y1="2" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>'],
467
- ["Warnings", stats.totalWarnings, "Issued", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg>'],
468
- ["Notes", stats.totalNotes, "Saved", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>'],
469
- ["Todo lists", stats.totalTodos, "Tracked", '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 11 3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>'],
470
- ];
471
-
472
- $("#stat-cards").innerHTML = cards
473
- .map(
474
- ([label, value, caption, icon]) => `
475
- <div class="stat">
476
- <div class="stat-top">
477
- <span class="stat-icon" aria-hidden="true">${icon}</span>
478
- <span class="label">${esc(label)}</span>
479
- </div>
480
- <div class="value">${esc(value ?? 0)}</div>
481
- <div class="stat-foot"><span>${esc(caption)}</span><i aria-hidden="true"></i></div>
482
- </div>`
483
- )
484
- .join("");
485
-
486
- const rows = [
487
- ["WhatsApp account", stats.botNumber ? shortJid(stats.botNumber) : "Not linked"],
488
- ["Command prefix", stats.prefix],
489
- ["AI key", stats.aiConfigured ? "Configured" : "Not set"],
490
- ["Database", stats.database ? "Connected" : "Down"],
491
- ["Uptime", humanUptime(stats.uptime)],
492
- ["Memory", `${(stats.memory.heapUsed / 1048576).toFixed(0)} MB`],
493
- ["Node", stats.nodeVersion],
494
- ];
495
-
496
- $("#overview-info").innerHTML = rows
497
- .map(
498
- ([label, value]) => `
499
- <div class="runtime-item">
500
- <div class="runtime-label">${esc(label)}</div>
501
- <div class="runtime-value">${esc(value)}</div>
502
- </div>`
503
- )
504
- .join("");
505
- }
506
-
507
- VIEWS.overview = {
508
- title: "Overview",
509
- load: guard(loadStats),
510
- };
511
-
512
- // --- connection ---------------------------------------------------------
513
-
514
- let qrRendered = null;
515
- let pairingRendered = null;
516
-
517
- function formatPairingCode(code) {
518
- const raw = String(code || "").replace(/\s|-/g, "");
519
- if (raw.length === 8) return `${raw.slice(0, 4)}-${raw.slice(4)}`;
520
- return raw;
521
- }
522
-
523
- function preferredPairMethod() {
524
- return /Android|iPhone|Mobile/i.test(navigator.userAgent) ? "pairing" : "qr";
525
- }
526
-
527
- function selectedPairMethod() {
528
- const picked = document.querySelector('input[name="pair-method"]:checked');
529
- return picked ? picked.value : preferredPairMethod();
530
- }
531
-
532
- function syncPairChooser() {
533
- const pairing = selectedPairMethod() === "pairing";
534
- const wrap = $("#pair-phone-wrap");
535
- if (wrap) wrap.hidden = !pairing;
536
- }
537
-
538
- function renderQr(text) {
539
- if (!text || qrRendered === text) return;
540
- qrRendered = text;
541
-
542
- const frame = $("#qr-frame");
543
- frame.innerHTML = "";
544
- // eslint-disable-next-line no-undef
545
- new QRCode(frame, {
546
- text,
547
- width: 240,
548
- height: 240,
549
- correctLevel: QRCode.CorrectLevel.H,
550
- });
551
- $("#qr-note").textContent = "Scan it from WhatsApp → Linked devices.";
552
- }
553
-
554
- function clearQr() {
555
- qrRendered = null;
556
- $("#qr-frame").innerHTML = "";
557
- $("#qr-note").textContent = "Waiting for a QR code…";
558
- }
559
-
560
- function renderPairingCode(code, phone) {
561
- if (!code || pairingRendered === code) return;
562
- pairingRendered = code;
563
- const el = $("#pairing-code");
564
- if (el) el.textContent = formatPairingCode(code);
565
- const phoneEl = $("#pairing-phone");
566
- if (phoneEl) {
567
- phoneEl.textContent = phone ? `For WhatsApp +${phone}` : "";
568
- }
569
- const note = $("#pairing-note");
570
- if (note) {
571
- note.textContent = "Link with phone number instead — not the QR camera.";
572
- }
573
- }
574
-
575
- function clearPairingCode() {
576
- pairingRendered = null;
577
- const el = $("#pairing-code");
578
- if (el) el.textContent = "••••-••••";
579
- const phoneEl = $("#pairing-phone");
580
- if (phoneEl) phoneEl.textContent = "";
581
- const note = $("#pairing-note");
582
- if (note) note.textContent = "Waiting for a pairing code…";
583
- }
584
-
585
- function retryHint(snapshot) {
586
- if (snapshot.state !== "reconnecting" || !snapshot.nextRetryAt) return "";
587
- const seconds = Math.max(0, Math.round((snapshot.nextRetryAt - Date.now()) / 1000));
588
- return ` Next attempt in ${seconds}s.`;
589
- }
590
-
591
- // A countdown that only ticks while there is one to show. Rendering it once
592
- // and leaving it would put a number on screen that stops being true a second
593
- // later.
594
- let retryTicker = null;
595
-
596
- function syncRetryTicker(snapshot) {
597
- const counting = snapshot.state === "reconnecting" && snapshot.nextRetryAt;
598
- if (counting && !retryTicker) {
599
- retryTicker = setInterval(() => {
600
- if (currentView === "connection") renderConnection();
601
- }, 1000);
602
- } else if (!counting && retryTicker) {
603
- clearInterval(retryTicker);
604
- retryTicker = null;
605
- }
606
- }
607
-
608
- /** Draw the Connection card from the last snapshot. No network call. */
609
- function renderConnection() {
610
- const snapshot = sessionSnapshot;
611
- if (!snapshot) return;
612
-
613
- const look = describeSession(snapshot.state);
614
- const who = snapshot.user?.id ? shortJid(snapshot.user.id) : "";
615
-
616
- $("#conn-state").innerHTML =
617
- `<span class="tag ${esc(look.tag)}">${esc(look.tagText)}</span>` +
618
- (who ? ` <span class="hint">${esc(who)}</span>` : "");
619
-
620
- $("#conn-detail").textContent = (snapshot.detail || "") + retryHint(snapshot);
621
-
622
- const alertBox = $("#conn-disconnect-alert");
623
- const alertText = $("#conn-disconnect-text");
624
- if (alertBox && alertText) {
625
- if (snapshot.lastDisconnect?.statusCode && snapshot.state !== "connected" && snapshot.state !== "idle") {
626
- const code = snapshot.lastDisconnect.statusCode;
627
- const reason = snapshot.lastDisconnect.reason || "Unknown";
628
- alertText.innerHTML = `⚠️ <strong>Connection failure (${esc(code)}: ${esc(reason)})</strong> — check network connectivity or proxy settings.`;
629
- alertBox.style.display = "block";
630
- } else {
631
- alertBox.style.display = "none";
632
- }
633
- }
634
-
635
- // The proxy line, and the one action that can apply a changed one. The
636
- // label is already redacted server-side — there is no password to leak
637
- // here because the browser was never told it.
638
- const proxyLine = $("#conn-proxy");
639
- if (snapshot.proxy) {
640
- proxyLine.textContent = `Connecting through ${snapshot.proxy}.`;
641
- } else if (snapshot.connected || snapshot.state === "waiting_for_qr") {
642
- proxyLine.textContent = "Connecting directly, with no proxy.";
643
- } else {
644
- proxyLine.textContent = "";
645
- }
646
- if (snapshot.proxyChanged) {
647
- proxyLine.textContent +=
648
- " The saved proxy settings differ from the connection in use — reconnect to apply them.";
649
- }
650
-
651
- // Only offered when it would do something: there has to be a live session
652
- // to replace, and a reason to replace it.
653
- const canReconnect = snapshot.canStop && snapshot.proxyChanged;
654
- $("#reconnect-btn").style.display = canReconnect ? "" : "none";
655
- $("#reconnect-btn").disabled = !canReconnect;
656
-
657
- // Buttons follow the backend, so a state that cannot accept an action
658
- // cannot be asked for one.
659
- $("#start-btn").disabled = !snapshot.canStart;
660
- $("#start-btn").textContent =
661
- snapshot.state === "logged_out" || snapshot.state === "idle"
662
- ? "Start session"
663
- : "Retry connection";
664
- $("#stop-btn").disabled = !snapshot.canStop;
665
- // Not "only while connected": a refused pairing leaves dead credentials
666
- // that can only be cleared by unlinking.
667
- $("#unlink-btn").disabled = !snapshot.canUnlink;
668
-
669
- const chooser = $("#pair-chooser");
670
- if (chooser) chooser.style.display = snapshot.canStart ? "" : "none";
671
-
672
- // Offer QR or pairing code only while a link attempt is actually waiting.
673
- const waiting = snapshot.state === "waiting_for_qr";
674
- $("#qr-panel").style.display = waiting ? "block" : "none";
675
- const showCode = waiting && (snapshot.hasPairingCode || snapshot.pairingMethod === "pairing");
676
- const qrBox = $("#qr-box");
677
- const pairingBox = $("#pairing-box");
678
- if (qrBox) qrBox.hidden = showCode;
679
- if (pairingBox) pairingBox.hidden = !showCode;
680
- if (!waiting) {
681
- clearQr();
682
- clearPairingCode();
683
- }
684
- }
685
-
686
- VIEWS.connection = {
687
- title: "Connection",
688
- // One request for the whole screen, including a QR that was already on
689
- // offer before this tab existed — a reload has to show the real backend
690
- // state, not an empty frame.
691
- load: guard(async () => {
692
- const { session, qr, pairingCode } = await api("/bot/session");
693
- setStatus(session);
694
- renderConnection();
695
- if (session.state === "waiting_for_qr") {
696
- if (pairingCode) renderPairingCode(pairingCode, session.pairingPhone);
697
- else if (qr) renderQr(qr);
698
- }
699
- }),
700
- };
701
-
702
- function confirmed(question, fn) {
703
- return guard(async () => {
704
- if (!confirm(question)) return;
705
- await fn();
706
- });
707
- }
708
-
709
- function initConnectionActions() {
710
- // Starting is idempotent on the server: a second click while a socket is
711
- // being made is answered with the state it is already in.
712
- $("#start-btn").addEventListener(
713
- "click",
714
- guard(async () => {
715
- // Disabled straight away so an impatient second click cannot even be
716
- // made, and put back from the backend's answer either way — a failed
717
- // request must not leave a dead button behind.
718
- $("#start-btn").disabled = true;
719
- try {
720
- const method = selectedPairMethod();
721
- const body = { method };
722
- if (method === "pairing") body.phone = ($("#pair-phone")?.value || "").trim();
723
- const { session } = await api("/bot/session/start", { method: "POST", body });
724
- setStatus(session);
725
- toast("Session starting…", "ok");
726
- } finally {
727
- renderConnection();
728
- }
729
- })
730
- );
731
-
732
- $("#reconnect-btn").addEventListener(
733
- "click",
734
- confirmed(
735
- "Reconnect WhatsApp now to apply the saved settings? The bot stops answering for a few seconds.",
736
- async () => {
737
- const { session } = await api("/bot/session/reconnect", { method: "POST" });
738
- setStatus(session);
739
- toast("Reconnecting with the new settings…", "ok");
740
- }
741
- )
742
- );
743
-
744
- $("#stop-btn").addEventListener(
745
- "click",
746
- confirmed(
747
- "Stop the WhatsApp session? The bot stops answering until you start it again. The pairing is kept.",
748
- async () => {
749
- const { session } = await api("/bot/session/stop", { method: "POST" });
750
- setStatus(session);
751
- toast("Session stopped.", "ok");
752
- }
753
- )
754
- );
755
-
756
- $("#unlink-btn").addEventListener(
757
- "click",
758
- confirmed(
759
- "Unlink this WhatsApp account? The bot stops answering until you start a new session and link again.",
760
- async () => {
761
- const { session } = await api("/bot/logout", { method: "POST" });
762
- setStatus(session);
763
- toast("Unlinked. Press Start session to pair again.", "ok");
764
- }
765
- )
766
- );
767
-
768
- $("#restart-btn").addEventListener(
769
- "click",
770
- confirmed(
771
- "Restart the bot? It only comes back on its own if it runs under a supervisor (pm2, systemd, Docker).",
772
- async () => {
773
- const data = await api("/bot/restart", { method: "POST" });
774
- toast(data.message || "Restarting…", "ok");
775
- }
776
- )
777
- );
778
- }
779
-
780
- // --- commands -----------------------------------------------------------
781
-
782
- let commandCache = [];
783
-
784
- function commandRow(command, levels) {
785
- const permissionCell = command.permissionLocked
786
- ? `<span class="locked" title="This command calls a WhatsApp admin action, so it always requires a group admin.">🔒 Group admin</span>`
787
- : `<select data-cmd="${esc(command.name)}" data-field="permission">
788
- ${levels
789
- .map(
790
- (level) =>
791
- `<option value="${esc(level)}"${level === command.permission ? " selected" : ""}>${esc(
792
- level.replace("_", " ").toLowerCase()
793
- )}</option>`
794
- )
795
- .join("")}
796
- </select>`;
797
-
798
- return `
799
- <tr>
800
- <td>
801
- <div class="cmd-name">${esc(command.name)}</div>
802
- <div class="hint">${esc(command.description || "")}</div>
803
- </td>
804
- <td>${command.category === "group" ? '<span class="tag info">group</span>' : '<span class="tag">general</span>'}</td>
805
- <td>
806
- <input type="text" class="alias-input" value="${esc(command.aliases.join(", "))}"
807
- data-cmd="${esc(command.name)}" data-field="aliases"
808
- placeholder="no aliases" />
809
- </td>
810
- <td>${permissionCell}</td>
811
- <td>
812
- <label class="switch">
813
- <input type="checkbox" data-cmd="${esc(command.name)}" data-field="enabled"
814
- ${command.enabled ? "checked" : ""} />
815
- <span class="track"></span>
816
- </label>
817
- </td>
818
- </tr>`;
819
- }
820
-
821
- function renderCommands() {
822
- const query = $("#cmd-search").value.trim().toLowerCase();
823
- const category = $("#cmd-filter").value;
824
-
825
- const rows = commandCache.commands.filter((command) => {
826
- if (category !== "all" && command.category !== category) return false;
827
- if (!query) return true;
828
- return (
829
- command.name.includes(query) ||
830
- command.aliases.some((alias) => alias.includes(query)) ||
831
- (command.description || "").toLowerCase().includes(query)
832
- );
833
- });
834
-
835
- $("#cmd-body").innerHTML = rows.length
836
- ? rows.map((command) => commandRow(command, commandCache.levels)).join("")
837
- : `<tr><td colspan="5"><div class="empty">Nothing matches that.</div></td></tr>`;
838
- }
839
-
840
- const patchCommand = guard(async (name, patch) => {
841
- const { command } = await api(`/commands/${encodeURIComponent(name)}`, {
842
- method: "PATCH",
843
- body: patch,
844
- });
845
- const index = commandCache.commands.findIndex((entry) => entry.name === name);
846
- if (index !== -1) commandCache.commands[index] = command;
847
- toast(`!${name} updated`, "ok");
848
- });
849
-
850
- VIEWS.commands = {
851
- title: "Commands",
852
- load: guard(async () => {
853
- commandCache = await api("/commands");
854
- $("#prefix-input").value = commandCache.prefix;
855
- renderCommands();
856
- }),
857
- };
858
-
859
- function initCommandActions() {
860
- $("#cmd-search").addEventListener("input", renderCommands);
861
- $("#cmd-filter").addEventListener("change", renderCommands);
862
-
863
- $("#prefix-save").addEventListener(
864
- "click",
865
- guard(async () => {
866
- const value = $("#prefix-input").value.trim();
867
- await api("/settings", { method: "PATCH", body: { key: "prefix", value } });
868
- toast(`Prefix is now "${value}"`, "ok");
869
- VIEWS.commands.load();
870
- })
871
- );
872
-
873
- // One listener for the whole table: the rows are re-rendered on every
874
- // search keystroke, so per-row handlers would have to be re-attached.
875
- const table = $("#cmd-body");
876
-
877
- table.addEventListener("change", (event) => {
878
- const target = event.target;
879
- const name = target.dataset?.cmd;
880
- if (!name) return;
881
-
882
- if (target.dataset.field === "permission") {
883
- patchCommand(name, { permission: target.value });
884
- } else if (target.dataset.field === "enabled") {
885
- patchCommand(name, { enabled: target.checked });
886
- } else if (target.dataset.field === "aliases") {
887
- const aliases = target.value
888
- .split(",")
889
- .map((alias) => alias.trim())
890
- .filter(Boolean);
891
- patchCommand(name, { aliases }).then(() => VIEWS.commands.load());
892
- }
893
- });
894
- }
895
-
896
- // --- AI -----------------------------------------------------------------
897
-
898
- let memoryScope = null;
899
-
900
- VIEWS.ai = {
901
- title: "AI",
902
- load: guard(async () => {
903
- const [{ persona }, { scopes }] = await Promise.all([
904
- api("/ai/persona"),
905
- api("/ai/memory"),
906
- ]);
907
-
908
- $("#persona-body").value = persona.body;
909
- $("#persona-file").textContent = persona.file;
910
-
911
- $("#memory-list").innerHTML = scopes.length
912
- ? scopes
913
- .map(
914
- (entry) => `
915
- <button class="btn btn-sm" type="button" data-scope="${esc(entry.scope)}">
916
- ${entry.scope === "global" ? "🌍" : "💬"} ${esc(entry.label)}
917
- <span class="hint">${esc(entry.entries)} entries</span>
918
- </button>`
919
- )
920
- .join("")
921
- : `<div class="hint">No memory files yet. The bot writes one the first time someone asks it to remember something.</div>`;
922
-
923
- if (memoryScope && !scopes.some((entry) => entry.scope === memoryScope)) {
924
- memoryScope = null;
925
- $("#memory-editor").style.display = "none";
926
- }
927
- }),
928
- };
929
-
930
- const openMemory = guard(async (scope) => {
931
- const { content } = await api(`/ai/memory/${encodeURIComponent(scope)}`);
932
- memoryScope = scope;
933
- $("#memory-editor").style.display = "block";
934
- $("#memory-scope").textContent = scope;
935
- $("#memory-content").value = content;
936
- });
937
-
938
- function initAiActions() {
939
- $("#persona-save").addEventListener(
940
- "click",
941
- guard(async () => {
942
- await api("/ai/persona", {
943
- method: "PUT",
944
- body: { body: $("#persona-body").value },
945
- });
946
- toast("System prompt saved — it applies to the next message.", "ok");
947
- })
948
- );
949
-
950
- $("#memory-list").addEventListener("click", (event) => {
951
- const button = event.target.closest("[data-scope]");
952
- if (button) openMemory(button.dataset.scope);
953
- });
954
-
955
- $("#memory-save").addEventListener(
956
- "click",
957
- guard(async () => {
958
- await api(`/ai/memory/${encodeURIComponent(memoryScope)}`, {
959
- method: "PUT",
960
- body: { content: $("#memory-content").value },
961
- });
962
- toast("Memory saved", "ok");
963
- VIEWS.ai.load();
964
- })
965
- );
966
-
967
- $("#memory-delete").addEventListener(
968
- "click",
969
- guard(async () => {
970
- if (!confirm(`Delete the memory file for ${memoryScope}? This can't be undone.`)) {
971
- return;
972
- }
973
- await api(`/ai/memory/${encodeURIComponent(memoryScope)}`, {
974
- method: "DELETE",
975
- });
976
- memoryScope = null;
977
- $("#memory-editor").style.display = "none";
978
- toast("Memory file deleted", "ok");
979
- VIEWS.ai.load();
980
- })
981
- );
982
- }
983
-
984
- // --- groups -------------------------------------------------------------
985
-
986
- function groupCard(group) {
987
- const id = esc(group.id);
988
- const title = esc(group.subject || group.id);
989
- const members =
990
- group.participants === null ? "" : `<span class="tag">${group.participants} members</span>`;
991
-
992
- const toggle = (field, label, checked) => `
993
- <label class="switch" style="margin-bottom:9px">
994
- <input type="checkbox" data-group="${id}" data-field="${field}" ${checked ? "checked" : ""} />
995
- <span class="track"></span>
996
- <span>${esc(label)}</span>
997
- </label>`;
998
-
999
- return `
1000
- <details class="card group-card">
1001
- <summary>
1002
- <span>${title}</span>
1003
- ${members}
1004
- ${group.antilink.enabled ? '<span class="tag warn">antilink</span>' : ""}
1005
- ${group.antispam.enabled ? '<span class="tag warn">antispam</span>' : ""}
1006
- <span class="chev">›</span>
1007
- </summary>
1008
-
1009
- <div class="group-body">
1010
- <div>
1011
- <h3>Links</h3>
1012
- ${toggle("antilink.enabled", "Block links", group.antilink.enabled)}
1013
- <label class="field">
1014
- <span>Mode</span>
1015
- <select data-group="${id}" data-field="antilink.mode">
1016
- ${["ALL", "WHITELIST", "BLACKLIST"]
1017
- .map(
1018
- (mode) =>
1019
- `<option value="${mode}"${mode === group.antilink.mode ? " selected" : ""}>${mode.toLowerCase()}</option>`
1020
- )
1021
- .join("")}
1022
- </select>
1023
- </label>
1024
- <label class="field">
1025
- <span>Allowed domains</span>
1026
- <input type="text" data-group="${id}" data-field="antilink.allowed_domains"
1027
- value="${esc(group.antilink.allowed_domains.join(", "))}"
1028
- placeholder="youtube.com, github.com" />
1029
- </label>
1030
- <label class="field">
1031
- <span>Then</span>
1032
- <select data-group="${id}" data-field="antilink.action">
1033
- ${["DELETE", "WARN", "KICK"]
1034
- .map(
1035
- (action) =>
1036
- `<option value="${action}"${action === (group.antilink.action || "WARN") ? " selected" : ""}>${action.toLowerCase()}</option>`
1037
- )
1038
- .join("")}
1039
- </select>
1040
- </label>
1041
- </div>
1042
-
1043
- <div>
1044
- <h3>Spam</h3>
1045
- ${toggle("antispam.enabled", "Anti-spam", group.antispam.enabled)}
1046
- <label class="field">
1047
- <span>Messages allowed</span>
1048
- <input type="number" min="2" max="100" data-group="${id}" data-field="antispam.message_count"
1049
- value="${esc(group.antispam.message_count)}" />
1050
- </label>
1051
- <label class="field">
1052
- <span>Within (seconds)</span>
1053
- <input type="number" min="1" max="600" data-group="${id}" data-field="antispam.time_window"
1054
- value="${esc(group.antispam.time_window)}" />
1055
- </label>
1056
- <label class="field">
1057
- <span>Then</span>
1058
- <select data-group="${id}" data-field="antispam.action">
1059
- ${["WARN", "KICK"]
1060
- .map(
1061
- (action) =>
1062
- `<option value="${action}"${action === group.antispam.action ? " selected" : ""}>${action.toLowerCase()}</option>`
1063
- )
1064
- .join("")}
1065
- </select>
1066
- </label>
1067
- </div>
1068
-
1069
- <div>
1070
- <h3>Media</h3>
1071
- ${toggle("media_control.enabled", "Restrict media", group.media_control.enabled)}
1072
- <div class="hint" style="margin-bottom:6px">Blocked types</div>
1073
- <div class="inline" style="margin-bottom:12px">
1074
- ${["image", "video", "sticker", "audio"]
1075
- .map(
1076
- (type) => `
1077
- <label class="inline" style="gap:5px">
1078
- <input type="checkbox" data-group="${id}" data-field="media.${type}"
1079
- ${group.media_control.blocked_types.includes(type) ? "checked" : ""} />
1080
- <span class="hint">${type}</span>
1081
- </label>`
1082
- )
1083
- .join("")}
1084
- </div>
1085
- <label class="field">
1086
- <span>Then</span>
1087
- <select data-group="${id}" data-field="media_control.action">
1088
- ${["DELETE", "WARN", "KICK"]
1089
- .map(
1090
- (action) =>
1091
- `<option value="${action}"${action === (group.media_control.action || "WARN") ? " selected" : ""}>${action.toLowerCase()}</option>`
1092
- )
1093
- .join("")}
1094
- </select>
1095
- </label>
1096
-
1097
- <h3>Joining</h3>
1098
- ${toggle(
1099
- "join_requests.auto_approve_enabled",
1100
- "Auto-approve requests",
1101
- group.join_requests.auto_approve_enabled
1102
- )}
1103
- </div>
1104
-
1105
- <div>
1106
- <h3>Warnings</h3>
1107
- <label class="field">
1108
- <span>Max warnings</span>
1109
- <input type="number" min="1" max="50" data-group="${id}" data-field="warn_system.max_warnings"
1110
- value="${esc(group.warn_system.max_warnings)}" />
1111
- </label>
1112
- <label class="field">
1113
- <span>Then</span>
1114
- <select data-group="${id}" data-field="warn_system.action">
1115
- ${["FLAG", "KICK"]
1116
- .map(
1117
- (action) =>
1118
- `<option value="${action}"${action === group.warn_system.action ? " selected" : ""}>${action.toLowerCase()}</option>`
1119
- )
1120
- .join("")}
1121
- </select>
1122
- </label>
1123
-
1124
- <h3>Welcome</h3>
1125
- ${toggle("welcome_system.enabled", "Welcome new members", group.welcome_system.enabled)}
1126
- </div>
1127
-
1128
- <div style="grid-column:1/-1">
1129
- <h3>Rules</h3>
1130
- <textarea data-group="${id}" data-field="rules" style="min-height:110px"
1131
- placeholder="Shown by !group rules">${esc(group.rules)}</textarea>
1132
- </div>
1133
-
1134
- <div style="grid-column:1/-1">
1135
- <button class="btn btn-primary" type="button" data-save-group="${id}">Save this group</button>
1136
- <span class="hint" style="margin-left:8px">Blacklisted: ${group.blacklist.length}</span>
1137
- </div>
1138
- </div>
1139
- </details>`;
1140
- }
1141
-
1142
- // Scoped to the group's own <details> element rather than to a selector
1143
- // built from the JID — a group id is full of characters a CSS selector would
1144
- // have to escape.
1145
- function collectGroupPatch(card) {
1146
- const read = (field) => $(`[data-field="${field}"]`, card);
1147
-
1148
- const blocked = ["image", "video", "sticker", "audio"].filter(
1149
- (type) => read(`media.${type}`)?.checked
1150
- );
1151
-
1152
- return {
1153
- antilink: {
1154
- enabled: read("antilink.enabled").checked,
1155
- mode: read("antilink.mode").value,
1156
- allowed_domains: read("antilink.allowed_domains")
1157
- .value.split(",")
1158
- .map((domain) => domain.trim())
1159
- .filter(Boolean),
1160
- action: read("antilink.action").value,
1161
- },
1162
- antispam: {
1163
- enabled: read("antispam.enabled").checked,
1164
- message_count: Number(read("antispam.message_count").value),
1165
- time_window: Number(read("antispam.time_window").value),
1166
- action: read("antispam.action").value,
1167
- },
1168
- media_control: {
1169
- enabled: read("media_control.enabled").checked,
1170
- blocked_types: blocked,
1171
- action: read("media_control.action").value,
1172
- },
1173
- welcome_system: { enabled: read("welcome_system.enabled").checked },
1174
- warn_system: {
1175
- max_warnings: Number(read("warn_system.max_warnings").value),
1176
- action: read("warn_system.action").value,
1177
- },
1178
- join_requests: {
1179
- auto_approve_enabled: read("join_requests.auto_approve_enabled").checked,
1180
- },
1181
- rules: read("rules").value,
1182
- };
1183
- }
1184
-
1185
- VIEWS.groups = {
1186
- title: "Groups",
1187
- load: guard(async () => {
1188
- const { groups } = await api("/groups");
1189
- $("#groups-list").innerHTML = groups.length
1190
- ? groups.map(groupCard).join("")
1191
- : `<div class="card"><div class="empty">The bot isn't in any group yet.</div></div>`;
1192
- }),
1193
- };
1194
-
1195
- function initGroupActions() {
1196
- $("#groups-list").addEventListener("click", (event) => {
1197
- const button = event.target.closest("[data-save-group]");
1198
- if (!button) return;
1199
-
1200
- const groupId = button.dataset.saveGroup;
1201
- const card = button.closest("details");
1202
- guard(async () => {
1203
- await api(`/groups/${encodeURIComponent(groupId)}`, {
1204
- method: "PATCH",
1205
- body: collectGroupPatch(card),
1206
- });
1207
- toast("Group settings saved", "ok");
1208
- })();
1209
- });
1210
- }
1211
-
1212
- // --- data tables --------------------------------------------------------
1213
-
1214
- function scheduleState(job) {
1215
- const lifecycleClass =
1216
- job.status === "active" || job.status === "pending"
1217
- ? " ok"
1218
- : job.status === "failed" || job.status === "invalid"
1219
- ? " danger"
1220
- : "";
1221
- const detail = job.lastRunAt
1222
- ? `<span class="schedule-detail">Last attempt ${esc(timeAgo(job.lastRunAt))}</span>`
1223
- : '<span class="schedule-detail">Not run yet</span>';
1224
- const delivery = job.lastDeliveryStatus
1225
- ? `<span class="tag${job.lastDeliveryStatus === "sent" ? " ok" : " danger"}">Last: ${esc(job.lastDeliveryStatus)}</span>`
1226
- : "";
1227
- const error = job.lastError
1228
- ? `<span class="schedule-error" title="${esc(job.lastError)}">${esc(job.lastError)}</span>`
1229
- : "";
1230
-
1231
- return `<div class="schedule-state">
1232
- <span class="tag${lifecycleClass}">${esc(job.status)}</span>
1233
- ${delivery}${detail}${error}
1234
- </div>`;
1235
- }
1236
-
1237
- function scheduleActions(job) {
1238
- const retryable =
1239
- job.status === "failed" || job.lastDeliveryStatus === "failed";
1240
- return `<div class="table-actions">
1241
- ${
1242
- retryable
1243
- ? `<button class="btn btn-sm" type="button" data-retry-schedule="${esc(job.id)}">Retry now</button>`
1244
- : ""
1245
- }
1246
- <button class="btn btn-sm btn-danger" type="button" data-drop-schedule="${esc(job.id)}">Delete</button>
1247
- </div>`;
1248
- }
1249
-
1250
- const TABLES = {
1251
- debts: {
1252
- endpoint: "/debts",
1253
- key: "debts",
1254
- columns: ["Group", "Debtor", "Creditor", "Amount", "Note", "Status"],
1255
- row: (debt) => [
1256
- `<code>${esc(shortJid(debt.group_id))}</code>`,
1257
- `<code>${esc(shortJid(debt.debtor_id))}</code>`,
1258
- `<code>${esc(shortJid(debt.creditor_id))}</code>`,
1259
- `<strong>${esc(debt.amount)} ${esc(debt.currency || "")}</strong>`,
1260
- `<span class="wrap">${esc(debt.description || "—")}</span>`,
1261
- debt.settled
1262
- ? '<span class="tag ok">settled</span>'
1263
- : '<span class="tag warn">open</span>',
1264
- ],
1265
- },
1266
- warnings: {
1267
- endpoint: "/warnings",
1268
- key: "warnings",
1269
- columns: ["Group", "User", "Count", "Reasons"],
1270
- row: (warning) => [
1271
- `<code>${esc(shortJid(warning.group_id))}</code>`,
1272
- `<code>${esc(shortJid(warning.user_id))}</code>`,
1273
- `<span class="tag warn">${warning.warnings.length}</span>`,
1274
- `<span class="wrap">${esc(
1275
- warning.warnings.map((entry) => entry.reason).join(" · ")
1276
- )}</span>`,
1277
- ],
1278
- },
1279
- notes: {
1280
- endpoint: "/notes",
1281
- key: "notes",
1282
- columns: ["Group", "Keyword", "Text"],
1283
- row: (note) => [
1284
- `<code>${esc(shortJid(note.group_id))}</code>`,
1285
- `<strong>${esc(note.keyword)}</strong>`,
1286
- `<span class="wrap">${esc(String(note.note_text ?? "").slice(0, 160))}</span>`,
1287
- ],
1288
- },
1289
- todos: {
1290
- endpoint: "/todos",
1291
- key: "todos",
1292
- columns: ["User", "Tasks", "Open"],
1293
- row: (todo) => [
1294
- `<code>${esc(shortJid(todo.user_id))}</code>`,
1295
- `<span class="wrap">${esc(
1296
- todo.tasks
1297
- .map((task) => (typeof task === "string" ? task : task.text || ""))
1298
- .join(" · ")
1299
- .slice(0, 160)
1300
- )}</span>`,
1301
- `<span class="tag">${todo.tasks.length}</span>`,
1302
- ],
1303
- },
1304
- schedules: {
1305
- endpoint: "/schedules",
1306
- key: "schedules",
1307
- columns: ["Target", "Schedule", "Message", "Delivery", "Actions"],
1308
- row: (job) => [
1309
- `<code>${esc(shortJid(job.targetJid))}</code>`,
1310
- `<span class="wrap">${esc(job.when || job.cronString || "—")}</span>`,
1311
- `<span class="wrap">${esc(String(job.message ?? "").slice(0, 120))}</span>`,
1312
- scheduleState(job),
1313
- scheduleActions(job),
1314
- ],
1315
- },
1316
- users: {
1317
- endpoint: "/users",
1318
- key: "users",
1319
- columns: ["Number", "Name", "Role", "Last seen"],
1320
- row: (user) => [
1321
- `<code>${esc(user.phone || shortJid(user.jid))}</code>`,
1322
- esc(user.displayName || "—"),
1323
- user.isOwner
1324
- ? '<span class="tag info">owner</span>'
1325
- : user.isAdmin
1326
- ? '<span class="tag ok">admin</span>'
1327
- : '<span class="tag">member</span>',
1328
- esc(timeAgo(user.lastSeen)),
1329
- ],
1330
- },
1331
- };
1332
-
1333
- let dataTab = "debts";
1334
-
1335
- const loadTable = guard(async () => {
1336
- const table = TABLES[dataTab];
1337
- $("#data-table").innerHTML = `<div class="loading">Loading…</div>`;
1338
-
1339
- const payload = await api(table.endpoint);
1340
- const rows = payload[table.key] || [];
1341
-
1342
- $("#data-table").innerHTML = rows.length
1343
- ? `<div class="table-wrap"><table>
1344
- <thead><tr>${table.columns.map((column) => `<th>${esc(column)}</th>`).join("")}</tr></thead>
1345
- <tbody>${rows
1346
- .map((row) => `<tr>${table.row(row).map((cell) => `<td>${cell}</td>`).join("")}</tr>`)
1347
- .join("")}</tbody>
1348
- </table></div>`
1349
- : `<div class="empty">Nothing here yet.</div>`;
1350
- });
1351
-
1352
- VIEWS.data = {
1353
- title: "Data",
1354
- load: loadTable,
1355
- };
1356
-
1357
- function initDataActions() {
1358
- $("#data-table").addEventListener("click", (event) => {
1359
- const retryButton = event.target.closest("[data-retry-schedule]");
1360
- if (retryButton) {
1361
- guard(async () => {
1362
- retryButton.disabled = true;
1363
- retryButton.textContent = "Retrying…";
1364
- try {
1365
- await api(
1366
- `/schedules/${encodeURIComponent(retryButton.dataset.retrySchedule)}/retry`,
1367
- { method: "POST" }
1368
- );
1369
- toast("Scheduled message sent", "ok");
1370
- } finally {
1371
- await loadTable();
1372
- }
1373
- })();
1374
- return;
1375
- }
1376
-
1377
- const button = event.target.closest("[data-drop-schedule]");
1378
- if (!button) return;
1379
- guard(async () => {
1380
- await api(`/schedules/${encodeURIComponent(button.dataset.dropSchedule)}`, {
1381
- method: "DELETE",
1382
- });
1383
- toast("Schedule deleted", "ok");
1384
- loadTable();
1385
- })();
1386
- });
1387
-
1388
- $("#data-tabs").addEventListener("click", (event) => {
1389
- const button = event.target.closest("[data-table]");
1390
- if (!button) return;
1391
- dataTab = button.dataset.table;
1392
- $$("#data-tabs .btn").forEach((tab) => {
1393
- const active = tab.dataset.table === dataTab;
1394
- tab.classList.toggle("btn-primary", active);
1395
- tab.setAttribute("aria-selected", String(active));
1396
- });
1397
- loadTable();
1398
- });
1399
- }
1400
-
1401
- // --- roles --------------------------------------------------------------
1402
-
1403
- function roleRows(list, role) {
1404
- if (!list.length) {
1405
- return `<tr><td colspan="3"><div class="empty">No ${role}s yet.</div></td></tr>`;
1406
- }
1407
- return list
1408
- .map(
1409
- (user) => `
1410
- <tr>
1411
- <td><code>${esc(user.phone || shortJid(user.jid))}</code></td>
1412
- <td>${esc(user.displayName || "—")}</td>
1413
- <td>
1414
- <button class="btn btn-sm btn-danger" type="button" data-revoke="${esc(user.phone || shortJid(user.jid))}"
1415
- data-role="${esc(role)}">Revoke</button>
1416
- </td>
1417
- </tr>`
1418
- )
1419
- .join("");
1420
- }
1421
-
1422
- VIEWS.roles = {
1423
- title: "Roles",
1424
- load: guard(async () => {
1425
- const { roles } = await api("/roles");
1426
- $("#owners-body").innerHTML = roleRows(roles.owners, "owner");
1427
- $("#admins-body").innerHTML = roleRows(roles.admins, "admin");
1428
- }),
1429
- };
1430
-
1431
- function initRoleActions() {
1432
- $("#role-add").addEventListener(
1433
- "click",
1434
- guard(async () => {
1435
- const target = $("#role-number").value.trim();
1436
- const role = $("#role-kind").value;
1437
- await api("/roles", { method: "POST", body: { target, role, action: "grant" } });
1438
- $("#role-number").value = "";
1439
- toast(`Added as ${role}`, "ok");
1440
- VIEWS.roles.load();
1441
- })
1442
- );
1443
-
1444
- $("#view-roles").addEventListener("click", (event) => {
1445
- const button = event.target.closest("[data-revoke]");
1446
- if (!button) return;
1447
- guard(async () => {
1448
- await api("/roles", {
1449
- method: "POST",
1450
- body: {
1451
- target: button.dataset.revoke,
1452
- role: button.dataset.role,
1453
- action: "revoke",
1454
- },
1455
- });
1456
- toast("Revoked", "ok");
1457
- VIEWS.roles.load();
1458
- })();
1459
- });
1460
- }
1461
-
1462
- // --- settings -----------------------------------------------------------
1463
-
1464
- let activeSettingsTab = "ai";
1465
-
1466
- function settingField(setting) {
1467
- if (!setting) return "";
1468
- const id = `set-${setting.key}`;
1469
- const source =
1470
- setting.source === "dashboard"
1471
- ? '<span class="source dashboard">' + t("saved_here") + '</span>'
1472
- : '<span class="source">' + t("default_val") + '</span>';
1473
- const restart = setting.restart
1474
- ? '<span class="source">' + t("restart_to_apply") + '</span>'
1475
- : "";
1476
-
1477
- let control;
1478
- if (setting.type === "secret") {
1479
- control = `
1480
- <div class="inline">
1481
- <input type="password" id="${id}" placeholder="${setting.configured ? "•••••••• (set)" : t("not_set")}"
1482
- autocomplete="new-password"${setting.configured ? ' data-configured="1"' : ""} />
1483
- <button class="btn btn-sm" type="button" data-save-setting="${esc(setting.key)}">${t("save")}</button>
1484
- ${setting.configured ? `<button class="btn btn-sm btn-danger" type="button" data-clear-setting="${esc(setting.key)}">${t("clear")}</button>` : ""}
1485
- </div>`;
1486
- } else if (setting.type === "bool") {
1487
- control = `
1488
- <div class="inline">
1489
- <label class="switch">
1490
- <input type="checkbox" id="${id}" ${setting.value ? "checked" : ""} data-auto-save="${esc(setting.key)}" />
1491
- <span class="track"></span>
1492
- </label>
1493
- <button class="btn btn-sm" type="button" data-save-setting="${esc(setting.key)}">${t("save")}</button>
1494
- </div>`;
1495
- } else if (Array.isArray(setting.choices) && setting.choices.length) {
1496
- control = `
1497
- <div class="inline">
1498
- <select id="${id}">
1499
- ${setting.choices
1500
- .map(
1501
- (choice) =>
1502
- `<option value="${esc(choice)}"${choice === setting.value ? " selected" : ""}>${esc(setting.choiceLabels?.[choice] || choice)}</option>`
1503
- )
1504
- .join("")}
1505
- </select>
1506
- <button class="btn btn-sm" type="button" data-save-setting="${esc(setting.key)}">${t("save")}</button>
1507
- </div>`;
1508
- } else {
1509
- control = `
1510
- <div class="inline">
1511
- <input type="${setting.type === "int" ? "number" : "text"}" id="${id}"
1512
- value="${esc(setting.value)}"
1513
- ${setting.min !== null ? `min="${setting.min}"` : ""}
1514
- ${setting.max !== null ? `max="${setting.max}"` : ""} />
1515
- <button class="btn btn-sm" type="button" data-save-setting="${esc(setting.key)}">${t("save")}</button>
1516
- </div>`;
1517
- }
1518
-
1519
- return `
1520
- <div class="setting-item" id="item-${esc(setting.key)}">
1521
- <div class="inline setting-label-row">
1522
- <label for="${id}" class="setting-label">${esc(setting.label)}</label>
1523
- ${source}${restart}
1524
- </div>
1525
- ${control}
1526
- ${setting.hint ? `<div class="hint setting-hint">${esc(setting.hint)}</div>` : ""}
1527
- </div>`;
1528
- }
1529
-
1530
- function renderAiSettingsTab(container, byKey) {
1531
- const currentProvider = byKey.get("ai_provider")?.value || "gemini";
1532
- const openaiBaseUrl = String(byKey.get("openai_base_url")?.value || "");
1533
- const activeModel =
1534
- currentProvider === "gemini"
1535
- ? byKey.get("gemini_model")?.value
1536
- : currentProvider === "openai"
1537
- ? byKey.get("openai_model")?.value
1538
- : byKey.get("anthropic_model")?.value;
1539
-
1540
- const mStr = String(activeModel || "").toLowerCase();
1541
- const supportsVision =
1542
- currentProvider === "gemini" ||
1543
- currentProvider === "anthropic" ||
1544
- mStr.includes("vision") ||
1545
- mStr.includes("vl") ||
1546
- mStr.includes("llava") ||
1547
- mStr.includes("4o") ||
1548
- mStr.includes("pixtral") ||
1549
- mStr.includes("qwen") ||
1550
- mStr.includes("llama-3.2-11b") ||
1551
- mStr.includes("llama-3.2-90b");
1552
-
1553
- let activeCard = currentProvider;
1554
- if (currentProvider === "openai") {
1555
- if (openaiBaseUrl.includes("groq.com")) activeCard = "groq";
1556
- else if (openaiBaseUrl.includes("11434") || openaiBaseUrl.includes("ollama")) activeCard = "ollama";
1557
- else activeCard = "openai";
1558
- }
1559
-
1560
- let providerFieldsHtml = "";
1561
- if (currentProvider === "gemini") {
1562
- const keys = ["gemini_api_key", "gemini_model"];
1563
- providerFieldsHtml = keys.map((k) => settingField(byKey.get(k))).join("");
1564
- } else if (currentProvider === "openai") {
1565
- const keys = ["openai_api_key", "openai_base_url", "openai_model"];
1566
- providerFieldsHtml = `
1567
- <div class="preset-chips">
1568
- <span class="hint" style="align-self:center; font-weight:600;">${t("apply_preset")}:</span>
1569
- <button class="preset-chip" type="button" data-preset="groq">⚡ Groq (Llama 3.3)</button>
1570
- <button class="preset-chip" type="button" data-preset="openai">🧠 OpenAI (GPT-4o)</button>
1571
- <button class="preset-chip" type="button" data-preset="ollama">🦙 Ollama (Local)</button>
1572
- <button class="preset-chip" type="button" data-preset="openrouter">🌐 OpenRouter</button>
1573
- </div>
1574
- ${keys.map((k) => settingField(byKey.get(k))).join("")}
1575
- `;
1576
- } else if (currentProvider === "anthropic") {
1577
- const keys = ["anthropic_api_key", "anthropic_model"];
1578
- providerFieldsHtml = keys.map((k) => settingField(byKey.get(k))).join("");
1579
- }
1580
-
1581
- const capKeys = ["bot_language", "ai_vision_enabled", "ai_stt_provider"];
1582
- if (
1583
- byKey.get("ai_stt_provider")?.value === "openai" ||
1584
- (byKey.get("ai_stt_provider")?.value === "auto" && currentProvider === "openai")
1585
- ) {
1586
- capKeys.push("openai_stt_model");
1587
- }
1588
- capKeys.push("ai_agent");
1589
- if (currentProvider === "gemini") {
1590
- capKeys.push("ai_google_search");
1591
- }
1592
- const capFieldsHtml = capKeys.map((k) => settingField(byKey.get(k))).join("");
1593
-
1594
- container.innerHTML = `
1595
- <!-- Step 1: Provider Selection Cards -->
1596
- <div class="card">
1597
- <div class="card-head">
1598
- <div>
1599
- <h2>${t("ai_wizard_title")}</h2>
1600
- <div class="hint">${t("ai_wizard_sub")}</div>
1601
- </div>
1602
- </div>
1603
-
1604
- <div class="provider-grid">
1605
- <div class="provider-card ${activeCard === "gemini" ? "active" : ""}" data-pick-provider="gemini">
1606
- <div class="provider-card-head">
1607
- <div class="provider-title"><span>🌟</span> ${t("provider_gemini")}</div>
1608
- <span class="provider-active-badge">${t("active_provider")}</span>
1609
- </div>
1610
- <div class="provider-desc">${t("provider_gemini_desc")}</div>
1611
- </div>
1612
-
1613
- <div class="provider-card ${activeCard === "groq" ? "active" : ""}" data-pick-provider="groq">
1614
- <div class="provider-card-head">
1615
- <div class="provider-title"><span>⚡</span> ${t("provider_groq")}</div>
1616
- <span class="provider-active-badge">${t("active_provider")}</span>
1617
- </div>
1618
- <div class="provider-desc">${t("provider_groq_desc")}</div>
1619
- </div>
1620
-
1621
- <div class="provider-card ${activeCard === "openai" ? "active" : ""}" data-pick-provider="openai">
1622
- <div class="provider-card-head">
1623
- <div class="provider-title"><span>🧠</span> ${t("provider_openai")}</div>
1624
- <span class="provider-active-badge">${t("active_provider")}</span>
1625
- </div>
1626
- <div class="provider-desc">${t("provider_openai_desc")}</div>
1627
- </div>
1628
-
1629
- <div class="provider-card ${activeCard === "ollama" ? "active" : ""}" data-pick-provider="ollama">
1630
- <div class="provider-card-head">
1631
- <div class="provider-title"><span>🦙</span> ${t("provider_ollama")}</div>
1632
- <span class="provider-active-badge">${t("active_provider")}</span>
1633
- </div>
1634
- <div class="provider-desc">${t("provider_ollama_desc")}</div>
1635
- </div>
1636
-
1637
- <div class="provider-card ${activeCard === "anthropic" ? "active" : ""}" data-pick-provider="anthropic">
1638
- <div class="provider-card-head">
1639
- <div class="provider-title"><span>🔮</span> ${t("provider_anthropic")}</div>
1640
- <span class="provider-active-badge">${t("active_provider")}</span>
1641
- </div>
1642
- <div class="provider-desc">${t("provider_anthropic_desc")}</div>
1643
- </div>
1644
- </div>
1645
- </div>
1646
-
1647
- <!-- Step 2: Credentials & Model for Active Provider -->
1648
- <div class="card">
1649
- <div class="card-head">
1650
- <h2>🔑 ${t("active_provider")}: ${esc(currentProvider.toUpperCase())} ${activeCard !== currentProvider ? `(${esc(activeCard.toUpperCase())})` : ""}</h2>
1651
- </div>
1652
- ${providerFieldsHtml}
1653
- </div>
1654
-
1655
- <!-- Step 3: Model Capabilities & Media Toggles (Point 3) -->
1656
- <div class="card">
1657
- <div class="card-head">
1658
- <div>
1659
- <h2>🎛️ ${t("capabilities_title")}</h2>
1660
- <div class="hint">${t("capabilities_sub")}</div>
1661
- </div>
1662
- </div>
1663
- ${capFieldsHtml}
1664
- <div style="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line-soft); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
1665
- <button class="btn btn-secondary" id="open-ai-advanced" type="button">
1666
- ⚙️ ${t("advanced_btn")}
1667
- </button>
1668
- </div>
1669
- </div>
1670
- `;
1671
-
1672
- const advContainer = $("#ai-advanced-fields");
1673
- if (advContainer) {
1674
- const advKeys = [
1675
- "ai_max_tool_steps",
1676
- "ai_tool_timeout_ms",
1677
- "ai_max_history",
1678
- "memory_context_chars",
1679
- "gemini_stt_model",
1680
- "gemini_image_model",
1681
- "google_search_api_key",
1682
- "google_search_cx",
1683
- ];
1684
- advContainer.innerHTML = advKeys
1685
- .map((k) => byKey.get(k))
1686
- .filter(Boolean)
1687
- .map(settingField)
1688
- .join("");
1689
- }
1690
- }
1691
-
1692
- VIEWS.settings = {
1693
- title: "Settings",
1694
- load: guard(async () => {
1695
- const { settings, prefix } = await api("/settings");
1696
- const byKey = new Map(settings.map((s) => [s.key, s]));
1697
-
1698
- $$(".settings-tab").forEach((b) => {
1699
- const isSelected = b.dataset.tab === activeSettingsTab;
1700
- b.classList.toggle("active", isSelected);
1701
- b.setAttribute("aria-selected", isSelected ? "true" : "false");
1702
- });
1703
-
1704
- const secContent = $("#settings-tab-security");
1705
- if (secContent) {
1706
- secContent.style.display = activeSettingsTab === "security" ? "block" : "none";
1707
- }
1708
-
1709
- const listEl = $("#settings-list");
1710
- if (!listEl) return;
1711
-
1712
- if (activeSettingsTab === "ai") {
1713
- renderAiSettingsTab(listEl, byKey);
1714
- } else if (activeSettingsTab === "general") {
1715
- const generalKeys = ["bot_timezone", "bot_min_delay_ms", "bot_max_delay_ms"];
1716
- const items = generalKeys.map((k) => byKey.get(k)).filter(Boolean);
1717
- listEl.innerHTML = `
1718
- <div class="card" style="margin-bottom: 20px;">
1719
- <div class="card-head"><h2>⌨️ Command Prefix (بادئة الأوامر)</h2></div>
1720
- <div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 14px;">
1721
- <input type="text" id="gen-prefix-input" maxlength="3" class="field" style="max-width: 90px; font-family: monospace; font-size: 1.15rem; text-align: center;" value="${escapeHtml(prefix || "!")}">
1722
- <button type="button" class="btn btn-primary" id="gen-prefix-save">Save Prefix</button>
1723
- <span class="hint" style="margin: 0;">e.g. <code>!help</code> or <code>/help</code></span>
1724
- </div>
1725
- </div>
1726
- <div class="card">
1727
- <div class="card-head"><h2>⚙️ ${t("settings_tab_general")}</h2></div>
1728
- ${items.map(settingField).join("")}
1729
- </div>`;
1730
-
1731
- const pInput = $("#gen-prefix-input");
1732
- const pSave = $("#gen-prefix-save");
1733
- if (pSave && pInput) {
1734
- pSave.addEventListener("click", guard(async () => {
1735
- const val = pInput.value.trim();
1736
- if (!val || val.length > 3) {
1737
- toast("Prefix must be 1 to 3 characters", "bad");
1738
- return;
1739
- }
1740
- await api("/settings", { method: "PATCH", body: { key: "prefix", value: val } });
1741
- toast(`Prefix updated to "${val}"`, "ok");
1742
- }));
1743
- }
1744
- } else if (activeSettingsTab === "security") {
1745
- const serverKeys = ["port", "bind_address", "trust_proxy", "public_domain", "dashboard_origin"];
1746
- const items = serverKeys.map((k) => byKey.get(k)).filter(Boolean);
1747
- listEl.innerHTML = `
1748
- <div class="card">
1749
- <div class="card-head"><h2>🌐 ${t("settings_tab_security")} &amp; Server</h2></div>
1750
- ${items.map(settingField).join("")}
1751
- </div>`;
1752
- } else if (activeSettingsTab === "whatsapp") {
1753
- const proxyKeys = [
1754
- "whatsapp_proxy_enabled",
1755
- "whatsapp_proxy_protocol",
1756
- "whatsapp_proxy_host",
1757
- "whatsapp_proxy_port",
1758
- "whatsapp_proxy_username",
1759
- "whatsapp_proxy_password",
1760
- ];
1761
- const items = proxyKeys.map((k) => byKey.get(k)).filter(Boolean);
1762
- listEl.innerHTML = `
1763
- <div class="card">
1764
- <div class="card-head"><h2>🌐 ${t("settings_tab_whatsapp")}</h2></div>
1765
- ${items.map(settingField).join("")}
1766
- </div>`;
1767
- } else if (activeSettingsTab === "media") {
1768
- const mediaKeys = [
1769
- "thumbnail_remote",
1770
- "thumbnail_remote_max_mb",
1771
- "thumbnail_remote_timeout_ms",
1772
- "ffmpeg_path",
1773
- "forward_score_ttl_days",
1774
- "openweathermap_api_key",
1775
- ];
1776
- const items = mediaKeys.map((k) => byKey.get(k)).filter(Boolean);
1777
- listEl.innerHTML = `
1778
- <div class="card">
1779
- <div class="card-head"><h2>📁 ${t("settings_tab_media")}</h2></div>
1780
- ${items.map(settingField).join("")}
1781
- </div>`;
1782
- }
1783
- }),
1784
- };
1785
-
1786
- function initSettingsActions() {
1787
- $("#pw-save").addEventListener(
1788
- "click",
1789
- guard(async () => {
1790
- const current = $("#pw-current").value;
1791
- const next = $("#pw-next").value;
1792
- await api("/security/password", { method: "POST", body: { current, next } });
1793
- $("#pw-current").value = "";
1794
- $("#pw-next").value = "";
1795
- toast("Password changed", "ok");
1796
- })
1797
- );
1798
-
1799
- // Tab switcher
1800
- $("#settings-nav-tabs")?.addEventListener("click", (e) => {
1801
- const tabBtn = e.target.closest("[data-tab]");
1802
- if (!tabBtn) return;
1803
- activeSettingsTab = tabBtn.dataset.tab;
1804
- VIEWS.settings.load();
1805
- });
1806
-
1807
- // Modal triggers
1808
- document.addEventListener("click", (e) => {
1809
- if (e.target.closest("#open-ai-advanced")) {
1810
- const modal = $("#ai-advanced-modal");
1811
- if (modal) modal.style.display = "flex";
1812
- } else if (e.target.closest("#ai-advanced-close") || e.target.closest("#ai-advanced-done")) {
1813
- const modal = $("#ai-advanced-modal");
1814
- if (modal) modal.style.display = "none";
1815
- }
1816
- });
1817
-
1818
- // Provider Card Picker
1819
- document.addEventListener("click", (e) => {
1820
- const card = e.target.closest("[data-pick-provider]");
1821
- if (!card) return;
1822
- const pick = card.dataset.pickProvider;
1823
- guard(async () => {
1824
- if (pick === "groq") {
1825
- await api("/settings", { method: "PATCH", body: { key: "ai_provider", value: "openai" } });
1826
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "https://api.groq.com/openai/v1" } });
1827
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "llama-3.3-70b-versatile" } });
1828
- await api("/settings", { method: "PATCH", body: { key: "openai_stt_model", value: "whisper-large-v3" } });
1829
- await api("/settings", { method: "PATCH", body: { key: "ai_vision_enabled", value: true } });
1830
- } else if (pick === "ollama") {
1831
- await api("/settings", { method: "PATCH", body: { key: "ai_provider", value: "openai" } });
1832
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "http://127.0.0.1:11434/v1" } });
1833
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "llama3.2" } });
1834
- } else if (pick === "openai") {
1835
- await api("/settings", { method: "PATCH", body: { key: "ai_provider", value: "openai" } });
1836
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "https://api.openai.com/v1" } });
1837
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "gpt-4o-mini" } });
1838
- } else if (pick === "gemini") {
1839
- await api("/settings", { method: "PATCH", body: { key: "ai_provider", value: "gemini" } });
1840
- } else if (pick === "anthropic") {
1841
- await api("/settings", { method: "PATCH", body: { key: "ai_provider", value: "anthropic" } });
1842
- await api("/settings", { method: "PATCH", body: { key: "anthropic_model", value: "claude-sonnet-4-5" } });
1843
- }
1844
- toast(t("saved"), "ok");
1845
- VIEWS.settings.load();
1846
- })();
1847
- });
1848
-
1849
- // Preset chips
1850
- document.addEventListener("click", (e) => {
1851
- const chip = e.target.closest("[data-preset]");
1852
- if (!chip) return;
1853
- const preset = chip.dataset.preset;
1854
- guard(async () => {
1855
- if (preset === "groq") {
1856
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "https://api.groq.com/openai/v1" } });
1857
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "llama-3.3-70b-versatile" } });
1858
- await api("/settings", { method: "PATCH", body: { key: "openai_stt_model", value: "whisper-large-v3" } });
1859
- await api("/settings", { method: "PATCH", body: { key: "ai_vision_enabled", value: true } });
1860
- } else if (preset === "openai") {
1861
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "https://api.openai.com/v1" } });
1862
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "gpt-4o-mini" } });
1863
- } else if (preset === "ollama") {
1864
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "http://127.0.0.1:11434/v1" } });
1865
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "llama3.2" } });
1866
- } else if (preset === "openrouter") {
1867
- await api("/settings", { method: "PATCH", body: { key: "openai_base_url", value: "https://openrouter.ai/api/v1" } });
1868
- await api("/settings", { method: "PATCH", body: { key: "openai_model", value: "google/gemini-2.5-flash" } });
1869
- }
1870
- toast(t("saved"), "ok");
1871
- VIEWS.settings.load();
1872
- })();
1873
- });
1874
-
1875
- // Auto-save switches on change
1876
- document.addEventListener("change", (e) => {
1877
- const autoSaveKey = e.target?.dataset?.autoSave;
1878
- if (autoSaveKey && e.target.type === "checkbox") {
1879
- const key = autoSaveKey;
1880
- const value = e.target.checked;
1881
- guard(async () => {
1882
- await api("/settings", { method: "PATCH", body: { key, value } });
1883
- toast(t("saved"), "ok");
1884
- VIEWS.settings.load();
1885
- if (key.startsWith("whatsapp_proxy_")) loadStats().catch(() => {});
1886
- })();
1887
- }
1888
- });
1889
-
1890
- // Button-based save and clear
1891
- document.addEventListener("click", (event) => {
1892
- const save = event.target.closest("[data-save-setting]");
1893
- const clear = event.target.closest("[data-clear-setting]");
1894
- if (!save && !clear) return;
1895
-
1896
- const key = save ? save.dataset.saveSetting : clear.dataset.clearSetting;
1897
- const input = document.getElementById(`set-${key}`);
1898
- if (!input) return;
1899
-
1900
- if (save && input.dataset.configured === "1" && input.value === "") {
1901
- toast("Left unchanged. Use Clear to remove it.");
1902
- return;
1903
- }
1904
-
1905
- const value = clear
1906
- ? ""
1907
- : input.type === "checkbox"
1908
- ? input.checked
1909
- : input.value;
1910
-
1911
- guard(async () => {
1912
- await api("/settings", { method: "PATCH", body: { key, value } });
1913
- toast(clear ? t("cleared") : t("saved"), "ok");
1914
- VIEWS.settings.load();
1915
- if (key.startsWith("whatsapp_proxy_")) loadStats().catch(() => {});
1916
- })();
1917
- });
1918
- }
1919
-
1920
- // --- boot ---------------------------------------------------------------
1921
-
1922
- // The socket is a one-way feed of what the backend is already doing. Opening
1923
- // it, losing it or reloading the page changes nothing about the WhatsApp
1924
- // session; a reconnect happens in the backend with every tab shut.
1925
- function initSocket() {
1926
- // eslint-disable-next-line no-undef
1927
- const socket = io();
1928
-
1929
- socket.on("session", (snapshot) => setStatus(snapshot));
1930
-
1931
- socket.on("qr", (qr) => {
1932
- renderQr(qr);
1933
- if (currentView !== "connection") {
1934
- toast("A new QR code is ready — open Connection to scan it.");
1935
- }
1936
- });
1937
-
1938
- socket.on("qr_cleared", () => clearQr());
1939
-
1940
- socket.on("pairing_code", (payload) => {
1941
- const code = payload && payload.code;
1942
- if (code) renderPairingCode(code, payload.phone);
1943
- if (currentView !== "connection") {
1944
- toast("A pairing code is ready — open Connection to enter it.");
1945
- }
1946
- });
1947
-
1948
- socket.on("pairing_code_cleared", () => clearPairingCode());
1949
-
1950
- // A socket that dropped may have missed transitions while it was away.
1951
- socket.on("connect", () => {
1952
- if (currentView === "connection") VIEWS.connection.load();
1953
- else loadStats().catch(() => {});
1954
- });
1955
- }
1956
-
1957
- initTheme();
1958
- initLang();
1959
- initRouting();
1960
- initConnectionActions();
1961
- {
1962
- const def = preferredPairMethod();
1963
- const radio = document.querySelector(`input[name="pair-method"][value="${def}"]`);
1964
- if (radio) radio.checked = true;
1965
- document.querySelectorAll('input[name="pair-method"]').forEach((el) => {
1966
- el.addEventListener("change", syncPairChooser);
1967
- });
1968
- syncPairChooser();
1969
- }
1970
- initCommandActions();
1971
- initAiActions();
1972
- initGroupActions();
1973
- initDataActions();
1974
- initRoleActions();
1975
- initSettingsActions();
1976
- initSocket();
1977
-
1978
- show(window.location.hash.slice(1));
1979
- loadStats().catch(() => {});
1980
- setInterval(() => loadStats().catch(() => {}), 15000);
1981
- })();