Aleksmorshen commited on
Commit
73dc801
·
verified ·
1 Parent(s): e6e8546

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +741 -619
app.py CHANGED
@@ -1,19 +1,18 @@
1
  import os
2
  import json
3
  import uuid
4
- from flask import Flask, Response, request
5
- from flask_socketio import SocketIO, emit, join_room, leave_room
 
6
 
7
  app = Flask(__name__)
8
- app.config['SECRET_KEY'] = 'a_very_secret_key_for_virton_messenger'
9
- socketio = SocketIO(app, async_mode='eventlet')
10
 
11
  DB_FILE = 'virton_db.json'
12
 
13
  def load_db():
14
  if not os.path.exists(DB_FILE):
15
  with open(DB_FILE, 'w') as f:
16
- json.dump({"users": {}, "chatrooms": {}}, f, indent=4)
17
  with open(DB_FILE, 'r') as f:
18
  return json.load(f)
19
 
@@ -21,9 +20,10 @@ def save_db(data):
21
  with open(DB_FILE, 'w') as f:
22
  json.dump(data, f, indent=4)
23
 
24
- @app.route('/')
25
- def index():
26
- html_content = """
 
27
  <!DOCTYPE html>
28
  <html lang="ru">
29
  <head>
@@ -31,151 +31,184 @@ def index():
31
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
32
  <title>Virton Messenger</title>
33
  <script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>
34
- <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
 
 
35
  <style>
36
  :root {
37
- --primary-bg: #10141a;
38
- --secondary-bg: #1c2128;
39
- --accent-blue: #0088cc;
 
 
 
40
  --accent-blue-hover: #00aaff;
41
- --text-primary: #e6edf3;
42
- --text-secondary: #7d8590;
43
- --border-color: #30363d;
44
- --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
 
 
 
 
 
 
45
  }
 
46
  body {
47
  font-family: var(--font-family);
48
  background-color: var(--primary-bg);
49
- color: var(--text-primary);
50
- margin: 0;
51
- overflow: hidden;
52
  display: flex;
53
  align-items: center;
54
  justify-content: center;
55
  height: 100vh;
 
56
  }
57
- .main-container {
 
58
  width: 100%;
59
  height: 100%;
60
  display: flex;
61
  flex-direction: column;
 
 
 
 
 
 
 
62
  }
63
- #login-view {
 
64
  display: flex;
65
  flex-direction: column;
66
  align-items: center;
67
  justify-content: center;
68
  height: 100%;
69
- background: radial-gradient(circle, rgba(0,136,204,0.1) 0%, rgba(16,20,26,0) 60%);
70
  }
71
- #login-view h1 {
 
72
  font-size: 3rem;
73
- font-weight: 600;
74
- color: var(--text-primary);
75
  margin-bottom: 10px;
 
 
 
 
 
 
 
 
76
  }
77
- #login-view p {
78
- font-size: 1.2rem;
79
- color: var(--text-secondary);
80
- margin-bottom: 30px;
81
  }
82
- #messenger-view {
 
83
  display: none;
84
- width: 100%;
85
- height: 100%;
86
  flex-direction: row;
 
 
87
  }
 
88
  .sidebar {
89
  width: 300px;
90
- background-color: var(--secondary-bg);
91
  border-right: 1px solid var(--border-color);
92
  display: flex;
93
  flex-direction: column;
94
- transition: width 0.3s;
 
95
  }
 
96
  .sidebar-header {
97
- padding: 20px;
98
  border-bottom: 1px solid var(--border-color);
99
- display: flex;
100
- flex-direction: column;
101
- align-items: flex-start;
102
  }
 
103
  .sidebar-header .user-info {
104
- font-size: 14px;
105
- color: var(--text-secondary);
106
- word-break: break-all;
107
- margin-bottom: 10px;
108
  }
109
- .sidebar-header #username-display {
110
- font-size: 18px;
111
  font-weight: 600;
112
- color: var(--text-primary);
113
- }
114
- .sidebar-header .username-actions a {
115
- color: var(--accent-blue);
116
  cursor: pointer;
117
- font-size: 12px;
118
- text-decoration: none;
119
- }
120
- .sidebar-header .username-actions a:hover {
121
- text-decoration: underline;
122
- }
123
- .room-list-container {
124
- padding: 10px 0;
125
- flex-grow: 1;
126
- overflow-y: auto;
127
  }
128
- .room-list-header {
129
- padding: 10px 20px;
130
- display: flex;
131
- justify-content: space-between;
132
- align-items: center;
133
  }
134
- .room-list-header h3 {
135
- margin: 0;
136
- font-size: 16px;
137
  }
138
- #create-room-btn {
139
- background: none;
 
 
 
 
140
  border: none;
141
- color: var(--accent-blue);
142
- font-size: 24px;
 
143
  cursor: pointer;
144
- padding: 5px;
 
145
  }
146
- #create-room-btn:hover {
147
- color: var(--accent-blue-hover);
148
  }
149
- #room-list {
150
- list-style: none;
151
- padding: 0;
152
- margin: 0;
 
 
 
153
  }
154
- #room-list li {
155
- padding: 15px 20px;
 
 
 
 
 
 
 
156
  cursor: pointer;
157
- border-bottom: 1px solid var(--border-color);
158
  transition: background-color 0.2s;
159
  display: flex;
160
  justify-content: space-between;
161
  align-items: center;
162
  }
163
- #room-list li:hover, #room-list li.active {
164
- background-color: rgba(0, 136, 204, 0.2);
165
  }
166
- .room-name {
167
- font-weight: 500;
 
168
  }
169
- .room-lock {
170
- color: var(--text-secondary);
171
- font-size: 12px;
 
172
  }
173
- .chat-area {
 
174
  flex-grow: 1;
175
  display: flex;
176
  flex-direction: column;
177
- background-color: var(--primary-bg);
178
  }
 
179
  .chat-placeholder {
180
  display: flex;
181
  flex-direction: column;
@@ -183,699 +216,788 @@ def index():
183
  justify-content: center;
184
  height: 100%;
185
  text-align: center;
186
- color: var(--text-secondary);
187
  }
188
- .chat-placeholder svg {
189
- width: 80px;
190
- height: 80px;
191
  margin-bottom: 20px;
192
- opacity: 0.5;
193
- }
194
- .chat-window {
195
- display: none;
196
- flex-direction: column;
197
- height: 100%;
198
  }
 
199
  .chat-header {
200
  padding: 15px 20px;
201
  border-bottom: 1px solid var(--border-color);
202
- background-color: var(--secondary-bg);
203
- display: flex;
204
- align-items: center;
205
- }
206
- .back-to-rooms {
207
- display: none;
208
- background: none;
209
- border: none;
210
- color: var(--text-primary);
211
- font-size: 24px;
212
- margin-right: 15px;
213
- cursor: pointer;
214
- }
215
- #chat-title {
216
- font-size: 18px;
217
  font-weight: 600;
218
  }
219
- .message-list {
 
220
  flex-grow: 1;
221
  padding: 20px;
222
  overflow-y: auto;
223
- display: flex;
224
- flex-direction: column-reverse;
225
- }
226
- .message-list-inner {
227
  display: flex;
228
  flex-direction: column;
229
  }
 
230
  .message {
231
  max-width: 70%;
232
  margin-bottom: 15px;
233
- padding: 10px 15px;
234
- border-radius: 18px;
235
  display: flex;
236
  flex-direction: column;
237
  }
 
 
 
 
 
 
 
 
 
 
 
238
  .message.sent {
 
 
 
 
239
  background-color: var(--accent-blue);
240
  color: white;
241
- align-self: flex-end;
242
  border-bottom-right-radius: 4px;
243
  }
244
  .message.received {
245
- background-color: var(--secondary-bg);
246
  align-self: flex-start;
247
- border-bottom-left-radius: 4px;
248
- }
249
- .message-sender {
250
- font-size: 12px;
251
- font-weight: 600;
252
- margin-bottom: 5px;
253
- opacity: 0.8;
254
  }
255
- .message-text {
256
- font-size: 15px;
257
- line-height: 1.4;
258
- white-space: pre-wrap;
259
- word-wrap: break-word;
260
  }
261
- .chat-input {
 
 
262
  padding: 20px;
263
  border-top: 1px solid var(--border-color);
264
- background-color: var(--secondary-bg);
265
- }
266
- .chat-input form {
267
- display: flex;
268
  }
269
  #message-input {
270
  flex-grow: 1;
271
- background-color: var(--primary-bg);
272
  border: 1px solid var(--border-color);
 
 
273
  border-radius: 20px;
274
- padding: 10px 15px;
275
- color: var(--text-primary);
276
- font-size: 15px;
277
  outline: none;
 
278
  }
279
  #message-input:focus {
280
  border-color: var(--accent-blue);
281
  }
282
- #send-btn {
283
- background-color: var(--accent-blue);
 
284
  border: none;
285
- border-radius: 50%;
286
- width: 42px;
287
- height: 42px;
288
  color: white;
289
- font-size: 20px;
290
- margin-left: 10px;
291
  cursor: pointer;
292
  transition: background-color 0.2s;
293
  }
294
- #send-btn:hover {
295
  background-color: var(--accent-blue-hover);
296
  }
297
- .modal {
298
- display: none;
 
 
 
 
299
  position: fixed;
300
- z-index: 1000;
301
- left: 0;
302
  top: 0;
 
303
  width: 100%;
304
  height: 100%;
305
- overflow: auto;
306
- background-color: rgba(0,0,0,0.6);
307
  align-items: center;
308
  justify-content: center;
 
309
  }
310
- .modal-content {
311
  background-color: var(--secondary-bg);
312
  padding: 30px;
313
- border: 1px solid var(--border-color);
314
- border-radius: 8px;
315
  width: 90%;
316
  max-width: 400px;
317
- box-shadow: 0 5px 15px rgba(0,0,0,0.5);
318
- position: relative;
 
 
 
 
 
319
  }
320
- .modal-content h2 {
321
- margin-top: 0;
 
 
 
322
  }
323
- .modal-content input[type="text"], .modal-content input[type="password"] {
324
  width: 100%;
325
  padding: 10px;
326
- margin: 10px 0;
327
- box-sizing: border-box;
328
  background-color: var(--primary-bg);
329
  border: 1px solid var(--border-color);
330
- color: var(--text-primary);
331
- border-radius: 4px;
 
332
  }
333
- .modal-content .radio-group {
334
- margin: 15px 0;
 
 
 
335
  }
336
- .modal-btn {
337
- background-color: var(--accent-blue);
338
- color: white;
339
- padding: 12px 20px;
340
  border: none;
 
341
  cursor: pointer;
342
- width: 100%;
343
- border-radius: 4px;
344
- font-size: 16px;
345
  }
346
- .modal-btn:hover {
347
- background-color: var(--accent-blue-hover);
 
348
  }
349
- .close-btn {
350
- color: #aaa;
351
- position: absolute;
352
- top: 10px;
353
- right: 20px;
354
- font-size: 28px;
355
- font-weight: bold;
356
- cursor: pointer;
357
  }
 
358
  @media (max-width: 768px) {
 
 
 
 
 
 
 
 
359
  .sidebar {
360
- position: absolute;
361
- left: 0;
362
- top: 0;
363
- height: 100%;
364
  width: 100%;
365
- z-index: 10;
366
- transition: transform 0.3s ease-in-out;
367
- transform: translateX(0);
 
 
368
  }
369
- .sidebar.hidden {
370
- transform: translateX(-100%);
371
  }
372
- .chat-area {
373
- width: 100%;
 
 
 
374
  }
375
- .back-to-rooms {
376
- display: block;
377
  }
378
  }
379
  </style>
380
  </head>
381
  <body>
382
 
383
- <div class="main-container">
384
-
385
- <div id="login-view">
386
  <h1>Virton Messenger</h1>
387
  <p>Анонимный мессенджер на блокчейне TON</p>
388
- <div id="ton-connect-button"></div>
389
  </div>
390
 
391
- <div id="messenger-view">
392
  <div class="sidebar">
393
  <div class="sidebar-header">
394
- <div id="username-display"></div>
395
- <div class="user-info" id="wallet-address-display"></div>
396
- <div class="username-actions">
397
- <a href="#" id="set-username-btn">Сменить имя</a>
398
  </div>
 
399
  </div>
400
- <div class="room-list-header">
401
- <h3>Чат-комнаты</h3>
402
- <button id="create-room-btn">+</button>
403
- </div>
404
- <div class="room-list-container">
405
- <ul id="room-list"></ul>
406
- </div>
407
  </div>
408
-
409
- <div class="chat-area">
410
  <div class="chat-placeholder" id="chat-placeholder">
411
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2.87998 12.021C2.55139 10.9333 3.23848 9.87998 4.33333 9.60677L19.2365 5.88836C20.4633 5.58385 21.5839 6.70446 21.2793 7.93126L17.5609 22.8344C17.2877 23.9293 16.2344 24.6164 15.1467 24.2878L10.3333 22.8C9.98606 22.697 9.69703 22.408 9.59398 22.0607L7.96132 16.4853L4.41421 12.9393C3.63316 12.1583 3.63316 10.8916 4.41421 10.1106C5.19526 9.32951 6.46193 9.32951 7.24298 10.1106L9.61334 12.481C9.99933 12.867 10.6316 12.867 11.0176 12.481C11.4036 12.095 11.4036 11.4628 11.0176 11.0768L2.87998 2.93934L2.87998 12.021Z"></path></svg>
412
  <h2>Добро пожаловать в Virton</h2>
413
- <p>Выберите чат-комнату или создайте новую.</p>
414
  </div>
415
- <div class="chat-window" id="chat-window">
416
- <div class="chat-header">
417
- <button class="back-to-rooms" id="back-to-rooms-btn">←</button>
418
- <h2 id="chat-title"></h2>
419
- </div>
420
- <div class="message-list" id="message-list">
421
- <div class="message-list-inner" id="message-list-inner"></div>
422
- </div>
423
- <div class="chat-input">
424
- <form id="message-form">
425
- <input type="text" id="message-input" placeholder="Введите сообщение..." autocomplete="off">
426
- <button id="send-btn" type="submit">➤</button>
427
- </form>
428
- </div>
429
  </div>
430
  </div>
431
  </div>
432
  </div>
433
 
434
- <div id="create-room-modal" class="modal">
435
- <div class="modal-content">
436
- <span class="close-btn">×</span>
437
  <h2>Создать новую комнату</h2>
438
  <form id="create-room-form">
439
- <input type="text" id="new-room-name" placeholder="Название комнаты" required>
440
- <div class="radio-group">
441
- <label><input type="radio" name="room-type" value="public" checked> Открытая</label>
442
- <label><input type="radio" name="room-type" value="private"> Закрытая</label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  </div>
444
- <input type="password" id="new-room-password" placeholder="Пароль (для закрытой комнаты)" style="display:none;">
445
- <button type="submit" class="modal-btn">Создать</button>
446
  </form>
447
  </div>
448
  </div>
449
-
450
- <div id="password-modal" class="modal">
451
- <div class="modal-content">
452
- <span class="close-btn">×</span>
453
- <h2 id="password-modal-title"></h2>
454
  <form id="password-form">
455
- <input type="password" id="room-password-input" placeholder="Введите пароль" required>
456
- <button type="submit" class="modal-btn">Войти</button>
 
 
 
 
 
 
457
  </form>
458
  </div>
459
  </div>
460
 
461
- <div id="username-modal" class="modal">
462
- <div class="modal-content">
463
- <span class="close-btn">×</span>
464
  <h2>Установить имя пользователя</h2>
 
465
  <form id="username-form">
466
- <input type="text" id="username-input" placeholder="Ваше имя (опционально)" required>
467
- <button type="submit" class="modal-btn">Сохранить</button>
 
 
 
 
 
 
468
  </form>
469
  </div>
470
  </div>
471
 
472
- <script>
473
- document.addEventListener('DOMContentLoaded', function () {
474
- const socket = io();
475
- const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
476
- manifestUrl: 'https://huggingface.co/spaces/Aleksmorshen/MorshenGroup/resolve/main/tonconnect-manifest.json',
477
- buttonRootId: 'ton-connect-button'
478
- });
479
-
480
- let userWallet = null;
481
- let currentUsername = '';
482
- let currentRoomId = null;
483
- let roomToJoin = null;
484
-
485
- const loginView = document.getElementById('login-view');
486
- const messengerView = document.getElementById('messenger-view');
487
- const roomList = document.getElementById('room-list');
488
- const chatPlaceholder = document.getElementById('chat-placeholder');
489
- const chatWindow = document.getElementById('chat-window');
490
- const messageList = document.getElementById('message-list');
491
- const messageListInner = document.getElementById('message-list-inner');
492
- const messageForm = document.getElementById('message-form');
493
- const messageInput = document.getElementById('message-input');
494
- const chatTitle = document.getElementById('chat-title');
495
- const usernameDisplay = document.getElementById('username-display');
496
- const walletAddressDisplay = document.getElementById('wallet-address-display');
497
- const sidebar = document.querySelector('.sidebar');
498
- const backToRoomsBtn = document.getElementById('back-to-rooms-btn');
499
-
500
- const modals = {
501
- createRoom: document.getElementById('create-room-modal'),
502
- password: document.getElementById('password-modal'),
503
- username: document.getElementById('username-modal')
504
- };
505
-
506
- function closeModal(modal) {
507
- if(modal) modal.style.display = 'none';
508
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
 
510
- function openModal(modal) {
511
- if(modal) modal.style.display = 'flex';
512
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
 
514
- Object.values(modals).forEach(modal => {
515
- if (modal) {
516
- modal.querySelector('.close-btn').addEventListener('click', () => closeModal(modal));
517
- }
518
- });
519
- window.addEventListener('click', (event) => {
520
- if (Object.values(modals).includes(event.target)) {
521
- closeModal(event.target);
522
- }
523
- });
524
-
525
- function isMobile() {
526
- return window.innerWidth <= 768;
527
- }
 
 
 
 
 
 
 
 
 
528
 
529
- function showChatView() {
530
- if (isMobile()) {
531
- sidebar.classList.add('hidden');
532
- }
533
- chatPlaceholder.style.display = 'none';
534
- chatWindow.style.display = 'flex';
535
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536
 
537
- function showRoomListView() {
538
- if (isMobile()) {
539
- sidebar.classList.remove('hidden');
540
- }
541
- chatWindow.style.display = 'none';
542
- chatPlaceholder.style.display = 'flex';
543
- currentRoomId = null;
544
- updateActiveRoomInList();
545
- }
546
-
547
- backToRoomsBtn.addEventListener('click', showRoomListView);
548
 
549
- tonConnectUI.onStatusChange(wallet => {
550
- if (wallet) {
551
- userWallet = wallet;
552
- loginView.style.display = 'none';
553
- messengerView.style.display = 'flex';
 
554
 
555
- socket.connect();
556
- socket.emit('authenticate', {
557
- address: userWallet.account.address
558
- });
559
- const shortAddress = `${userWallet.account.address.slice(0, 6)}...${userWallet.account.address.slice(-4)}`;
560
- walletAddressDisplay.innerText = shortAddress;
561
-
562
- } else {
563
- userWallet = null;
564
- loginView.style.display = 'flex';
565
- messengerView.style.display = 'none';
566
- socket.disconnect();
567
- }
568
- });
569
-
570
- socket.on('authenticated', (data) => {
571
- currentUsername = data.username || 'Anonymous';
572
- usernameDisplay.innerText = currentUsername;
573
- renderRoomList(data.rooms);
574
- });
575
-
576
- socket.on('update_room_list', (rooms) => {
577
- renderRoomList(rooms);
578
- });
579
-
580
- function renderRoomList(rooms) {
581
- roomList.innerHTML = '';
582
- rooms.forEach(room => {
583
- const li = document.createElement('li');
584
- li.dataset.roomId = room.id;
585
- li.dataset.roomType = room.type;
586
- li.dataset.roomName = room.name;
587
- li.innerHTML = `<span class="room-name">${room.name}</span>
588
- ${room.type === 'private' ? '<span class="room-lock">🔒</span>' : ''}`;
589
- li.addEventListener('click', () => handleRoomClick(room));
590
- roomList.appendChild(li);
591
- });
592
- updateActiveRoomInList();
593
- }
594
-
595
- function handleRoomClick(room) {
596
- if (room.type === 'private') {
597
- roomToJoin = room;
598
- document.getElementById('password-modal-title').innerText = `Войти в "${room.name}"`;
599
- document.getElementById('room-password-input').value = '';
600
- openModal(modals.password);
601
- } else {
602
- joinRoom(room.id);
603
- }
604
- }
605
-
606
- document.getElementById('password-form').addEventListener('submit', (e) => {
607
- e.preventDefault();
608
- const password = document.getElementById('room-password-input').value;
609
- if (roomToJoin && password) {
610
- joinRoom(roomToJoin.id, password);
611
- }
612
- });
613
-
614
- function joinRoom(roomId, password = null) {
615
- if (currentRoomId) {
616
- socket.emit('leave_room', { room_id: currentRoomId });
617
- }
618
- socket.emit('join_room', { room_id: roomId, password: password });
619
- }
620
 
621
- socket.on('join_error', (data) => {
622
- alert(data.error);
623
- closeModal(modals.password);
624
- });
625
-
626
- socket.on('room_joined', (data) => {
627
- currentRoomId = data.room.id;
628
- chatTitle.innerText = data.room.name;
629
- messageListInner.innerHTML = '';
630
- data.messages.forEach(addMessage);
631
- closeModal(modals.password);
632
- showChatView();
633
- updateActiveRoomInList();
634
- messageList.scrollTop = 0;
635
- });
636
-
637
- function updateActiveRoomInList() {
638
- const rooms = roomList.querySelectorAll('li');
639
- rooms.forEach(r => {
640
- if (r.dataset.roomId === currentRoomId) {
641
- r.classList.add('active');
642
- } else {
643
- r.classList.remove('active');
644
  }
645
- });
646
- }
647
 
648
- socket.on('new_message', (message) => {
649
- if (message.room_id === currentRoomId) {
650
- addMessage(message, true);
651
- }
652
- });
653
-
654
- function addMessage(msg, isNew = false) {
655
- const messageEl = document.createElement('div');
656
- const isSent = msg.user_address === userWallet.account.address;
657
- messageEl.className = `message ${isSent ? 'sent' : 'received'}`;
658
-
659
- const senderName = isSent ? 'Вы' : (msg.username || `${msg.user_address.slice(0,6)}...`);
660
-
661
- messageEl.innerHTML = `
662
- <div class="message-sender">${senderName}</div>
663
- <div class="message-text">${escapeHTML(msg.text)}</div>
664
- `;
665
- messageListInner.prepend(messageEl);
666
- if (isNew) {
667
- messageList.scrollTop = 0;
668
- }
669
- }
670
-
671
- function escapeHTML(str) {
672
- return str.replace(/[&<>"']/g, function(match) {
673
- return {
674
- '&': '&',
675
- '<': '<',
676
- '>': '>',
677
- '"': '"',
678
- "'": '''
679
- }[match];
680
- });
681
- }
682
 
683
- messageForm.addEventListener('submit', (e) => {
684
- e.preventDefault();
685
- const text = messageInput.value.trim();
686
- if (text && currentRoomId) {
687
- socket.emit('send_message', { room_id: currentRoomId, text: text });
688
- messageInput.value = '';
689
- }
690
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691
 
692
- document.getElementById('create-room-btn').addEventListener('click', () => {
693
- openModal(modals.createRoom);
694
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
 
696
- document.querySelectorAll('input[name="room-type"]').forEach(radio => {
697
- radio.addEventListener('change', function() {
698
- document.getElementById('new-room-password').style.display = this.value === 'private' ? 'block' : 'none';
699
- });
700
- });
701
 
702
- document.getElementById('create-room-form').addEventListener('submit', (e) => {
703
- e.preventDefault();
704
- const name = document.getElementById('new-room-name').value;
705
- const type = document.querySelector('input[name="room-type"]:checked').value;
706
- const password = document.getElementById('new-room-password').value;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
707
 
708
- if (type === 'private' && !password) {
709
- alert('Для закрытой комнаты нужен пароль.');
710
- return;
711
- }
712
-
713
- socket.emit('create_room', { name, type, password });
714
- closeModal(modals.createRoom);
715
- e.target.reset();
716
- document.getElementById('new-room-password').style.display = 'none';
717
- });
718
-
719
- document.getElementById('set-username-btn').addEventListener('click', (e) => {
720
- e.preventDefault();
721
- document.getElementById('username-input').value = currentUsername === 'Anonymous' ? '' : currentUsername;
722
- openModal(modals.username);
723
- });
724
-
725
- document.getElementById('username-form').addEventListener('submit', (e) => {
726
- e.preventDefault();
727
- const newUsername = document.getElementById('username-input').value.trim();
728
- if (newUsername) {
729
- socket.emit('set_username', { username: newUsername });
730
- }
731
- });
732
-
733
- socket.on('username_updated', (data) => {
734
- currentUsername = data.username;
735
- usernameDisplay.innerText = currentUsername;
736
- closeModal(modals.username);
737
- });
738
- });
739
- </script>
740
 
 
 
741
  </body>
742
  </html>
743
  """
