sldshr commited on
Commit
c12320c
·
verified ·
1 Parent(s): f62fb35

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +70 -1276
index.html CHANGED
@@ -3,1312 +3,106 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>WebClient 2010 - SQL Edition</title>
 
7
  <style>
8
- /* Стили в духе 2010-х годов (Windows 7 Aero / Старые мессенджеры) */
9
- :root {
10
- --bg-color: #d8e6f3;
11
- --grad-top: #e4eff8;
12
- --grad-bot: #b8d4eb;
13
- --border-color: #799aab;
14
- --text-dark: #1e395b;
15
- --win-bg: #f4f7f9;
16
- --menubar-top: #6ba2d4;
17
- --menubar-bot: #3371b6;
18
- }
19
-
20
- * {
21
- box-sizing: border-box;
22
- user-select: none;
23
- }
24
-
25
- body {
26
- margin: 0;
27
- padding: 0;
28
- font-family: Tahoma, Verdana, Arial, sans-serif;
29
- font-size: 13px;
30
- background-color: var(--bg-color);
31
- color: var(--text-dark);
32
- height: 100vh;
33
- display: flex;
34
- flex-direction: column;
35
- overflow: hidden;
36
- }
37
-
38
- .menubar {
39
- background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
40
- border-bottom: 1px solid #14406f;
41
- padding: 5px 10px;
42
- display: flex;
43
- gap: 10px;
44
- box-shadow: 0 2px 5px rgba(0,0,0,0.2);
45
- z-index: 100;
46
- }
47
-
48
- .btn {
49
- background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
50
- border: 1px solid var(--border-color);
51
- border-radius: 3px;
52
- padding: 4px 12px;
53
- color: #0f2c4c;
54
- font-family: Tahoma, sans-serif;
55
- font-size: 12px;
56
- cursor: pointer;
57
- box-shadow: inset 1px 1px 1px rgba(255,255,255,0.8), 1px 1px 2px rgba(0,0,0,0.1);
58
- text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
59
- transition: all 0.1s;
60
- }
61
-
62
- .btn:hover {
63
- background: linear-gradient(to bottom, #fff 0%, #eef3f7 50%, #d4e3ef 51%, #f0f7fb 100%);
64
- }
65
-
66
- .btn:active {
67
- background: linear-gradient(to bottom, #b5c6d0 0%, #d8e1e7 100%);
68
- box-shadow: inset 1px 1px 3px rgba(0,0,0,0.3);
69
- padding-top: 5px;
70
- padding-bottom: 3px;
71
- }
72
-
73
- .window {
74
- position: absolute;
75
- width: 350px;
76
- background: var(--win-bg);
77
- border: 1px solid var(--border-color);
78
- border-radius: 4px;
79
- box-shadow: 3px 3px 10px rgba(0,0,0,0.4);
80
- display: none;
81
- z-index: 1000;
82
- flex-direction: column;
83
- overflow: hidden;
84
- }
85
-
86
- .window.active {
87
- display: flex;
88
- }
89
-
90
- .window-header {
91
- background: linear-gradient(to bottom, #d4e4ef 0%, #86aecc 100%);
92
- padding: 5px 8px;
93
- font-weight: bold;
94
- color: #0f2c4c;
95
- border-bottom: 1px solid var(--border-color);
96
- cursor: move;
97
- display: flex;
98
- justify-content: space-between;
99
- align-items: center;
100
- border-radius: 3px 3px 0 0;
101
- text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
102
- }
103
-
104
- .window-close {
105
- background: linear-gradient(to bottom, #e8a2a2 0%, #cc3333 100%);
106
- border: 1px solid #7a1c1c;
107
- color: white;
108
- font-weight: bold;
109
- width: 18px;
110
- height: 18px;
111
- line-height: 14px;
112
- text-align: center;
113
- cursor: pointer;
114
- border-radius: 2px;
115
- font-size: 10px;
116
- box-shadow: inset 1px 1px 1px rgba(255,255,255,0.4);
117
- }
118
-
119
- .window-close:hover {
120
- background: linear-gradient(to bottom, #ffb3b3 0%, #ff4d4d 100%);
121
- }
122
-
123
- .window-body {
124
- padding: 15px;
125
- display: flex;
126
- flex-direction: column;
127
- gap: 10px;
128
- min-height: 0;
129
- }
130
-
131
- .input-group {
132
- display: flex;
133
- flex-direction: column;
134
- gap: 3px;
135
- }
136
-
137
- input[type="text"], input[type="password"] {
138
- border: 1px solid #999;
139
- box-shadow: inset 1px 1px 2px #ccc;
140
- padding: 5px;
141
- border-radius: 2px;
142
- font-family: Tahoma, sans-serif;
143
- user-select: text;
144
- }
145
-
146
- .workspace {
147
- flex: 1;
148
- display: flex;
149
- padding: 5px;
150
- gap: 5px;
151
- height: calc(100vh - 35px);
152
- }
153
-
154
- .panel {
155
- background: white;
156
- border: 1px solid var(--border-color);
157
- border-radius: 2px;
158
- box-shadow: inset 1px 1px 3px rgba(0,0,0,0.1);
159
- display: flex;
160
- flex-direction: column;
161
- }
162
-
163
- .panel-header {
164
- background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
165
- border-bottom: 1px solid var(--border-color);
166
- padding: 4px 8px;
167
- font-weight: bold;
168
- font-size: 11px;
169
- color: #555;
170
- }
171
-
172
- .sidebar {
173
- width: 200px;
174
- min-width: 160px;
175
- flex-shrink: 0;
176
- display: flex;
177
- flex-direction: column;
178
- }
179
-
180
- .chat-area {
181
- flex: 1;
182
- display: flex;
183
- flex-direction: column;
184
- }
185
-
186
- .chat-messages {
187
- flex: 1;
188
- padding: 10px;
189
- overflow-y: auto;
190
- user-select: text;
191
- display: flex;
192
- flex-direction: column;
193
- gap: 5px;
194
- }
195
-
196
- .chat-input-area {
197
- border-top: 1px solid var(--border-color);
198
- padding: 5px;
199
- display: flex;
200
- gap: 5px;
201
- background: #f4f7f9;
202
- }
203
-
204
- .chat-input-area input {
205
- flex: 1;
206
- }
207
-
208
- .list-item {
209
- padding: 4px 8px;
210
- cursor: pointer;
211
- border-bottom: 1px solid #eee;
212
- display: flex;
213
- justify-content: space-between;
214
- }
215
-
216
- .list-item:hover {
217
- background-color: #e4eff8;
218
- }
219
-
220
- .list-item.active {
221
- background-color: #3371b6;
222
- color: white;
223
- }
224
-
225
- .msg {
226
- font-family: Verdana, sans-serif;
227
- font-size: 12px;
228
- border-radius: 3px;
229
- display: flex;
230
- flex-wrap: wrap;
231
- align-items: baseline;
232
- gap: 5px;
233
- padding: 2px 0;
234
- }
235
-
236
- .msg:hover {
237
- background-color: rgba(0,0,0,0.03);
238
- }
239
-
240
- .msg .time { color: #888; font-size: 10px; margin-right: 5px; }
241
- .msg .author { font-weight: bold; color: #1e5799; margin-right: 5px; }
242
- .msg.system .author { color: #cc3333; }
243
-
244
- .msg .content {
245
- word-wrap: break-word;
246
- overflow-wrap: anywhere;
247
- white-space: pre-wrap;
248
- display: inline-block;
249
- max-width: 100%;
250
- flex: 1;
251
- }
252
-
253
- .quote-block {
254
- border-left: 3px solid var(--menubar-bot);
255
- background: #f0f4f8;
256
- padding: 5px 8px;
257
- margin: 3px 0 5px 0;
258
- border-radius: 0 3px 3px 0;
259
- font-size: 11px;
260
- color: #555;
261
- width: 100%;
262
- }
263
-
264
- .quote-block .q-author { font-weight: bold; color: var(--menubar-bot); }
265
- .quote-block .q-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
266
-
267
- .action-banner {
268
- background: #e4eff8;
269
- border-top: 1px solid var(--border-color);
270
- padding: 5px 10px;
271
- display: flex;
272
- justify-content: space-between;
273
- align-items: center;
274
- font-weight: bold;
275
- font-size: 11px;
276
- color: var(--text-dark);
277
- }
278
-
279
- .category-header {
280
- background: linear-gradient(to right, #d4e4ef 0%, #f4f7f9 100%);
281
- padding: 2px 8px;
282
- font-size: 10px;
283
- font-weight: bold;
284
- color: #555;
285
- margin-top: 5px;
286
- border-top: 1px solid var(--border-color);
287
- border-bottom: 1px solid #eee;
288
- }
289
-
290
- .code-block {
291
- background: #fdfdfd;
292
- border: 1px solid #ccc;
293
- border-radius: 2px;
294
- margin: 5px 0;
295
- font-family: monospace;
296
- font-size: 11px;
297
- position: relative;
298
- }
299
-
300
- .code-header {
301
- background: #eee;
302
- border-bottom: 1px solid #ccc;
303
- padding: 2px 5px;
304
- text-align: right;
305
- }
306
-
307
- .code-block pre {
308
- margin: 0;
309
- padding: 5px;
310
- overflow-x: auto;
311
- white-space: pre-wrap;
312
- font-family: inherit;
313
- }
314
-
315
- .mobile-tabs {
316
- display: none;
317
- background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
318
- padding: 5px;
319
- gap: 5px;
320
- }
321
-
322
- .mobile-tabs .btn { flex: 1; }
323
-
324
- @media (max-width: 768px) {
325
- .workspace { flex-direction: column; gap: 0; padding: 0; height: calc(100vh - 70px); }
326
- .sidebar { width: 100%; height: 100%; display: none; border: none; }
327
- .chat-area { display: none; border: none; height: 100%; }
328
- .mobile-tabs { display: flex; }
329
-
330
- .workspace[data-tab="channels"] .sidebar-left { display: flex; }
331
- .workspace[data-tab="chat"] .chat-area { display: flex; }
332
- .workspace[data-tab="users"] .sidebar-right { display: flex; }
333
-
334
- .window { width: 90%; left: 5% !important; top: 10% !important; }
335
- }
336
-
337
- /* Утилиты */
338
- .hidden { display: none !important; }
339
- #docx-window { width: 600px; max-width: 95vw; height: 400px; max-height: 90vh; }
340
- #docx-content { overflow-y: auto; flex: 1; user-select: text; font-family: monospace; white-space: pre-wrap; font-size: 12px; padding: 10px; background: white;}
341
-
342
- /* НОВЫЕ СТИЛИ (Resizers, Tabs, Polls, Ping) */
343
- .resizer {
344
- width: 5px;
345
- background: linear-gradient(to right, #e4eff8 0%, #b8d4eb 100%);
346
- cursor: col-resize;
347
- flex-shrink: 0;
348
- border-left: 1px solid var(--border-color);
349
- border-right: 1px solid #fff;
350
- }
351
- .resizer:hover, .resizer:active { background: #86aecc; }
352
-
353
- .tabs-header {
354
- display: flex;
355
- flex-wrap: wrap;
356
- background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
357
- border-bottom: 1px solid var(--border-color);
358
- padding: 2px 2px 0 2px;
359
- gap: 2px;
360
- }
361
- .tab-btn {
362
- background: #e4eff8;
363
- border: 1px solid var(--border-color);
364
- border-bottom: none;
365
- padding: 4px 10px;
366
- cursor: pointer;
367
- border-radius: 3px 3px 0 0;
368
- font-size: 11px;
369
- font-family: Tahoma, sans-serif;
370
- color: #555;
371
- }
372
- .tab-btn.active { background: white; font-weight: bold; color: #1e395b; padding-bottom: 5px; margin-bottom: -1px; z-index: 2; border-bottom: 1px solid white;}
373
- .docx-tab { overflow-y: auto; flex: 1; user-select: text; font-family: monospace; white-space: pre-wrap; font-size: 12px; padding: 10px; background: white; display: none; }
374
- .docx-tab.active { display: block; }
375
-
376
- .msg.pinged {
377
- background-color: #ffffe0;
378
- border-left: 2px solid #ffcc00;
379
- padding-left: 3px;
380
- }
381
- .poll-container {
382
- background: #f4f7f9; border: 1px solid var(--border-color); border-radius: 3px; padding: 8px; margin: 5px 0; font-family: Tahoma; font-size: 11px; width: fit-content; min-width: 200px; box-shadow: inset 1px 1px 2px #fff;
383
- }
384
- .poll-opt { display: flex; align-items: center; justify-content: space-between; margin-top: 5px; gap: 10px;}
385
- .poll-opt .btn { font-size: 10px; padding: 2px 6px; }
386
-
387
- .recent-servers { border: 1px solid #ccc; background: white; max-height: 60px; overflow-y: auto; margin-bottom: 10px; border-radius: 2px; box-shadow: inset 1px 1px 3px #eee; }
388
- .recent-servers .list-item { font-size: 11px; padding: 2px 5px; }
389
-
390
- /* Кнопки действий у сообщений */
391
- .msg-actions {
392
- display: none;
393
- margin-left: 10px;
394
- vertical-align: top;
395
- }
396
- .msg:hover .msg-actions {
397
- display: inline-flex;
398
- gap: 3px;
399
- }
400
- .msg-actions .btn {
401
- padding: 1px 4px;
402
- font-size: 9px;
403
- margin-right: 2px;
404
- }
405
- @media (max-width: 768px) {
406
- .msg-actions {
407
- display: inline-flex;
408
- gap: 3px;
409
- }
410
- }
411
  </style>
412
  </head>
413
- <body>
414
 
415
- <div class="menubar">
416
- <button class="btn" onclick="openWindow('connect-window')">Подключиться</button>
417
- <button class="btn hidden" id="btn-disconnect" onclick="disconnect()">Отключиться</button>
418
- <button class="btn" onclick="openWindow('docx-window')">DOCX / FAQ</button>
419
- <div style="flex:1"></div>
420
- <div id="user-status" style="color: white; line-height: 24px; text-shadow: 1px 1px 1px #000; font-weight: bold;">Не подключен</div>
421
- </div>
422
-
423
- <div class="workspace" data-tab="chat">
424
- <!-- Левая колонка: Каналы -->
425
- <div class="panel sidebar sidebar-left" id="panel-left">
426
- <div class="panel-header">Каналы</div>
427
- <div id="channels-list" style="overflow-y: auto; flex: 1;">
428
- <div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>
429
- </div>
430
- <div style="padding: 5px; border-top: 1px solid var(--border-color); background: #f4f7f9; display: flex; gap:4px; flex-shrink: 0;">
431
- <input type="text" id="new-channel-name" placeholder="Имя канала" style="flex: 1; min-width: 50px;">
432
- <button class="btn" onclick="createChannel()" style="flex-shrink: 0;">+</button>
433
- </div>
434
  </div>
435
 
436
- <div class="resizer" id="resizer-left"></div>
437
-
438
- <!-- Центральная колонка: Чат -->
439
- <div class="panel chat-area" id="panel-chat">
440
- <div class="panel-header" id="chat-title">Чат</div>
441
- <div class="chat-messages" id="messages-list">
442
- <div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>
443
- </div>
444
-
445
- <!-- Баннер действия (ответ/редактирование) -->
446
- <div id="action-banner" class="action-banner hidden">
447
- <span id="action-banner-text">Действие...</span>
448
- <button class="btn" style="padding: 1px 5px; background: #cc3333; color: white; border:none;" onclick="cancelAction()">X</button>
449
- </div>
450
-
451
- <div class="chat-input-area">
452
- <input type="text" id="msg-input" placeholder="Сообщение или команда (например, !опрос Вопрос Ответ1 Ответ2)" onkeydown="handleEnter(event)">
453
- <button class="btn" onclick="sendMessage()">Отправить</button>
454
- </div>
455
- </div>
456
-
457
- <div class="resizer" id="resizer-right"></div>
458
-
459
- <!-- Правая колонка: Пользователи -->
460
- <div class="panel sidebar sidebar-right" id="panel-right">
461
- <div class="panel-header">Пользователи</div>
462
- <div id="users-list" style="overflow-y: auto; flex: 1;">
463
- <div style="padding: 10px; color: #888;">Пусто</div>
464
- </div>
465
- </div>
466
- </div>
467
-
468
- <div class="mobile-tabs">
469
- <button class="btn" onclick="setMobileTab('channels')">Каналы</button>
470
- <button class="btn" onclick="setMobileTab('chat')">Чат</button>
471
- <button class="btn" onclick="setMobileTab('users')">Люди</button>
472
- </div>
473
-
474
- <div id="connect-window" class="window" style="top: 100px; left: 100px;">
475
- <div class="window-header">
476
- <span>⚙️ Настройки подключения</span>
477
- <div class="window-close" onclick="closeWindow('connect-window')">X</div>
478
- </div>
479
-
480
- <div class="window-body" id="connect-step-1">
481
- <div style="font-size: 11px; color: #555; margin-bottom: 2px;">Последние серверы:</div>
482
- <div class="recent-servers" id="recent-servers-list"></div>
483
-
484
- <div class="input-group">
485
- <label>Supabase Project URL:</label>
486
- <input type="text" id="supa-url" placeholder="https://xxxx.supabase.co" value="">
487
- </div>
488
- <div class="input-group">
489
- <label>Anon Key:</label>
490
- <input type="password" id="supa-key" placeholder="eyJhbGciOiJIUzI1NiIsInR5c...">
491
- </div>
492
- <button class="btn" style="margin-top: 10px;" onclick="checkConnection()">Check (Проверить)</button>
493
- <div id="connect-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
494
- </div>
495
-
496
- <div class="window-body hidden" id="connect-step-2">
497
- <div style="color: green; font-size: 11px; margin-bottom: 10px;">✅ Сервер доступен!</div>
498
- <div class="input-group">
499
- <label>Имя пользователя (Ник):</label>
500
- <input type="text" id="auth-user" placeholder="Например: admin">
501
- </div>
502
- <div class="input-group">
503
- <label>Пароль (Пинкод):</label>
504
- <input type="password" id="auth-pass" placeholder="***">
505
- </div>
506
- <div style="display: flex; gap: 10px; margin-top: 10px;">
507
- <button class="btn" style="flex:1" onclick="login()">Вход</button>
508
- <button class="btn" style="flex:1" onclick="register()">Регистрация</button>
509
- </div>
510
- <div id="auth-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
511
- </div>
512
- </div>
513
-
514
- <div id="docx-window" class="window" style="top: 50px; left: 50px;">
515
- <div class="window-header">
516
- <span>📄 DOCX - Руководство WebClient</span>
517
- <div class="window-close" onclick="closeWindow('docx-window')">X</div>
518
- </div>
519
- <div class="tabs-header">
520
- <button class="tab-btn active" onclick="switchDocxTab('tab-setup', this)">Настройка проекта</button>
521
- <button class="tab-btn" onclick="switchDocxTab('tab-sql', this)">SQL код</button>
522
- <button class="tab-btn" onclick="switchDocxTab('tab-rls', this)">RLS защита (обязательно)</button>
523
- <button class="tab-btn" onclick="switchDocxTab('tab-cmd', this)">Команды</button>
524
- <button class="tab-btn" onclick="switchDocxTab('tab-faq', this)">FAQ</button>
525
- </div>
526
- <div class="window-body" style="padding: 0; flex: 1; display: flex; flex-direction: column; min-height: 0;">
527
-
528
- <div id="tab-setup" class="docx-tab active">
529
- = НАСТРОЙКА ПРОЕКТА SUPABASE =
530
-
531
- WebClient работает на базе Supabase (бесплатная альтернатива Firebase с SQL под капотом). Вам нужно создать свой сервер баз данных.
532
-
533
- ШАГ 1: РЕГИСТРАЦИЯ И СОЗДАНИЕ
534
- 1. Перейдите на сайт supabase.com и зарегистрируйтесь (можно через GitHub).
535
- 2. Нажмите кнопку "New Project". Выберите организацию, введите название проекта и надежный пароль для базы данных.
536
- 3. Выберите регион (например, Central EU) и нажмите "Create new project".
537
- 4. Подождите пару минут, пока сервер инициализируется.
538
-
539
- ШАГ 2: ПОЛУЧЕНИЕ КЛЮЧЕЙ (ДЛЯ ПОДКЛЮЧЕНИЯ)
540
- 1. В левом меню панели Supabase найдите иконку шестеренки ("Project Settings").
541
- 2. Перейдите во вкладку "API".
542
- 3. Здесь вам нужны два значения:
543
- - Project URL (выглядит как https://xxxxxx.supabase.co)
544
- - Project API keys -> anon / public (длинный токен)
545
- 4. Именно эти два значения нужно вводить в WebClient при нажатии кнопки "Подключиться".
546
-
547
- ШАГ 3: БАЗА ДАННЫХ
548
- После создания проекта перейдите во вкладку "SQL Editor" (иконка с символами SQL в левом меню).
549
- Перейдите в следующие вкладки "SQL код" и "RLS защита" в этом окне, чтобы получить нужные скрипты.
550
- </div>
551
-
552
- <div id="tab-sql" class="docx-tab">
553
- = СОЗДАНИЕ ТАБЛИЦ (SQL) =
554
-
555
- Скопируйте код ниже, вставьте его в SQL Editor в панели Supabase и нажмите "Run" (Выполнить). Это создаст структуру базы данных для чата.
556
-
557
- <div class="code-block">
558
- <div class="code-header"><button class="btn" style="padding:1px 5px; font-size:9px;" onclick="copyCode('sql-tables')">Копировать</button></div>
559
- <pre id="sql-tables">-- 1. Таблица пользователей
560
  CREATE TABLE users (
561
  id SERIAL PRIMARY KEY,
562
  username TEXT UNIQUE NOT NULL,
563
  password TEXT NOT NULL,
564
- role TEXT DEFAULT 'user' -- 'admin' или 'user', 'banned'
565
  );
566
 
567
- -- 2. Таблица каналов
568
  CREATE TABLE channels (
569
  id SERIAL PRIMARY KEY,
570
  name TEXT UNIQUE NOT NULL
571
  );
572
 
573
- -- 3. Таблица сообщений
574
  CREATE TABLE messages (
575
  id SERIAL PRIMARY KEY,
576
  channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE,
577
- user_id INTEGER REFERENCES users(id),
578
  content TEXT NOT NULL,
579
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
580
  );
581
 
582
- -- 4. Базовые данные (Создаем канал по умолчанию)
583
- INSERT INTO channels (name) VALUES ('general');</pre>
584
- </div>
585
- </div>
586
-
587
- <div id="tab-rls" class="docx-tab">
588
- = RLS ЗАЩИТА (ОБЯЗАТЕЛЬНО) =
589
-
590
- Supabase PostgREST API (через который работает клиент) по умолчанию блокирует любые запросы к таблицам, если не настроены политики доступа (Row Level Security).
591
- Без этого шага WebClient будет выдавать ошибки доступа!
592
 
593
- Скопируйте и выполните этот код в SQL Editor после создания таблиц:
 
 
 
 
 
 
 
 
594
 
595
- <div class="code-block">
596
- <div class="code-header"><button class="btn" style="padding:1px 5px; font-size:9px;" onclick="copyCode('sql-rls')">Копировать</button></div>
597
- <pre id="sql-rls">-- Включаем защиту для всех таблиц
598
  ALTER TABLE users ENABLE ROW LEVEL SECURITY;
599
  ALTER TABLE channels ENABLE ROW LEVEL SECURITY;
600
  ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
601
 
602
- -- Так как наш "old school" WebClient сам занимается аутентификацией
603
- -- и хранит пароли в открытом виде (в рамках эксперимента/стиля),
604
- -- мы разрешаем публичный доступ к REST API для этих таблиц:
605
- CREATE POLICY "Allow all users" ON users FOR ALL USING (true);
606
- CREATE POLICY "Allow all channels" ON channels FOR ALL USING (true);
607
- CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
608
- </div>
609
-
610
- Внимание: Этот метод аутентификации (просто хранение пароля в таблице users) не является безопасным для реальных проектов с конфиденциальными данными. Он используется здесь исключительно в образовательных целях для имитации простых систем начала 2010-х годов!
611
- </div>
612
-
613
- <div id="tab-cmd" class="docx-tab">
614
- = КОМАНДЫ ЧАТА =
615
-
616
- В WebClient поддерживаются встроенные команды, которые можно вводить в поле сообщения:
617
-
618
- 1. Опросы (Голосования)
619
- Синтаксис: !опрос Название Вариант1 Вариант2 ...
620
- Пример: !опрос Какой_язык_лучше? JS Python C++
621
- (Используйте нижние подчеркивания вместо пробелов в названиях вариантов)
622
-
623
- 2. Пинги (Упоминания)
624
- Синтаксис: @имяпользователя
625
- Пример: Привет, @admin !
626
- Если кто-то напишет ваше имя через @, сообщение подсветится желтым фоном. Вы также можете нажать кнопку "Ответить" рядом с чужим сообщением, чтобы упомянуть автора.
627
- </div>
628
-
629
- <div id="tab-faq" class="docx-tab">
630
- = ЧАСТЫЕ ВОПРОСЫ (FAQ) =
631
-
632
- В: Как редактировать/удалять/пересылать сообщения?
633
- О: Наведите курсор на сообщение (на телефоне кнопки видны всегда). Справа появятся кнопки действий. Вы можете удалять/редактировать только свои сообщения (если вы не admin).
634
-
635
- В: Как сделать себя администратором?
636
- О: Зарегистрируйте аккаунт через клиент. Затем зайдите в панель управления Supabase -> Table Editor -> таблица 'users'. Найдите свою учетную запись и вручную измените значение колонки 'role' с 'user' на 'admin'. После этого в клиенте у вас появятся красные кнопки [BAN] в списке пользователей и права на удаление чужих сообщений.
637
-
638
- В: Как работают окна и панели?
639
- О: Окна можно перетаскивать за синий заголовок. Также можно изменять ширину боковых панелей (каналов и пользователей), потянув за узкие разделители между панелями. Они не могут быть сжаты слишком сильно для сохранения целостности интерфейса.
640
-
641
- В: Как отключиться от текущего сервера и войти на другой?
642
- О: На верхней панели при успешном подключении появляется кнопка "Отключиться". Нажмите её, чтобы сбросить соединение и вернуться в начальное меню выбора сервера.
643
- </div>
644
  </div>
645
  </div>
646
-
647
- <script>
648
- // --- 1. Логика перетаскивания окон ---
649
- function makeDraggable(el) {
650
- const header = el.querySelector('.window-header');
651
- let startX, startY, initialX, initialY;
652
-
653
- const target = header ? header : el;
654
-
655
- target.addEventListener('mousedown', (e) => {
656
- if (e.target.classList.contains('window-close')) return;
657
- e.preventDefault();
658
-
659
- document.querySelectorAll('.window').forEach(w => w.style.zIndex = 1000);
660
- el.style.zIndex = 1001;
661
-
662
- startX = e.clientX;
663
- startY = e.clientY;
664
- initialX = el.offsetLeft;
665
- initialY = el.offsetTop;
666
-
667
- const onMouseMove = (ev) => {
668
- el.style.left = initialX + (ev.clientX - startX) + "px";
669
- el.style.top = initialY + (ev.clientY - startY) + "px";
670
- };
671
-
672
- const onMouseUp = () => {
673
- document.removeEventListener('mousemove', onMouseMove);
674
- document.removeEventListener('mouseup', onMouseUp);
675
- };
676
-
677
- document.addEventListener('mousemove', onMouseMove);
678
- document.addEventListener('mouseup', onMouseUp);
679
- });
680
- }
681
-
682
- document.querySelectorAll('.window').forEach(makeDraggable);
683
-
684
- function openWindow(id) {
685
- const win = document.getElementById(id);
686
- win.classList.add('active');
687
- if(win.style.top === "100px") {
688
- win.style.top = (window.innerHeight / 2 - win.offsetHeight / 2) + "px";
689
- win.style.left = (window.innerWidth / 2 - win.offsetWidth / 2) + "px";
690
- }
691
- }
692
-
693
- function closeWindow(id) {
694
- document.getElementById(id).classList.remove('active');
695
- }
696
-
697
- function setMobileTab(tab) {
698
- document.querySelector('.workspace').setAttribute('data-tab', tab);
699
- }
700
-
701
- // --- Логика вкладок DOCX ---
702
- function switchDocxTab(tabId, btn) {
703
- document.querySelectorAll('.docx-tab').forEach(t => t.classList.remove('active'));
704
- document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
705
- document.getElementById(tabId).classList.add('active');
706
- if(btn) btn.classList.add('active');
707
- }
708
-
709
- // --- Логика ресайзеров ---
710
- function initResizers() {
711
- const resLeft = document.getElementById('resizer-left');
712
- const resRight = document.getElementById('resizer-right');
713
- const pLeft = document.getElementById('panel-left');
714
- const pRight = document.getElementById('panel-right');
715
-
716
- resLeft.addEventListener('mousedown', (e) => {
717
- e.preventDefault();
718
- document.body.style.cursor = 'col-resize';
719
- const onMouseMove = (ev) => { pLeft.style.width = Math.max(160, Math.min(ev.clientX, 400)) + 'px'; };
720
- const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
721
- document.addEventListener('mousemove', onMouseMove);
722
- document.addEventListener('mouseup', onMouseUp);
723
- });
724
-
725
- resRight.addEventListener('mousedown', (e) => {
726
- e.preventDefault();
727
- document.body.style.cursor = 'col-resize';
728
- const onMouseMove = (ev) => { pRight.style.width = Math.max(160, Math.min(document.body.clientWidth - ev.clientX, 400)) + 'px'; };
729
- const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
730
- document.addEventListener('mousemove', onMouseMove);
731
- document.addEventListener('mouseup', onMouseUp);
732
- });
733
- }
734
-
735
- // --- 2. Состояние приложения и REST API ---
736
- const state = {
737
- url: '',
738
- key: '',
739
- user: null,
740
- channels: [],
741
- activeChannel: null,
742
- usersCache: {},
743
- polls: {},
744
- lastMsgId: 0,
745
- polling: null,
746
- editingId: null,
747
- replyingToName: null,
748
- replyingToSnippet: null
749
- };
750
-
751
- async function api(table, method = 'GET', body = null, query = '') {
752
- if (!state.url || !state.key) return null;
753
-
754
- const endpoint = `${state.url}/rest/v1/${table}${query ? '?' + query : ''}`;
755
- const headers = {
756
- 'apikey': state.key,
757
- 'Authorization': `Bearer ${state.key}`,
758
- 'Content-Type': 'application/json',
759
- 'Prefer': 'return=representation'
760
- };
761
-
762
- const config = { method, headers };
763
- if (body) config.body = JSON.stringify(body);
764
-
765
- try {
766
- const res = await fetch(endpoint, config);
767
- if (!res.ok) {
768
- const errText = await res.text();
769
- throw new Error(errText || `HTTP ${res.status}`);
770
- }
771
- if (method === 'DELETE' || res.status === 204) return true;
772
- return await res.json();
773
- } catch (e) {
774
- console.error("API Error:", e);
775
- throw e;
776
- }
777
- }
778
-
779
- // --- 3. Логика Подключения и Авторизации ---
780
-
781
- function loadRecentServers() {
782
- let list = JSON.parse(localStorage.getItem('webclient_recent') || '[]');
783
- const container = document.getElementById('recent-servers-list');
784
- if(list.length === 0) {
785
- container.innerHTML = '<div style="padding: 5px; color:#888; font-size:10px;">Нет сохраненных серверов</div>';
786
- return;
787
- }
788
- container.innerHTML = list.map(s => `<div class="list-item" onclick="document.getElementById('supa-url').value='${s.url}'; document.getElementById('supa-key').value='${s.key}';">🔌 ${s.url.replace('https://','')}</div>`).join('');
789
- }
790
-
791
- function saveRecentServer(url, key) {
792
- let list = JSON.parse(localStorage.getItem('webclient_recent') || '[]');
793
- list = list.filter(s => s.url !== url);
794
- list.unshift({url, key});
795
- if(list.length > 5) list.pop();
796
- localStorage.setItem('webclient_recent', JSON.stringify(list));
797
- loadRecentServers();
798
- }
799
-
800
- async function checkConnection() {
801
- const urlInput = document.getElementById('supa-url').value.trim();
802
- const keyInput = document.getElementById('supa-key').value.trim();
803
- const errDiv = document.getElementById('connect-error');
804
-
805
- if (!urlInput || !keyInput) {
806
- errDiv.innerText = "Заполните URL и Key";
807
- return;
808
- }
809
-
810
- state.url = urlInput.endsWith('/') ? urlInput.slice(0, -1) : urlInput;
811
- state.key = keyInput;
812
- errDiv.innerText = "Проверка...";
813
-
814
- try {
815
- await api('channels', 'GET', null, 'select=id&limit=1');
816
- saveRecentServer(state.url, state.key);
817
- document.getElementById('connect-step-1').classList.add('hidden');
818
- document.getElementById('connect-step-2').classList.remove('hidden');
819
- errDiv.innerText = "";
820
- } catch (e) {
821
- errDiv.innerText = "Ошибка: Проверьте данные или права (RLS). " + e.message;
822
- state.url = ''; state.key = '';
823
- }
824
- }
825
-
826
- async function login() {
827
- const u = document.getElementById('auth-user').value.trim();
828
- const p = document.getElementById('auth-pass').value.trim();
829
- const err = document.getElementById('auth-error');
830
-
831
- if (!u || !p) return err.innerText = "Введите логин и пароль";
832
-
833
- try {
834
- const users = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}&password=eq.${encodeURIComponent(p)}`);
835
- if (users && users.length > 0) {
836
- state.user = users[0];
837
- if (state.user.role === 'banned') {
838
- throw new Error("Вы забанены на этом сервере!");
839
- }
840
- finishAuth();
841
- } else {
842
- err.innerText = "Неверный логин или пароль";
843
- }
844
- } catch(e) {
845
- err.innerText = e.message;
846
- }
847
- }
848
-
849
- async function register() {
850
- const u = document.getElementById('auth-user').value.trim();
851
- const p = document.getElementById('auth-pass').value.trim();
852
- const err = document.getElementById('auth-error');
853
-
854
- if (!u || !p) return err.innerText = "Введите логин и пароль";
855
-
856
- try {
857
- const exist = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}`);
858
- if (exist && exist.length > 0) throw new Error("Ник уже занят");
859
-
860
- const res = await api('users', 'POST', { username: u, password: p, role: 'user' });
861
- if (res && res.length > 0) {
862
- state.user = res[0];
863
- finishAuth();
864
- }
865
- } catch(e) {
866
- err.innerText = e.message;
867
- }
868
- }
869
-
870
- function finishAuth() {
871
- closeWindow('connect-window');
872
- document.getElementById('user-status').innerText = `👤 ${state.user.username} [${state.user.role}]`;
873
- document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Соединение установлено. Авторизация успешна.</div>`;
874
- document.getElementById('btn-disconnect').classList.remove('hidden');
875
-
876
- fetchAllUsers();
877
- loadChannels();
878
-
879
- if(state.polling) clearInterval(state.polling);
880
- state.polling = setInterval(appTick, 2000);
881
- }
882
-
883
- function disconnect() {
884
- state.user = null;
885
- state.activeChannel = null;
886
- state.channels = [];
887
- state.usersCache = {};
888
- state.editingId = null;
889
- state.replyingToName = null;
890
- state.replyingToSnippet = null;
891
- if(state.polling) clearInterval(state.polling);
892
-
893
- document.getElementById('user-status').innerText = 'Не подключен';
894
- document.getElementById('messages-list').innerHTML = '<div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>';
895
- document.getElementById('btn-disconnect').classList.add('hidden');
896
- document.getElementById('chat-title').innerText = 'Чат';
897
-
898
- renderChannels();
899
- renderUsersList();
900
- openWindow('connect-window');
901
- }
902
-
903
- async function fetchAllUsers() {
904
- try {
905
- const users = await api('users', 'GET', null, 'select=id,username,role');
906
- if (users) {
907
- users.forEach(u => state.usersCache[u.id] = u);
908
- renderUsersList();
909
- }
910
- } catch(e) {}
911
- }
912
-
913
- // --- 4. Логика Чата (Каналы, Сообщения) ---
914
-
915
- async function loadChannels() {
916
- try {
917
- const chans = await api('channels', 'GET', null, 'order=id.asc');
918
- if (chans) {
919
- state.channels = chans;
920
- renderChannels();
921
- if (chans.length > 0 && !state.activeChannel) {
922
- joinChannel(chans[0].id);
923
- }
924
- }
925
- } catch(e) { console.error("Load channels err", e); }
926
- }
927
-
928
- function renderChannels() {
929
- const cl = document.getElementById('channels-list');
930
- cl.innerHTML = '';
931
- if(!state.user) {
932
- cl.innerHTML = '<div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>';
933
- return;
934
- }
935
-
936
- const serverChans = state.channels.filter(c => c.name === 'general');
937
- const userChans = state.channels.filter(c => c.name !== 'general');
938
-
939
- const createChanEl = (c) => {
940
- const div = document.createElement('div');
941
- div.className = `list-item ${state.activeChannel === c.id ? 'active' : ''}`;
942
- div.innerHTML = `<span>#${c.name}</span>`;
943
- if (state.user && state.user.role === 'admin' && c.name !== 'general') {
944
- div.innerHTML += `<span style="color:#ffb3b3;" onclick="deleteChannel(${c.id}, event)">x</span>`;
945
- }
946
- div.onclick = () => joinChannel(c.id);
947
- return div;
948
- };
949
-
950
- if(serverChans.length > 0) {
951
- cl.innerHTML += '<div class="category-header">Серверные каналы</div>';
952
- serverChans.forEach(c => cl.appendChild(createChanEl(c)));
953
- }
954
- if(userChans.length > 0) {
955
- cl.innerHTML += '<div class="category-header">Пользовательские каналы</div>';
956
- userChans.forEach(c => cl.appendChild(createChanEl(c)));
957
- }
958
- }
959
-
960
- async function createChannel() {
961
- if(!state.user) return;
962
- const input = document.getElementById('new-channel-name');
963
- const name = input.value.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '');
964
- if (!name) return;
965
-
966
- try {
967
- await api('channels', 'POST', { name });
968
- input.value = '';
969
- loadChannels();
970
- } catch(e) { alert("Ошибка создания канала: " + e.message); }
971
- }
972
-
973
- async function deleteChannel(id, event) {
974
- event.stopPropagation();
975
- if(!confirm("Удалить канал?")) return;
976
- try {
977
- await api('channels', 'DELETE', null, `id=eq.${id}`);
978
- if (state.activeChannel === id) state.activeChannel = null;
979
- loadChannels();
980
- } catch(e) {}
981
- }
982
-
983
- async function joinChannel(id) {
984
- state.activeChannel = id;
985
- state.lastMsgId = 0;
986
- state.polls = {};
987
- const c = state.channels.find(x => x.id === id);
988
- document.getElementById('chat-title').innerText = `Чат :: #${c ? c.name : 'Unknown'}`;
989
- document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Вы вошли в канал #${c ? c.name : 'Unknown'}</div>`;
990
- renderChannels();
991
- await fetchMessages();
992
- }
993
-
994
- async function getUser(id) {
995
- if (state.usersCache[id]) return state.usersCache[id];
996
- try {
997
- const u = await api('users', 'GET', null, `id=eq.${id}&select=id,username,role`);
998
- if (u && u.length > 0) {
999
- state.usersCache[id] = u[0];
1000
- renderUsersList();
1001
- return u[0];
1002
- }
1003
- } catch(e) {}
1004
- return { username: 'Unknown' };
1005
- }
1006
-
1007
- function renderUsersList() {
1008
- const ul = document.getElementById('users-list');
1009
- ul.innerHTML = '';
1010
- Object.values(state.usersCache).forEach(u => {
1011
- const div = document.createElement('div');
1012
- div.className = 'list-item';
1013
- div.innerHTML = `<span>${u.role === 'admin' ? '@' : ''}${u.username}</span>`;
1014
-
1015
- if (state.user && state.user.role === 'admin' && u.id !== state.user.id) {
1016
- div.innerHTML += `<span style="color:red; font-size:10px;" onclick="banUser(${u.id}, event)">[BAN]</span>`;
1017
- }
1018
- ul.appendChild(div);
1019
- });
1020
- }
1021
-
1022
- async function banUser(userId, event) {
1023
- event.stopPropagation();
1024
- if(!confirm("Забанить пользователя?")) return;
1025
- try {
1026
- await api('users', 'PATCH', { role: 'banned' }, `id=eq.${userId}`);
1027
- alert("Пользователь забанен!");
1028
- delete state.usersCache[userId];
1029
- } catch(e) { alert("Ошибка: " + e.message); }
1030
- }
1031
-
1032
- function escapeHTML(str) {
1033
- return str.replace(/[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag]));
1034
- }
1035
-
1036
- function copyCode(id) {
1037
- const text = document.getElementById(id).innerText;
1038
- const ta = document.createElement('textarea');
1039
- ta.value = text;
1040
- document.body.appendChild(ta);
1041
- ta.select();
1042
- try { document.execCommand('copy'); } catch(e){}
1043
- document.body.removeChild(ta);
1044
- }
1045
-
1046
- function formatContent(text) {
1047
- return escapeHTML(text);
1048
- }
1049
-
1050
- // Функции для ответа и редактирования (баннер)
1051
- function startReply(username, rawContent) {
1052
- cancelAction();
1053
- state.replyingToName = username;
1054
- let cleanText = rawContent.replace(/\[R:.*?\](.*?)\[\/R\]/g, "").trim();
1055
- state.replyingToSnippet = cleanText.length > 40 ? cleanText.substring(0, 40) + '...' : cleanText;
1056
-
1057
- document.getElementById('action-banner-text').innerText = `Отвечая ${username}: ${state.replyingToSnippet}`;
1058
- document.getElementById('action-banner').classList.remove('hidden');
1059
- document.getElementById('msg-input').focus();
1060
- }
1061
-
1062
- function startEdit(id, rawContent) {
1063
- cancelAction();
1064
- state.editingId = id;
1065
- document.getElementById('action-banner-text').innerText = `Редактирование сообщения`;
1066
- document.getElementById('action-banner').classList.remove('hidden');
1067
-
1068
- const input = document.getElementById('msg-input');
1069
- input.value = rawContent;
1070
- input.focus();
1071
- }
1072
-
1073
- function cancelAction() {
1074
- state.editingId = null;
1075
- state.replyingToName = null;
1076
- state.replyingToSnippet = null;
1077
- document.getElementById('action-banner').classList.add('hidden');
1078
- document.getElementById('msg-input').value = '';
1079
- }
1080
-
1081
- async function deleteMsg(id) {
1082
- if(confirm("Удалить это сообщение?")) {
1083
- try {
1084
- await api('messages', 'DELETE', null, `id=eq.${id}`);
1085
- fetchMessages();
1086
- } catch(e) { alert("Ошибка: " + e.message); }
1087
- }
1088
- }
1089
-
1090
- async function fetchMessages() {
1091
- if (!state.activeChannel || !state.user) return;
1092
- try {
1093
- const msgs = await api('messages', 'GET', null, `channel_id=eq.${state.activeChannel}&order=id.desc&limit=50`);
1094
- if (!msgs) return;
1095
- msgs.reverse();
1096
-
1097
- const ml = document.getElementById('messages-list');
1098
- const isAtBottom = (ml.scrollHeight - ml.scrollTop - ml.clientHeight) < 20;
1099
-
1100
- const currentMsgIds = new Set(Array.from(ml.querySelectorAll('.msg[data-id]')).map(el => parseInt(el.dataset.id)));
1101
- const fetchedMsgIds = new Set(msgs.map(m => m.id));
1102
-
1103
- currentMsgIds.forEach(id => {
1104
- if (!fetchedMsgIds.has(id)) {
1105
- const el = document.getElementById('msg-' + id);
1106
- if (el) el.remove();
1107
- }
1108
- });
1109
-
1110
- for (const m of msgs) {
1111
- const u = await getUser(m.user_id);
1112
- const time = new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
1113
-
1114
- if (m.content.startsWith('[VOTE] ')) {
1115
- const parts = m.content.split(' ');
1116
- const pId = parseInt(parts[1]);
1117
- const optIdx = parseInt(parts[2]);
1118
- if (!state.polls[pId]) state.polls[pId] = { q: '', opts: [], votes: {} };
1119
- state.polls[pId].votes[m.user_id] = optIdx;
1120
-
1121
- renderPollHTML(pId);
1122
- continue;
1123
- }
1124
-
1125
- let el = document.getElementById('msg-' + m.id);
1126
-
1127
- if (el) {
1128
- if (el.dataset.raw !== m.content) {
1129
- el.dataset.raw = m.content;
1130
- if (!m.content.startsWith('[POLL] ')) {
1131
- let displayContent = m.content;
1132
- let quoteHTML = '';
1133
- const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1134
- if (match) {
1135
- const rName = match[1];
1136
- const rSnippet = match[2];
1137
- displayContent = match[3];
1138
- quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1139
- }
1140
- el.querySelector('.content').innerHTML = quoteHTML + formatContent(displayContent);
1141
- // Обновляем кнопки действий (вдруг права изменились)
1142
- updateMessageActions(el, m, u);
1143
- }
1144
- }
1145
- continue;
1146
- }
1147
-
1148
- const div = document.createElement('div');
1149
- div.id = 'msg-' + m.id;
1150
- div.dataset.id = m.id;
1151
- div.dataset.raw = m.content;
1152
-
1153
- const isPing = m.content.includes('@' + state.user.username);
1154
- div.className = `msg ${isPing ? 'pinged' : ''}`;
1155
-
1156
- if (m.content.startsWith('[POLL] ')) {
1157
- try {
1158
- const pData = JSON.parse(m.content.substring(7));
1159
- const pId = m.id;
1160
- if(!state.polls[pId]) state.polls[pId] = { q: pData[0], opts: pData.slice(1), votes: {} };
1161
-
1162
- div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <div id="poll-container-${pId}"></div>`;
1163
- ml.appendChild(div);
1164
- renderPollHTML(pId);
1165
- } catch(e) {}
1166
- } else {
1167
- let displayContent = m.content;
1168
- let quoteHTML = '';
1169
- const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1170
- if (match) {
1171
- const rName = match[1];
1172
- const rSnippet = match[2];
1173
- displayContent = match[3];
1174
- quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1175
- }
1176
- div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <span class="content">${quoteHTML}${formatContent(displayContent)}</span>`;
1177
- ml.appendChild(div);
1178
- updateMessageActions(div, m, u);
1179
- }
1180
- }
1181
- if (isAtBottom) {
1182
- ml.scrollTop = ml.scrollHeight;
1183
- }
1184
- } catch(e) { console.error("Msg fetch err", e); }
1185
- }
1186
-
1187
- function updateMessageActions(el, m, u) {
1188
- // Добавляем или обновляем блок кнопок действий
1189
- let actionsDiv = el.querySelector('.msg-actions');
1190
- if (!actionsDiv) {
1191
- actionsDiv = document.createElement('div');
1192
- actionsDiv.className = 'msg-actions';
1193
- el.appendChild(actionsDiv);
1194
- }
1195
-
1196
- let actionsHtml = '';
1197
- // Кнопка "Ответить" доступна всегда
1198
- actionsHtml += `<button class="btn" onclick="startReply('${u.username}', '${m.content.replace(/'/g, "\\'").replace(/"/g, '&quot;')}')">Ответить</button>`;
1199
-
1200
- // Кнопка "Ред." только для своих не-опросов
1201
- if (m.user_id === state.user.id && !m.content.startsWith('[POLL] ')) {
1202
- actionsHtml += `<button class="btn" onclick="startEdit(${m.id}, '${m.content.replace(/'/g, "\\'").replace(/"/g, '&quot;')}')">Ред.</button>`;
1203
- }
1204
-
1205
- // Кнопка "Удал." для своих или для админа
1206
- if (m.user_id === state.user.id || state.user.role === 'admin') {
1207
- actionsHtml += `<button class="btn" onclick="deleteMsg(${m.id})">Удал.</button>`;
1208
- }
1209
-
1210
- actionsDiv.innerHTML = actionsHtml;
1211
- }
1212
-
1213
- function renderPollHTML(pId) {
1214
- const container = document.getElementById(`poll-container-${pId}`);
1215
- if (!container || !state.polls[pId]) return;
1216
- const poll = state.polls[pId];
1217
-
1218
- let html = `<div class="poll-container"><b>📊 ${poll.q}</b>`;
1219
- poll.opts.forEach((opt, idx) => {
1220
- let count = Object.values(poll.votes).filter(v => v === idx).length;
1221
- let activeVote = poll.votes[state.user.id] === idx ? 'style="font-weight:bold; color:#0f2c4c;"' : '';
1222
- html += `<div class="poll-opt">
1223
- <button class="btn" onclick="votePoll(${pId}, ${idx})">${opt}</button>
1224
- <span ${activeVote}>Голосов: ${count}</span>
1225
- </div>`;
1226
- });
1227
- html += `</div>`;
1228
- container.innerHTML = html;
1229
- }
1230
-
1231
- async function votePoll(msgId, optIdx) {
1232
- if(!state.user || !state.activeChannel) return;
1233
- try {
1234
- await api('messages', 'POST', {
1235
- channel_id: state.activeChannel,
1236
- user_id: state.user.id,
1237
- content: `[VOTE] ${msgId} ${optIdx}`
1238
- });
1239
- await fetchMessages();
1240
- } catch(e) { alert("Ошибка голосования: " + e.message); }
1241
- }
1242
-
1243
- function handleEnter(e) {
1244
- if (e.key === 'Enter') {
1245
- e.preventDefault();
1246
- sendMessage();
1247
- }
1248
- }
1249
-
1250
- async function sendMessage() {
1251
- const input = document.getElementById('msg-input');
1252
- let text = input.value.trim();
1253
- if (!text || !state.user || !state.activeChannel) return;
1254
-
1255
- input.disabled = true;
1256
- try {
1257
- const pollMatch = text.match(/^!опрос\s+(.+)/i);
1258
- if (pollMatch) {
1259
- const parts = pollMatch[1].split(/\s+/);
1260
- if (parts.length >= 3) {
1261
- text = `[POLL] ${JSON.stringify(parts)}`;
1262
- } else {
1263
- alert("Синтаксис: !опрос Название Вариант1 Вариант2");
1264
- input.disabled = false;
1265
- return;
1266
- }
1267
- }
1268
-
1269
- let finalContent = text;
1270
- if (state.replyingToName && !state.editingId) {
1271
- finalContent = `[R:${state.replyingToName}]${state.replyingToSnippet}[/R]${text}`;
1272
- }
1273
-
1274
- if (state.editingId) {
1275
- await api('messages', 'PATCH', { content: finalContent }, `id=eq.${state.editingId}`);
1276
- cancelAction();
1277
- } else {
1278
- await api('messages', 'POST', {
1279
- channel_id: state.activeChannel,
1280
- user_id: state.user.id,
1281
- content: finalContent
1282
- });
1283
- cancelAction();
1284
- }
1285
-
1286
- input.value = '';
1287
- await fetchMessages();
1288
- } catch(e) {
1289
- alert("Не удалось отправить: " + e.message);
1290
- } finally {
1291
- input.disabled = false;
1292
- input.focus();
1293
- }
1294
- }
1295
-
1296
- let tickCounter = 0;
1297
- function appTick() {
1298
- fetchMessages();
1299
-
1300
- tickCounter++;
1301
- if (tickCounter % 5 === 0) {
1302
- loadChannels();
1303
- fetchAllUsers();
1304
- }
1305
- }
1306
-
1307
- window.onload = () => {
1308
- initResizers();
1309
- loadRecentServers();
1310
- };
1311
-
1312
- </script>
1313
  </body>
1314
  </html>
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Настройка сервера (Supabase)</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
  <style>
9
+ body { font-family: 'Inter', sans-serif; }
10
+ pre { background-color: #1e1e1e; color: #d4d4d4; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; font-size: 0.9rem; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  </style>
12
  </head>
13
+ <body class="bg-gray-50 text-gray-800 antialiased p-4 md:p-8">
14
 
15
+ <div class="max-w-3xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100">
16
+ <div class="bg-blue-600 p-6 text-white text-center">
17
+ <h1 class="text-3xl font-bold">Настройка сервера Supabase</h1>
18
+ <p class="mt-2 text-blue-100">Инструкция по созданию базы данных и настройке безопасности (RLS)</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </div>
20
 
21
+ <div class="p-6 md:p-8 space-y-8">
22
+
23
+ <section>
24
+ <h2 class="text-2xl font-semibold text-gray-900 border-b pb-2 mb-4">1. Подготовка</h2>
25
+ <ul class="list-disc pl-5 space-y-2 text-gray-700">
26
+ <li>Зарегистрируйтесь на <a href="https://supabase.com/" class="text-blue-600 hover:underline font-medium">Supabase</a> и создайте новый проект.</li>
27
+ <li>Скопируйте <strong>Project URL</strong> и <strong>anon key</strong> (они понадобятся для входа в приложении).</li>
28
+ <li>Перейдите во вкладку <strong>SQL Editor</strong> в левом меню панели управления Supabase.</li>
29
+ </ul>
30
+ </section>
31
+
32
+ <section>
33
+ <h2 class="text-2xl font-semibold text-gray-900 border-b pb-2 mb-4">2. Создание таблиц</h2>
34
+ <p class="text-gray-700 mb-4">Скопируйте и выполните следующий код в SQL Editor, чтобы создать структуру базы данных.</p>
35
+ <pre><code>-- Создание таблицы пользователей
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  CREATE TABLE users (
37
  id SERIAL PRIMARY KEY,
38
  username TEXT UNIQUE NOT NULL,
39
  password TEXT NOT NULL,
40
+ role TEXT DEFAULT 'user'
41
  );
42
 
43
+ -- Создание таблицы каналов
44
  CREATE TABLE channels (
45
  id SERIAL PRIMARY KEY,
46
  name TEXT UNIQUE NOT NULL
47
  );
48
 
49
+ -- Создание таблицы сообщений
50
  CREATE TABLE messages (
51
  id SERIAL PRIMARY KEY,
52
  channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE,
53
+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
54
  content TEXT NOT NULL,
55
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc', NOW())
56
  );
57
 
58
+ -- Добавляем тестовый канал, чтобы вам было где общаться
59
+ INSERT INTO channels (name) VALUES ('general'), ('offtop');</code></pre>
60
+ </section>
 
 
 
 
 
 
 
61
 
62
+ <section>
63
+ <h2 class="text-2xl font-semibold text-gray-900 border-b pb-2 mb-4">3. Настройка безопасности (Row Level Security)</h2>
64
+ <p class="text-gray-700 mb-2">Так как мы используем кастомную систему авторизации (через передачу user_id, а не встроенный Supabase Auth), нам нужно разрешить приложению работать с таблицами анонимно, но при этом закрыть потенциально опасные действия.</p>
65
+
66
+ <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4">
67
+ <p class="text-sm text-yellow-800">
68
+ <strong>Важно:</strong> Для абсолютной безопасности (чтобы пользователи не могли удалять чужие сообщения, отправляя поддельные API запросы) необходимо интегрировать систему Supabase Auth (JWT токены). Данные правила (Policies) обеспечивают <u>базовую работу</u> нашего кастомного клиента.
69
+ </p>
70
+ </div>
71
 
72
+ <pre><code>-- Включаем систему безопасности RLS
 
 
73
  ALTER TABLE users ENABLE ROW LEVEL SECURITY;
74
  ALTER TABLE channels ENABLE ROW LEVEL SECURITY;
75
  ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
76
 
77
+ -- -----------------------------------------------------
78
+ -- ПОЛИТИКИ ДЛЯ ПОЛЬЗОВАТЕЛЕЙ (users)
79
+ -- Разрешаем читать список всех пользователей
80
+ CREATE POLICY "Public Users Select" ON users FOR SELECT USING (true);
81
+ -- Разрешаем регистрацию новых пользователей (Insert)
82
+ CREATE POLICY "Public Users Insert" ON users FOR INSERT WITH CHECK (true);
83
+
84
+ -- -----------------------------------------------------
85
+ -- ПОЛИТИКИ ДЛЯ КАНАЛОВ (channels)
86
+ -- Читать список каналов могут все
87
+ CREATE POLICY "Public Channels Select" ON channels FOR SELECT USING (true);
88
+ -- Запрещаем создание новых каналов через клиент (только админы через Supabase)
89
+
90
+ -- -----------------------------------------------------
91
+ -- ПОЛИТИКИ ДЛЯ СООБЩЕНИЙ (messages)
92
+ -- Читать сообщения могут все
93
+ CREATE POLICY "Public Messages Select" ON messages FOR SELECT USING (true);
94
+ -- Писать сообщения могут все
95
+ CREATE POLICY "Public Messages Insert" ON messages FOR INSERT WITH CHECK (true);
96
+ -- Редактировать сообщения могут все
97
+ CREATE POLICY "Public Messages Update" ON messages FOR UPDATE USING (true);
98
+ -- Удалять сообщения могут все
99
+ CREATE POLICY "Public Messages Delete" ON messages FOR DELETE USING (true);</code></pre>
100
+ </section>
101
+
102
+ <section class="text-center pt-4 border-t">
103
+ <p class="text-gray-600">После выполнения этих SQL-скриптов сервер готов к работе с вашим Android-клиентом!</p>
104
+ </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  </div>
106
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  </body>
108
  </html>