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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +735 -884
app.py CHANGED
@@ -1,1003 +1,854 @@
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
 
19
- def save_db(data):
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>
30
- <meta charset="UTF-8">
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;
215
- align-items: center;
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)
 
1
  import os
2
  import json
3
  import uuid
4
+ from datetime import datetime
 
5
  from flask import Flask, Response, request, jsonify
6
+ from werkzeug.security import generate_password_hash, check_password_hash
7
 
8
  app = Flask(__name__)
9
 
10
+ DB_FILE = 'db.json'
11
 
12
+ def init_db():
13
  if not os.path.exists(DB_FILE):
14
  with open(DB_FILE, 'w') as f:
15
+ json.dump({
16
+ "users": {},
17
+ "chatrooms": {},
18
+ "messages": {}
19
+ }, f, indent=4)
20
+
21
+ def read_db():
22
  with open(DB_FILE, 'r') as f:
23
  return json.load(f)
24
 
25
+ def write_db(data):
26
  with open(DB_FILE, 'w') as f:
27
  json.dump(data, f, indent=4)
28
 
29
+ @app.route('/')
30
+ def index():
31
+ html_content = '''
32
+ <!DOCTYPE html>
33
+ <html lang="ru">
34
+ <head>
35
+ <meta charset="UTF-8">
36
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
37
+ <title>Virton Messenger</title>
38
+ <script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>
39
+ <style>
40
+ :root {
41
+ --primary-bg: #1A1A1A;
42
+ --secondary-bg: #242424;
43
+ --tertiary-bg: #2E2E2E;
44
+ --text-primary: #FFFFFF;
45
+ --text-secondary: #B0B0B0;
46
+ --accent-blue: #0088CC;
47
+ --accent-blue-hover: #0099e6;
48
+ --border-color: #3A3A3A;
49
+ --error-color: #ff4d4d;
50
+ --success-color: #4CAF50;
51
+ }
52
+
53
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
54
+
55
+ * {
56
+ box-sizing: border-box;
57
+ margin: 0;
58
+ padding: 0;
59
+ }
60
+
61
+ body {
62
+ font-family: 'Roboto', sans-serif;
63
+ background-color: var(--primary-bg);
64
+ color: var(--text-primary);
65
+ display: flex;
66
+ align-items: center;
67
+ justify-content: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  height: 100vh;
69
+ overflow: hidden;
70
  }
71
+
72
+ #app-container {
73
+ display: none;
74
+ width: 100%;
75
+ height: 100%;
76
+ max-width: 1200px;
77
+ max-height: 900px;
78
+ background-color: var(--secondary-bg);
79
+ border-radius: 12px;
80
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
81
+ display: flex;
82
+ flex-direction: row;
83
+ overflow: hidden;
84
+ }
85
+
86
+ #login-view {
87
+ display: flex;
88
  flex-direction: column;
89
+ align-items: center;
90
+ justify-content: center;
91
+ text-align: center;
92
  }
93
+ #login-view img {
94
+ width: 120px;
95
+ height: 120px;
96
+ margin-bottom: 20px;
97
+ }
98
+ #login-view h1 {
99
+ font-size: 2.5rem;
100
+ color: var(--accent-blue);
101
+ margin-bottom: 10px;
102
+ }
103
+ #login-view p {
104
+ font-size: 1.1rem;
105
+ color: var(--text-secondary);
106
+ margin-bottom: 30px;
107
+ }
108
+
109
  .sidebar {
110
+ width: 300px;
111
+ background-color: var(--primary-bg);
112
+ display: flex;
113
+ flex-direction: column;
114
+ border-right: 1px solid var(--border-color);
115
+ }
116
+
117
+ .sidebar-header {
118
+ padding: 20px;
119
  border-bottom: 1px solid var(--border-color);
120
+ display: flex;
121
+ flex-direction: column;
122
+ }
123
+ .sidebar-header h2 {
124
+ color: var(--accent-blue);
125
+ margin-bottom: 15px;
126
+ }
127
+ .user-profile {
128
+ font-size: 0.9em;
129
+ word-break: break-all;
130
+ color: var(--text-secondary);
131
+ margin-bottom: 10px;
132
+ }
133
+ .username-form { display: flex; }
134
+ .username-input { flex-grow: 1; margin-right: 5px; }
135
+
136
+ .create-room-btn {
137
+ background-color: var(--accent-blue);
138
+ color: white;
139
+ border: none;
140
  padding: 10px;
141
+ border-radius: 5px;
142
+ cursor: pointer;
143
+ font-weight: 500;
144
+ transition: background-color 0.2s;
145
+ margin-top: 15px;
146
  }
147
+ .create-room-btn:hover { background-color: var(--accent-blue-hover); }
148
+
149
+ #chatroom-list {
150
+ flex-grow: 1;
151
+ overflow-y: auto;
152
+ padding: 10px 0;
153
+ }
154
+ .chatroom-item {
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
+ .chatroom-item:hover { background-color: var(--tertiary-bg); }
164
+ .chatroom-item.active { background-color: var(--accent-blue); color: white; }
165
+ .chatroom-item.active .lock-icon { filter: brightness(0) invert(1); }
166
+ .lock-icon {
167
+ width: 16px;
168
+ height: 16px;
169
+ opacity: 0.7;
170
+ }
171
+
172
+ .chat-area {
173
+ flex-grow: 1;
174
+ display: flex;
175
+ flex-direction: column;
176
  }
177
+ .chat-placeholder {
178
+ display: flex;
179
+ flex-direction: column;
180
+ align-items: center;
181
+ justify-content: center;
182
  height: 100%;
183
+ text-align: center;
184
+ color: var(--text-secondary);
185
  }
186
+ .chat-placeholder img { width: 100px; margin-bottom: 20px; opacity: 0.5; }
187
+ .chat-header {
188
+ padding: 20px;
189
+ border-bottom: 1px solid var(--border-color);
190
+ font-weight: 500;
191
+ font-size: 1.2rem;
192
+ }
193
+ #messages-container {
194
+ flex-grow: 1;
195
+ padding: 20px;
196
+ overflow-y: auto;
197
+ display: flex;
198
+ flex-direction: column;
199
+ }
200
+
201
+ .message {
202
+ max-width: 70%;
203
+ padding: 10px 15px;
204
+ border-radius: 18px;
205
+ margin-bottom: 10px;
206
+ display: flex;
207
+ flex-direction: column;
208
+ }
209
+ .message-sender {
210
+ font-size: 0.8em;
211
+ font-weight: 500;
212
+ color: var(--accent-blue);
213
+ margin-bottom: 4px;
214
+ word-break: break-all;
215
+ }
216
+ .message-text { font-size: 1em; line-height: 1.4; word-wrap: break-word; }
217
+ .message-time {
218
+ font-size: 0.7em;
219
+ color: var(--text-secondary);
220
+ align-self: flex-end;
221
+ margin-top: 5px;
222
+ }
223
+
224
+ .message.sent {
225
+ background-color: var(--accent-blue);
226
+ color: white;
227
+ align-self: flex-end;
228
+ border-bottom-right-radius: 4px;
229
+ }
230
+ .message.sent .message-sender { color: white; opacity: 0.9; }
231
+
232
+ .message.received {
233
+ background-color: var(--tertiary-bg);
234
+ align-self: flex-start;
235
+ border-bottom-left-radius: 4px;
236
  }
237
+
238
+ .message-form {
239
+ display: flex;
240
+ padding: 20px;
241
+ border-top: 1px solid var(--border-color);
242
+ }
243
+ #message-input {
244
+ flex-grow: 1;
245
+ padding: 12px;
246
+ border: 1px solid var(--border-color);
247
+ background-color: var(--tertiary-bg);
248
+ color: white;
249
+ border-radius: 20px;
250
+ margin-right: 10px;
251
+ outline: none;
252
+ }
253
+ #message-input:focus { border-color: var(--accent-blue); }
254
+
255
+ .send-btn {
256
+ padding: 12px 20px;
257
+ background-color: var(--accent-blue);
258
+ color: white;
259
+ border: none;
260
+ border-radius: 20px;
261
+ cursor: pointer;
262
+ transition: background-color 0.2s;
263
+ }
264
+ .send-btn:hover { background-color: var(--accent-blue-hover); }
265
+
266
+ .modal-overlay {
267
+ position: fixed;
268
+ top: 0;
269
+ left: 0;
270
+ width: 100%;
271
+ height: 100%;
272
+ background-color: rgba(0,0,0,0.7);
273
+ display: none;
274
+ align-items: center;
275
+ justify-content: center;
276
+ z-index: 1000;
277
+ }
278
+ .modal-content {
279
+ background-color: var(--secondary-bg);
280
+ padding: 30px;
281
+ border-radius: 10px;
282
+ width: 90%;
283
+ max-width: 400px;
284
+ }
285
+ .modal-content h3 { margin-bottom: 20px; }
286
+ .modal-content label { display: block; margin-bottom: 5px; color: var(--text-secondary); }
287
+ .modal-content input {
288
+ width: 100%;
289
  padding: 10px;
290
+ margin-bottom: 15px;
291
+ background-color: var(--tertiary-bg);
292
+ border: 1px solid var(--border-color);
293
+ color: white;
294
+ border-radius: 5px;
295
+ }
296
+ .modal-actions { display: flex; justify-content: flex-end; gap: 10px; }
297
+ .modal-btn {
298
+ padding: 10px 20px;
299
+ border-radius: 5px;
300
+ border: none;
301
+ cursor: pointer;
302
+ font-weight: 500;
303
+ }
304
+ .primary-btn { background-color: var(--accent-blue); color: white; }
305
+ .primary-btn:hover { background-color: var(--accent-blue-hover); }
306
+ .secondary-btn { background-color: var(--tertiary-bg); color: white; }
307
+
308
+ input, button { font-family: 'Roboto', sans-serif; font-size: 1rem; }
309
+
310
+ #ton-connect-button {
311
+ border-radius: 20px;
312
  }
313
+
314
+ #status-bar {
315
+ position: fixed;
316
+ bottom: 10px;
317
+ left: 50%;
318
+ transform: translateX(-50%);
319
+ background-color: var(--tertiary-bg);
320
+ color: white;
321
+ padding: 8px 15px;
322
+ border-radius: 5px;
323
+ font-size: 0.9em;
324
+ display: none;
325
+ opacity: 0;
326
+ transition: opacity 0.5s;
327
+ z-index: 2000;
328
+ }
329
+ #status-bar.success { background-color: var(--success-color); }
330
+ #status-bar.error { background-color: var(--error-color); }
331
+ #status-bar.visible { display: block; opacity: 1; }
332
+
333
+ @media (max-width: 768px) {
334
+ #app-container {
335
+ flex-direction: column;
336
+ max-height: 100vh;
337
+ border-radius: 0;
338
+ }
339
+ .sidebar {
340
+ width: 100%;
341
+ height: 250px;
342
+ flex-shrink: 0;
343
+ border-right: none;
344
+ border-bottom: 1px solid var(--border-color);
345
+ }
346
+ .chat-area {
347
+ height: calc(100% - 250px);
348
+ }
349
+ .modal-content {
350
+ width: 95%;
351
+ }
352
+ }
353
+ </style>
354
+ </head>
355
+ <body>
356
 
357
+ <div id="login-view">
358
+ <img src="https://ton.org/download/ton_symbol.svg" alt="TON Symbol">
359
  <h1>Virton Messenger</h1>
360
  <p>Анонимный мессенджер на блокчейне TON</p>
361
+ <div id="ton-connect-button"></div>
362
  </div>
363
 
364
+ <div id="app-container" style="display: none;">
365
  <div class="sidebar">
366
  <div class="sidebar-header">
367
+ <h2>Чаты</h2>
368
+ <div class="user-profile">
369
+ <div id="user-wallet"></div>
370
+ <div id="user-nickname"></div>
371
+ <form class="username-form" id="username-form">
372
+ <input type="text" id="username-input" class="username-input" placeholder="Ваш никнейм (опционально)" autocomplete="off">
373
+ <button type="submit" class="create-room-btn" style="margin-top:0; padding: 5px 10px;">✓</button>
374
+ </form>
375
  </div>
376
+ <button id="create-room-show-modal" class="create-room-btn">Создать новый чат</button>
377
  </div>
378
+ <div id="chatroom-list"></div>
 
379
  </div>
380
+ <div class="chat-area">
381
+ <div id="chat-placeholder" class="chat-placeholder">
382
+ <img src="https://ton.org/download/ton_symbol.svg" alt="TON Symbol">
383
+ <h2>Выберите чат для начала общения</h2>
384
+ <p>Или создайте свой собственный</p>
385
  </div>
386
+ <div id="chat-window" style="display: none; width: 100%; height: 100%; flex-direction: column;">
387
+ <div id="chat-header" class="chat-header"></div>
388
+ <div id="messages-container"></div>
389
+ <form id="message-form" class="message-form">
390
  <input type="text" id="message-input" placeholder="Введите сообщение..." autocomplete="off">
391
+ <button type="submit" class="send-btn">Отправить</button>
392
  </form>
393
  </div>
394
  </div>
395
  </div>
396
+
397
+ <div id="create-room-modal" class="modal-overlay">
398
+ <div class="modal-content">
399
+ <h3>Создать новы�� чат</h3>
400
+ <form id="create-room-form">
401
+ <label for="room-name">Название чата</label>
402
+ <input type="text" id="room-name" required>
403
+ <label for="room-password">Пароль (оставьте пустым для открытого чата)</label>
404
+ <input type="password" id="room-password">
405
+ <div class="modal-actions">
406
+ <button type="button" id="create-room-cancel" class="modal-btn secondary-btn">Отмена</button>
407
+ <button type="submit" class="modal-btn primary-btn">Создать</button>
408
+ </div>
409
+ </form>
410
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  </div>
 
412
 
413
+ <div id="password-modal" class="modal-overlay">
414
+ <div class="modal-content">
415
+ <h3>Требуется пароль</h3>
416
+ <form id="password-form">
417
+ <label for="password-input">Введите пароль для входа в чат</label>
418
+ <input type="password" id="password-input" required>
419
+ <div class="modal-actions">
420
+ <button type="button" id="password-cancel" class="modal-btn secondary-btn">Отмена</button>
421
+ <button type="submit" class="modal-btn primary-btn">Войти</button>
422
+ </div>
423
+ </form>
424
+ </div>
425
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
 
427
+ <div id="status-bar"></div>
 
 
 
 
 
 
 
 
 
 
 
428
 
429
+ <script>
430
+ document.addEventListener('DOMContentLoaded', () => {
431
+ const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
432
+ manifestUrl: 'https://huggingface.co/spaces/Aleksmorshen/MorshenGroup/resolve/main/tonconnect-manifest.json',
433
+ buttonRootId: 'ton-connect-button'
434
+ });
435
 
436
+ let currentUser = { address: null, username: null };
437
+ let activeChatroomId = null;
438
+ let messagePollingInterval = null;
439
+ let chatroomsData = {};
440
+
441
+ const loginView = document.getElementById('login-view');
442
+ const appContainer = document.getElementById('app-container');
443
+ const chatPlaceholder = document.getElementById('chat-placeholder');
444
+ const chatWindow = document.getElementById('chat-window');
445
+
446
+ function showStatus(message, type = 'info', duration = 3000) {
447
+ const statusBar = document.getElementById('status-bar');
448
+ statusBar.textContent = message;
449
+ statusBar.className = 'status-bar';
450
+ if (type === 'success') {
451
+ statusBar.classList.add('success');
452
+ } else if (type === 'error') {
453
+ statusBar.classList.add('error');
454
  }
455
+ statusBar.classList.add('visible');
456
+ setTimeout(() => {
457
+ statusBar.classList.remove('visible');
458
+ }, duration);
459
+ }
460
 
461
+ async function apiCall(endpoint, options = {}) {
462
+ try {
463
+ const response = await fetch(endpoint, options);
464
+ if (!response.ok) {
465
+ const errorData = await response.json().catch(() => ({ error: 'Request failed with status ' + response.status }));
466
+ throw new Error(errorData.error || 'Unknown error');
467
+ }
468
+ return await response.json();
469
+ } catch (error) {
470
+ console.error(`API call to ${endpoint} failed:`, error);
471
+ showStatus(`Ошибка: ${error.message}`, 'error');
472
+ throw error;
473
+ }
474
+ }
475
+
476
+ function truncateAddress(address) {
477
+ if (!address) return '';
478
+ return `${address.substring(0, 4)}...${address.substring(address.length - 4)}`;
479
+ }
480
 
481
+ function updateUserInfo() {
482
+ document.getElementById('user-wallet').textContent = `Кошелек: ${truncateAddress(currentUser.address)}`;
483
+ const nicknameEl = document.getElementById('user-nickname');
484
+ const usernameInput = document.getElementById('username-input');
485
+ if (currentUser.username) {
486
+ nicknameEl.textContent = `Никнейм: ${currentUser.username}`;
487
+ usernameInput.value = currentUser.username;
 
 
488
  } else {
489
+ nicknameEl.textContent = 'Никнейм не установлен';
490
+ usernameInput.value = '';
491
  }
492
+ }
493
+
494
+ document.getElementById('username-form').addEventListener('submit', async (e) => {
495
+ e.preventDefault();
496
+ const newUsername = document.getElementById('username-input').value.trim();
497
+ if (!newUsername || newUsername.length < 3) {
498
+ showStatus('Никнейм должен быть не короче 3 символов.', 'error');
499
+ return;
500
+ }
501
+ try {
502
+ await apiCall('/api/set_username', {
503
+ method: 'POST',
504
+ headers: { 'Content-Type': 'application/json' },
505
+ body: JSON.stringify({ address: currentUser.address, username: newUsername })
506
+ });
507
+ currentUser.username = newUsername;
508
+ updateUserInfo();
509
+ showStatus('Никнейм успешно обновлен!', 'success');
510
+ if (activeChatroomId) renderMessages(activeChatroomId);
511
+ } catch (err) {}
512
  });
 
 
513
 
514
+ async function initializeUser(address) {
515
+ currentUser.address = address;
516
+ try {
517
+ const data = await apiCall('/api/user_data', {
518
+ method: 'POST',
519
+ headers: { 'Content-Type': 'application/json' },
520
+ body: JSON.stringify({ address: currentUser.address })
521
+ });
522
+ currentUser.username = data.username;
523
+ } catch (err) {
524
+ currentUser.username = null;
 
 
 
 
 
 
525
  }
526
+ updateUserInfo();
527
+ loginView.style.display = 'none';
528
+ appContainer.style.display = 'flex';
529
+ fetchChatrooms();
530
  }
 
531
 
532
+ function renderChatrooms(rooms) {
533
+ const list = document.getElementById('chatroom-list');
534
+ list.innerHTML = '';
535
+ chatroomsData = {};
536
+ rooms.forEach(room => {
537
+ chatroomsData[room.id] = room;
538
+ const item = document.createElement('div');
539
+ item.className = 'chatroom-item';
540
+ if (room.id === activeChatroomId) {
541
+ item.classList.add('active');
542
+ }
543
+ item.dataset.id = room.id;
544
+ item.dataset.private = room.is_private;
545
+
546
+ const nameSpan = document.createElement('span');
547
+ nameSpan.textContent = room.name;
548
+ item.appendChild(nameSpan);
549
+
550
+ if (room.is_private) {
551
+ const lockIcon = document.createElement('img');
552
+ lockIcon.src = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZmZmZiIgd2lkdGg9IjI0cHgiIGhlaWdodD0iMjRweCI+PHBhdGggZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIvPjxwYXRoIGQ9Ik0xOCAxMGgtMVY3YzAtMi43Ni0yLjI0LTUtNS01UzcgNC4yNCA3IDd2M0g2Yy0xLjEgMC0yIC45LTIgMnYxMGMwIDEuMS45IDIgMiAyaDEyYzEuMSAwIDItLjkgMi0yVjEyYzAtMS4xLS45LTItMi0yem0tNiA5Yy0xLjEgMC0yLS45LTItMnM5LTJIDItMiAyIC45IDIgMi0uOSAyLTItMnpNOC4xIDExaDcuOFY3YzAtMi4xLTcuOS0yLjEtNy44IDB2NHoiLz48L3N2Zz4=';
553
+ lockIcon.className = 'lock-icon';
554
+ item.appendChild(lockIcon);
555
+ }
556
+
557
+ item.addEventListener('click', () => selectChatroom(room.id, room.is_private));
558
+ list.appendChild(item);
559
+ });
560
  }
561
+
562
+ async function fetchChatrooms() {
563
+ try {
564
+ const data = await apiCall('/api/chatrooms');
565
+ renderChatrooms(data.chatrooms);
566
+ } catch (err) {}
567
  }
568
+
569
+ function renderMessages(messages) {
570
+ const container = document.getElementById('messages-container');
571
+ container.innerHTML = '';
572
+ messages.forEach(msg => {
573
+ const msgDiv = document.createElement('div');
574
+ msgDiv.className = 'message ' + (msg.sender_address === currentUser.address ? 'sent' : 'received');
575
+
576
+ const senderDiv = document.createElement('div');
577
+ senderDiv.className = 'message-sender';
578
+ senderDiv.textContent = msg.display_name;
579
+
580
+ const textDiv = document.createElement('div');
581
+ textDiv.className = 'message-text';
582
+ textDiv.textContent = msg.text;
583
+
584
+ const timeDiv = document.createElement('div');
585
+ timeDiv.className = 'message-time';
586
+ timeDiv.textContent = new Date(msg.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
587
+
588
+ msgDiv.appendChild(senderDiv);
589
+ msgDiv.appendChild(textDiv);
590
+ msgDiv.appendChild(timeDiv);
591
+ container.appendChild(msgDiv);
592
+ });
593
+ container.scrollTop = container.scrollHeight;
594
  }
595
 
596
+ async function fetchMessages(roomId) {
597
+ try {
598
+ const data = await apiCall(`/api/messages/${roomId}`);
599
+ renderMessages(data.messages);
600
+ } catch (err) {
601
+ if (messagePollingInterval) clearInterval(messagePollingInterval);
 
 
 
 
 
 
 
 
 
 
 
602
  }
 
 
 
 
 
 
 
603
  }
 
 
 
 
 
 
 
 
 
 
 
 
604
 
605
+ function selectChatroom(roomId, isPrivate) {
606
+ const roomData = chatroomsData[roomId];
607
+ if (!roomData) return;
608
 
609
+ const proceedToRoom = () => {
610
+ if (activeChatroomId === roomId) return;
 
 
 
 
 
 
 
 
611
 
612
+ if (messagePollingInterval) clearInterval(messagePollingInterval);
 
 
 
613
 
614
+ activeChatroomId = roomId;
615
+
616
+ document.querySelectorAll('.chatroom-item').forEach(el => el.classList.remove('active'));
617
+ document.querySelector(`.chatroom-item[data-id="${roomId}"]`).classList.add('active');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
 
619
+ document.getElementById('chat-header').textContent = roomData.name;
620
+ chatPlaceholder.style.display = 'none';
621
+ chatWindow.style.display = 'flex';
622
+
623
+ fetchMessages(roomId);
624
+ messagePollingInterval = setInterval(() => fetchMessages(roomId), 3000);
625
+ };
626
+
627
+ if (isPrivate) {
628
+ const passwordModal = document.getElementById('password-modal');
629
+ const passwordForm = document.getElementById('password-form');
630
+ const passwordInput = document.getElementById('password-input');
631
+ passwordModal.style.display = 'flex';
632
+ passwordInput.value = '';
633
+ passwordInput.focus();
634
+
635
+ const formSubmitHandler = async (e) => {
636
+ e.preventDefault();
637
+ passwordForm.removeEventListener('submit', formSubmitHandler);
638
+ const password = passwordInput.value;
639
+ passwordModal.style.display = 'none';
640
+ try {
641
+ await apiCall('/api/join_chatroom', {
642
+ method: 'POST',
643
+ headers: { 'Content-Type': 'application/json' },
644
+ body: JSON.stringify({ chatroom_id: roomId, password })
645
+ });
646
+ proceedToRoom();
647
+ } catch (err) {
648
+ showStatus('Неверный пароль', 'error');
649
+ }
650
+ };
651
+ passwordForm.addEventListener('submit', formSubmitHandler);
652
+
653
+ document.getElementById('password-cancel').onclick = () => {
654
+ passwordModal.style.display = 'none';
655
+ passwordForm.removeEventListener('submit', formSubmitHandler);
656
+ };
657
 
658
+ } else {
659
+ proceedToRoom();
660
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  }
 
662
 
663
+ document.getElementById('message-form').addEventListener('submit', async (e) => {
664
+ e.preventDefault();
665
+ const input = document.getElementById('message-input');
666
+ const text = input.value.trim();
667
+ if (text && activeChatroomId) {
668
+ input.value = '';
669
+ try {
670
+ await apiCall('/api/send_message', {
671
+ method: 'POST',
672
+ headers: { 'Content-Type': 'application/json' },
673
+ body: JSON.stringify({
674
+ chatroom_id: activeChatroomId,
675
+ sender_address: currentUser.address,
676
+ text: text
677
+ })
678
+ });
679
+ fetchMessages(activeChatroomId);
680
+ } catch (err) {}
681
+ }
682
+ });
683
 
684
+ const createRoomModal = document.getElementById('create-room-modal');
685
+ document.getElementById('create-room-show-modal').addEventListener('click', () => {
686
+ createRoomModal.style.display = 'flex';
687
+ document.getElementById('create-room-form').reset();
688
+ });
689
+ document.getElementById('create-room-cancel').addEventListener('click', () => {
690
+ createRoomModal.style.display = 'none';
691
+ });
692
+ document.getElementById('create-room-form').addEventListener('submit', async (e) => {
693
+ e.preventDefault();
694
+ const name = document.getElementById('room-name').value.trim();
695
+ const password = document.getElementById('room-password').value;
696
+ if (!name) return;
697
+
698
+ try {
699
+ await apiCall('/api/create_chatroom', {
700
+ method: 'POST',
701
+ headers: { 'Content-Type': 'application/json' },
702
+ body: JSON.stringify({
703
+ name,
704
+ password: password || null,
705
+ creator_address: currentUser.address
706
+ })
707
+ });
708
+ createRoomModal.style.display = 'none';
709
+ showStatus('Чат успешно создан!', 'success');
710
+ fetchChatrooms();
711
+ } catch (err) {}
712
+ });
713
 
714
+ tonConnectUI.onStatusChange(wallet => {
715
+ if (wallet) {
716
+ const address = TON_CONNECT_UI.toUserFriendlyAddress(wallet.account.address, false);
717
+ initializeUser(address);
718
+ } else {
719
+ currentUser = { address: null, username: null };
720
+ appContainer.style.display = 'none';
721
+ loginView.style.display = 'flex';
722
+ if (messagePollingInterval) clearInterval(messagePollingInterval);
723
+ activeChatroomId = null;
724
+ }
725
+ });
 
 
 
 
 
 
 
 
 
 
 
726
  });
727
+ </script>
728
+ </body>
729
+ </html>
730
+ '''
731
+ return Response(html_content, mimetype='text/html')
732
 
 
 
 
 
 
 
 
 
 
733
 