744
- return Response(html_content, mimetype='text/html')
745
 
746
- @socketio.on('connect')
747
- def handle_connect():
748
- print('Client connected')
749
-
750
- @socketio.on('disconnect')
751
- def handle_disconnect():
752
- print('Client disconnected')
753
 
754
- @socketio.on('authenticate')
755
- def handle_auth(data):
756
- address = data['address']
 
 
 
 
757
  db = load_db()
758
  if address not in db['users']:
759
- db['users'][address] = {'username': ''}
 
 
 
760
  save_db(db)
 
 
761
 
762
- user_data = db['users'][address]
763
- rooms = [{"id": r_id, "name": r_data["name"], "type": r_data["type"]} for r_id, r_data in db['chatrooms'].items()]
764
-
765
- emit('authenticated', {
766
- 'username': user_data.get('username'),
767
- 'rooms': rooms
768
- })
769
-
770
- @socketio.on('set_username')
771
- def handle_set_username(data):
772
- address = next((addr for addr, sid in socketio.server.manager.sid_map.items() if sid == request.sid), None)
773
- if not address:
774
- address = next((addr for addr, user_session in socketio.server.manager.sessions.items() if request.sid in user_session), None)
775
-
776
- if address:
777
- db = load_db()
778
- username = data.get('username', '').strip()
779
- if 2 <= len(username) <= 20:
780
- db['users'][address]['username'] = username
781
- save_db(db)
782
- emit('username_updated', {'username': username})
783
-
784
- @socketio.on('create_room')
785
- def handle_create_room(data):
786
- address = next((addr for addr, sid in socketio.server.manager.sid_map.items() if sid == request.sid), None)
787
  if not address:
