Полный рефакторинг сервера и клиента, голосовые сообщения, аудио/видео, 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:
Комаров Данил Анатольевич 6
2026-05-29 05:23:22 +03:00
parent 83ef0d5ab3
commit 63bf73d2c4
18 changed files with 760 additions and 485 deletions
+49 -71
View File
@@ -1,6 +1,7 @@
# Чат с общей комнатой # Чат с общей комнатой
Веб-приложение чата с одной общей комнатой на WebSocket. Поддерживает текстовые сообщения, отправку файлов и отображение изображений. Веб-приложение чата с одной общей комнатой на WebSocket.
Текстовые сообщения, файлы, изображения, аудио, видео и голосовые сообщения.
**Сервер:** Node.js + `ws` **Сервер:** Node.js + `ws`
**Клиент:** React + Vite **Клиент:** React + Vite
@@ -18,7 +19,7 @@ npm install
npm start npm start
``` ```
Запускает WebSocket сервер на `ws://localhost:8080`. WebSocket сервер на `ws://localhost:8080`.
### Клиент ### Клиент
@@ -28,8 +29,8 @@ npm install
npx vite npx vite
``` ```
Запускает dev-сервер на `http://localhost:3000`. Dev-сервер на `http://localhost:3000`.
В режиме разработки клиент подключается напрямую к `ws://localhost:8080`. Клиент подключается напрямую к `ws://localhost:8080`.
### Пользователи по умолчанию ### Пользователи по умолчанию
@@ -42,15 +43,10 @@ npx vite
## Production (Docker) ## Production (Docker)
### Сборка образа ### Сборка и запуск
```bash ```bash
docker build -t chat-app . docker build -t chat-app .
```
### Запуск контейнера
```bash
docker run -d -p 80:80 chat-app docker run -d -p 80:80 chat-app
``` ```
@@ -59,11 +55,12 @@ docker run -d -p 80:80 chat-app
### Как это работает ### Как это работает
- **nginx** на порту 80 раздаёт статику React и проксирует WebSocket - **nginx** на порту 80 раздаёт статику React и проксирует WebSocket
- Путь `/` → статические файлы клиента (`index.html`, JS, CSS) - Путь `/` → статические файлы клиента
- Путь `/ws` → прокси на Node.js WebSocket сервер (порт 8080 внутри контейнера) - Путь `/ws` → прокси на Node.js сервер (порт 8080 внутри контейнера)
- nginx поддерживает Upgrade до WebSocket, таймаут соединения — 24 часа - nginx поддерживает Upgrade до WebSocket, таймаут соединения — 24 часа
- Максимальный размер загружаемых файлов через nginx — 50 МБ - Максимальный размер загружаемых файлов через 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 МБ) | Максимальный размер файла в байтах | | `MAX_FILE_SIZE` | `10485760` (10 МБ) | Максимальный размер файла в байтах |
| `USERS_FILE` | `users.json` | Путь к файлу с пользователями | | `USERS_FILE` | `users.json` | Путь к файлу с пользователями |
Пример:
```bash ```bash
$env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js $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 сервера | | `VITE_WS_URL` | `ws://localhost:8080` | `/ws` | URL WebSocket сервера |
Настройки хранятся в файлах: Настройки в `client/.env.development` (dev) и `client/.env` (production).
- `client/.env.development` — для `npx vite` (dev-режим)
- `client/.env` — для `vite build` (production-сборка)
--- ---
@@ -99,81 +92,54 @@ $env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
### Аутентификация ### Аутентификация
Клиент → Сервер:
```json ```json
// → сервер
{ "type": "auth", "login": "alice", "password": "123" } { "type": "auth", "login": "alice", "password": "123" }
``` // ← ответ
Сервер → Клиент:
```json
{ "type": "auth_result", "success": true } { "type": "auth_result", "success": true }
```
```json
{ "type": "auth_result", "success": false, "reason": "Invalid login or password" } { "type": "auth_result", "success": false, "reason": "Invalid login or password" }
``` ```
### Текстовое сообщение ### Текстовое сообщение
Клиент → Сервер:
```json ```json
// → сервер
{ "type": "text", "text": "Привет!" } { "type": "text", "text": "Привет!" }
``` // ← всем
Сервер → Все:
```json
{ "type": "text", "from": "alice", "timestamp": 1717000000000, "text": "Привет!" } { "type": "text", "from": "alice", "timestamp": 1717000000000, "text": "Привет!" }
``` ```
### Файл / изображение ### Файл / изображение / аудио / видео
Клиент → Сервер:
```json ```json
{ // → сервер
"type": "file", { "type": "file", "filename": "cat.png", "mime": "image/png", "data": "<base64>" }
"filename": "cat.png", // ← всем (от сервера добавлены from и timestamp)
"mime": "image/png", { "type": "file", "from": "alice", "timestamp": 1717000000000, "filename": "cat.png", "mime": "image/png", "data": "<base64>" }
"data": "<base64>"
}
``` ```
Сервер → Все (такая же структура, добавлены `from` и `timestamp`): Клиент определяет тип файла по MIME: `image/*` — картинка, `audio/*` — плеер, `video/*` — плеер, остальное — скачивание.
```json
{
"type": "file",
"from": "alice",
"timestamp": 1717000000000,
"filename": "cat.png",
"mime": "image/png",
"data": "<base64>"
}
```
### Системные сообщения ### Системные сообщения
Сервер → Все:
```json ```json
{ "type": "system", "text": "alice joined the chat" } { "type": "system", "text": "alice joined the chat" }
{ "type": "system", "text": "alice left the chat" }
``` ```
--- ---
## Функциональность ## Функциональность
- **Текстовые сообщения** — отображаются с логином отправителя и временем - **Текстовые сообщения** — логин отправителя, время, ссылки (http/https) автоматически становятся кликабельными
- **Файлы** — любые типы, до 10 МБ (настраивается). Файлы передаются через base64 в JSON - **Файлы** — любые типы, до 10 МБ (настраивается), base64 в JSON
- **Изображения** — автоматически определяются по MIME-типу (`image/*`), рендерятся как `<img>`, клик открывает в новой вкладке - **Изображения** — `image/*` `<img>`, клик открывает в новой вкладке
- **Не-изображения** — отображаются как ссылка для скачивания с именем файла - **Аудио** — `audio/*``<audio controls>` + ссылка скачивания
- **Уведомления на неактивной вкладке** — звуковой сигнал (Web Audio API) и красная точка на favicon - **Видео** — `video/*``<video>` с controls + ссылка скачивания
- **Голосовые сообщения** — кнопка микрофона, запись через `MediaRecorder`, отправка как файл
- **Уведомления** — звук (Web Audio API) и красная точка на favicon при сообщении на неактивной вкладке
- **Системные сообщения** — подключение/отключение участников - **Системные сообщения** — подключение/отключение участников
- **Скролл** — автоматический, кастомный тонкий скроллбар в теме приложения - **Автоскролл** — кастомный тонкий скроллбар
--- ---
@@ -182,27 +148,39 @@ $env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
``` ```
chat/ chat/
├── server/ ├── server/
│ ├── server.js # WebSocket сервер │ ├── config.js # Настройки из env
│ ├── auth.js # Загрузка пользователей, authenticate()
│ ├── clients.js # Управление соединениями, broadcast()
│ ├── server.js # Точка входа, WebSocketServer
│ ├── users.json # Хардкоженые логины/пароли │ ├── users.json # Хардкоженые логины/пароли
│ └── package.json │ └── package.json
├── client/ ├── client/
│ ├── src/ │ ├── src/
│ │ ├── App.jsx # Корневой компонент │ │ ├── App.jsx / .css
│ │ ├── App.css │ │ ├── main.jsx
│ │ ├── main.jsx # Точка входа │ │ ├── hooks/
│ │ │ ├── useWebSocket.js # WebSocket + auth
│ │ │ └── useChatMessages.js # Приём сообщений + уведомления
│ │ ├── utils/
│ │ │ ├── blob.js # base64 → Blob URL
│ │ │ ├── linkify.jsx # URL → React-ссылки
│ │ │ └── notify.js # Звук + favicon
│ │ └── components/ │ │ └── components/
│ │ ├── Login.jsx / .css │ │ ├── Login.jsx / .css
│ │ ├── Chat.jsx / .css │ │ ├── Chat.jsx / .css
│ │ ├── MessageList.jsx │ │ ├── MessageList.jsx
│ │ ├── Message.jsx / .css │ │ ├── Message.jsx / .css
│ │ ── MessageInput.jsx / .css │ │ ── MessageInput.jsx / .css
│ │ └── VoiceRecorder.jsx / .css
│ ├── .env # Production настройки │ ├── .env # Production настройки
│ ├── .env.development # Dev настройки │ ├── .env.development # Dev настройки
│ ├── index.html │ ├── index.html
│ ├── vite.config.js │ ├── vite.config.js
│ └── package.json │ └── package.json
├── Dockerfile # Многостадийная сборка ├── Dockerfile # Многостадийная сборка
├── docker-entrypoint.sh # Точка входа контейнера ├── docker-entrypoint.sh # Auto-restart при падении
├── nginx.conf # Конфигурация nginx ├── nginx.conf
├── .dockerignore
├── .gitignore
└── README.md └── README.md
``` ```
+5 -66
View File
@@ -1,75 +1,14 @@
import React, { useState, useRef, useCallback, useEffect } from 'react'; import React from 'react';
import Login from './components/Login'; import Login from './components/Login';
import Chat from './components/Chat'; import Chat from './components/Chat';
import useWebSocket from './hooks/useWebSocket';
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
export default function App() { export default function App() {
const [loggedIn, setLoggedIn] = useState(false); const { login, loggedIn, error, ws, loginToServer, logout } = useWebSocket();
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();
}
};
}, []);
if (!loggedIn) { 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} />;
} }
+4 -120
View File
@@ -1,126 +1,11 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React from 'react';
import MessageList from './MessageList'; import MessageList from './MessageList';
import MessageInput from './MessageInput'; import MessageInput from './MessageInput';
import useChatMessages from '../hooks/useChatMessages';
import './Chat.css'; 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 }) { export default function Chat({ ws, login, onLogout }) {
const [messages, setMessages] = useState([]); const { messages, connected, error } = useChatMessages(ws, login);
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]);
return ( return (
<div className="chat-container"> <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> <h2>Chat room logged in as <strong>{login}</strong></h2>
<button className="logout-btn" onClick={onLogout}>Logout</button> <button className="logout-btn" onClick={onLogout}>Logout</button>
</div> </div>
{error && !connected && <div className="chat-error">{error}</div>} {error && <div className={connected ? 'chat-notification' : 'chat-error'}>{error}</div>}
{error && connected && <div className="chat-notification">{error}</div>}
<MessageList messages={messages} currentUser={login} /> <MessageList messages={messages} currentUser={login} />
<MessageInput ws={ws} /> <MessageInput ws={ws} />
</div> </div>
+20
View File
@@ -127,3 +127,23 @@
font-size: 0.85rem; font-size: 0.85rem;
margin-top: 0.3rem; 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;
}
+49 -81
View File
@@ -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'; import './Message.css';
function formatTime(ts) { function formatTime(ts) {
const d = new Date(ts); return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} }
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,!?)}\]"'\\])/gi; const FILE_ICON = '\u{1F4CE}';
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;
}
}
export default function Message({ message, isOwn }) { 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 isSystem = message.type === 'system';
const isFile = message.type === 'file'; 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) { if (isFile && message.data) {
return dataURLToBlobUrl(`data:${message.mime};base64,${message.data}`); return dataURLToBlobUrl(`data:${mime};base64,${message.data}`);
} }
return null; return null;
}, [isFile, message.data, message.mime]); }, [isFile, message.data, 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]);
if (isSystem) { if (isSystem) {
return ( return <div className="message-system"><span>{message.text}</span></div>;
<div className="message-system">
<span>{message.text}</span>
</div>
);
} }
return ( return (
@@ -82,31 +40,41 @@ export default function Message({ message, isOwn }) {
</div> </div>
<div className="message-body"> <div className="message-body">
{message.text && <p>{linkifyText(message.text)}</p>} {message.text && <p>{linkifyText(message.text)}</p>}
{isFile && isImage && blobUrl && ( {isFile && typeGroup === 'image' && (fileUrl ? (
<a href={blobUrl} target="_blank" rel="noreferrer"> <a href={fileUrl} target="_blank" rel="noreferrer">
<img <img className="message-image" src={fileUrl} alt={message.filename} />
className="message-image"
src={blobUrl}
alt={message.filename}
/>
</a> </a>
)} ) : <div className="message-file-error">Failed to load image</div>)}
{isFile && isImage && !blobUrl && ( {isFile && typeGroup === 'audio' && (fileUrl ? (
<div className="message-file-error">Failed to load image</div> <div className="message-audio">
)} <audio controls src={fileUrl} className="message-audio-player" />
{isFile && !isImage && downloadUrl && ( <a className="message-file-link" href={fileUrl} download={message.filename}>
<a <span className="file-icon">{FILE_ICON}</span>
className="message-file-link"
href={downloadUrl}
download={message.filename}
>
<span className="file-icon">&#128206;</span>
{message.filename} {message.filename}
</a> </a>
)} </div>
{isFile && !isImage && !downloadUrl && ( ) : <div className="message-file-error">Failed to load audio</div>)}
<div className="message-file-error">Failed to load file</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>
</div> </div>
); );
+21 -23
View File
@@ -1,11 +1,21 @@
import React, { useState, useRef } from 'react'; import React, { useState, useRef } from 'react';
import VoiceRecorder from './VoiceRecorder';
import './MessageInput.css'; import './MessageInput.css';
const MAX_FILE_SIZE = 10 * 1024 * 1024; 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 }) { export default function MessageInput({ ws }) {
const [text, setText] = useState(''); const [text, setText] = useState('');
const fileInputRef = useRef(null); const fileRef = useRef(null);
const sendText = (e) => { const sendText = (e) => {
e.preventDefault(); e.preventDefault();
@@ -14,35 +24,27 @@ export default function MessageInput({ ws }) {
setText(''); setText('');
}; };
const handleFileSelect = (e) => { const handleFileSelect = async (e) => {
const file = e.target.files[0]; const file = e.target.files[0];
e.target.value = '';
if (!file) return; if (!file) return;
if (file.size > MAX_FILE_SIZE) { if (file.size > MAX_FILE_SIZE) {
alert('File too large. Maximum is 10 MB.'); alert('File too large. Maximum is 10 MB.');
e.target.value = '';
return; return;
} }
const reader = new FileReader(); try {
reader.onload = () => { const data = await readFileAsBase64(file);
const base64 = reader.result.split(',')[1];
ws.send(JSON.stringify({ ws.send(JSON.stringify({
type: 'file', type: 'file',
filename: file.name, filename: file.name,
mime: file.type || 'application/octet-stream', mime: file.type || 'application/octet-stream',
data: base64 data,
})); }));
}; } catch {
reader.onerror = () => {
alert('Failed to read file'); alert('Failed to read file');
}; }
reader.readAsDataURL(file);
e.target.value = '';
};
const handleAttachClick = () => {
fileInputRef.current?.click();
}; };
return ( return (
@@ -55,17 +57,13 @@ export default function MessageInput({ ws }) {
value={text} value={text}
onChange={(e) => setText(e.target.value)} 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">
&#128206; &#128206;
</button> </button>
<button type="submit" className="send-btn">Send</button> <button type="submit" className="send-btn">Send</button>
</form> </form>
<input <input ref={fileRef} type="file" className="file-input-hidden" onChange={handleFileSelect} />
ref={fileInputRef}
type="file"
className="file-input-hidden"
onChange={handleFileSelect}
/>
</div> </div>
); );
} }
+60
View File
@@ -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;
}
+141
View File
@@ -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>
);
}
+68
View File
@@ -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 };
}
+73
View File
@@ -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 };
}
+16
View File
@@ -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;
}
}
+23
View File
@@ -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;
}
+51
View File
@@ -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
View File
@@ -1,16 +1,27 @@
#!/bin/sh #!/bin/sh
set -e set -e
# Start nginx in foreground
nginx -g 'daemon off;' & nginx -g 'daemon off;' &
NGINX_PID=$! 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 /server/server.js &
NODE_PID=$! NODE_PID=$!
trap 'kill $NODE_PID $NGINX_PID 2>/dev/null; exit' SIGTERM SIGINT SIGQUIT
# Forward signals to both processes
trap 'kill $NGINX_PID $NODE_PID 2>/dev/null; exit' SIGTERM SIGINT
# Exit if node server stops
wait $NODE_PID 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
+21
View File
@@ -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 };
+78
View File
@@ -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 };
+7
View File
@@ -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
View File
@@ -1,129 +1,68 @@
const fs = require('fs');
const path = require('path');
const { WebSocketServer } = require('ws'); 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 server = new WebSocketServer({ port: config.port });
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE, 10) || 10 * 1024 * 1024; console.log(`WebSocket server running on ws://0.0.0.0:${config.port}`);
const usersPath = path.join(__dirname, process.env.USERS_FILE || 'users.json'); server.on('connection', (ws, req) => {
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) => {
const clientIp = req.socket.remoteAddress; const clientIp = req.socket.remoteAddress;
console.log(`New connection from ${clientIp}`); console.log(`Connection from ${clientIp}`);
let authenticated = false; const send = createJsonSender(ws);
let userLogin = null; const client = createClientHandlers(ws, send);
const handle = client.wrapHandler((parsed) => {
ws.on('message', (data) => { switch (parsed.type) {
let parsed; case 'auth': {
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 user = authenticate(parsed.login, parsed.password); const user = authenticate(parsed.login, parsed.password);
if (user) { if (user) {
authenticated = true; return client.handleAuth(user.login);
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'
}));
} }
} else { client.handleAuthFail('Invalid login or password');
ws.send(JSON.stringify({ type: 'error', message: 'Authenticate first' })); return null;
} }
return; case 'text': {
}
if (parsed.type === 'text') {
if (!parsed.text || typeof parsed.text !== 'string') { if (!parsed.text || typeof parsed.text !== 'string') {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid text message' })); send({ type: 'error', message: 'Invalid text message' });
return; return null;
} }
console.log(`Text from ${userLogin}: ${parsed.text.substring(0, 50)}`); console.log(`Text from ${client.getLogin()}: ${parsed.text.substring(0, 50)}`);
broadcast({ return { type: 'text', from: client.getLogin(), timestamp: Date.now(), text: parsed.text };
type: 'text',
from: userLogin,
timestamp: Date.now(),
text: parsed.text
}, null);
return;
} }
case 'file': {
if (parsed.type === 'file') { const error = validateFile(parsed);
if (!parsed.filename || !parsed.mime || !parsed.data) { if (error) {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid file message' })); send({ type: 'error', message: error });
return; return null;
} }
const size = Math.ceil((parsed.data.length * 3) / 4); console.log(`File from ${client.getLogin()}: ${parsed.filename} (${parsed.mime})`);
if (size > MAX_FILE_SIZE) { return {
ws.send(JSON.stringify({ type: 'error', message: 'File too large (max 10 MB)' })); type: 'file', from: client.getLogin(), timestamp: Date.now(),
return; filename: parsed.filename, mime: parsed.mime, data: parsed.data,
};
} }
console.log(`File from ${userLogin}: ${parsed.filename} (${parsed.mime}, ~${size} bytes)`); default:
broadcast({ send({ type: 'error', message: 'Unknown message type' });
type: 'file', return null;
from: userLogin,
timestamp: Date.now(),
filename: parsed.filename,
mime: parsed.mime,
data: parsed.data
}, null);
return;
} }
ws.send(JSON.stringify({ type: 'error', message: 'Unknown message type' }));
}); });
ws.on('close', (code, reason) => { ws.on('message', (raw) => {
console.log(`Connection closed${userLogin ? ` for ${userLogin}` : ''} (code: ${code})`); const msg = handle(raw);
if (userLogin) { if (msg) {
broadcast({ broadcast(server, msg, null);
type: 'system', }
text: `${userLogin} left the chat` });
}, 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) => { 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);
}
});
}