DmitrMakeev commited on
Commit
c7d861a
·
verified ·
1 Parent(s): 961009e

Update chat.html

Browse files
Files changed (1) hide show
  1. chat.html +186 -81
chat.html CHANGED
@@ -174,102 +174,207 @@
174
  </head>
175
 
176
 
 
 
 
 
177
  <body>
 
178
  <div class="chat-container">
179
  <div class="chat-header">
180
  <h2>🌿 Secure Chat</h2>
181
  <div class="security-badge">AES ШИФРОВАНИЕ</div>
182
  </div>
183
 
184
- <div class="encryption-notice">Введите общий ключ шифрования ниже</div>
185
-
186
- <input type="password" id="key-input" class="key-input" placeholder="🔑 Ключ шифрования (один и тот же у обоих)" />
187
-
188
- <div class="messages-container" id="messages"></div>
 
 
 
 
 
 
 
 
189
 
190
- <div class="input-container">
191
- <textarea class="message-input" id="message-input" placeholder="Введите сообщение..."></textarea>
192
- <div class="button-row">
193
- <button class="send-button" id="send-btn">Отправить</button>
194
- <button class="clear-button" id="clear-btn">🗑 Очистить</button>
 
 
 
 
 
 
 
195
  </div>
196
  </div>
197
  </div>
198
 
199
  <script>