788
- address = next((addr for addr, user_session in socketio.server.manager.sessions.items() if request.sid in user_session), None)
 
 
 
 
 
 
 
 
 
789
 
790
- if not address: return
791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792
  db = load_db()
793
  room_id = str(uuid.uuid4())
794
- room_name = data.get('name', 'Новая комната').strip()
795
- room_type = data.get('type', 'public')
796
- password = data.get('password') if room_type == 'private' else None
797
-
798
- if not (2 <= len(room_name) <= 30):
799
- return
800
-
801
  db['chatrooms'][room_id] = {
802
- 'name': room_name,
 
803
  'type': room_type,
804
- 'password': password,
805
- 'creator': address,
806
  'messages': []
807
  }
808
  save_db(db)
 
809
 
810
- rooms = [{"id": r_id, "name": r_data["name"], "type": r_data["type"]} for r_id, r_data in db['chatrooms'].items()]
811
- emit('update_room_list', rooms, broadcast=True)
812
-
813
- @socketio.on('join_room')
814
- def handle_join_room(data):
815
- address = next((addr for addr, sid in socketio.server.manager.sid_map.items() if sid == request.sid), None)
816
- if not address:
817
- address = next((addr for addr, user_session in socketio.server.manager.sessions.items() if request.sid in user_session), None)
818
-
819
- if not address: return
820
-
821
- db = load_db()
822
- room_id = data.get('room_id')
823
  password = data.get('password')