734
+ @app.route('/api/user_data', methods=['POST'])
735
+ def get_user_data():
736
  data = request.get_json()
737
  address = data.get('address')
738
  if not address:
739
  return jsonify({'error': 'Address is required'}), 400
740
+ db = read_db()
741
+ user_info = db['users'].get(address)
742
+ username = user_info.get('username') if user_info else None
743
+ return jsonify({'username': username})
744
+
745
+ @app.route('/api/set_username', methods=['POST'])
 
 
 
 
 
 
746
  def set_username():
747
  data = request.get_json()
748
  address = data.get('address')
749
+ username = data.get('username')
750
+ if not address or not username:
751
+ return jsonify({'error': 'Address and username are required'}), 400
752
+ if len(username) < 3:
753
+ return jsonify({'error': 'Username must be at least 3 characters long'}), 400
754
 
755
+ db = read_db()
 
 
 
756
  if address not in db['users']:
757
+ db['users'][address] = {}
 
758
  db['users'][address]['username'] = username
759
+ write_db(db)
760
+ return jsonify({'success': True})
 
 
761
 
762
  @app.route('/api/chatrooms', methods=['GET'])
763
  def get_chatrooms():
764
+ db = read_db()
765
+ chatrooms_list = []
766
+ for room_id, room_data in db['chatrooms'].items():
767
+ chatrooms_list.append({
768
+ 'id': room_id,
769
+ 'name': room_data['name'],
770
+ 'is_private': room_data['is_private']
771
+ })
772
+ return jsonify({'chatrooms': chatrooms_list})
773
+
774
+ @app.route('/api/create_chatroom', methods=['POST'])
775
  def create_chatroom():