200
- const userId = "{{ user_id }}";
201
- let lastId = 0;
202
- let encryptionKey = '';
203
-
204
- const keyInput = document.getElementById('key-input');
205
- const msgInput = document.getElementById('message-input');
206
- const messagesDiv = document.getElementById('messages');
207
-
208
- document.getElementById('send-btn').onclick = sendMessage;
209
- document.getElementById('clear-btn').onclick = clearChat;
210
- keyInput.oninput = () => encryptionKey = keyInput.value.trim();
211
-
212
- async function sendMessage() {
213
- const text = msgInput.value.trim();
214
- if (!text || !encryptionKey) return alert('Введите сообщение и ключ');
215
-
216
- const encrypted = CryptoJS.AES.encrypt(text, encryptionKey).toString();
217
-
218
- await fetch('/send_message', {
219
- method: 'POST',
220
- headers: { 'Content-Type': 'application/json' },
221
- body: JSON.stringify({ user_id: userId, encrypted_text: encrypted })
222
- });
223
-
224
- msgInput.value = '';
225
- loadNewMessages();
226
- }
227
-
228
- async function loadMessages() {
229
- const res = await fetch('/get_messages');
230
- const data = await res.json();
231
- renderMessages(data.messages);
232
- }
233
-
234
- async function loadNewMessages() {
235
- const res = await fetch(`/get_new_messages?last_id=${lastId}`);
236
- const data = await res.json();
237
- if (data.messages.length) renderMessages(data.messages, false);
238
- }
239
-
240
- async function clearChat() {
241
- if (!confirm('Очистить чат?')) return;
242
- await fetch('/clear_chat', { method: 'POST' });
243
- messagesDiv.innerHTML = '';
244
- lastId = 0;
245
- }
246
-
247
- function renderMessages(msgs, clear = true) {
248
- if (clear) messagesDiv.innerHTML = '';
249
- msgs.forEach(m => {
250
- // если это уже было добавлено — пропускаем
251
- if (document.getElementById('msg-' + m.id)) return;
252
-
253
- lastId = Math.max(lastId, m.id);
254
- let decrypted = '[🔒 Сообщение зашифровано]';
255
- if (encryptionKey) {
256
- try {
257
- decrypted = CryptoJS.AES.decrypt(m.encrypted_text, encryptionKey).toString(CryptoJS.enc.Utf8) || decrypted;
258
- } catch {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  }
260
- const div = document.createElement('div');
261
- div.id = 'msg-' + m.id; // уникальный ID для проверки
262
- div.className = 'message ' + (m.user_id === userId ? 'own' : 'other');
263
- div.innerHTML = `<div><b>${m.username}</b> • ${m.timestamp}</div><div>${decrypted}</div>`;
264
- messagesDiv.appendChild(div);
265
- });
266
- messagesDiv.scrollTop = messagesDiv.scrollHeight;
267
- }
268
-
269
-
270
- setInterval(loadNewMessages, 2000);
271
- loadMessages();
272
  </script>
 
273
  </body>
 
 
 
 
274
  </html>
275
 
 
174
  </head>
175
 
176
 
177
+
178
+
179
+
180
+
181
  <body>
182
+
183
  <div class="chat-container">
184
  <div class="chat-header">
185
  <h2>🌿 Secure Chat</h2>
186
  <div class="security-badge">AES ШИФРОВАНИЕ</div>
187
  </div>
188
 
189
+ <!-- ЭКРАН ВХОДА С НИКОМ -->
190
+ <div id="login-section" style="padding: 20px; background: #e6fffa; border-bottom: 2px solid #48bb78; text-align: center;">
191
+ <h3 style="margin-bottom: 10px; color: #2f855a;">👤 Введите ваш ник</h3>
192
+ <input type="text" id="username-input" placeholder="Ваш ник"
193
+ style="width: 60%; padding: 10px 15px; border: 2px solid #48bb78; border-radius: 10px; font-size: 16px; text-align: center;">
194
+ <button id="join-btn"
195
+ style="margin-left: 10px; padding: 10px 25px; background: #48bb78; color: white; border: none; border-radius: 10px; cursor: pointer; font-weight: bold; font-size: 16px;">
196
+ Войти в чат
197
+ </button>
198
+ <div style="margin-top: 8px; font-size: 0.85em; color: #38a169;">
199
+ 🔐 Этот ник будут видеть другие участники
200
+ </div>
201
+ </div>
202
 
203
+ <!-- САМ ЧАТ (СКРЫТ ДО ВХОДА) -->
204
+ <div id="chat-section" style="display: none; flex-direction: column; height: 100%;">
205
+ <div class="encryption-notice">🔒 Все сообщения шифруются на вашем устройстве</div>
206
+
207
+ <div class="messages-container" id="messages"></div>
208
+
209
+ <div class="input-container">
210
+ <textarea class="message-input" id="message-input" placeholder="Введите сообщение..."></textarea>
211
+ <div class="button-row">
212
+ <button class="send-button" id="send-btn">Отправить</button>
213
+ <button class="clear-button" id="clear-btn">🗑 Очистить</button>
214
+ </div>
215
  </div>
216
  </div>
217
  </div>
218
 
219
  <script>
220
+ // === ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ ===
221
+ let username = '';
222
+ let lastId = 0;
223
+ const FIXED_KEY = 'my-secret-key-2024'; // Общий ключ шифрования
224
+
225
+ // === DOM-ЭЛЕМЕНТЫ ===
226
+ const loginSection = document.getElementById('login-section');
227
+ const chatSection = document.getElementById('chat-section');
228
+ const usernameInput = document.getElementById('username-input');
229
+ const joinBtn = document.getElementById('join-btn');
230
+ const messagesDiv = document.getElementById('messages');
231
+ const msgInput = document.getElementById('message-input');
232
+ const sendBtn = document.getElementById('send-btn');
233
+ const clearBtn = document.getElementById('clear-btn');
234
+
235
+ // === ВХОД В ЧАТ ===
236
+ function enterChat() {
237
+ const name = usernameInput.value.trim();
238
+ if (!name) {
239
+ alert('Пожалуйста, введите ваш ник!');
240
+ return;
241
+ }
242
+ username = name;
243
+ localStorage.setItem('chat_username', name); // сохраняем
244
+
245
+ loginSection.style.display = 'none';
246
+ chatSection.style.display = 'flex';
247
+
248
+ loadMessages();
249
+ // Запускаем автообновление, если ещё не запущено
250
+ if (!window._pollingStarted) {
251
+ window._pollingStarted = true;
252
+ setInterval(loadNewMessages, 2000);
253
+ }
254
+ }
255
+
256
+ joinBtn.onclick = enterChat;
257
+ usernameInput.onkeydown = function(e) {
258
+ if (e.key === 'Enter') enterChat();
259
+ };
260
+
261
+ // Автовход, если ник сохранён (опционально)
262
+ const savedName = localStorage.getItem('chat_username');
263
+ if (savedName) {
264
+ usernameInput.value = savedName;
265
+ // Можно раскомментировать для авто-входа:
266
+ // setTimeout(enterChat, 500);
267
+ }
268
+
269
+ // === ШИФРОВАНИЕ ===
270
+ function encryptMessage(text) {
271
+ return CryptoJS.AES.encrypt(text, FIXED_KEY).toString();
272
+ }
273
+
274
+ function decryptMessage(encrypted) {
275
+ try {
276
+ const decrypted = CryptoJS.AES.decrypt(encrypted, FIXED_KEY).toString(CryptoJS.enc.Utf8);
277
+ return decrypted || '🔒 Не удалось расшифровать';
278
+ } catch {
279
+ return '🔒 Ошибка расшифровки';
280
+ }
281
+ }
282
+
283
+ // === ОТПРАВКА ===
284
+ async function sendMessage() {
285
+ const text = msgInput.value.trim();
286
+ if (!text) {
287
+ alert('Введите сообщение');
288
+ return;
289
+ }
290
+ if (!username) {
291
+ alert('Сначала войдите в чат');
292
+ return;
293
+ }
294
+
295
+ const encrypted = encryptMessage(text);
296
+ await fetch('/send_message', {
297
+ method: 'POST',
298
+ headers: { 'Content-Type': 'application/json' },
299
+ body: JSON.stringify({
300
+ username: username,
301
+ encrypted_text: encrypted
302
+ })
303
+ });
304
+ msgInput.value = '';
305
+ loadNewMessages();
306
+ }
307
+
308
+ // === ЗАГРУЗКА ===
309
+ async function loadMessages() {
310
+ const res = await fetch('/get_messages');
311
+ const data = await res.json();
312
+ renderMessages(data.messages, true);
313
+ }
314
+
315
+ async function loadNewMessages() {
316
+ const res = await fetch(`/get_new_messages?last_id=${lastId}`);
317
+ const data = await res.json();
318
+ if (data.messages.length) {
319
+ renderMessages(data.messages, false);
320
+ }
321
+ }
322
+
323
+ // === ОЧИСТКА ===
324
+ async function clearChat() {
325
+ if (!confirm('Очистить чат для всех?')) return;
326
+ await fetch('/clear_chat', { method: 'POST' });
327
+ messagesDiv.innerHTML = '';
328
+ lastId = 0;
329
+ }
330
+
331
+ // === ОТРИСОВКА ===
332
+ function renderMessages(msgs, clear = true) {
333
+ if (clear) messagesDiv.innerHTML = '';
334
+
335
+ msgs.forEach(m => {
336
+ if (document.getElementById('msg-' + m.id)) return;
337
+ lastId = Math.max(lastId, m.id);
338
+
339
+ const decrypted = decryptMessage(m.encrypted_text);
340
+ const isOwn = m.username === username;
341
+
342
+ const div = document.createElement('div');
343
+ div.id = 'msg-' + m.id;
344
+ div.className = 'message ' + (isOwn ? 'own' : 'other');
345
+ div.innerHTML = `
346
+ <div class="message-info">
347
+ <b>${m.username}</b> • ${m.timestamp}
348
+ </div>
349
+ <div>${decrypted}</div>
350
+ `;
351
+ messagesDiv.appendChild(div);
352
+ });
353
+
354
+ messagesDiv.scrollTop = messagesDiv.scrollHeight;
355
+ }
356
+
357
+ // === КНОПКИ ===
358
+ sendBtn.onclick = sendMessage;
359
+ clearBtn.onclick = clearChat;
360
+
361
+ msgInput.onkeydown = function(e) {
362
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
363
+ sendBtn.click();
364
+ }
365
+ };
366
+
367
+ // Если чат уже должен быть открыт (например, после перезагрузки)
368
+ // можно проверить и восстановить состояние
369
+ if (localStorage.getItem('chat_username') && loginSection.style.display !== 'none') {
370
+ // ничего не делаем, ждём ручного входа
371
  }
 
 
 
 
 
 
 
 
 
 
 
 
372
  </script>
373
+
374
  </body>
375
+
376
+
377
+
378
+
379
  </html>
380