Полный рефакторинг сервера и клиента, голосовые сообщения, аудио/видео, Docker
Сервер: - Вынесена конфигурация в server/config.js (порт, размер файла из env) - Вынесена аутентификация в server/auth.js (загрузка users.json, authenticate()) - Вынесено управление соединениями в server/clients.js (createJsonSender, broadcast, validateFile) - server/server.js стал точкой входа — минимальный код Клиент: - Вынесены хуки: hooks/useWebSocket.js (WebSocket + auth), hooks/useChatMessages.js (сообщения + уведомления) - Вынесены утилиты: utils/blob.js (base64 → Blob URL), utils/linkify.jsx (URL → ссылки), utils/notify.js (звук + favicon) Новые функции: - VoiceRecorder — запись голоса через MediaRecorder, отправка как файл - Аудио/видео плеер в Message (audio/*, video/* с controls) - URL linkification — http/https ссылки автоматически кликабельны - Звуковое уведомление (Web Audio API) при сообщении на неактивной вкладке - Красная точка на favicon при непрочитанных сообщениях Инфраструктура: - docker-entrypoint.sh: авто-перезапуск Node.js сервера при падении - Обновлён README.md: новая структура проекта, список функций, примеры - Кастомный тонкий скроллбар в Message.css
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
# Чат с общей комнатой
|
||||
|
||||
Веб-приложение чата с одной общей комнатой на WebSocket. Поддерживает текстовые сообщения, отправку файлов и отображение изображений.
|
||||
Веб-приложение чата с одной общей комнатой на WebSocket.
|
||||
Текстовые сообщения, файлы, изображения, аудио, видео и голосовые сообщения.
|
||||
|
||||
**Сервер:** Node.js + `ws`
|
||||
**Клиент:** React + Vite
|
||||
@@ -18,7 +19,7 @@ npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
Запускает WebSocket сервер на `ws://localhost:8080`.
|
||||
WebSocket сервер на `ws://localhost:8080`.
|
||||
|
||||
### Клиент
|
||||
|
||||
@@ -28,8 +29,8 @@ npm install
|
||||
npx vite
|
||||
```
|
||||
|
||||
Запускает dev-сервер на `http://localhost:3000`.
|
||||
В режиме разработки клиент подключается напрямую к `ws://localhost:8080`.
|
||||
Dev-сервер на `http://localhost:3000`.
|
||||
Клиент подключается напрямую к `ws://localhost:8080`.
|
||||
|
||||
### Пользователи по умолчанию
|
||||
|
||||
@@ -42,15 +43,10 @@ npx vite
|
||||
|
||||
## Production (Docker)
|
||||
|
||||
### Сборка образа
|
||||
### Сборка и запуск
|
||||
|
||||
```bash
|
||||
docker build -t chat-app .
|
||||
```
|
||||
|
||||
### Запуск контейнера
|
||||
|
||||
```bash
|
||||
docker run -d -p 80:80 chat-app
|
||||
```
|
||||
|
||||
@@ -59,11 +55,12 @@ docker run -d -p 80:80 chat-app
|
||||
### Как это работает
|
||||
|
||||
- **nginx** на порту 80 раздаёт статику React и проксирует WebSocket
|
||||
- Путь `/` → статические файлы клиента (`index.html`, JS, CSS)
|
||||
- Путь `/ws` → прокси на Node.js WebSocket сервер (порт 8080 внутри контейнера)
|
||||
- Путь `/` → статические файлы клиента
|
||||
- Путь `/ws` → прокси на Node.js сервер (порт 8080 внутри контейнера)
|
||||
- nginx поддерживает Upgrade до WebSocket, таймаут соединения — 24 часа
|
||||
- Максимальный размер загружаемых файлов через nginx — 50 МБ
|
||||
- После остановки Node.js контейнер завершается (через `wait`)
|
||||
- **Auto-restart:** если Node.js сервер упал, entrypoint перезапускает его через 1 секунду
|
||||
- Чистое завершение (exit 0, SIGTERM) — контейнер останавливается без перезапуска
|
||||
|
||||
---
|
||||
|
||||
@@ -77,8 +74,6 @@ docker run -d -p 80:80 chat-app
|
||||
| `MAX_FILE_SIZE` | `10485760` (10 МБ) | Максимальный размер файла в байтах |
|
||||
| `USERS_FILE` | `users.json` | Путь к файлу с пользователями |
|
||||
|
||||
Пример:
|
||||
|
||||
```bash
|
||||
$env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
|
||||
```
|
||||
@@ -89,9 +84,7 @@ $env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
|
||||
|-----------|-------------------|--------------------------|---------|
|
||||
| `VITE_WS_URL` | `ws://localhost:8080` | `/ws` | URL WebSocket сервера |
|
||||
|
||||
Настройки хранятся в файлах:
|
||||
- `client/.env.development` — для `npx vite` (dev-режим)
|
||||
- `client/.env` — для `vite build` (production-сборка)
|
||||
Настройки в `client/.env.development` (dev) и `client/.env` (production).
|
||||
|
||||
---
|
||||
|
||||
@@ -99,81 +92,54 @@ $env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
|
||||
|
||||
### Аутентификация
|
||||
|
||||
Клиент → Сервер:
|
||||
|
||||
```json
|
||||
// → сервер
|
||||
{ "type": "auth", "login": "alice", "password": "123" }
|
||||
```
|
||||
|
||||
Сервер → Клиент:
|
||||
|
||||
```json
|
||||
// ← ответ
|
||||
{ "type": "auth_result", "success": true }
|
||||
```
|
||||
|
||||
```json
|
||||
{ "type": "auth_result", "success": false, "reason": "Invalid login or password" }
|
||||
```
|
||||
|
||||
### Текстовое сообщение
|
||||
|
||||
Клиент → Сервер:
|
||||
|
||||
```json
|
||||
// → сервер
|
||||
{ "type": "text", "text": "Привет!" }
|
||||
```
|
||||
|
||||
Сервер → Все:
|
||||
|
||||
```json
|
||||
// ← всем
|
||||
{ "type": "text", "from": "alice", "timestamp": 1717000000000, "text": "Привет!" }
|
||||
```
|
||||
|
||||
### Файл / изображение
|
||||
|
||||
Клиент → Сервер:
|
||||
### Файл / изображение / аудио / видео
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "file",
|
||||
"filename": "cat.png",
|
||||
"mime": "image/png",
|
||||
"data": "<base64>"
|
||||
}
|
||||
// → сервер
|
||||
{ "type": "file", "filename": "cat.png", "mime": "image/png", "data": "<base64>" }
|
||||
// ← всем (от сервера добавлены from и timestamp)
|
||||
{ "type": "file", "from": "alice", "timestamp": 1717000000000, "filename": "cat.png", "mime": "image/png", "data": "<base64>" }
|
||||
```
|
||||
|
||||
Сервер → Все (такая же структура, добавлены `from` и `timestamp`):
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "file",
|
||||
"from": "alice",
|
||||
"timestamp": 1717000000000,
|
||||
"filename": "cat.png",
|
||||
"mime": "image/png",
|
||||
"data": "<base64>"
|
||||
}
|
||||
```
|
||||
Клиент определяет тип файла по MIME: `image/*` — картинка, `audio/*` — плеер, `video/*` — плеер, остальное — скачивание.
|
||||
|
||||
### Системные сообщения
|
||||
|
||||
Сервер → Все:
|
||||
|
||||
```json
|
||||
{ "type": "system", "text": "alice joined the chat" }
|
||||
{ "type": "system", "text": "alice left the chat" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Функциональность
|
||||
|
||||
- **Текстовые сообщения** — отображаются с логином отправителя и временем
|
||||
- **Файлы** — любые типы, до 10 МБ (настраивается). Файлы передаются через base64 в JSON
|
||||
- **Изображения** — автоматически определяются по MIME-типу (`image/*`), рендерятся как `<img>`, клик открывает в новой вкладке
|
||||
- **Не-изображения** — отображаются как ссылка для скачивания с именем файла
|
||||
- **Уведомления на неактивной вкладке** — звуковой сигнал (Web Audio API) и красная точка на favicon
|
||||
- **Текстовые сообщения** — логин отправителя, время, ссылки (http/https) автоматически становятся кликабельными
|
||||
- **Файлы** — любые типы, до 10 МБ (настраивается), base64 в JSON
|
||||
- **Изображения** — `image/*` → `<img>`, клик открывает в новой вкладке
|
||||
- **Аудио** — `audio/*` → `<audio controls>` + ссылка скачивания
|
||||
- **Видео** — `video/*` → `<video>` с controls + ссылка скачивания
|
||||
- **Голосовые сообщения** — кнопка микрофона, запись через `MediaRecorder`, отправка как файл
|
||||
- **Уведомления** — звук (Web Audio API) и красная точка на favicon при сообщении на неактивной вкладке
|
||||
- **Системные сообщения** — подключение/отключение участников
|
||||
- **Скролл** — автоматический, кастомный тонкий скроллбар в теме приложения
|
||||
- **Автоскролл** — кастомный тонкий скроллбар
|
||||
|
||||
---
|
||||
|
||||
@@ -182,27 +148,39 @@ $env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
|
||||
```
|
||||
chat/
|
||||
├── server/
|
||||
│ ├── server.js # WebSocket сервер
|
||||
│ ├── config.js # Настройки из env
|
||||
│ ├── auth.js # Загрузка пользователей, authenticate()
|
||||
│ ├── clients.js # Управление соединениями, broadcast()
|
||||
│ ├── server.js # Точка входа, WebSocketServer
|
||||
│ ├── users.json # Хардкоженые логины/пароли
|
||||
│ └── package.json
|
||||
├── client/
|
||||
│ ├── src/
|
||||
│ │ ├── App.jsx # Корневой компонент
|
||||
│ │ ├── App.css
|
||||
│ │ ├── main.jsx # Точка входа
|
||||
│ │ ├── App.jsx / .css
|
||||
│ │ ├── main.jsx
|
||||
│ │ ├── hooks/
|
||||
│ │ │ ├── useWebSocket.js # WebSocket + auth
|
||||
│ │ │ └── useChatMessages.js # Приём сообщений + уведомления
|
||||
│ │ ├── utils/
|
||||
│ │ │ ├── blob.js # base64 → Blob URL
|
||||
│ │ │ ├── linkify.jsx # URL → React-ссылки
|
||||
│ │ │ └── notify.js # Звук + favicon
|
||||
│ │ └── components/
|
||||
│ │ ├── Login.jsx / .css
|
||||
│ │ ├── Chat.jsx / .css
|
||||
│ │ ├── MessageList.jsx
|
||||
│ │ ├── Message.jsx / .css
|
||||
│ │ └── MessageInput.jsx / .css
|
||||
│ │ ├── MessageInput.jsx / .css
|
||||
│ │ └── VoiceRecorder.jsx / .css
|
||||
│ ├── .env # Production настройки
|
||||
│ ├── .env.development # Dev настройки
|
||||
│ ├── index.html
|
||||
│ ├── vite.config.js
|
||||
│ └── package.json
|
||||
├── Dockerfile # Многостадийная сборка
|
||||
├── docker-entrypoint.sh # Точка входа контейнера
|
||||
├── nginx.conf # Конфигурация nginx
|
||||
├── docker-entrypoint.sh # Auto-restart при падении
|
||||
├── nginx.conf
|
||||
├── .dockerignore
|
||||
├── .gitignore
|
||||
└── README.md
|
||||
```
|
||||
|
||||
+5
-66
@@ -1,75 +1,14 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import React from 'react';
|
||||
import Login from './components/Login';
|
||||
import Chat from './components/Chat';
|
||||
|
||||
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
|
||||
import useWebSocket from './hooks/useWebSocket';
|
||||
|
||||
export default function App() {
|
||||
const [loggedIn, setLoggedIn] = useState(false);
|
||||
const [login, setLogin] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const wsRef = useRef(null);
|
||||
|
||||
const handleLogin = useCallback((userLogin, password) => {
|
||||
setError('');
|
||||
const ws = new WebSocket(WS_URL);
|
||||
|
||||
ws.onopen = () => {
|
||||
ws.send(JSON.stringify({ type: 'auth', login: userLogin, password }));
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'auth_result') {
|
||||
if (msg.success) {
|
||||
setLogin(userLogin);
|
||||
setLoggedIn(true);
|
||||
} else {
|
||||
setError(msg.reason || 'Authentication failed');
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
setError('Cannot connect to server');
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
if (!loggedIn) {
|
||||
setError('Connection closed');
|
||||
}
|
||||
};
|
||||
|
||||
wsRef.current = ws;
|
||||
}, [loggedIn]);
|
||||
|
||||
const handleLogout = useCallback(() => {
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
setLoggedIn(false);
|
||||
setLogin('');
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
const { login, loggedIn, error, ws, loginToServer, logout } = useWebSocket();
|
||||
|
||||
if (!loggedIn) {
|
||||
return <Login onLogin={handleLogin} error={error} />;
|
||||
return <Login onLogin={loginToServer} error={error} />;
|
||||
}
|
||||
|
||||
return <Chat ws={wsRef.current} login={login} onLogout={handleLogout} />;
|
||||
return <Chat ws={ws} login={login} onLogout={logout} />;
|
||||
}
|
||||
|
||||
@@ -1,126 +1,11 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import React from 'react';
|
||||
import MessageList from './MessageList';
|
||||
import MessageInput from './MessageInput';
|
||||
import useChatMessages from '../hooks/useChatMessages';
|
||||
import './Chat.css';
|
||||
|
||||
function setFavicon(hasNotification) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
ctx.fillStyle = '#4a9eff';
|
||||
ctx.beginPath();
|
||||
ctx.arc(16, 16, 14, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.font = 'bold 18px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('CH', 16, 16);
|
||||
|
||||
if (hasNotification) {
|
||||
ctx.fillStyle = '#ff4444';
|
||||
ctx.beginPath();
|
||||
ctx.arc(26, 6, 5, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = '#1a1a2e';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
let link = document.querySelector('link[rel="icon"]');
|
||||
if (!link) {
|
||||
link = document.createElement('link');
|
||||
link.rel = 'icon';
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
link.href = canvas.toDataURL();
|
||||
}
|
||||
|
||||
export default function Chat({ ws, login, onLogout }) {
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [connected, setConnected] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const hasNotifRef = useRef(false);
|
||||
const messagesRef = useRef(messages);
|
||||
messagesRef.current = messages;
|
||||
|
||||
const addMessage = useCallback((msg) => {
|
||||
setMessages(prev => [...prev, { ...msg, id: Date.now() + Math.random() }]);
|
||||
if (
|
||||
document.hidden &&
|
||||
msg.from &&
|
||||
msg.from !== login &&
|
||||
(msg.type === 'text' || msg.type === 'file')
|
||||
) {
|
||||
if (!hasNotifRef.current) {
|
||||
hasNotifRef.current = true;
|
||||
setFavicon(true);
|
||||
}
|
||||
try {
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.frequency.value = 520;
|
||||
gain.gain.value = 0.15;
|
||||
osc.start();
|
||||
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15);
|
||||
osc.stop(ctx.currentTime + 0.15);
|
||||
osc.onended = () => ctx.close();
|
||||
} catch {}
|
||||
}
|
||||
}, [login]);
|
||||
|
||||
useEffect(() => {
|
||||
setFavicon(false);
|
||||
const onVisible = () => {
|
||||
if (hasNotifRef.current) {
|
||||
hasNotifRef.current = false;
|
||||
setFavicon(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ws) return;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'text') {
|
||||
addMessage(msg);
|
||||
} else if (msg.type === 'file') {
|
||||
addMessage(msg);
|
||||
} else if (msg.type === 'system') {
|
||||
addMessage(msg);
|
||||
} else if (msg.type === 'error') {
|
||||
setError(msg.message);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
setError('Connection lost');
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
setConnected(false);
|
||||
setError('Connection error');
|
||||
};
|
||||
}, [ws, addMessage]);
|
||||
const { messages, connected, error } = useChatMessages(ws, login);
|
||||
|
||||
return (
|
||||
<div className="chat-container">
|
||||
@@ -128,8 +13,7 @@ export default function Chat({ ws, login, onLogout }) {
|
||||
<h2>Chat room — logged in as <strong>{login}</strong></h2>
|
||||
<button className="logout-btn" onClick={onLogout}>Logout</button>
|
||||
</div>
|
||||
{error && !connected && <div className="chat-error">{error}</div>}
|
||||
{error && connected && <div className="chat-notification">{error}</div>}
|
||||
{error && <div className={connected ? 'chat-notification' : 'chat-error'}>{error}</div>}
|
||||
<MessageList messages={messages} currentUser={login} />
|
||||
<MessageInput ws={ws} />
|
||||
</div>
|
||||
|
||||
@@ -127,3 +127,23 @@
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.3rem;
|
||||
}
|
||||
|
||||
.message-audio, .message-video {
|
||||
margin-top: 0.3rem;
|
||||
}
|
||||
|
||||
.message-audio-player {
|
||||
width: 100%;
|
||||
height: 40px;
|
||||
border-radius: 6px;
|
||||
background: #1a1a2e;
|
||||
}
|
||||
|
||||
.message-video-player {
|
||||
width: 100%;
|
||||
max-height: 300px;
|
||||
border-radius: 8px;
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
background: #000;
|
||||
}
|
||||
|
||||
@@ -1,77 +1,35 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { linkifyText } from '../utils/linkify.jsx';
|
||||
import { dataURLToBlobUrl } from '../utils/blob';
|
||||
import './Message.css';
|
||||
|
||||
function formatTime(ts) {
|
||||
const d = new Date(ts);
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,!?)}\]"'\\])/gi;
|
||||
|
||||
function linkifyText(text) {
|
||||
const parts = [];
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
URL_REGEX.lastIndex = 0;
|
||||
while ((match = URL_REGEX.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
parts.push(text.slice(lastIndex, match.index));
|
||||
}
|
||||
parts.push(
|
||||
<a key={match.index} href={match[0]} target="_blank" rel="noopener noreferrer">
|
||||
{match[0]}
|
||||
</a>
|
||||
);
|
||||
lastIndex = match.index + match[0].length;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
parts.push(text.slice(lastIndex));
|
||||
}
|
||||
return parts.length ? parts : text;
|
||||
}
|
||||
|
||||
function dataURLToBlobUrl(dataUrl) {
|
||||
try {
|
||||
const arr = dataUrl.split(',');
|
||||
const mime = arr[0].match(/:(.*?);/)[1];
|
||||
const bstr = atob(arr[1]);
|
||||
const n = bstr.length;
|
||||
const u8arr = new Uint8Array(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
u8arr[i] = bstr.charCodeAt(i);
|
||||
}
|
||||
const blob = new Blob([u8arr], { type: mime });
|
||||
return URL.createObjectURL(blob);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const FILE_ICON = '\u{1F4CE}';
|
||||
|
||||
export default function Message({ message, isOwn }) {
|
||||
const isImage = message.mime && message.mime.startsWith('image/');
|
||||
const [videoExpanded, setVideoExpanded] = useState(false);
|
||||
const mime = message.mime;
|
||||
const isSystem = message.type === 'system';
|
||||
const isFile = message.type === 'file';
|
||||
const typeGroup = isFile
|
||||
? mime?.startsWith('image/') ? 'image'
|
||||
: mime?.startsWith('video/') ? 'video'
|
||||
: mime?.startsWith('audio/') ? 'audio'
|
||||
: 'file'
|
||||
: null;
|
||||
|
||||
const blobUrl = useMemo(() => {
|
||||
const fileUrl = useMemo(() => {
|
||||
if (isFile && message.data) {
|
||||
return dataURLToBlobUrl(`data:${message.mime};base64,${message.data}`);
|
||||
return dataURLToBlobUrl(`data:${mime};base64,${message.data}`);
|
||||
}
|
||||
return null;
|
||||
}, [isFile, message.data, message.mime]);
|
||||
|
||||
const downloadUrl = useMemo(() => {
|
||||
if (isFile && message.data && !isImage) {
|
||||
return dataURLToBlobUrl(`data:${message.mime};base64,${message.data}`);
|
||||
}
|
||||
return null;
|
||||
}, [isFile, message.data, message.mime, isImage]);
|
||||
}, [isFile, message.data, mime]);
|
||||
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div className="message-system">
|
||||
<span>{message.text}</span>
|
||||
</div>
|
||||
);
|
||||
return <div className="message-system"><span>{message.text}</span></div>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -82,31 +40,41 @@ export default function Message({ message, isOwn }) {
|
||||
</div>
|
||||
<div className="message-body">
|
||||
{message.text && <p>{linkifyText(message.text)}</p>}
|
||||
{isFile && isImage && blobUrl && (
|
||||
<a href={blobUrl} target="_blank" rel="noreferrer">
|
||||
<img
|
||||
className="message-image"
|
||||
src={blobUrl}
|
||||
alt={message.filename}
|
||||
/>
|
||||
{isFile && typeGroup === 'image' && (fileUrl ? (
|
||||
<a href={fileUrl} target="_blank" rel="noreferrer">
|
||||
<img className="message-image" src={fileUrl} alt={message.filename} />
|
||||
</a>
|
||||
)}
|
||||
{isFile && isImage && !blobUrl && (
|
||||
<div className="message-file-error">Failed to load image</div>
|
||||
)}
|
||||
{isFile && !isImage && downloadUrl && (
|
||||
<a
|
||||
className="message-file-link"
|
||||
href={downloadUrl}
|
||||
download={message.filename}
|
||||
>
|
||||
<span className="file-icon">📎</span>
|
||||
) : <div className="message-file-error">Failed to load image</div>)}
|
||||
{isFile && typeGroup === 'audio' && (fileUrl ? (
|
||||
<div className="message-audio">
|
||||
<audio controls src={fileUrl} className="message-audio-player" />
|
||||
<a className="message-file-link" href={fileUrl} download={message.filename}>
|
||||
<span className="file-icon">{FILE_ICON}</span>
|
||||
{message.filename}
|
||||
</a>
|
||||
)}
|
||||
{isFile && !isImage && !downloadUrl && (
|
||||
<div className="message-file-error">Failed to load file</div>
|
||||
)}
|
||||
</div>
|
||||
) : <div className="message-file-error">Failed to load audio</div>)}
|
||||
{isFile && typeGroup === 'video' && (fileUrl ? (
|
||||
<div className="message-video">
|
||||
<video
|
||||
className="message-video-player"
|
||||
src={fileUrl}
|
||||
controls={videoExpanded}
|
||||
preload="metadata"
|
||||
onClick={() => setVideoExpanded(true)}
|
||||
/>
|
||||
<a className="message-file-link" href={fileUrl} download={message.filename}>
|
||||
<span className="file-icon">{FILE_ICON}</span>
|
||||
{message.filename}
|
||||
</a>
|
||||
</div>
|
||||
) : <div className="message-file-error">Failed to load video</div>)}
|
||||
{isFile && typeGroup === 'file' && (fileUrl ? (
|
||||
<a className="message-file-link" href={fileUrl} download={message.filename}>
|
||||
<span className="file-icon">{FILE_ICON}</span>
|
||||
{message.filename}
|
||||
</a>
|
||||
) : <div className="message-file-error">Failed to load file</div>)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import React, { useState, useRef } from 'react';
|
||||
import VoiceRecorder from './VoiceRecorder';
|
||||
import './MessageInput.css';
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||
|
||||
function readFileAsBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result.split(',')[1]);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export default function MessageInput({ ws }) {
|
||||
const [text, setText] = useState('');
|
||||
const fileInputRef = useRef(null);
|
||||
const fileRef = useRef(null);
|
||||
|
||||
const sendText = (e) => {
|
||||
e.preventDefault();
|
||||
@@ -14,35 +24,27 @@ export default function MessageInput({ ws }) {
|
||||
setText('');
|
||||
};
|
||||
|
||||
const handleFileSelect = (e) => {
|
||||
const handleFileSelect = async (e) => {
|
||||
const file = e.target.files[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
alert('File too large. Maximum is 10 MB.');
|
||||
e.target.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const base64 = reader.result.split(',')[1];
|
||||
try {
|
||||
const data = await readFileAsBase64(file);
|
||||
ws.send(JSON.stringify({
|
||||
type: 'file',
|
||||
filename: file.name,
|
||||
mime: file.type || 'application/octet-stream',
|
||||
data: base64
|
||||
data,
|
||||
}));
|
||||
};
|
||||
reader.onerror = () => {
|
||||
} catch {
|
||||
alert('Failed to read file');
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
e.target.value = '';
|
||||
};
|
||||
|
||||
const handleAttachClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -55,17 +57,13 @@ export default function MessageInput({ ws }) {
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="attach-btn" onClick={handleAttachClick} title="Attach file">
|
||||
<VoiceRecorder ws={ws} />
|
||||
<button type="button" className="attach-btn" onClick={() => fileRef.current?.click()} title="Attach file">
|
||||
📎
|
||||
</button>
|
||||
<button type="submit" className="send-btn">Send</button>
|
||||
</form>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="file-input-hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<input ref={fileRef} type="file" className="file-input-hidden" onChange={handleFileSelect} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
.voice-recorder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.voice-recorder-btn {
|
||||
padding: 0.7rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 1.1rem;
|
||||
transition: background 0.2s;
|
||||
background: #2a2a4a;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.voice-recorder-btn:hover {
|
||||
background: #3a3a5a;
|
||||
}
|
||||
|
||||
.voice-recorder-btn.recording {
|
||||
background: #5c1a1a;
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { box-shadow: 0 0 0 0 rgba(255, 60, 60, 0.5); }
|
||||
50% { box-shadow: 0 0 0 6px rgba(255, 60, 60, 0); }
|
||||
}
|
||||
|
||||
.voice-recorder-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.voice-recorder-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.voice-recorder-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #ff4444;
|
||||
animation: blink 1s step-end infinite;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% { opacity: 0; }
|
||||
}
|
||||
|
||||
.voice-recorder-timer {
|
||||
font-size: 0.85rem;
|
||||
color: #ff8a8a;
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 3em;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import './VoiceRecorder.css';
|
||||
|
||||
function readFileAsBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result.split(',')[1]);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
function getSupportedMime() {
|
||||
const types = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/ogg',
|
||||
'audio/mp4',
|
||||
];
|
||||
return types.find(t => MediaRecorder.isTypeSupported(t)) || '';
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
const m = String(Math.floor(seconds / 60)).padStart(2, '0');
|
||||
const s = String(seconds % 60).padStart(2, '0');
|
||||
return `${m}:${s}`;
|
||||
}
|
||||
|
||||
export default function VoiceRecorder({ ws }) {
|
||||
const [state, setState] = useState('idle');
|
||||
const [duration, setDuration] = useState(0);
|
||||
const mediaRecorderRef = useRef(null);
|
||||
const chunksRef = useRef([]);
|
||||
const streamRef = useRef(null);
|
||||
const timerRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
if (streamRef.current) streamRef.current.getTracks().forEach(t => t.stop());
|
||||
};
|
||||
}, []);
|
||||
|
||||
const stopRecording = useCallback(() => {
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
|
||||
mediaRecorderRef.current.stop();
|
||||
}
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(t => t.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const startRecording = useCallback(async () => {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
streamRef.current = stream;
|
||||
} catch {
|
||||
alert('Microphone access denied');
|
||||
return;
|
||||
}
|
||||
|
||||
const mime = getSupportedMime();
|
||||
chunksRef.current = [];
|
||||
|
||||
const recorder = new MediaRecorder(streamRef.current, mime ? { mimeType: mime } : {});
|
||||
mediaRecorderRef.current = recorder;
|
||||
|
||||
recorder.ondataavailable = (e) => {
|
||||
if (e.data.size > 0) chunksRef.current.push(e.data);
|
||||
};
|
||||
|
||||
recorder.onstop = async () => {
|
||||
setState('sending');
|
||||
const blob = new Blob(chunksRef.current, { type: mime || 'audio/webm' });
|
||||
const ext = mime.includes('mp4') ? '.mp4' : mime.includes('ogg') ? '.ogg' : '.webm';
|
||||
const file = new File([blob], `voice${ext}`, { type: mime || 'audio/webm' });
|
||||
|
||||
try {
|
||||
const data = await readFileAsBase64(file);
|
||||
ws.send(JSON.stringify({
|
||||
type: 'file',
|
||||
filename: file.name,
|
||||
mime: file.type,
|
||||
data,
|
||||
}));
|
||||
} catch {
|
||||
alert('Failed to send voice message');
|
||||
}
|
||||
setState('idle');
|
||||
setDuration(0);
|
||||
};
|
||||
|
||||
recorder.onerror = () => {
|
||||
alert('Recording error');
|
||||
setState('idle');
|
||||
setDuration(0);
|
||||
};
|
||||
|
||||
recorder.start(100);
|
||||
setState('recording');
|
||||
setDuration(0);
|
||||
|
||||
timerRef.current = setInterval(() => {
|
||||
setDuration(prev => prev + 1);
|
||||
}, 1000);
|
||||
}, [ws]);
|
||||
|
||||
const handleClick = () => {
|
||||
if (state === 'recording') {
|
||||
stopRecording();
|
||||
} else if (state === 'idle') {
|
||||
startRecording();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`voice-recorder ${state}`}>
|
||||
{state === 'recording' && (
|
||||
<div className="voice-recorder-indicator">
|
||||
<span className="voice-recorder-dot" />
|
||||
<span className="voice-recorder-timer">{formatDuration(duration)}</span>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={`voice-recorder-btn ${state}`}
|
||||
onClick={handleClick}
|
||||
disabled={state === 'sending'}
|
||||
title={state === 'recording' ? 'Stop recording' : 'Record voice message'}
|
||||
>
|
||||
{state === 'sending' ? '...' : '\u{1F3A4}'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { playBeep, drawFavicon } from '../utils/notify';
|
||||
|
||||
export default function useChatMessages(ws, login) {
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [connected, setConnected] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const hasNotifRef = useRef(false);
|
||||
|
||||
const addMessage = useCallback((msg) => {
|
||||
setMessages(prev => [...prev, { ...msg, id: Date.now() + Math.random() }]);
|
||||
if (
|
||||
document.hidden &&
|
||||
msg.from &&
|
||||
msg.from !== login &&
|
||||
(msg.type === 'text' || msg.type === 'file')
|
||||
) {
|
||||
if (!hasNotifRef.current) {
|
||||
hasNotifRef.current = true;
|
||||
drawFavicon(true);
|
||||
}
|
||||
playBeep();
|
||||
}
|
||||
}, [login]);
|
||||
|
||||
useEffect(() => {
|
||||
drawFavicon(false);
|
||||
const onVisible = () => {
|
||||
if (hasNotifRef.current) {
|
||||
hasNotifRef.current = false;
|
||||
drawFavicon(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => document.removeEventListener('visibilitychange', onVisible);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ws) return;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'text' || msg.type === 'file' || msg.type === 'system') {
|
||||
addMessage(msg);
|
||||
} else if (msg.type === 'error') {
|
||||
setError(msg.message);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
setError('Connection lost');
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
setConnected(false);
|
||||
setError('Connection error');
|
||||
};
|
||||
}, [ws, addMessage]);
|
||||
|
||||
return { messages, connected, error };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
|
||||
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
|
||||
|
||||
export default function useWebSocket() {
|
||||
const [login, setLogin] = useState('');
|
||||
const [loggedIn, setLoggedIn] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [ws, setWs] = useState(null);
|
||||
const loggedInRef = useRef(false);
|
||||
|
||||
const loginToServer = useCallback((userLogin, password) => {
|
||||
setError('');
|
||||
const socket = new WebSocket(WS_URL);
|
||||
|
||||
socket.onopen = () => {
|
||||
socket.send(JSON.stringify({ type: 'auth', login: userLogin, password }));
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'auth_result') {
|
||||
if (msg.success) {
|
||||
setLogin(userLogin);
|
||||
setLoggedIn(true);
|
||||
loggedInRef.current = true;
|
||||
setWs(socket);
|
||||
} else {
|
||||
setError(msg.reason || 'Authentication failed');
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = () => {
|
||||
if (!loggedInRef.current) {
|
||||
setError('Cannot connect to server');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = () => {
|
||||
if (!loggedInRef.current) {
|
||||
setError('Connection closed');
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
setWs(null);
|
||||
setLogin('');
|
||||
setLoggedIn(false);
|
||||
loggedInRef.current = false;
|
||||
}, [ws]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
};
|
||||
}, [ws]);
|
||||
|
||||
return { login, loggedIn, error, ws, loginToServer, logout };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export function dataURLToBlobUrl(dataUrl) {
|
||||
try {
|
||||
const arr = dataUrl.split(',');
|
||||
const mime = arr[0].match(/:(.*?);/)[1];
|
||||
const bstr = atob(arr[1]);
|
||||
const n = bstr.length;
|
||||
const u8arr = new Uint8Array(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
u8arr[i] = bstr.charCodeAt(i);
|
||||
}
|
||||
const blob = new Blob([u8arr], { type: mime });
|
||||
return URL.createObjectURL(blob);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,!?)}\]"'\\])/gi;
|
||||
|
||||
export function linkifyText(text) {
|
||||
const parts = [];
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
URL_REGEX.lastIndex = 0;
|
||||
while ((match = URL_REGEX.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
parts.push(text.slice(lastIndex, match.index));
|
||||
}
|
||||
parts.push(
|
||||
<a key={match.index} href={match[0]} target="_blank" rel="noopener noreferrer">
|
||||
{match[0]}
|
||||
</a>
|
||||
);
|
||||
lastIndex = match.index + match[0].length;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
parts.push(text.slice(lastIndex));
|
||||
}
|
||||
return parts.length ? parts : text;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
export function playBeep() {
|
||||
try {
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.frequency.value = 520;
|
||||
gain.gain.value = 0.15;
|
||||
osc.start();
|
||||
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15);
|
||||
osc.stop(ctx.currentTime + 0.15);
|
||||
osc.onended = () => ctx.close();
|
||||
} catch { /* audio not supported */ }
|
||||
}
|
||||
|
||||
export function drawFavicon(hasNotification) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
ctx.fillStyle = '#4a9eff';
|
||||
ctx.beginPath();
|
||||
ctx.arc(16, 16, 14, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.font = 'bold 18px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('CH', 16, 16);
|
||||
|
||||
if (hasNotification) {
|
||||
ctx.fillStyle = '#ff4444';
|
||||
ctx.beginPath();
|
||||
ctx.arc(26, 6, 5, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = '#1a1a2e';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
let link = document.querySelector('link[rel="icon"]');
|
||||
if (!link) {
|
||||
link = document.createElement('link');
|
||||
link.rel = 'icon';
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
link.href = canvas.toDataURL();
|
||||
}
|
||||
+18
-7
@@ -1,16 +1,27 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Start nginx in foreground
|
||||
nginx -g 'daemon off;' &
|
||||
NGINX_PID=$!
|
||||
|
||||
# Start WebSocket server
|
||||
trap 'kill $NGINX_PID 2>/dev/null; exit' SIGTERM SIGINT SIGQUIT
|
||||
|
||||
shutdown() {
|
||||
kill $NGINX_PID 2>/dev/null
|
||||
exit
|
||||
}
|
||||
|
||||
while true; do
|
||||
node /server/server.js &
|
||||
NODE_PID=$!
|
||||
|
||||
# Forward signals to both processes
|
||||
trap 'kill $NGINX_PID $NODE_PID 2>/dev/null; exit' SIGTERM SIGINT
|
||||
|
||||
# Exit if node server stops
|
||||
trap 'kill $NODE_PID $NGINX_PID 2>/dev/null; exit' SIGTERM SIGINT SIGQUIT
|
||||
wait $NODE_PID
|
||||
EXIT_CODE=$?
|
||||
|
||||
if [ $EXIT_CODE -eq 0 ] || [ $EXIT_CODE -eq 143 ] || [ $EXIT_CODE -eq 130 ] || [ $EXIT_CODE -eq 137 ]; then
|
||||
shutdown
|
||||
fi
|
||||
|
||||
echo "Server exited with code $EXIT_CODE, restarting in 1 second..."
|
||||
sleep 1
|
||||
done
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const config = require('./config');
|
||||
|
||||
const usersPath = path.join(__dirname, config.usersFile);
|
||||
let users;
|
||||
|
||||
try {
|
||||
users = JSON.parse(fs.readFileSync(usersPath, 'utf-8'));
|
||||
console.log(`Loaded ${users.length} user(s) from ${config.usersFile}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to load ${config.usersFile}:`, err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function authenticate(login, password) {
|
||||
const user = users.find(u => u.login === login && u.password === password);
|
||||
return user || null;
|
||||
}
|
||||
|
||||
module.exports = { authenticate };
|
||||
@@ -0,0 +1,78 @@
|
||||
const config = require('./config');
|
||||
|
||||
function createJsonSender(ws) {
|
||||
return (data) => {
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(JSON.stringify(data));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createClientHandlers(ws, sendJson) {
|
||||
let authenticated = false;
|
||||
let login = null;
|
||||
|
||||
function getLogin() { return login; }
|
||||
|
||||
function handleAuth(userLogin) {
|
||||
authenticated = true;
|
||||
login = userLogin;
|
||||
console.log(`Authenticated: ${login}`);
|
||||
sendJson({ type: 'auth_result', success: true });
|
||||
return { type: 'system', text: `${login} joined the chat` };
|
||||
}
|
||||
|
||||
function handleAuthFail(reason) {
|
||||
sendJson({ type: 'auth_result', success: false, reason });
|
||||
}
|
||||
|
||||
function wrapHandler(handler) {
|
||||
return (raw) => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(raw.toString());
|
||||
} catch {
|
||||
sendJson({ type: 'error', message: 'Invalid JSON' });
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
if (parsed.type === 'auth') {
|
||||
return handler({ type: 'auth', login: parsed.login, password: parsed.password });
|
||||
}
|
||||
sendJson({ type: 'error', message: 'Authenticate first' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return handler(parsed);
|
||||
};
|
||||
}
|
||||
|
||||
return { getLogin, handleAuth, handleAuthFail, wrapHandler };
|
||||
}
|
||||
|
||||
function formatSizeEstimate(base64Length) {
|
||||
return Math.ceil((base64Length * 3) / 4);
|
||||
}
|
||||
|
||||
function validateFile(parsed) {
|
||||
if (!parsed.filename || !parsed.mime || !parsed.data) {
|
||||
return 'Invalid file message';
|
||||
}
|
||||
const size = formatSizeEstimate(parsed.data.length);
|
||||
if (size > config.maxFileSize) {
|
||||
return `File too large (max ${config.maxFileSize / 1024 / 1024} MB)`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function broadcast(server, message, excludeWs) {
|
||||
const json = JSON.stringify(message);
|
||||
server.clients.forEach(client => {
|
||||
if (client !== excludeWs && client.readyState === 1) {
|
||||
client.send(json);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { createJsonSender, createClientHandlers, validateFile, broadcast };
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
port: parseInt(process.env.PORT, 10) || 8080,
|
||||
maxFileSize: parseInt(process.env.MAX_FILE_SIZE, 10) || 10 * 1024 * 1024,
|
||||
usersFile: process.env.USERS_FILE || 'users.json',
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
+45
-106
@@ -1,129 +1,68 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { WebSocketServer } = require('ws');
|
||||
const config = require('./config');
|
||||
const { authenticate } = require('./auth');
|
||||
const { createJsonSender, createClientHandlers, validateFile, broadcast } = require('./clients');
|
||||
|
||||
const PORT = parseInt(process.env.PORT, 10) || 8080;
|
||||
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE, 10) || 10 * 1024 * 1024;
|
||||
const server = new WebSocketServer({ port: config.port });
|
||||
console.log(`WebSocket server running on ws://0.0.0.0:${config.port}`);
|
||||
|
||||
const usersPath = path.join(__dirname, process.env.USERS_FILE || 'users.json');
|
||||
let validUsers;
|
||||
try {
|
||||
validUsers = JSON.parse(fs.readFileSync(usersPath, 'utf-8'));
|
||||
console.log(`Loaded ${validUsers.length} users from users.json`);
|
||||
} catch (err) {
|
||||
console.error('Failed to load users.json:', err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function authenticate(login, password) {
|
||||
return validUsers.find(u => u.login === login && u.password === password) || null;
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer({ port: PORT });
|
||||
console.log(`WebSocket server running on ws://localhost:${PORT}`);
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
server.on('connection', (ws, req) => {
|
||||
const clientIp = req.socket.remoteAddress;
|
||||
console.log(`New connection from ${clientIp}`);
|
||||
console.log(`Connection from ${clientIp}`);
|
||||
|
||||
let authenticated = false;
|
||||
let userLogin = null;
|
||||
|
||||
ws.on('message', (data) => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(data.toString());
|
||||
} catch (e) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
if (parsed.type === 'auth') {
|
||||
const send = createJsonSender(ws);
|
||||
const client = createClientHandlers(ws, send);
|
||||
const handle = client.wrapHandler((parsed) => {
|
||||
switch (parsed.type) {
|
||||
case 'auth': {
|
||||
const user = authenticate(parsed.login, parsed.password);
|
||||
if (user) {
|
||||
authenticated = true;
|
||||
userLogin = parsed.login;
|
||||
console.log(`User authenticated: ${userLogin}`);
|
||||
ws.send(JSON.stringify({ type: 'auth_result', success: true }));
|
||||
broadcast({
|
||||
type: 'system',
|
||||
text: `${userLogin} joined the chat`
|
||||
}, null);
|
||||
} else {
|
||||
console.log(`Auth failed for login: ${parsed.login}`);
|
||||
ws.send(JSON.stringify({
|
||||
type: 'auth_result',
|
||||
success: false,
|
||||
reason: 'Invalid login or password'
|
||||
}));
|
||||
return client.handleAuth(user.login);
|
||||
}
|
||||
} else {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Authenticate first' }));
|
||||
client.handleAuthFail('Invalid login or password');
|
||||
return null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.type === 'text') {
|
||||
case 'text': {
|
||||
if (!parsed.text || typeof parsed.text !== 'string') {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Invalid text message' }));
|
||||
return;
|
||||
send({ type: 'error', message: 'Invalid text message' });
|
||||
return null;
|
||||
}
|
||||
console.log(`Text from ${userLogin}: ${parsed.text.substring(0, 50)}`);
|
||||
broadcast({
|
||||
type: 'text',
|
||||
from: userLogin,
|
||||
timestamp: Date.now(),
|
||||
text: parsed.text
|
||||
}, null);
|
||||
return;
|
||||
console.log(`Text from ${client.getLogin()}: ${parsed.text.substring(0, 50)}`);
|
||||
return { type: 'text', from: client.getLogin(), timestamp: Date.now(), text: parsed.text };
|
||||
}
|
||||
|
||||
if (parsed.type === 'file') {
|
||||
if (!parsed.filename || !parsed.mime || !parsed.data) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Invalid file message' }));
|
||||
return;
|
||||
case 'file': {
|
||||
const error = validateFile(parsed);
|
||||
if (error) {
|
||||
send({ type: 'error', message: error });
|
||||
return null;
|
||||
}
|
||||
const size = Math.ceil((parsed.data.length * 3) / 4);
|
||||
if (size > MAX_FILE_SIZE) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'File too large (max 10 MB)' }));
|
||||
return;
|
||||
console.log(`File from ${client.getLogin()}: ${parsed.filename} (${parsed.mime})`);
|
||||
return {
|
||||
type: 'file', from: client.getLogin(), timestamp: Date.now(),
|
||||
filename: parsed.filename, mime: parsed.mime, data: parsed.data,
|
||||
};
|
||||
}
|
||||
console.log(`File from ${userLogin}: ${parsed.filename} (${parsed.mime}, ~${size} bytes)`);
|
||||
broadcast({
|
||||
type: 'file',
|
||||
from: userLogin,
|
||||
timestamp: Date.now(),
|
||||
filename: parsed.filename,
|
||||
mime: parsed.mime,
|
||||
data: parsed.data
|
||||
}, null);
|
||||
return;
|
||||
default:
|
||||
send({ type: 'error', message: 'Unknown message type' });
|
||||
return null;
|
||||
}
|
||||
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Unknown message type' }));
|
||||
});
|
||||
|
||||
ws.on('close', (code, reason) => {
|
||||
console.log(`Connection closed${userLogin ? ` for ${userLogin}` : ''} (code: ${code})`);
|
||||
if (userLogin) {
|
||||
broadcast({
|
||||
type: 'system',
|
||||
text: `${userLogin} left the chat`
|
||||
}, null);
|
||||
ws.on('message', (raw) => {
|
||||
const msg = handle(raw);
|
||||
if (msg) {
|
||||
broadcast(server, msg, null);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', (code) => {
|
||||
console.log(`Disconnected: ${client.getLogin() || 'unauthenticated'} (code: ${code})`);
|
||||
if (client.getLogin()) {
|
||||
broadcast(server, { type: 'system', text: `${client.getLogin()} left the chat` }, null);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('error', (err) => {
|
||||
console.error(`WebSocket error${userLogin ? ` for ${userLogin}` : ''}:`, err.message);
|
||||
console.error(`Socket error (${client.getLogin() || 'unknown'}):`, err.message);
|
||||
});
|
||||
});
|
||||
|
||||
function broadcast(message, excludeWs) {
|
||||
const json = JSON.stringify(message);
|
||||
wss.clients.forEach(client => {
|
||||
if (client !== excludeWs && client.readyState === 1) {
|
||||
client.send(json);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user