Here's a comprehensive WebSocket server for a help desk application using Soketi (which is compatible with Pusher protocol):
import { createServer } from 'http';
import { WebSocketServer, WebSocket } from 'ws';
import { parse } from 'url';
import { v4 as uuidv4 } from 'uuid';
interface User {
id: string;
username: string;
websocket: WebSocket;
isAdmin: boolean;
lastSeen: Date;
}
interface Message {
id: string;
chatId: string;
senderId: string;
senderUsername: string;
content: string;
timestamp: Date;
type: 'message' | 'system';
}
interface Chat {
id: string;
userId: string;
username: string;
adminId: string;
messages: Message[];
status: 'active' | 'closed';
createdAt: Date;
lastActivity: Date;
}
interface WebSocketMessage {
event: string;
data: any;
channel?: string;
}
class HelpDeskServer {
private users: Map<string, User> = new Map();
private chats: Map<string, Chat> = new Map();
private userChatMap: Map<string, string> = new Map(); // userId -> chatId
private wss: WebSocketServer;
private server: any;
constructor(port: number = 8080) {
this.server = createServer();
this.wss = new WebSocketServer({
server: this.server,
verifyClient: (info) => {
const url = parse(info.req.url!, true);
const token = url.query.token as string;
const isAdmin = token === 'secret';
// Store auth info for later use
(info.req as any).isAdmin = isAdmin;
(info.req as any).token = token;
return true; // Allow all connections, we'll handle auth in connection handler
}
});
this.setupWebSocketHandlers();
this.server.listen(port, () => {
console.log(`Help Desk WebSocket server running on port ${port}`);
console.log(`Admin connection: ws://localhost:${port}?token=secret`);
console.log(`User connection: ws://localhost:${port}`);
});
}
private setupWebSocketHandlers(): void {
this.wss.on('connection', (ws: WebSocket, req) => {
const url = parse(req.url!, true);
const isAdmin = (req as any).isAdmin;
console.log(`New connection - Admin: ${isAdmin}`);
ws.on('message', (data: Buffer) => {
try {
const message: WebSocketMessage = JSON.parse(data.toString());
this.handleMessage(ws, message, isAdmin);
} catch (error) {
console.error('Error parsing message:', error);
this.sendError(ws, 'Invalid message format');
}
});
ws.on('close', () => {
this.handleDisconnection(ws);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
// Send connection acknowledgment
this.sendMessage(ws, 'connection', {
status: 'connected',
isAdmin,
timestamp: new Date().toISOString()
});
});
}
private handleMessage(ws: WebSocket, message: WebSocketMessage, isAdmin: boolean): void {
const { event, data } = message;
switch (event) {
case 'auth':
this.handleAuth(ws, data, isAdmin);
break;
case 'send_message':
this.handleSendMessage(ws, data);
break;
case 'get_chats':
this.handleGetChats(ws, data);
break;
case 'get_chat_history':
this.handleGetChatHistory(ws, data);
break;
case 'close_chat':
this.handleCloseChat(ws, data);
break;
case 'typing':
this.handleTyping(ws, data);
break;
default:
this.sendError(ws, `Unknown event: ${event}`);
}
}
private handleAuth(ws: WebSocket, data: any, isAdmin: boolean): void {
const { username } = data;
if (!username) {
this.sendError(ws, 'Username is required');
return;
}
// Check if username is already taken (except for admin)
const existingUser = Array.from(this.users.values()).find(u => u.username === username);
if (existingUser && !isAdmin) {
this.sendError(ws, 'Username already taken');
return;
}
// For admin, always use 'admin' as username
const finalUsername = isAdmin ? 'admin' : username;
// Remove existing user if reconnecting
this.removeUserByWebSocket(ws);
const user: User = {
id: uuidv4(),
username: finalUsername,
websocket: ws,
isAdmin,
lastSeen: new Date()
};
this.users.set(user.id, user);
(ws as any).userId = user.id;
console.log(`User authenticated: ${finalUsername} (Admin: ${isAdmin})`);
this.sendMessage(ws, 'auth_success', {
userId: user.id,
username: finalUsername,
isAdmin,
timestamp: new Date().toISOString()
});
// If user (not admin), create or resume chat
if (!isAdmin) {
this.createOrResumeChat(user);
} else {
// Send admin the list of active chats
this.sendAdminChatList(ws);
}
}
private handleSendMessage(ws: WebSocket, data: any): void {
const userId = (ws as any).userId;
const user = this.users.get(userId);
if (!user) {
this.sendError(ws, 'User not authenticated');
return;
}
const { content, chatId } = data;
if (!content || content.trim() === '') {
this.sendError(ws, 'Message content is required');
return;
}
let targetChatId = chatId;
// If user is not admin, use their assigned chat
if (!user.isAdmin) {
targetChatId = this.userChatMap.get(userId);
if (!targetChatId) {
this.sendError(ws, 'No active chat found');
return;
}
}
const chat = this.chats.get(targetChatId);
if (!chat) {
this.sendError(ws, 'Chat not found');
return;
}
// Check if admin is trying to send to a chat they have access to
if (user.isAdmin && chat.adminId !== userId) {
// Allow admin to take over any chat
chat.adminId = userId;
}
const message: Message = {
id: uuidv4(),
chatId: targetChatId,
senderId: userId,
senderUsername: user.username,
content: content.trim(),
timestamp: new Date(),
type: 'message'
};
chat.messages.push(message);
chat.lastActivity = new Date();
// Send message to all participants in the chat
this.broadcastToChat(targetChatId, 'new_message', {
message: this.formatMessage(message),
chatId: targetChatId
});
// Update admin with chat list if message from user
if (!user.isAdmin) {
this.broadcastToAdmins('chat_updated', {
chat: this.formatChat(chat)
});
}
console.log(`Message sent in chat ${targetChatId}: ${user.username}: ${content}`);
}
private handleGetChats(ws: WebSocket, data: any): void {
const userId = (ws as any).userId;
const user = this.users.get(userId);
if (!user || !user.isAdmin) {
this.sendError(ws, 'Admin access required');
return;
}
this.sendAdminChatList(ws);
}
private handleGetChatHistory(ws: WebSocket, data: any): void {
const userId = (ws as any).userId;
const user = this.users.get(userId);
if (!user) {
this.sendError(ws, 'User not authenticated');
return;
}
const { chatId } = data;
let targetChatId = chatId;
// If user is not admin, use their assigned chat
if (!user.isAdmin) {
targetChatId = this.userChatMap.get(userId);
}
if (!targetChatId) {
this.sendError(ws, 'Chat ID required');
return;
}
const chat = this.chats.get(targetChatId);
if (!chat) {
this.sendError(ws, 'Chat not found');
return;
}
// Check access permissions
if (!user.isAdmin && chat.userId !== userId) {
this.sendError(ws, 'Access denied');
return;
}
this.sendMessage(ws, 'chat_history', {
chatId: targetChatId,
messages: chat.messages.map(m => this.formatMessage(m)),
chat: this.formatChat(chat)
});
}
private handleCloseChat(ws: WebSocket, data: any): void {
const userId = (ws as any).userId;
const user = this.users.get(userId);
if (!user || !user.isAdmin) {
this.sendError(ws, 'Admin access required');
return;
}
const { chatId } = data;
const chat = this.chats.get(chatId);
if (!chat) {
this.sendError(ws, 'Chat not found');
return;
}
chat.status = 'closed';
// Add system message
const systemMessage: Message = {
id: uuidv4(),
chatId,
senderId: 'system',
senderUsername: 'System',
content: 'Chat has been closed by admin',
timestamp: new Date(),
type: 'system'
};
chat.messages.push(systemMessage);
// Notify all participants
this.broadcastToChat(chatId, 'chat_closed', {
chatId,
message: this.formatMessage(systemMessage)
});
// Update admin chat list
this.broadcastToAdmins('chat_updated', {
chat: this.formatChat(chat)
});
console.log(`Chat ${chatId} closed by admin`);
}
private handleTyping(ws: WebSocket, data: any): void {
const userId = (ws as any).userId;
const user = this.users.get(userId);
if (!user) {
this.sendError(ws, 'User not authenticated');
return;
}
const { chatId, isTyping } = data;
let targetChatId = chatId;
if (!user.isAdmin) {
targetChatId = this.userChatMap.get(userId);
}
if (!targetChatId) {
return;
}
// Broadcast typing status to other participants in the chat
this.broadcastToChat(targetChatId, 'user_typing', {
userId,
username: user.username,
isTyping,
chatId: targetChatId
}, userId);
}
private createOrResumeChat(user: User): void {
// Check if user already has an active chat
let chatId = this.userChatMap.get(user.id);
let chat = chatId ? this.chats.get(chatId) : null;
if (!chat || chat.status === 'closed') {
// Create new chat
chatId = uuidv4();
chat = {
id: chatId,
userId: user.id,
username: user.username,
adminId: '', // Will be assigned when admin responds
messages: [],
status: 'active',
createdAt: new Date(),
lastActivity: new Date()
};
// Add welcome message
const welcomeMessage: Message = {
id: uuidv4(),
chatId,
senderId: 'system',
senderUsername: 'System',
content: `Welcome ${user.username}! An admin will be with you shortly.`,
timestamp: new Date(),
type: 'system'
};
chat.messages.push(welcomeMessage);
this.chats.set(chatId, chat);
this.userChatMap.set(user.id, chatId);
console.log(`New chat created: ${chatId} for user ${user.username}`);
// Notify admins of new chat
this.broadcastToAdmins('new_chat', {
chat: this.formatChat(chat)
});
} else {
console.log(`Resuming chat: ${chatId} for user ${user.username}`);
}
// Send chat info to user
this.sendMessage(user.websocket, 'chat_assigned', {
chatId,
chat: this.formatChat(chat),
messages: chat.messages.map(m => this.formatMessage(m))
});
}
private sendAdminChatList(ws: WebSocket): void {
const activeChats = Array.from(this.chats.values())
.filter(chat => chat.status === 'active')
.sort((a, b) => b.lastActivity.getTime() - a.lastActivity.getTime());
this.sendMessage(ws, 'chat_list', {
chats: activeChats.map(chat => this.formatChat(chat))
});
}
private broadcastToChat(chatId: string, event: string, data: any, excludeUserId?: string): void {
const chat = this.chats.get(chatId);
if (!chat) return;
// Send to user in the chat
const user = this.users.get(chat.userId);
if (user && user.id !== excludeUserId && user.websocket.readyState === WebSocket.OPEN) {
this.sendMessage(user.websocket, event, data);
}
// Send to admin handling the chat
if (chat.adminId) {
const admin = this.users.get(chat.adminId);
if (admin && admin.id !== excludeUserId && admin.websocket.readyState === WebSocket.OPEN) {
this.sendMessage(admin.websocket, event, data);
}
}
}
private broadcastToAdmins(event: string, data: any): void {
this.users.forEach(user => {
if (user.isAdmin && user.websocket.readyState === WebSocket.OPEN) {
this.sendMessage(user.websocket, event, data);
}
});
}
private handleDisconnection(ws: WebSocket): void {
const userId = (ws as any).userId;
if (userId) {
const user = this.users.get(userId);
if (user) {
console.log(`User disconnected: ${user.username}`);
this.users.delete(userId);
}
}
}
private removeUserByWebSocket(ws: WebSocket): void {
for (const [userId, user] of this.users.entries()) {
if (user.websocket === ws) {
this.users.delete(userId);
break;
}
}
}
private sendMessage(ws: WebSocket, event: string, data: any): void {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify