1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

add websockets suppor3

This commit is contained in:
MoonTestUse1
2025-01-05 01:54:17 +06:00
parent a81310d0e7
commit 65d9eddb53
5 changed files with 75 additions and 14 deletions

View File

@@ -1,8 +1,13 @@
"""Main application module""" """Main application module"""
from fastapi import FastAPI from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from . import models from . import models
from .routers import admin, employees, requests, auth, statistics from .routers import admin, employees, requests, auth, statistics
import logging
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI( app = FastAPI(
# Включаем автоматическое перенаправление со слэшем # Включаем автоматическое перенаправление со слэшем
@@ -38,3 +43,9 @@ app.include_router(employees.router, prefix="/api/employees", tags=["employees"]
app.include_router(requests.router, prefix="/api/requests", tags=["requests"]) app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
app.include_router(admin.router, prefix="/api/admin", tags=["admin"]) app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"]) app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
@app.middleware("http")
async def log_requests(request: Request, call_next):
logger.info(f"Request: {request.method} {request.url}")
response = await call_next(request)
return response

View File

@@ -21,21 +21,35 @@ async def websocket_admin_endpoint(websocket: WebSocket):
await notification_manager.connect(websocket, "admin") await notification_manager.connect(websocket, "admin")
try: try:
while True: while True:
data = await websocket.receive_text() data = await websocket.receive_json()
logger.info(f"Received message from admin: {data}") logger.info(f"Received message from admin: {data}")
if data.get("type") == "ping":
await notification_manager.handle_ping(websocket)
except WebSocketDisconnect: except WebSocketDisconnect:
logger.info("Admin WebSocket disconnected") logger.info("Admin WebSocket disconnected")
notification_manager.disconnect(websocket, "admin") notification_manager.disconnect(websocket, "admin")
except Exception as e:
logger.error(f"Error in admin websocket: {e}")
notification_manager.disconnect(websocket, "admin")
@router.websocket("/ws/employee/{employee_id}") @router.websocket("/ws/employee/{employee_id}")
async def websocket_employee_endpoint(websocket: WebSocket, employee_id: int): async def websocket_employee_endpoint(websocket: WebSocket, employee_id: int):
"""WebSocket endpoint для сотрудников""" """WebSocket endpoint для сотрудников"""
logger.info(f"Employee {employee_id} WebSocket connection attempt")
await notification_manager.connect(websocket, "employee") await notification_manager.connect(websocket, "employee")
try: try:
while True: while True:
data = await websocket.receive_text() data = await websocket.receive_json()
# Здесь можно добавить обработку сообщений от сотрудника logger.info(f"Received message from employee {employee_id}: {data}")
if data.get("type") == "ping":
await notification_manager.handle_ping(websocket)
except WebSocketDisconnect: except WebSocketDisconnect:
logger.info(f"Employee {employee_id} WebSocket disconnected")
notification_manager.disconnect(websocket, "employee")
except Exception as e:
logger.error(f"Error in employee websocket: {e}")
notification_manager.disconnect(websocket, "employee") notification_manager.disconnect(websocket, "employee")
@router.post("/", response_model=Request) @router.post("/", response_model=Request)

View File

@@ -2,6 +2,7 @@ from fastapi import WebSocket
from typing import Dict, List from typing import Dict, List
import json import json
import logging import logging
import asyncio
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -58,4 +59,12 @@ class NotificationManager:
for connection in disconnected: for connection in disconnected:
self.disconnect(connection, "employee") self.disconnect(connection, "employee")
async def handle_ping(self, websocket: WebSocket):
"""Обработка ping сообщений"""
try:
await websocket.send_json({"type": "pong"})
logger.debug("Sent pong response")
except Exception as e:
logger.error(f"Error sending pong: {e}")
notification_manager = NotificationManager() notification_manager = NotificationManager()

View File

@@ -8,6 +8,7 @@ class WebSocketClient {
private messageHandlers: ((data: any) => void)[] = [] private messageHandlers: ((data: any) => void)[] = []
private currentType: 'admin' | 'employee' | null = null private currentType: 'admin' | 'employee' | null = null
private currentId: number | undefined = undefined private currentId: number | undefined = undefined
private pingInterval: number | null = null
// Состояние подключения // Состояние подключения
isConnected = ref(false) isConnected = ref(false)
@@ -28,6 +29,10 @@ class WebSocketClient {
console.log('WebSocket: Closing existing connection') console.log('WebSocket: Closing existing connection')
this.socket.close() this.socket.close()
this.socket = null this.socket = null
if (this.pingInterval) {
clearInterval(this.pingInterval)
this.pingInterval = null
}
} }
try { try {
@@ -37,19 +42,28 @@ class WebSocketClient {
console.log('WebSocket: Connected successfully') console.log('WebSocket: Connected successfully')
this.isConnected.value = true this.isConnected.value = true
this.reconnectAttempts = 0 this.reconnectAttempts = 0
// Устанавливаем ping интервал для поддержания соединения
this.pingInterval = window.setInterval(() => {
if (this.socket?.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify({ type: 'ping' }))
}
}, 30000) // Пинг каждые 30 секунд
} }
this.socket.onmessage = (event) => { this.socket.onmessage = (event) => {
console.log('WebSocket: Message received', event.data) console.log('WebSocket: Message received', event.data)
try { try {
const data = JSON.parse(event.data) const data = JSON.parse(event.data)
this.messageHandlers.forEach(handler => { if (data.type !== 'pong') { // Игнорируем pong сообщения
try { this.messageHandlers.forEach(handler => {
handler(data) try {
} catch (error) { handler(data)
console.error('WebSocket: Error in message handler:', error) } catch (error) {
} console.error('WebSocket: Error in message handler:', error)
}) }
})
}
} catch (error) { } catch (error) {
console.error('WebSocket: Error parsing message:', error) console.error('WebSocket: Error parsing message:', error)
} }
@@ -58,6 +72,10 @@ class WebSocketClient {
this.socket.onclose = (event) => { this.socket.onclose = (event) => {
console.log('WebSocket: Connection closed', event.code, event.reason) console.log('WebSocket: Connection closed', event.code, event.reason)
this.isConnected.value = false this.isConnected.value = false
if (this.pingInterval) {
clearInterval(this.pingInterval)
this.pingInterval = null
}
this.tryReconnect() this.tryReconnect()
} }
@@ -106,6 +124,10 @@ class WebSocketClient {
this.socket.close() this.socket.close()
this.socket = null this.socket = null
} }
if (this.pingInterval) {
clearInterval(this.pingInterval)
this.pingInterval = null
}
this.currentType = null this.currentType = null
this.currentId = undefined this.currentId = undefined
this.isConnected.value = false this.isConnected.value = false

View File

@@ -6,6 +6,11 @@ upstream frontend_upstream {
server support-frontend:5173; server support-frontend:5173;
} }
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server { server {
listen 80; listen 80;
server_name itformhelp.ru www.itformhelp.ru; server_name itformhelp.ru www.itformhelp.ru;
@@ -15,7 +20,7 @@ server {
proxy_pass http://frontend_upstream; proxy_pass http://frontend_upstream;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade; proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
@@ -33,7 +38,7 @@ server {
proxy_pass http://backend_upstream; proxy_pass http://backend_upstream;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade; proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;