init
This commit is contained in:
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
npm-debug.log
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
**/dist
|
||||||
|
client/node_modules
|
||||||
|
server/node_modules
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env.local
|
||||||
|
npm-debug.log*
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Stage 1: Build client
|
||||||
|
FROM node:18-alpine AS client-builder
|
||||||
|
WORKDIR /client
|
||||||
|
COPY client/package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY client/ .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Stage 2: Production image
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Install Node.js for the server
|
||||||
|
RUN apk add --no-cache nodejs npm
|
||||||
|
|
||||||
|
# Remove default nginx config
|
||||||
|
RUN rm /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Copy custom nginx config
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Copy client build
|
||||||
|
COPY --from=client-builder /client/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Copy server
|
||||||
|
WORKDIR /server
|
||||||
|
COPY server/package*.json ./
|
||||||
|
RUN npm ci --omit=dev
|
||||||
|
COPY server/ .
|
||||||
|
|
||||||
|
# Copy entrypoint
|
||||||
|
COPY docker-entrypoint.sh /docker-entrypoint.sh
|
||||||
|
RUN chmod +x /docker-entrypoint.sh
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
ENTRYPOINT ["/docker-entrypoint.sh"]
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
# Чат с общей комнатой
|
||||||
|
|
||||||
|
Веб-приложение чата с одной общей комнатой на WebSocket. Поддерживает текстовые сообщения, отправку файлов и отображение изображений.
|
||||||
|
|
||||||
|
**Сервер:** Node.js + `ws`
|
||||||
|
**Клиент:** React + Vite
|
||||||
|
**Прокси:** nginx (production-сборка)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Быстрый запуск (разработка)
|
||||||
|
|
||||||
|
### Сервер
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd server
|
||||||
|
npm install
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
Запускает WebSocket сервер на `ws://localhost:8080`.
|
||||||
|
|
||||||
|
### Клиент
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd client
|
||||||
|
npm install
|
||||||
|
npx vite
|
||||||
|
```
|
||||||
|
|
||||||
|
Запускает dev-сервер на `http://localhost:3000`.
|
||||||
|
В режиме разработки клиент подключается напрямую к `ws://localhost:8080`.
|
||||||
|
|
||||||
|
### Пользователи по умолчанию
|
||||||
|
|
||||||
|
| Логин | Пароль |
|
||||||
|
|-------|--------|
|
||||||
|
| alice | 123 |
|
||||||
|
| bob | 456 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Production (Docker)
|
||||||
|
|
||||||
|
### Сборка образа
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t chat-app .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Запуск контейнера
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d -p 80:80 chat-app
|
||||||
|
```
|
||||||
|
|
||||||
|
Открой `http://localhost`.
|
||||||
|
|
||||||
|
### Как это работает
|
||||||
|
|
||||||
|
- **nginx** на порту 80 раздаёт статику React и проксирует WebSocket
|
||||||
|
- Путь `/` → статические файлы клиента (`index.html`, JS, CSS)
|
||||||
|
- Путь `/ws` → прокси на Node.js WebSocket сервер (порт 8080 внутри контейнера)
|
||||||
|
- nginx поддерживает Upgrade до WebSocket, таймаут соединения — 24 часа
|
||||||
|
- Максимальный размер загружаемых файлов через nginx — 50 МБ
|
||||||
|
- После остановки Node.js контейнер завершается (через `wait`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Переменные окружения
|
||||||
|
|
||||||
|
### Сервер
|
||||||
|
|
||||||
|
| Переменная | По умолчанию | Описание |
|
||||||
|
|-----------|-------------|---------|
|
||||||
|
| `PORT` | `8080` | Порт WebSocket сервера |
|
||||||
|
| `MAX_FILE_SIZE` | `10485760` (10 МБ) | Максимальный размер файла в байтах |
|
||||||
|
| `USERS_FILE` | `users.json` | Путь к файлу с пользователями |
|
||||||
|
|
||||||
|
Пример:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$env:PORT=9090; $env:MAX_FILE_SIZE=2097152; node server.js
|
||||||
|
```
|
||||||
|
|
||||||
|
### Клиент
|
||||||
|
|
||||||
|
| Переменная | По умолчанию (dev) | По умолчанию (production) | Описание |
|
||||||
|
|-----------|-------------------|--------------------------|---------|
|
||||||
|
| `VITE_WS_URL` | `ws://localhost:8080` | `/ws` | URL WebSocket сервера |
|
||||||
|
|
||||||
|
Настройки хранятся в файлах:
|
||||||
|
- `client/.env.development` — для `npx vite` (dev-режим)
|
||||||
|
- `client/.env` — для `vite build` (production-сборка)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Протокол обмена
|
||||||
|
|
||||||
|
### Аутентификация
|
||||||
|
|
||||||
|
Клиент → Сервер:
|
||||||
|
|
||||||
|
```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>"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Сервер → Все (такая же структура, добавлены `from` и `timestamp`):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "file",
|
||||||
|
"from": "alice",
|
||||||
|
"timestamp": 1717000000000,
|
||||||
|
"filename": "cat.png",
|
||||||
|
"mime": "image/png",
|
||||||
|
"data": "<base64>"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Системные сообщения
|
||||||
|
|
||||||
|
Сервер → Все:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "type": "system", "text": "alice joined the chat" }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Функциональность
|
||||||
|
|
||||||
|
- **Текстовые сообщения** — отображаются с логином отправителя и временем
|
||||||
|
- **Файлы** — любые типы, до 10 МБ (настраивается). Файлы передаются через base64 в JSON
|
||||||
|
- **Изображения** — автоматически определяются по MIME-типу (`image/*`), рендерятся как `<img>`, клик открывает в новой вкладке
|
||||||
|
- **Не-изображения** — отображаются как ссылка для скачивания с именем файла
|
||||||
|
- **Уведомления на неактивной вкладке** — звуковой сигнал (Web Audio API) и красная точка на favicon
|
||||||
|
- **Системные сообщения** — подключение / отключение участников
|
||||||
|
- **Скролл** — автоматический, кастомный тонкий скроллбар в теме приложения
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Структура проекта
|
||||||
|
|
||||||
|
```
|
||||||
|
chat/
|
||||||
|
├── server/
|
||||||
|
│ ├── server.js # WebSocket сервер
|
||||||
|
│ ├── users.json # Хардкоженые логины/пароли
|
||||||
|
│ └── package.json
|
||||||
|
├── client/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── App.jsx # Корневой компонент
|
||||||
|
│ │ ├── App.css
|
||||||
|
│ │ ├── main.jsx # Точка входа
|
||||||
|
│ │ └── components/
|
||||||
|
│ │ ├── Login.jsx / .css
|
||||||
|
│ │ ├── Chat.jsx / .css
|
||||||
|
│ │ ├── MessageList.jsx
|
||||||
|
│ │ ├── Message.jsx / .css
|
||||||
|
│ │ └── MessageInput.jsx / .css
|
||||||
|
│ ├── .env # Production настройки
|
||||||
|
│ ├── .env.development # Dev настройки
|
||||||
|
│ ├── index.html
|
||||||
|
│ ├── vite.config.js
|
||||||
|
│ └── package.json
|
||||||
|
├── Dockerfile # Многостадийная сборка
|
||||||
|
├── docker-entrypoint.sh # Точка входа контейнера
|
||||||
|
├── nginx.conf # Конфигурация nginx
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_WS_URL=/ws
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_WS_URL=ws://localhost:8080
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Chat Room</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1719
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "chat-client",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
"vite": "^5.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
*, *::before, *::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body, #root {
|
||||||
|
height: 100%;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
|
||||||
|
Ubuntu, Cantarell, sans-serif;
|
||||||
|
background: #1a1a2e;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #7ec8e3;
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||||
|
import Login from './components/Login';
|
||||||
|
import Chat from './components/Chat';
|
||||||
|
|
||||||
|
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!loggedIn) {
|
||||||
|
return <Login onLogin={handleLogin} error={error} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Chat ws={wsRef.current} login={login} onLogout={handleLogout} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
.chat-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 1rem 0;
|
||||||
|
border-bottom: 1px solid #2a2a4a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header h2 {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logout-btn {
|
||||||
|
padding: 0.4rem 1rem;
|
||||||
|
border: 1px solid #5c5c7a;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: transparent;
|
||||||
|
color: #e0e0e0;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logout-btn:hover {
|
||||||
|
background: #2a2a4a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-error {
|
||||||
|
background: #5c1a1a;
|
||||||
|
color: #ff8a8a;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-notification {
|
||||||
|
background: #1a3a5c;
|
||||||
|
color: #8ab8ff;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
|
import MessageList from './MessageList';
|
||||||
|
import MessageInput from './MessageInput';
|
||||||
|
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]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="chat-container">
|
||||||
|
<div className="chat-header">
|
||||||
|
<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>}
|
||||||
|
<MessageList messages={messages} currentUser={login} />
|
||||||
|
<MessageInput ws={ws} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
.login-container {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form {
|
||||||
|
background: #16213e;
|
||||||
|
padding: 2.5rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 360px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form h1 {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-size: 1.6rem;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-error {
|
||||||
|
background: #5c1a1a;
|
||||||
|
color: #ff8a8a;
|
||||||
|
padding: 0.6rem 1rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form input {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border: 1px solid #2a2a4a;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #1a1a2e;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 1rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form input:focus {
|
||||||
|
border-color: #4a9eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form button {
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #4a9eff;
|
||||||
|
color: #fff;
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form button:hover {
|
||||||
|
background: #357abd;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import './Login.css';
|
||||||
|
|
||||||
|
export default function Login({ onLogin, error }) {
|
||||||
|
const [login, setLogin] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!login.trim() || !password.trim()) return;
|
||||||
|
onLogin(login.trim(), password);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="login-container">
|
||||||
|
<form className="login-form" onSubmit={handleSubmit}>
|
||||||
|
<h1>Chat Login</h1>
|
||||||
|
{error && <div className="login-error">{error}</div>}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Login"
|
||||||
|
value={login}
|
||||||
|
onChange={(e) => setLogin(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit">Sign In</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
.message-list {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 1rem 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: #3a3a5a transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-list::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-list::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-list::-webkit-scrollbar-thumb {
|
||||||
|
background: #3a3a5a;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-list::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #4a4a6a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-list-empty {
|
||||||
|
text-align: center;
|
||||||
|
color: #6a6a8a;
|
||||||
|
margin-top: 3rem;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-system {
|
||||||
|
text-align: center;
|
||||||
|
color: #6a6a8a;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
padding: 0.3rem 0;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
max-width: 75%;
|
||||||
|
padding: 0.6rem 1rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-own {
|
||||||
|
align-self: flex-end;
|
||||||
|
background: #2b4a7a;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-other {
|
||||||
|
align-self: flex-start;
|
||||||
|
background: #2a2a4a;
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-author {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: #8ab8ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-time {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: #6a6a8a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-body p {
|
||||||
|
margin-bottom: 0.3rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-body p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-image {
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 300px;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
transition: opacity 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-image:hover {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-file-link {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
border-radius: 6px;
|
||||||
|
text-decoration: none;
|
||||||
|
color: #7ec8e3;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-file-link:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-icon {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-file-error {
|
||||||
|
color: #ff6a6a;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import React, { useMemo } from 'react';
|
||||||
|
import './Message.css';
|
||||||
|
|
||||||
|
function formatTime(ts) {
|
||||||
|
const d = new Date(ts);
|
||||||
|
return d.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Message({ message, isOwn }) {
|
||||||
|
const isImage = message.mime && message.mime.startsWith('image/');
|
||||||
|
const isSystem = message.type === 'system';
|
||||||
|
const isFile = message.type === 'file';
|
||||||
|
|
||||||
|
const blobUrl = useMemo(() => {
|
||||||
|
if (isFile && message.data) {
|
||||||
|
return dataURLToBlobUrl(`data:${message.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]);
|
||||||
|
|
||||||
|
if (isSystem) {
|
||||||
|
return (
|
||||||
|
<div className="message-system">
|
||||||
|
<span>{message.text}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`message ${isOwn ? 'message-own' : 'message-other'}`}>
|
||||||
|
<div className="message-header">
|
||||||
|
<span className="message-author">{message.from}</span>
|
||||||
|
<span className="message-time">{formatTime(message.timestamp)}</span>
|
||||||
|
</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}
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
{message.filename}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{isFile && !isImage && !downloadUrl && (
|
||||||
|
<div className="message-file-error">Failed to load file</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
.message-input-container {
|
||||||
|
padding: 1rem 0;
|
||||||
|
border-top: 1px solid #2a2a4a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-field {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.7rem 1rem;
|
||||||
|
border: 1px solid #2a2a4a;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #16213e;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-field:focus {
|
||||||
|
border-color: #4a9eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attach-btn, .send-btn {
|
||||||
|
padding: 0.7rem 1.2rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attach-btn {
|
||||||
|
background: #2a2a4a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attach-btn:hover {
|
||||||
|
background: #3a3a5a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-btn {
|
||||||
|
background: #4a9eff;
|
||||||
|
color: #fff;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-btn:hover {
|
||||||
|
background: #357abd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-input-hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import React, { useState, useRef } from 'react';
|
||||||
|
import './MessageInput.css';
|
||||||
|
|
||||||
|
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
export default function MessageInput({ ws }) {
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const fileInputRef = useRef(null);
|
||||||
|
|
||||||
|
const sendText = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!text.trim()) return;
|
||||||
|
ws.send(JSON.stringify({ type: 'text', text: text.trim() }));
|
||||||
|
setText('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileSelect = (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
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];
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
type: 'file',
|
||||||
|
filename: file.name,
|
||||||
|
mime: file.type || 'application/octet-stream',
|
||||||
|
data: base64
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
reader.onerror = () => {
|
||||||
|
alert('Failed to read file');
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
e.target.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAttachClick = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="message-input-container">
|
||||||
|
<form className="message-input-form" onSubmit={sendText}>
|
||||||
|
<input
|
||||||
|
className="message-input-field"
|
||||||
|
type="text"
|
||||||
|
placeholder="Type a message..."
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="button" className="attach-btn" onClick={handleAttachClick} title="Attach file">
|
||||||
|
📎
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="send-btn">Send</button>
|
||||||
|
</form>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
className="file-input-hidden"
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import React, { useRef, useEffect } from 'react';
|
||||||
|
import Message from './Message';
|
||||||
|
|
||||||
|
export default function MessageList({ messages, currentUser }) {
|
||||||
|
const bottomRef = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
}, [messages]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="message-list">
|
||||||
|
{messages.length === 0 && (
|
||||||
|
<div className="message-list-empty">No messages yet. Start chatting!</div>
|
||||||
|
)}
|
||||||
|
{messages.map((msg) => (
|
||||||
|
<Message key={msg.id} message={msg} isOwn={msg.from === currentUser} />
|
||||||
|
))}
|
||||||
|
<div ref={bottomRef} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import App from './App';
|
||||||
|
import './App.css';
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
port: 3000
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Start nginx in foreground
|
||||||
|
nginx -g 'daemon off;' &
|
||||||
|
NGINX_PID=$!
|
||||||
|
|
||||||
|
# Start WebSocket server
|
||||||
|
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
|
||||||
|
wait $NODE_PID
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
client_max_body_size 50M;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/css application/javascript image/svg+xml;
|
||||||
|
gzip_min_length 256;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
add_header Cache-Control "public, max-age=3600";
|
||||||
|
}
|
||||||
|
|
||||||
|
location /ws {
|
||||||
|
proxy_pass http://127.0.0.1:8080;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_read_timeout 86400;
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+36
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"name": "chat-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "chat-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "^8.16.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.21.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
|
||||||
|
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "chat-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "WebSocket chat server with file sharing",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "^8.16.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { WebSocketServer } = require('ws');
|
||||||
|
|
||||||
|
const PORT = parseInt(process.env.PORT, 10) || 8080;
|
||||||
|
const MAX_FILE_SIZE = parseInt(process.env.MAX_FILE_SIZE, 10) || 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
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) => {
|
||||||
|
const clientIp = req.socket.remoteAddress;
|
||||||
|
console.log(`New 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 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'
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ws.send(JSON.stringify({ type: 'error', message: 'Authenticate first' }));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.type === 'text') {
|
||||||
|
if (!parsed.text || typeof parsed.text !== 'string') {
|
||||||
|
ws.send(JSON.stringify({ type: 'error', message: 'Invalid text message' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(`Text from ${userLogin}: ${parsed.text.substring(0, 50)}`);
|
||||||
|
broadcast({
|
||||||
|
type: 'text',
|
||||||
|
from: userLogin,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
text: parsed.text
|
||||||
|
}, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.type === 'file') {
|
||||||
|
if (!parsed.filename || !parsed.mime || !parsed.data) {
|
||||||
|
ws.send(JSON.stringify({ type: 'error', message: 'Invalid file message' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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 ${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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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('error', (err) => {
|
||||||
|
console.error(`WebSocket error${userLogin ? ` for ${userLogin}` : ''}:`, err.message);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function broadcast(message, excludeWs) {
|
||||||
|
const json = JSON.stringify(message);
|
||||||
|
wss.clients.forEach(client => {
|
||||||
|
if (client !== excludeWs && client.readyState === 1) {
|
||||||
|
client.send(json);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[
|
||||||
|
{ "login": "alice", "password": "123" },
|
||||||
|
{ "login": "bob", "password": "456" }
|
||||||
|
]
|
||||||
Reference in New Issue
Block a user