776
  data = request.get_json()
777
  name = data.get('name')
 
778
  password = data.get('password')
779
  creator_address = data.get('creator_address')
780
+ if not name or not creator_address:
781
+ return jsonify({'error': 'Name and creator address are required'}), 400
782
+
783
+ db = read_db()
 
 
 
 
784
  room_id = str(uuid.uuid4())
785
  db['chatrooms'][room_id] = {
 
786
  'name': name,
787
+ 'creator': creator_address,
788
+ 'is_private': bool(password),
789
+ 'password_hash': generate_password_hash(password) if password else None
 
790
  }
791
+ db['messages'][room_id] = []
792
+ write_db(db)
793
+ return jsonify({'success': True, 'chatroom_id': room_id})
794
+
795
+ @app.route('/api/join_chatroom', methods=['POST'])
796
+ def join_chatroom():
797
  data = request.get_json()
798
+ chatroom_id = data.get('chatroom_id')
799
  password = data.get('password')
800
+ db = read_db()
801
+ chatroom = db['chatrooms'].get(chatroom_id)
802
+ if not chatroom:
803
+ return jsonify({'error': 'Chatroom not found'}), 404
804
+ if chatroom['is_private']:
805
+ if not password or not check_password_hash(chatroom['password_hash'], password):
 
 
 
 
 