824
 
825
- if room_id not in db['chatrooms']:
826
- emit('join_error', {'error': 'Комната не найдена'})
827
- return
828
-
829
- room_data = db['chatrooms'][room_id]
830
- if room_data['type'] == 'private' and room_data['password'] != password:
831
- emit('join_error', {'error': 'Неверный пароль'})
832
- return
833
-
834
- join_room(room_id)
835
- socketio.server.manager.sid_map[request.sid] = address
836
- emit('room_joined', {
837
- 'room': {'id': room_id, 'name': room_data['name'], 'type': room_data['type']},
838
- 'messages': room_data.get('messages', [])[-50:]
839
- })
840
-
841
- @socketio.on('leave_room')
842
- def handle_leave_room(data):
843
- room_id = data.get('room_id')
844
- leave_room(room_id)
845
-
846
- @socketio.on('send_message')
847
- def handle_send_message(data):
848
- address = next((addr for addr, sid in socketio.server.manager.sid_map.items() if sid == request.sid), None)
849
  if not address:
850
- address = next((addr for addr, user_session in socketio.server.manager.sessions.items() if request.sid in user_session), None)
851
 
852
- if not address: return
 
 
 
 
 
 
 
 
 
853
 
 
 
854
  db = load_db()
855
- room_id = data.get('room_id')
856
- text = data.get('text', '').strip()
 
 
 
 
 
 
 
 
 
857
 
858
- if not (text and room_id in db['chatrooms']):
859
- return
860
-
861
- user = db['users'].get(address, {})
 
 
 
 
862
  message = {
863
- 'user_address': address,
864
- 'username': user.get('username'),
865
  'text': text,
866
- 'timestamp': json.dumps(uuid.uuid4().hex)
 
 
867
  }
868
-
869
- db['chatrooms'][room_id]['messages'].append(message)
870
- if len(db['chatrooms'][room_id]['messages']) > 100:
871
- db['chatrooms'][room_id]['messages'] = db['chatrooms'][room_id]['messages'][-100:]
872
  save_db(db)
873
-
874
- message_to_send = message.copy()
875
- message_to_send['room_id'] = room_id
876
- emit('new_message', message_to_send, to=room_id)
877
-
878
 
879
  if __name__ == '__main__':
880
- load_db()
881
- socketio.run(app, host='0.0.0.0', port=7860, debug=False)
 
1
  import os
2
  import json
3
  import uuid
4
+ import time
5
+ import hashlib
6
+ from flask import Flask, Response, request, jsonify
7
 
8
  app = Flask(__name__)
 
 
9
 
10
  DB_FILE = 'virton_db.json'
11
 
12
  def load_db():
13
  if not os.path.exists(DB_FILE):
14
  with open(DB_FILE, 'w') as f:
15
+ json.dump({"chatrooms": {}, "users": {}}, f)
16
  with open(DB_FILE, 'r') as f:
17
  return json.load(f)
18
 
 
20
  with open(DB_FILE, 'w') as f:
21
  json.dump(data, f, indent=4)
22
 
23
+ def hash_password(password):
24
+ return hashlib.sha256(password.encode('utf-8')).hexdigest()
25
+
26
+ HTML_TEMPLATE = """
27
  <!DOCTYPE html>
28
  <html lang="ru">
29
  <head>
 
31
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
32
  <title>Virton Messenger</title>
33
  <script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>
34
+ <link rel="preconnect" href="https://fonts.googleapis.com">
35
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
36
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
37
  <style>
38
  :root {
39
+ --primary-bg: #121212;
40
+ --secondary-bg: #1e1e1e;
41
+ --tertiary-bg: #2a2a2a;
42
+ --primary-text: #e0e0e0;
43
+ --secondary-text: #a0a0a0;
44
+ --accent-blue: #0098EA;
45
  --accent-blue-hover: #00aaff;
46
+ --border-color: #333;
47
+ --error-color: #ff4d4d;
48
+ --success-color: #4caf50;
49
+ --font-family: 'Inter', sans-serif;
50
+ }
51
+
52
+ * {
53
+ box-sizing: border-box;
54
+ margin: 0;
55
+ padding: 0;
56
  }
57
+
58
  body {
59
  font-family: var(--font-family);
60
  background-color: var(--primary-bg);
61
+ color: var(--primary-text);
 
 
62
  display: flex;
63
  align-items: center;
64
  justify-content: center;
65
  height: 100vh;
66
+ overflow: hidden;
67
  }
68
+
69
+ .container {
70
  width: 100%;
71
  height: 100%;
72
  display: flex;
73
  flex-direction: column;
74
+ max-width: 1200px;
75
+ max-height: 900px;
76
+ background-color: var(--secondary-bg);
77
+ border-radius: 16px;
78
+ overflow: hidden;
79
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
80
+ border: 1px solid var(--border-color);
81
  }
82
+
83
+ .auth-view {
84
  display: flex;
85
  flex-direction: column;
86
  align-items: center;
87
  justify-content: center;
88
  height: 100%;
89
+ background: linear-gradient(135deg, rgba(0, 152, 234, 0.1) 0%, rgba(18, 18, 18, 0) 50%);
90
  }
91
+
92
+ .auth-view h1 {
93
  font-size: 3rem;
94
+ font-weight: 700;
 
95
  margin-bottom: 10px;
96
+ background: -webkit-linear-gradient(45deg, #0098EA, #00C6FB);
97
+ -webkit-background-clip: text;
98
+ -webkit-text-fill-color: transparent;
99
+ }
100
+ .auth-view p {
101
+ font-size: 1.1rem;
102
+ color: var(--secondary-text);
103
+ margin-bottom: 40px;
104
  }
105
+ #ton-connect-button-container {
106
+ transform: scale(1.2);
 
 
107
  }
108
+
109
+ .main-app {
110
  display: none;
 
 
111
  flex-direction: row;
112
+ height: 100%;
113
+ width: 100%;
114
  }
115
+
116
  .sidebar {
117
  width: 300px;
118
+ background-color: var(--primary-bg);
119
  border-right: 1px solid var(--border-color);
120
  display: flex;
121
  flex-direction: column;
122
+ padding: 15px;
123
+ transition: width 0.3s ease;
124
  }
125
+
126
  .sidebar-header {
127
+ padding-bottom: 15px;
128
  border-bottom: 1px solid var(--border-color);
129
+ margin-bottom: 15px;
 
 
130
  }
131
+
132
  .sidebar-header .user-info {
133
+ display: flex;
134
+ align-items: center;
135
+ gap: 10px;
136
+ margin-bottom: 15px;
137
  }
138
+
139
+ .sidebar-header .user-info .username {
140
  font-weight: 600;
 
 
 
 
141
  cursor: pointer;
 
 
 
 
 
 
 
 
 
 
142
  }
143
+
144
+ .sidebar-header .user-info .username:hover {
145
+ color: var(--accent-blue);
 
 
146
  }
147
+
148
+ #ton-connect-button-sidebar {
149
+ width: 100%;
150
  }
151
+
152
+ .create-room-btn {
153
+ width: 100%;
154
+ padding: 12px;
155
+ background-color: var(--accent-blue);
156
+ color: white;
157
  border: none;
158
+ border-radius: 8px;
159
+ font-size: 1rem;
160
+ font-weight: 600;
161
  cursor: pointer;
162
+ transition: background-color 0.2s;
163
+ margin-top: 10px;
164
  }
165
+ .create-room-btn:hover {
166
+ background-color: var(--accent-blue-hover);
167
  }
168
+
169
+ .chat-list-header {
170
+ color: var(--secondary-text);
171
+ text-transform: uppercase;
172
+ font-size: 0.8rem;
173
+ font-weight: 700;
174
+ margin-bottom: 10px;
175
  }
176
+
177
+ #chat-list {
178
+ flex-grow: 1;
179
+ overflow-y: auto;
180
+ }
181
+
182
+ .chat-list-item {
183
+ padding: 12px;
184
+ border-radius: 8px;
185
  cursor: pointer;
186
+ margin-bottom: 5px;
187
  transition: background-color 0.2s;
188
  display: flex;
189
  justify-content: space-between;
190
  align-items: center;
191
  }
192
+ .chat-list-item:hover {
193
+ background-color: var(--tertiary-bg);
194
  }
195
+ .chat-list-item.active {
196
+ background-color: var(--accent-blue);
197
+ color: white;
198
  }
199
+
200
+ .chat-list-item .lock-icon {
201
+ opacity: 0.7;
202
+ font-size: 0.8rem;
203
  }
204
+
205
+ .chat-view {
206
  flex-grow: 1;
207
  display: flex;
208
  flex-direction: column;
209
+ background-color: var(--secondary-bg);
210
  }
211
+
212
  .chat-placeholder {
213
  display: flex;
214
  flex-direction: column;
 
216
  justify-content: center;
217
  height: 100%;
218
  text-align: center;
219
+ color: var(--secondary-text);
220
  }
221
+
222
+ .chat-placeholder-icon {
223
+ font-size: 4rem;
224
  margin-bottom: 20px;
225
+ opacity: 0.3;
 
 
 
 
 
226
  }
227
+
228
  .chat-header {
229
  padding: 15px 20px;
230
  border-bottom: 1px solid var(--border-color);
231
+ background-color: var(--tertiary-bg);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  font-weight: 600;
233
  }
234
+
235
+ .messages-container {
236
  flex-grow: 1;
237
  padding: 20px;
238
  overflow-y: auto;
 
 
 
 
239
  display: flex;
240
  flex-direction: column;
241
  }
242
+
243
  .message {
244
  max-width: 70%;
245
  margin-bottom: 15px;
 
 
246
  display: flex;
247
  flex-direction: column;
248
  }
249
+ .message-content {
250
+ padding: 10px 15px;
251
+ border-radius: 18px;
252
+ line-height: 1.4;
253
+ }
254
+ .message-sender {
255
+ font-size: 0.8rem;
256
+ color: var(--secondary-text);
257
+ margin-bottom: 4px;
258
+ font-weight: 500;
259
+ }
260
  .message.sent {
261
+ align-self: flex-end;
262
+ align-items: flex-end;
263
+ }
264
+ .message.sent .message-content {
265
  background-color: var(--accent-blue);
266
  color: white;
 
267
  border-bottom-right-radius: 4px;
268
  }
269
  .message.received {
 
270
  align-self: flex-start;
271
+ align-items: flex-start;
 
 
 
 
 
 
272
  }
273
+ .message.received .message-content {
274
+ background-color: var(--tertiary-bg);
275
+ border-bottom-left-radius: 4px;
 
 
276
  }
277
+
278
+ .message-input-form {
279
+ display: flex;
280
  padding: 20px;
281
  border-top: 1px solid var(--border-color);
282
+ background-color: var(--tertiary-bg);
 
 
 
283
  }
284
  #message-input {
285
  flex-grow: 1;
286
+ padding: 12px 15px;
287
  border: 1px solid var(--border-color);
288
+ background-color: var(--secondary-bg);
289
+ color: var(--primary-text);
290
  border-radius: 20px;
291
+ font-size: 1rem;
 
 
292
  outline: none;
293
+ transition: border-color 0.2s;
294
  }
295
  #message-input:focus {
296
  border-color: var(--accent-blue);
297
  }
298
+ #send-button {
299
+ margin-left: 10px;
300
+ padding: 0 20px;
301
  border: none;
302
+ background-color: var(--accent-blue);
 
 
303
  color: white;
304
+ border-radius: 20px;
305
+ font-size: 1rem;
306
  cursor: pointer;
307
  transition: background-color 0.2s;
308
  }
309
+ #send-button:hover {
310
  background-color: var(--accent-blue-hover);
311
  }
312
+ #send-button:disabled {
313
+ background-color: var(--tertiary-bg);
314
+ cursor: not-allowed;
315
+ }
316
+
317
+ .modal-overlay {
318
  position: fixed;
 
 
319
  top: 0;
320
+ left: 0;
321
  width: 100%;
322
  height: 100%;
323
+ background-color: rgba(0, 0, 0, 0.7);
324
+ display: none;
325
  align-items: center;
326
  justify-content: center;
327
+ z-index: 1000;
328
  }
329
+ .modal {
330
  background-color: var(--secondary-bg);
331
  padding: 30px;
332
+ border-radius: 12px;
 
333
  width: 90%;
334
  max-width: 400px;
335
+ border: 1px solid var(--border-color);
336
+ }
337
+ .modal h2 {
338
+ margin-bottom: 20px;
339
+ }
340
+ .modal-form-group {
341
+ margin-bottom: 15px;
342
  }
343
+ .modal-form-group label {
344
+ display: block;
345
+ margin-bottom: 5px;
346
+ color: var(--secondary-text);
347
+ font-size: 0.9rem;
348
  }
349
+ .modal-input, .modal-select {
350
  width: 100%;
351
  padding: 10px;
 
 
352
  background-color: var(--primary-bg);
353
  border: 1px solid var(--border-color);
354
+ color: var(--primary-text);
355
+ border-radius: 8px;
356
+ font-size: 1rem;
357
  }
358
+ .modal-buttons {
359
+ margin-top: 25px;
360
+ display: flex;
361
+ justify-content: flex-end;
362
+ gap: 10px;
363
  }
364
+ .modal-button {
365
+ padding: 10px 20px;
 
 
366
  border: none;
367
+ border-radius: 8px;
368
  cursor: pointer;
369
+ font-weight: 600;
 
 
370
  }
371
+ .modal-button.primary {
372
+ background-color: var(--accent-blue);
373
+ color: white;
374
  }
375
+ .modal-button.secondary {
376
+ background-color: var(--tertiary-bg);
377
+ color: var(--primary-text);
378
+ }
379
+
380
+ .hidden {
381
+ display: none !important;
 
382
  }
383
+
384
  @media (max-width: 768px) {
385
+ .container {
386
+ max-height: none;
387
+ height: 100vh;
388
+ border-radius: 0;
389
+ }
390
+ .main-app {
391
+ flex-direction: column;
392
+ }
393
  .sidebar {
 
 
 
 
394
  width: 100%;
395
+ height: auto;
396
+ border-right: none;
397
+ border-bottom: 1px solid var(--border-color);
398
+ flex-shrink: 0;
399
+ padding: 10px;
400
  }
401
+ #chat-list {
402
+ max-height: 150px;
403
  }
404
+ .chat-view {
405
+ height: 100%;
406
+ }
407
+ .auth-view h1 {
408
+ font-size: 2.5rem;
409
  }
410
+ .message-input-form {
411
+ padding: 10px;
412
  }
413
  }
414
  </style>
415
  </head>
416
  <body>
417
 
418
+ <div class="container">
419
+ <div id="auth-view" class="auth-view">
 
420
  <h1>Virton Messenger</h1>
421
  <p>Анонимный мессенджер на блокчейне TON</p>
422
+ <div id="ton-connect-button-container"></div>
423
  </div>
424
 
425
+ <div id="main-app" class="main-app">
426
  <div class="sidebar">
427
  <div class="sidebar-header">
428
+ <div class="user-info">
429
+ <span class="username" id="username-display" title="Нажмите, чтобы изменить"></span>
 
 
430
  </div>
431
+ <button class="create-room-btn" id="create-room-show-modal-btn">Создать комнату</button>
432
  </div>
433
+ <div class="chat-list-header">Комнаты</div>
434
+ <div id="chat-list"></div>
 
 
 
 
 
435
  </div>
436
+ <div class="chat-view" id="chat-view-container">
 
437
  <div class="chat-placeholder" id="chat-placeholder">
438
+ <div class="chat-placeholder-icon">💬</div>
439
  <h2>Добро пожаловать в Virton</h2>
440
+ <p>Выберите комнату, чтобы начать общение, или создайте свою.</p>
441
  </div>
442
+ <div id="chat-room" class="hidden">
443
+ <div class="chat-header" id="chat-room-name"></div>
444
+ <div class="messages-container" id="messages-container"></div>
445
+ <form class="message-input-form" id="message-form">
446
+ <input type="text" id="message-input" placeholder="Введите сообщение..." autocomplete="off">
447
+ <button type="submit" id="send-button" disabled>Отправить</button>
448
+ </form>
 
 
 
 
 
 
 
449
  </div>
450
  </div>
451
  </div>
452
  </div>
453
 
454
+ <!-- Modals -->
455
+ <div id="create-room-modal" class="modal-overlay">
456
+ <div class="modal">
457
  <h2>Создать новую комнату</h2>
458
  <form id="create-room-form">
459
+ <div class="modal-form-group">
460
+ <label for="room-name">Название комнаты</label>
461
+ <input type="text" id="room-name" class="modal-input" required>
462
+ </div>
463
+ <div class="modal-form-group">
464
+ <label for="room-type">Тип комнаты</label>
465
+ <select id="room-type" class="modal-select">
466
+ <option value="public">Открытая</option>
467
+ <option value="private">Закрытая (с паролем)</option>
468
+ </select>
469
+ </div>
470
+ <div class="modal-form-group hidden" id="room-password-group">
471
+ <label for="room-password">Пароль</label>
472
+ <input type="password" id="room-password" class="modal-input">
473
+ </div>
474
+ <div class="modal-buttons">
475
+ <button type="button" class="modal-button secondary" id="create-room-cancel-btn">Отмена</button>
476
+ <button type="submit" class="modal-button primary">Создать</button>
477
  </div>
 
 
478
  </form>
479
  </div>
480
  </div>
481
+
482
+ <div id="password-modal" class="modal-overlay">
483
+ <div class="modal">
484
+ <h2>Вход в закрытую комнату</h2>
485
+ <p>Комната "<span id="password-modal-room-name"></span>" защищена паролем.</p>
486
  <form id="password-form">
487
+ <div class="modal-form-group">
488
+ <label for="join-password">Пароль</label>
489
+ <input type="password" id="join-password" class="modal-input" required>
490
+ </div>
491
+ <div class="modal-buttons">
492
+ <button type="button" class="modal-button secondary" id="password-cancel-btn">Отмена</button>
493
+ <button type="submit" class="modal-button primary">Войти</button>
494
+ </div>
495
  </form>
496
  </div>
497
  </div>
498
 
499
+ <div id="username-modal" class="modal-overlay">
500
+ <div class="modal">
 
501
  <h2>Установить имя пользователя</h2>
502
+ <p>Это имя будет отображаться другим пользователям. Если оставить поле пустым, будет использоваться ваш адрес кошелька.</p>
503
  <form id="username-form">
504
+ <div class="modal-form-group">
505
+ <label for="new-username">Имя пользователя (опционально)</label>
506
+ <input type="text" id="new-username" class="modal-input" maxlength="20">
507
+ </div>
508
+ <div class="modal-buttons">
509
+ <button type="button" class="modal-button secondary" id="username-cancel-btn">Отмена</button>
510
+ <button type="submit" class="modal-button primary">Сохранить</button>
511
+ </div>
512
  </form>
513
  </div>
514
  </div>
515
 
516
+ <script>
517
+ document.addEventListener('DOMContentLoaded', () => {
518
+ const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
519
+ manifestUrl: 'https://gist.githubusercontent.com/Aleksmorshen/524b31a39b360b54133499426f4995a0/raw/tonconnect-manifest.json',
520
+ buttonRootId: 'ton-connect-button-container'
521
+ });
522
+
523
+ const state = {
524
+ wallet: null,
525
+ username: '',
526
+ chatrooms: [],
527
+ currentRoomId: null,
528
+ messages: [],
529
+ messagePollingInterval: null
530
+ };
531
+
532
+ const ui = {
533
+ authView: document.getElementById('auth-view'),
534
+ mainApp: document.getElementById('main-app'),
535
+ chatList: document.getElementById('chat-list'),
536
+ chatPlaceholder: document.getElementById('chat-placeholder'),
537
+ chatRoom: document.getElementById('chat-room'),
538
+ chatRoomName: document.getElementById('chat-room-name'),
539
+ messagesContainer: document.getElementById('messages-container'),
540
+ messageForm: document.getElementById('message-form'),
541
+ messageInput: document.getElementById('message-input'),
542
+ sendButton: document.getElementById('send-button'),
543
+ usernameDisplay: document.getElementById('username-display'),
544
+ createRoomModal: {
545
+ overlay: document.getElementById('create-room-modal'),
546
+ form: document.getElementById('create-room-form'),
547
+ roomName: document.getElementById('room-name'),
548
+ roomType: document.getElementById('room-type'),
549
+ passwordGroup: document.getElementById('room-password-group'),
550
+ passwordInput: document.getElementById('room-password'),
551
+ cancelBtn: document.getElementById('create-room-cancel-btn'),
552
+ showBtn: document.getElementById('create-room-show-modal-btn')
553
+ },
554
+ passwordModal: {
555
+ overlay: document.getElementById('password-modal'),
556
+ form: document.getElementById('password-form'),
557
+ roomName: document.getElementById('password-modal-room-name'),
558
+ passwordInput: document.getElementById('join-password'),
559
+ cancelBtn: document.getElementById('password-cancel-btn'),
560
+ data: { roomIdToJoin: null }
561
+ },
562
+ usernameModal: {
563
+ overlay: document.getElementById('username-modal'),
564
+ form: document.getElementById('username-form'),
565
+ input: document.getElementById('new-username'),
566
+ cancelBtn: document.getElementById('username-cancel-btn')
567
+ }
568
+ };
569
+
570
+ const formatAddress = (addr) => `${addr.slice(0, 4)}...${addr.slice(-4)}`;
571
+
572
+ async function apiCall(endpoint, method = 'GET', body = null) {
573
+ const options = {
574
+ method,
575
+ headers: { 'Content-Type': 'application/json' }
576
+ };
577
+ if (body) {
578
+ options.body = JSON.stringify(body);
579
+ }
580
+ const response = await fetch(`/api${endpoint}`, options);
581
+ if (!response.ok) {
582
+ const errorData = await response.json();
583
+ throw new Error(errorData.error || 'API call failed');
584
+ }
585
+ return response.json();
586
+ }
587
 
588
+ function renderChatList() {
589
+ ui.chatList.innerHTML = '';
590
+ state.chatrooms.forEach(room => {
591
+ const item = document.createElement('div');
592
+ item.className = 'chat-list-item';
593
+ item.dataset.roomId = room.id;
594
+ if (room.id === state.currentRoomId) {
595
+ item.classList.add('active');
596
+ }
597
+
598
+ const nameSpan = document.createElement('span');
599
+ nameSpan.textContent = room.name;
600
+
601
+ item.appendChild(nameSpan);
602
+
603
+ if (room.type === 'private') {
604
+ const lockIcon = document.createElement('span');
605
+ lockIcon.className = 'lock-icon';
606
+ lockIcon.textContent = '🔒';
607
+ item.appendChild(lockIcon);
608
+ }
609
+
610
+ item.addEventListener('click', () => joinRoom(room.id));
611
+ ui.chatList.appendChild(item);
612
+ });
613
+ }
614
 
615
+ function renderMessages() {
616
+ ui.messagesContainer.innerHTML = '';
617
+ state.messages.forEach(msg => {
618
+ const messageEl = document.createElement('div');
619
+ messageEl.className = 'message';
620
+ const senderAddress = msg.sender_address;
621
+
622
+ if (senderAddress === state.wallet.account.address) {
623
+ messageEl.classList.add('sent');
624
+ } else {
625
+ messageEl.classList.add('received');
626
+ }
627
+
628
+ const senderName = msg.username || formatAddress(senderAddress);
629
+
630
+ messageEl.innerHTML = `
631
+ <div class="message-sender">${senderName}</div>
632
+ <div class="message-content">${msg.text}</div>
633
+ `;
634
+ ui.messagesContainer.appendChild(messageEl);
635
+ });
636
+ ui.messagesContainer.scrollTop = ui.messagesContainer.scrollHeight;
637
+ }
638
 
639
+ async function fetchChatrooms() {
640
+ try {
641
+ const data = await apiCall('/chatrooms');
642
+ state.chatrooms = data.chatrooms;
643
+ renderChatList();
644
+ } catch (error) {
645
+ console.error('Failed to fetch chatrooms:', error);
646
+ }
647
+ }
648
+
649
+ async function fetchMessages(roomId) {
650
+ if (!roomId) return;
651
+ try {
652
+ const data = await apiCall(`/chatrooms/${roomId}/messages`);
653
+ if (JSON.stringify(state.messages) !== JSON.stringify(data.messages)) {
654
+ state.messages = data.messages;
655
+ renderMessages();
656
+ }
657
+ } catch (error) {
658
+ console.error('Failed to fetch messages:', error);
659
+ stopMessagePolling();
660
+ }
661
+ }
662
 
663
+ function startMessagePolling() {
664
+ stopMessagePolling();
665
+ if (state.currentRoomId) {
666
+ fetchMessages(state.currentRoomId);
667
+ state.messagePollingInterval = setInterval(() => {
668
+ fetchMessages(state.currentRoomId);
669
+ }, 3000);
670
+ }
671
+ }
 
 
672
 
673
+ function stopMessagePolling() {
674
+ if (state.messagePollingInterval) {
675
+ clearInterval(state.messagePollingInterval);
676
+ state.messagePollingInterval = null;
677
+ }
678
+ }
679
 
680
+ async function joinRoom(roomId, password = null) {
681
+ const room = state.chatrooms.find(r => r.id === roomId);
682
+ if (!room) return;
683
+
684
+ if (room.type === 'private' && !password) {
685
+ ui.passwordModal.data.roomIdToJoin = roomId;
686
+ ui.passwordModal.roomName.textContent = room.name;
687
+ ui.passwordModal.overlay.style.display = 'flex';
688
+ ui.passwordModal.passwordInput.focus();
689
+ return;
690
+ }
691
+
692
+ try {
693
+ await apiCall(`/chatrooms/${roomId}/join`, 'POST', {
694
+ address: state.wallet.account.address,
695
+ password: password
696
+ });
697
+
698
+ state.currentRoomId = roomId;
699
+ state.messages = [];
700
+ ui.chatRoomName.textContent = room.name;
701
+ ui.chatPlaceholder.classList.add('hidden');
702
+ ui.chatRoom.classList.remove('hidden');
703
+ ui.messageInput.value = '';
704
+ ui.sendButton.disabled = false;
705
+
706
+ if (ui.passwordModal.overlay.style.display === 'flex') {
707
+ ui.passwordModal.overlay.style.display = 'none';
708
+ ui.passwordModal.form.reset();
709
+ }
710
+
711
+ renderChatList();
712
+ startMessagePolling();
713
+
714
+ } catch (error) {
715
+ alert(`Не удалось войти в комнату: ${error.message}`);
716
+ ui.passwordModal.form.reset();
717
+ }
718
+ }
719
+
720
+ function onConnect(wallet) {
721
+ state.wallet = wallet;
722
+ ui.authView.style.display = 'none';
723
+ ui.mainApp.style.display = 'flex';
724
+
725
+ apiCall('/user', 'POST', { address: wallet.account.address })
726
+ .then(data => {
727
+ state.username = data.username;
728
+ updateUsernameDisplay();
729
+ });
730
+
731
+ fetchChatrooms();
732
+ }
 
 
 
 
 
 
 
 
 
 
 
 
733
 
734
+ function onDisconnect() {
735
+ stopMessagePolling();
736
+ state.wallet = null;
737
+ state.currentRoomId = null;
738
+ state.username = '';
739
+ ui.authView.style.display = 'flex';
740
+ ui.mainApp.style.display = 'none';
741
+ ui.chatPlaceholder.classList.remove('hidden');
742
+ ui.chatRoom.classList.add('hidden');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  }
 
 
744
 
745
+ function updateUsernameDisplay() {
746
+ const displayName = state.username || formatAddress(state.wallet.account.address);
747
+ ui.usernameDisplay.textContent = displayName;
748
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
 
750
+ tonConnectUI.onStatusChange(wallet => {
751
+ if (wallet) {
752
+ onConnect(wallet);
753
+ } else {
754
+ onDisconnect();
755
+ }
756
+ });
757
+
758
+ ui.createRoomModal.showBtn.addEventListener('click', () => {
759
+ ui.createRoomModal.overlay.style.display = 'flex';
760
+ });
761
+
762
+ ui.createRoomModal.cancelBtn.addEventListener('click', () => {
763
+ ui.createRoomModal.overlay.style.display = 'none';
764
+ ui.createRoomModal.form.reset();
765
+ ui.createRoomModal.passwordGroup.classList.add('hidden');
766
+ });
767
+
768
+ ui.createRoomModal.roomType.addEventListener('change', (e) => {
769
+ if (e.target.value === 'private') {
770
+ ui.createRoomModal.passwordGroup.classList.remove('hidden');
771
+ ui.createRoomModal.passwordInput.required = true;
772
+ } else {
773
+ ui.createRoomModal.passwordGroup.classList.add('hidden');
774
+ ui.createRoomModal.passwordInput.required = false;
775
+ }
776
+ });
777
 
778
+ ui.createRoomModal.form.addEventListener('submit', async (e) => {
779
+ e.preventDefault();
780
+ const roomName = ui.createRoomModal.roomName.value.trim();
781
+ const roomType = ui.createRoomModal.roomType.value;
782
+ const password = ui.createRoomModal.passwordInput.value;
783
+
784
+ if (!roomName) return;
785
+ if (roomType === 'private' && !password) {
786
+ alert('Для закрытой комнаты необходим пароль.');
787
+ return;
788
+ }
789
+
790
+ try {
791
+ await apiCall('/chatrooms', 'POST', {
792
+ name: roomName,
793
+ type: roomType,
794
+ password: roomType === 'private' ? password : null,
795
+ creator_address: state.wallet.account.address
796
+ });
797
+ ui.createRoomModal.overlay.style.display = 'none';
798
+ ui.createRoomModal.form.reset();
799
+ ui.createRoomModal.passwordGroup.classList.add('hidden');
800
+ fetchChatrooms();
801
+ } catch (error) {
802
+ alert(`Ошибка создания комнаты: ${error.message}`);
803
+ }
804
+ });
805
 
806
+ ui.passwordModal.cancelBtn.addEventListener('click', () => {
807
+ ui.passwordModal.overlay.style.display = 'none';
808
+ ui.passwordModal.form.reset();
809
+ });
 
810
 
811
+ ui.passwordModal.form.addEventListener('submit', (e) => {
812
+ e.preventDefault();
813
+ const password = ui.passwordModal.passwordInput.value;
814
+ joinRoom(ui.passwordModal.data.roomIdToJoin, password);
815
+ });
816
+
817
+ ui.messageForm.addEventListener('submit', async (e) => {
818
+ e.preventDefault();
819
+ const text = ui.messageInput.value.trim();
820
+ if (!text || !state.currentRoomId) return;
821
+
822
+ ui.sendButton.disabled = true;
823
+
824
+ try {
825
+ await apiCall(`/chatrooms/${state.currentRoomId}/messages`, 'POST', {
826
+ text: text,
827
+ sender_address: state.wallet.account.address,
828
+ username: state.username
829
+ });
830
+ ui.messageInput.value = '';
831
+ fetchMessages(state.currentRoomId);
832
+ } catch (error) {
833
+ console.error('Failed to send message:', error);
834
+ alert('Не удалось отправить сообщение.');
835
+ } finally {
836
+ ui.sendButton.disabled = false;
837
+ ui.messageInput.focus();
838
+ }
839
+ });
840
 
841
+ ui.usernameDisplay.addEventListener('click', () => {
842
+ ui.usernameModal.input.value = state.username;
843
+ ui.usernameModal.overlay.style.display = 'flex';
844
+ });
845
+
846
+ ui.usernameModal.cancelBtn.addEventListener('click', () => {
847
+ ui.usernameModal.overlay.style.display = 'none';
848
+ });
849
+
850
+ ui.usernameModal.form.addEventListener('submit', async (e) => {
851
+ e.preventDefault();
852
+ const newUsername = ui.usernameModal.input.value.trim();
853
+ try {
854
+ const data = await apiCall('/user/set_username', 'POST', {
855
+ address: state.wallet.account.address,
856
+ username: newUsername
857
+ });
858
+ state.username = data.username;
859
+ updateUsernameDisplay();
860
+ ui.usernameModal.overlay.style.display = 'none';
861
+ } catch (error) {
862
+ alert(`Ошибка: ${error.message}`);
863
+ }
864
+ });
 
 
 
 
 
 
 
 
865
 
866
+ });
867
+ </script>
868
  </body>
869
  </html>
870
  """
 
