Download backend/src/socket/index.ts from qf46578/OmniCS: direct link, hf CLI and curl.
- Browser
- Download file 6.59 kB
-
https://huggingface.co/qf46578/OmniCS/resolve/main/backend/src/socket/index.ts
- Command line
-
hf download hf://qf46578/OmniCS/backend/src/socket/index.ts
-
curl -L -o index.ts https://huggingface.co/qf46578/OmniCS/resolve/main/backend/src/socket/index.ts
6.59 kB
| import { Server, Socket } from 'socket.io'; | |
| import { AppDataSource } from '../database/data-source'; | |
| import { Conversation } from '../entities/conversation.entity'; | |
| import { Message } from '../entities/message.entity'; | |
| import { createLogger } from '../utils/logger'; | |
| import { MessageService } from '../services/message.service'; | |
| const logger = createLogger('socket'); | |
| const conversationRepo = AppDataSource.getRepository(Conversation); | |
| const messageRepo = AppDataSource.getRepository(Message); | |
| interface AuthenticatedSocket extends Socket { | |
| userId?: string; | |
| roleId?: string; | |
| username?: string; | |
| } | |
| export function setupSocketIO(io: Server): void { | |
| // 认证中间件 | |
| io.use((socket: AuthenticatedSocket, next) => { | |
| const token = socket.handshake.auth.token; | |
| if (!token) { | |
| return next(new Error('Authentication required')); | |
| } | |
| try { | |
| // 简单验证,实际应使用JWT验证 | |
| // const decoded = jwt.verify(token, secret); | |
| // socket.userId = decoded.userId; | |
| // socket.roleId = decoded.roleId; | |
| // socket.username = decoded.username; | |
| // 暂时简化处理 | |
| socket.userId = socket.handshake.auth.userId || 'anonymous'; | |
| socket.roleId = socket.handshake.auth.roleId; | |
| socket.username = socket.handshake.auth.username || 'anonymous'; | |
| next(); | |
| } catch (error) { | |
| next(new Error('Invalid token')); | |
| } | |
| }); | |
| io.on('connection', (socket: AuthenticatedSocket) => { | |
| logger.info(`Client connected: ${socket.id} (User: ${socket.username})`); | |
| // 加入会话房间 | |
| socket.on('conversation:join', async (conversationId: string) => { | |
| try { | |
| socket.join(`conversation:${conversationId}`); | |
| logger.debug(`Socket ${socket.id} joined conversation ${conversationId}`); | |
| // 发送系统消息 | |
| socket.emit('conversation:joined', { | |
| conversationId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } catch (error) { | |
| socket.emit('error', { message: 'Failed to join conversation' }); | |
| } | |
| }); | |
| // 离开会话房间 | |
| socket.on('conversation:leave', (conversationId: string) => { | |
| socket.leave(`conversation:${conversationId}`); | |
| logger.debug(`Socket ${socket.id} left conversation ${conversationId}`); | |
| }); | |
| // 发送消息 | |
| socket.on('message:send', async (data: { | |
| conversationId: string; | |
| content: string; | |
| contentType?: 'text' | 'image'; | |
| mediaUrl?: string; | |
| }) => { | |
| try { | |
| const messageService = new MessageService(); | |
| const message = await messageService.sendUserMessage( | |
| data.conversationId, | |
| data.content, | |
| socket.userId || 'system', | |
| data.contentType || 'text', | |
| data.mediaUrl | |
| ); | |
| // 广播给房间内所有人 | |
| io.to(`conversation:${data.conversationId}`).emit('message:new', message); | |
| logger.info(`Message sent in conversation ${data.conversationId}`); | |
| } catch (error) { | |
| logger.error('Failed to send message:', error); | |
| socket.emit('error', { message: 'Failed to send message' }); | |
| } | |
| }); | |
| // 正在输入 | |
| socket.on('message:typing', (conversationId: string) => { | |
| socket.to(`conversation:${conversationId}`).emit('user:typing', { | |
| userId: socket.userId, | |
| username: socket.username, | |
| }); | |
| }); | |
| // 处理AI生成的消息 | |
| socket.on('message:ai-generate', async (data: { | |
| conversationId: string; | |
| customerMessage: string; | |
| senderId: string; | |
| senderName?: string; | |
| }) => { | |
| try { | |
| const messageService = new MessageService(); | |
| const result = await messageService.processInboundMessage( | |
| data.conversationId, | |
| data.customerMessage, | |
| data.senderId, | |
| data.senderName | |
| ); | |
| // 返回AI生成的结果 | |
| socket.emit('message:ai-result', { | |
| conversationId: data.conversationId, | |
| message: result.message, | |
| action: result.action, | |
| transferTo: result.transferTo, | |
| processingTimeMs: result.processingTimeMs, | |
| }); | |
| // 如果需要转接,通知相关人员 | |
| if (result.action === 'transfer' && result.transferTo) { | |
| io.emit('transfer:required', { | |
| conversationId: data.conversationId, | |
| transferTo: result.transferTo, | |
| }); | |
| } | |
| // 广播新消息 | |
| if (result.action === 'reply') { | |
| io.to(`conversation:${data.conversationId}`).emit('message:new', result.message); | |
| } | |
| } catch (error) { | |
| logger.error('AI generation failed:', error); | |
| socket.emit('error', { message: 'AI generation failed' }); | |
| } | |
| }); | |
| // 转接会话 | |
| socket.on('conversation:transfer', async (data: { | |
| conversationId: string; | |
| toUserId?: string; | |
| toRoleId?: string; | |
| reason?: string; | |
| }) => { | |
| try { | |
| const conversation = await conversationRepo.findOne({ | |
| where: { id: data.conversationId }, | |
| }); | |
| if (!conversation) { | |
| return socket.emit('error', { message: 'Conversation not found' }); | |
| } | |
| conversation.assignedUserId = data.toUserId || null; | |
| conversation.assignedRoleId = data.toRoleId || null; | |
| conversation.status = 'transferred'; | |
| conversation.needsTransfer = false; | |
| conversation.transferReason = data.reason || null; | |
| await conversationRepo.save(conversation); | |
| // 通知相关人员 | |
| io.emit('conversation:transferred', { | |
| conversationId: data.conversationId, | |
| toUserId: data.toUserId, | |
| toRoleId: data.toRoleId, | |
| }); | |
| logger.info(`Conversation ${data.conversationId} transferred`); | |
| } catch (error) { | |
| logger.error('Transfer failed:', error); | |
| socket.emit('error', { message: 'Transfer failed' }); | |
| } | |
| }); | |
| // 断开连接 | |
| socket.on('disconnect', () => { | |
| logger.info(`Client disconnected: ${socket.id}`); | |
| }); | |
| }); | |
| // 广播新会话 | |
| const broadcastNewConversation = (conversation: Conversation) => { | |
| io.emit('conversation:new', conversation); | |
| }; | |
| // 广播消息更新 | |
| const broadcastMessage = (conversationId: string, message: Message) => { | |
| io.to(`conversation:${conversationId}`).emit('message:new', message); | |
| }; | |
| // 导出广播函数供其他模块使用 | |
| (global as any).socketIO = { | |
| io, | |
| broadcastNewConversation, | |
| broadcastMessage, | |
| }; | |
| logger.info('Socket.IO setup complete'); | |
| } | |