806
  return jsonify({'error': 'Invalid password'}), 403
 
807
  return jsonify({'success': True})
808
 
809
+ @app.route('/api/messages/<chatroom_id>', methods=['GET'])
810
+ def get_messages(chatroom_id):
811
+ db = read_db()
812
+ if chatroom_id not in db['messages']:
813
+ return jsonify({'error': 'Chatroom not found'}), 404
814
+
815
+ messages_with_names = []
816
+ for msg in db['messages'][chatroom_id]:
817
+ sender_address = msg['sender_address']
818
+ user_info = db['users'].get(sender_address)
819
+ display_name = user_info.get('username') if user_info and user_info.get('username') else f"{sender_address[:4]}...{sender_address[-4:]}"
820
+
821
+ msg_copy = msg.copy()
822
+ msg_copy['display_name'] = display_name
823
+ messages_with_names.append(msg_copy)
824
 
825
+ return jsonify({'messages': messages_with_names})
826
+
827
+ @app.route('/api/send_message', methods=['POST'])
828
+ def send_message():
829
  data = request.get_json()
830
+ chatroom_id = data.get('chatroom_id')
831
  sender_address = data.get('sender_address')
832
+ text = data.get('text')
 
 
 
833
 
834
+ if not all([chatroom_id, sender_address, text]):
835
+ return jsonify({'error': 'Missing data'}), 400
836
+
837
+ db = read_db()
838
+ if chatroom_id not in db['messages']:
839
+ return jsonify({'error': 'Chatroom not found'}), 404
840
 
841
  message = {
842
  'id': str(uuid.uuid4()),
 
843
  'sender_address': sender_address,
844
+ 'text': text,
845
+ 'timestamp': datetime.utcnow().isoformat() + "Z"
846
  }
847
+ db['messages'][chatroom_id].append(message)
848
+ write_db(db)
849
+ return jsonify({'success': True})
850
+
851
 
852
  if __name__ == '__main__':
853
+ init_db()
854
  app.run(host='0.0.0.0', port=7860)