871
 
872
+ @app.route('/')
873
+ def index():
874
+ return Response(HTML_TEMPLATE, mimetype='text/html')
 
 
 
 
875
 
876
+ @app.route('/api/user', methods=['POST'])
877
+ def get_or_create_user():
878
+ data = request.get_json()
879
+ address = data.get('address')
880
+ if not address:
881
+ return jsonify({'error': 'Address is required'}), 400
882
+
883
  db = load_db()
884
  if address not in db['users']:
885
+ db['users'][address] = {
886
+ 'address': address,
887
+ 'username': ''
888
+ }
889
  save_db(db)
890
+
891
+ return jsonify(db['users'][address])
892
 
893
+ @app.route('/api/user/set_username', methods=['POST'])
894
+ def set_username():
895
+ data = request.get_json()
896
+ address = data.get('address')
897
+ username = data.get('username', '').strip()
898
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899
  if not address:
900
+ return jsonify({'error': 'Address is required'}), 400
901
+
902
+ db = load_db()
903
+ if address not in db['users']:
904
+ return jsonify({'error': 'User not found'}), 404
905
+
906
+ db['users'][address]['username'] = username
907
+ save_db(db)
908
+
909
+ return jsonify({'success': True, 'username': username})
910
 
 
911
 
912
+ @app.route('/api/chatrooms', methods=['GET'])
913
+ def get_chatrooms():
914
+ db = load_db()
915
+ chatrooms_list = [
916
+ {'id': room_id, 'name': room['name'], 'type': room['type']}
917
+ for room_id, room in db['chatrooms'].items()
918
+ ]
919
+ return jsonify({'chatrooms': sorted(chatrooms_list, key=lambda x: x['name'])})
920
+
921
+ @app.route('/api/chatrooms', methods=['POST'])
922
+ def create_chatroom():
923
+ data = request.get_json()
924
+ name = data.get('name')
925
+ room_type = data.get('type')
926
+ password = data.get('password')
927
+ creator_address = data.get('creator_address')
928
+
929
+ if not all([name, room_type, creator_address]):
930
+ return jsonify({'error': 'Missing required fields'}), 400
931
+
932
+ if room_type == 'private' and not password:
933
+ return jsonify({'error': 'Password is required for private rooms'}), 400
934
+
935
  db = load_db()
936
  room_id = str(uuid.uuid4())
 
 
 
 
 
 
 
937
  db['chatrooms'][room_id] = {
938
+ 'id': room_id,
939
+ 'name': name,
940
  'type': room_type,
941
+ 'password_hash': hash_password(password) if room_type == 'private' else None,
942
+ 'creator_address': creator_address,
943
  'messages': []
944
  }
945
  save_db(db)
946
+ return jsonify({'success': True, 'room_id': room_id}), 201
947
 
948
+ @app.route('/api/chatrooms/<room_id>/join', methods=['POST'])
949
+ def join_chatroom(room_id):
950
+ data = request.get_json()
951
+ address = data.get('address')
 
 
 
 
 
 
 
 
 
952
  password = data.get('password')
953
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
954
  if not address:
955
+ return jsonify({'error': 'Address is required'}), 400
956
 
957
+ db = load_db()
958
+ room = db['chatrooms'].get(room_id)
959
+ if not room:
960
+ return jsonify({'error': 'Room not found'}), 404
961
+
962
+ if room['type'] == 'private':
963
+ if not password or hash_password(password) != room['password_hash']:
964
+ return jsonify({'error': 'Invalid password'}), 403
965
+
966
+ return jsonify({'success': True})
967
 
968
+ @app.route('/api/chatrooms/<room_id>/messages', methods=['GET'])
969
+ def get_messages(room_id):
970
  db = load_db()
971
+ room = db['chatrooms'].get(room_id)
972
+ if not room:
973
+ return jsonify({'error': 'Room not found'}), 404
974
+ return jsonify({'messages': room['messages'][-100:]})
975
+
976
+ @app.route('/api/chatrooms/<room_id>/messages', methods=['POST'])
977
+ def post_message(room_id):
978
+ data = request.get_json()
979
+ text = data.get('text')
980
+ sender_address = data.get('sender_address')
981
+ username = data.get('username')
982
 
983
+ if not all([text, sender_address]):
984
+ return jsonify({'error': 'Missing required fields'}), 400
985
+
986
+ db = load_db()
987
+ room = db['chatrooms'].get(room_id)
988
+ if not room:
989
+ return jsonify({'error': 'Room not found'}), 404
990
+
991
  message = {
992
+ 'id': str(uuid.uuid4()),
 
993
  'text': text,
994
+ 'sender_address': sender_address,
995
+ 'username': username,
996
+ 'timestamp': time.time()
997
  }
998
+ room['messages'].append(message)
 
 
 
999
  save_db(db)
1000
+ return jsonify({'success': True}), 201
 
 
 
 
1001
 
1002
  if __name__ == '__main__':
1003
+ app.run(host='0.0.0.0', port=7860)