Spaces:
Sleeping
Sleeping
Download apps/api/src/websocket/events.gateway.ts from Benaah/MicProtocol: direct link, hf CLI and curl.
- Browser
- Download file 28.1 kB
-
https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/src/websocket/events.gateway.ts
- Command line
-
hf download hf://spaces/Benaah/MicProtocol/apps/api/src/websocket/events.gateway.ts
-
curl -L -o events.gateway.ts https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/src/websocket/events.gateway.ts
28.1 kB
| import { | |
| Logger, | |
| UnauthorizedException, | |
| ForbiddenException, | |
| } from "@nestjs/common"; | |
| import { | |
| WebSocketGateway, | |
| WebSocketServer, | |
| SubscribeMessage, | |
| MessageBody, | |
| ConnectedSocket, | |
| OnGatewayConnection, | |
| OnGatewayDisconnect, | |
| } from "@nestjs/websockets"; | |
| import { Server, Socket } from "socket.io"; | |
| import { AdminPermission, AdminRole, resolveAdminPermissions } from "@micprotocol/shared-types"; | |
| import { BetterAuthService } from "../auth/better-auth-identity.service"; | |
| import { PrismaService } from "../prisma/prisma.service"; | |
| import { deriveAdminRole } from "../common/platform-admin"; | |
| import { isOriginAllowed } from "../common/origin-policy"; | |
| // The /events namespace only carries small JSON ids (join/leave) β never | |
| // large blobs (chat lives in mic-realtime). Cap incoming message payloads | |
| // well below Socket.io's 1MB default. | |
| const MAX_MESSAGE_BUFFER_BYTES = 64 * 1024; | |
| interface AuthenticatedSocket extends Socket { | |
| data: { | |
| userId?: string; | |
| isAdmin?: boolean; | |
| adminRole?: AdminRole | null; | |
| adminPermissions?: Set<AdminPermission>; | |
| }; | |
| } | |
| interface RoomSubscription { | |
| podcastId: string; | |
| } | |
| interface AdminBroadcast { | |
| event: string; | |
| data: Record<string, unknown>; | |
| } | |
| interface AdminDisconnectUser { | |
| userId: string; | |
| reason?: string; | |
| } | |
| ({ | |
| cors: { | |
| // Shared policy with the HTTP layer (common/origin-policy.ts): | |
| // explicit origins + any `<slug>.ROOT_DOMAIN` workspace subdomain. | |
| origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => | |
| callback(null, isOriginAllowed(origin)), | |
| credentials: true, | |
| }, | |
| namespace: "/events", | |
| maxHttpBufferSize: MAX_MESSAGE_BUFFER_BYTES, | |
| }) | |
| export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect { | |
| private readonly logger = new Logger(EventsGateway.name); | |
| () | |
| server!: Server; | |
| constructor( | |
| private readonly betterAuthService: BetterAuthService, | |
| private readonly prisma: PrismaService, | |
| ) {} | |
| // βββ Per-socket rate limiting βββββββββββββββββββββ | |
| // The global ThrottlerGuard only applies to HTTP; socket handlers are | |
| // otherwise unlimited. Bound every mutating/room-joining handler, not just | |
| // join:podcast, to prevent connection-based DoS. | |
| private readonly maxJoinsPerWindow = 30; | |
| private readonly joinWindowMs = 60_000; | |
| private readonly maxEventsPerWindow = 120; | |
| private readonly eventWindowMs = 60_000; | |
| private readonly joinTimestamps = new Map<string, number[]>(); | |
| private readonly eventTimestamps = new Map<string, number[]>(); | |
| private isRateLimited( | |
| map: Map<string, number[]>, | |
| socketId: string, | |
| max: number, | |
| windowMs: number, | |
| ): boolean { | |
| const now = Date.now(); | |
| const cutoff = now - windowMs; | |
| const recent = (map.get(socketId) || []).filter((t) => t > cutoff); | |
| if (recent.length >= max) { | |
| map.set(socketId, recent); | |
| return true; | |
| } | |
| recent.push(now); | |
| map.set(socketId, recent); | |
| return false; | |
| } | |
| private isJoinRateLimited(socketId: string): boolean { | |
| return this.isRateLimited( | |
| this.joinTimestamps, | |
| socketId, | |
| this.maxJoinsPerWindow, | |
| this.joinWindowMs, | |
| ); | |
| } | |
| private isEventRateLimited(socketId: string): boolean { | |
| return this.isRateLimited( | |
| this.eventTimestamps, | |
| socketId, | |
| this.maxEventsPerWindow, | |
| this.eventWindowMs, | |
| ); | |
| } | |
| private isValidId(value: unknown, maxLength = 64): value is string { | |
| return ( | |
| typeof value === "string" && | |
| value.length > 0 && | |
| value.length <= maxLength | |
| ); | |
| } | |
| // βββ Admin context resolution βββββββββββββββββββββ | |
| // Mirrors adminPermissionProcedure (trpc.init.ts): explicit adminRole wins, | |
| // legacy isAdmin-only keeps SUPER_ADMIN, neither β not an admin. Never fall | |
| // back to READ_ONLY for role-less callers. | |
| private async resolveAdminContext( | |
| userId: string, | |
| ): Promise<{ | |
| isAdmin: boolean; | |
| adminRole: AdminRole | null; | |
| permissions: Set<AdminPermission>; | |
| } | null> { | |
| const user = await this.prisma.user.findUnique({ | |
| where: { id: userId }, | |
| select: { | |
| isAdmin: true, | |
| adminRole: true, | |
| adminPermissions: true, | |
| suspendedAt: true, | |
| }, | |
| }); | |
| if (!user || user.suspendedAt) return null; | |
| const role = deriveAdminRole({ isAdmin: user.isAdmin, adminRole: user.adminRole }); | |
| if (!role) return null; | |
| const permissions = resolveAdminPermissions( | |
| role, | |
| user.adminPermissions as Record<string, boolean> | null, | |
| ); | |
| return { | |
| isAdmin: !!user.isAdmin, | |
| adminRole: role, | |
| permissions, | |
| }; | |
| } | |
| private hasAdminPermission( | |
| socket: AuthenticatedSocket, | |
| permission: AdminPermission, | |
| ): boolean { | |
| return socket.data.adminPermissions?.has(permission) ?? false; | |
| } | |
| async handleConnection(client: AuthenticatedSocket) { | |
| try { | |
| // Extract token from handshake auth or query | |
| const token = | |
| (client.handshake.auth?.token as string) || | |
| (client.handshake.query?.token as string); | |
| if (!token) { | |
| this.logger.warn(`Connection rejected: no token provided (${client.id})`); | |
| client.emit("auth:error", { message: "Authentication required" }); | |
| client.disconnect(true); | |
| return; | |
| } | |
| // Verify session via Better Auth | |
| const identity = await this.betterAuthService.getSessionFromBearer( | |
| `Bearer ${token}`, | |
| ); | |
| if (!identity) { | |
| this.logger.warn(`Connection rejected: invalid token (${client.id})`); | |
| client.emit("auth:error", { message: "Invalid token" }); | |
| client.disconnect(true); | |
| return; | |
| } | |
| // Resolve admin context for this user (defense in depth; admin-only | |
| // socket events check permissions on each call too). | |
| const adminCtx = await this.resolveAdminContext(identity.userId); | |
| // Store identity on socket | |
| client.data.userId = identity.userId; | |
| if (adminCtx) { | |
| client.data.isAdmin = adminCtx.isAdmin; | |
| client.data.adminRole = adminCtx.adminRole; | |
| client.data.adminPermissions = adminCtx.permissions; | |
| this.logger.log( | |
| `Client connected: ${client.id} (user: ${identity.userId}, admin: ${adminCtx.adminRole ?? "none"})`, | |
| ); | |
| } else { | |
| this.logger.log( | |
| `Client connected: ${client.id} (user: ${identity.userId})`, | |
| ); | |
| } | |
| // Auto-join user room for direct events | |
| client.join(`user:${identity.userId}`); | |
| } catch (error) { | |
| this.logger.warn( | |
| `Connection rejected: auth failed (${client.id}): ${ | |
| error instanceof Error ? error.message : String(error) | |
| }`, | |
| ); | |
| client.emit("auth:error", { message: "Authentication failed" }); | |
| client.disconnect(true); | |
| } | |
| } | |
| handleDisconnect(client: AuthenticatedSocket) { | |
| const userId = client.data?.userId || "unknown"; | |
| this.joinTimestamps.delete(client.id); | |
| this.eventTimestamps.delete(client.id); | |
| this.logger.log(`Client disconnected: ${client.id} (user: ${userId})`); | |
| } | |
| // βββ Client-facing socket events ββββββββββββββββββ | |
| ("join:podcast") | |
| async handleJoinPodcast( | |
| () client: AuthenticatedSocket, | |
| () data: RoomSubscription, | |
| ) { | |
| const userId = client.data?.userId; | |
| if (!userId) { | |
| return { event: "error", message: "Not authenticated" }; | |
| } | |
| if (this.isJoinRateLimited(client.id)) { | |
| return { event: "error", message: "Too many room joins β try again shortly" }; | |
| } | |
| // Validate input shape before touching the DB | |
| const podcastId = data?.podcastId; | |
| if (!this.isValidId(podcastId)) { | |
| return { event: "error", message: "Invalid podcastId" }; | |
| } | |
| // Verify user is a member of this podcast's workspace | |
| const podcast = await this.prisma.podcast.findUnique({ | |
| where: { id: podcastId }, | |
| select: { | |
| workspace: { | |
| select: { | |
| members: { | |
| select: { userId: true }, | |
| }, | |
| }, | |
| }, | |
| }, | |
| }); | |
| const isMember = podcast?.workspace?.members?.some( | |
| (m) => m.userId === userId, | |
| ); | |
| if (!isMember) { | |
| this.logger.warn( | |
| `User ${userId} denied access to podcast room ${podcastId}`, | |
| ); | |
| return { event: "error", message: "Not a member of this podcast" }; | |
| } | |
| const room = `podcast:${podcastId}`; | |
| client.join(room); | |
| this.logger.log(`Client ${client.id} joined room ${room}`); | |
| return { event: "joined", room }; | |
| } | |
| ("leave:podcast") | |
| handleLeavePodcast( | |
| () client: AuthenticatedSocket, | |
| () data: { podcastId: string }, | |
| ) { | |
| const podcastId = data?.podcastId; | |
| if (!this.isValidId(podcastId)) { | |
| return { event: "error", message: "Invalid podcastId" }; | |
| } | |
| const room = `podcast:${podcastId}`; | |
| client.leave(room); | |
| this.logger.log(`Client ${client.id} left room ${room}`); | |
| return { event: "left", room }; | |
| } | |
| ("join:user") | |
| handleJoinUserRoom( | |
| () client: AuthenticatedSocket, | |
| () data: { userId: string }, | |
| ) { | |
| const targetUserId = data?.userId; | |
| if (!this.isValidId(targetUserId, 128)) { | |
| return { event: "error", message: "Invalid userId" }; | |
| } | |
| // Users can only join their own user room | |
| if (client.data?.userId !== targetUserId) { | |
| return { event: "error", message: "Cannot join another user's room" }; | |
| } | |
| const room = `user:${targetUserId}`; | |
| client.join(room); | |
| this.logger.log(`Client ${client.id} joined user room ${room}`); | |
| return { event: "joined", room }; | |
| } | |
| ("leave:user") | |
| handleLeaveUserRoom( | |
| () client: AuthenticatedSocket, | |
| () data: { userId: string }, | |
| ) { | |
| const targetUserId = data?.userId; | |
| if (!this.isValidId(targetUserId, 128)) { | |
| return { event: "error", message: "Invalid userId" }; | |
| } | |
| const room = `user:${targetUserId}`; | |
| client.leave(room); | |
| this.logger.log(`Client ${client.id} left user room ${room}`); | |
| return { event: "left", room }; | |
| } | |
| ("join:workspace") | |
| async handleJoinWorkspace( | |
| () client: AuthenticatedSocket, | |
| () data: { workspaceId: string }, | |
| ) { | |
| const userId = client.data?.userId; | |
| if (!userId) { | |
| return { event: "error", message: "Not authenticated" }; | |
| } | |
| const workspaceId = data?.workspaceId; | |
| if (!this.isValidId(workspaceId)) { | |
| return { event: "error", message: "Invalid workspaceId" }; | |
| } | |
| // Verify user is a member of this workspace | |
| const workspace = await this.prisma.workspace.findUnique({ | |
| where: { id: workspaceId }, | |
| select: { | |
| members: { | |
| where: { userId }, | |
| select: { userId: true }, | |
| }, | |
| }, | |
| }); | |
| const isMember = workspace?.members?.some((m) => m.userId === userId); | |
| if (!isMember) { | |
| this.logger.warn( | |
| `User ${userId} denied access to workspace room ${workspaceId}`, | |
| ); | |
| return { event: "error", message: "Not a member of this workspace" }; | |
| } | |
| const room = `workspace:${workspaceId}`; | |
| client.join(room); | |
| this.logger.log(`Client ${client.id} joined workspace room ${room}`); | |
| return { event: "joined", room }; | |
| } | |
| ("leave:workspace") | |
| handleLeaveWorkspace( | |
| () client: AuthenticatedSocket, | |
| () data: { workspaceId: string }, | |
| ) { | |
| const workspaceId = data?.workspaceId; | |
| if (!this.isValidId(workspaceId)) { | |
| return { event: "error", message: "Invalid workspaceId" }; | |
| } | |
| const room = `workspace:${workspaceId}`; | |
| client.leave(room); | |
| this.logger.log(`Client ${client.id} left workspace room ${room}`); | |
| return { event: "left", room }; | |
| } | |
| // βββ Admin-only socket events βββββββββββββββββββββ | |
| // Require platform-admin permission on every call (defense in depth; | |
| // admin context is also resolved at connection time). | |
| ("admin:broadcast") | |
| async handleAdminBroadcast( | |
| () client: AuthenticatedSocket, | |
| () data: AdminBroadcast, | |
| ) { | |
| const userId = client.data?.userId; | |
| if (!userId) { | |
| return { event: "error", message: "Not authenticated" }; | |
| } | |
| if (this.isEventRateLimited(client.id)) { | |
| return { event: "error", message: "Too many requests β try again shortly" }; | |
| } | |
| if (!this.hasAdminPermission(client, AdminPermission.ANNOUNCEMENTS_WRITE)) { | |
| this.logger.warn( | |
| `User ${userId} attempted admin:broadcast without ANNOUNCEMENTS_WRITE`, | |
| ); | |
| return { event: "error", message: "Insufficient permissions" }; | |
| } | |
| if (!data?.event || typeof data.event !== "string") { | |
| return { event: "error", message: "Invalid event name" }; | |
| } | |
| this.server.emit(data.event, { | |
| ...data.data, | |
| timestamp: new Date().toISOString(), | |
| source: "admin", | |
| actor: userId, | |
| }); | |
| this.logger.log( | |
| `Admin ${userId} broadcast event ${data.event} to all clients`, | |
| ); | |
| return { event: "broadcast-sent", broadcastEvent: data.event }; | |
| } | |
| ("admin:disconnect-user") | |
| async handleAdminDisconnectUser( | |
| () client: AuthenticatedSocket, | |
| () data: AdminDisconnectUser, | |
| ) { | |
| const userId = client.data?.userId; | |
| if (!userId) { | |
| return { event: "error", message: "Not authenticated" }; | |
| } | |
| if (this.isEventRateLimited(client.id)) { | |
| return { event: "error", message: "Too many requests β try again shortly" }; | |
| } | |
| if (!this.hasAdminPermission(client, AdminPermission.USERS_SUSPEND)) { | |
| this.logger.warn( | |
| `User ${userId} attempted admin:disconnect-user without USERS_SUSPEND`, | |
| ); | |
| return { event: "error", message: "Insufficient permissions" }; | |
| } | |
| const targetUserId = data?.userId; | |
| if (!this.isValidId(targetUserId, 128)) { | |
| return { event: "error", message: "Invalid userId" }; | |
| } | |
| if (targetUserId === userId) { | |
| return { event: "error", message: "Cannot disconnect yourself" }; | |
| } | |
| // Disconnect all sockets belonging to the target user | |
| const sockets = this.server.sockets.sockets; | |
| let disconnected = 0; | |
| for (const [id, socket] of sockets) { | |
| const authenticated = socket as AuthenticatedSocket; | |
| if (authenticated.data?.userId === targetUserId) { | |
| authenticated.disconnect(true); | |
| disconnected++; | |
| } | |
| } | |
| this.logger.log( | |
| `Admin ${userId} force-disconnected ${disconnected} socket(s) for user ${targetUserId}`, | |
| ); | |
| return { | |
| event: "user-disconnected", | |
| targetUserId, | |
| disconnected, | |
| reason: data.reason ?? undefined, | |
| }; | |
| } | |
| ("admin:rooms") | |
| async handleAdminRooms( | |
| () client: AuthenticatedSocket, | |
| ) { | |
| const userId = client.data?.userId; | |
| if (!userId) { | |
| return { event: "error", message: "Not authenticated" }; | |
| } | |
| if (this.isEventRateLimited(client.id)) { | |
| return { event: "error", message: "Too many requests β try again shortly" }; | |
| } | |
| if ( | |
| !this.hasAdminPermission(client, AdminPermission.OPS_READ) && | |
| !client.data.isAdmin | |
| ) { | |
| this.logger.warn( | |
| `User ${userId} attempted admin:rooms without OPS_READ`, | |
| ); | |
| return { event: "error", message: "Insufficient permissions" }; | |
| } | |
| // Build a snapshot of active rooms and their occupant counts | |
| const rooms: Record<string, number> = {}; | |
| for (const [room, clients] of this.server.sockets.adapter.rooms) { | |
| // Skip the socket's own id entries (adapter rooms include socket ids) | |
| if (clients.size === 0) continue; | |
| // Only include named rooms (not socket.id rooms) | |
| if (!this.server.sockets.sockets.has(room)) { | |
| rooms[room] = clients.size; | |
| } | |
| } | |
| const adminCtx = client.data.adminRole ?? "none"; | |
| this.logger.log( | |
| `Admin ${userId} (${adminCtx}) listed ${Object.keys(rooms).length} active rooms`, | |
| ); | |
| return { | |
| event: "rooms", | |
| rooms, | |
| connectedClients: this.server.sockets.sockets.size, | |
| timestamp: new Date().toISOString(), | |
| }; | |
| } | |
| // βββ Server-side event emitters ββββββββββββββββββββ | |
| notifyGuestStatusChange(podcastId: string, guestId: string, status: string) { | |
| this.server.to(`podcast:${podcastId}`).emit("guest:status-changed", { | |
| guestId, | |
| status, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyNewBooking(podcastId: string, booking: Record<string, unknown>) { | |
| this.server.to(`podcast:${podcastId}`).emit("booking:created", { | |
| booking, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyAssetSubmitted(podcastId: string, submission: Record<string, unknown>) { | |
| this.server.to(`podcast:${podcastId}`).emit("asset:submitted", { | |
| submission, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyOutreachEvent( | |
| podcastId: string, | |
| event: string, | |
| data: Record<string, unknown>, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit(`outreach:${event}`, { | |
| ...data, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyEpisodeUpdate(podcastId: string, episode: Record<string, unknown>) { | |
| this.server.to(`podcast:${podcastId}`).emit("episode:updated", { | |
| episode, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Network / Trust Score Events βββββββββββββββββ | |
| notifyTrustScoreChanged( | |
| podcastId: string, | |
| profileId: string, | |
| oldScore: number, | |
| newScore: number, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("network:trust-score-changed", { | |
| profileId, | |
| oldScore, | |
| newScore, | |
| delta: newScore - oldScore, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyBadgeGranted( | |
| podcastId: string, | |
| profileId: string, | |
| badgeType: string, | |
| trustScoreImpact: number, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("network:badge-granted", { | |
| profileId, | |
| badgeType, | |
| trustScoreImpact, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyBadgeRevoked( | |
| podcastId: string, | |
| profileId: string, | |
| badgeType: string, | |
| trustScoreImpact: number, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("network:badge-revoked", { | |
| profileId, | |
| badgeType, | |
| trustScoreImpact, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyVerificationStatusChanged( | |
| podcastId: string, | |
| profileId: string, | |
| oldStatus: string, | |
| newStatus: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("network:verification-status-changed", { | |
| profileId, | |
| oldStatus, | |
| newStatus, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyNetworkBookingUpdate( | |
| podcastId: string, | |
| bookingId: string, | |
| status: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("network:booking-status-changed", { | |
| bookingId, | |
| status, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ In-app Notification broadcast ββββββββββββββββββ | |
| notifyInAppNotification(podcastId: string, data: Record<string, unknown>) { | |
| this.server.to(`podcast:${podcastId}`).emit("notification:in-app", { | |
| ...data, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Export progress events βββββββββββββββββββββββββ | |
| notifyExportProgress( | |
| userId: string, | |
| exportJobId: string, | |
| clipId: string, | |
| platform: string, | |
| progress: number, | |
| ) { | |
| this.server.to(`user:${userId}`).emit("export:progress", { | |
| exportJobId, | |
| clipId, | |
| platform, | |
| progress, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyExportCompleted( | |
| userId: string, | |
| exportJobId: string, | |
| clipId: string, | |
| platform: string, | |
| cdnUrl: string, | |
| ) { | |
| this.server.to(`user:${userId}`).emit("export:completed", { | |
| exportJobId, | |
| clipId, | |
| platform, | |
| cdnUrl, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyExportFailed( | |
| userId: string, | |
| exportJobId: string, | |
| clipId: string, | |
| platform: string, | |
| error: string, | |
| ) { | |
| this.server.to(`user:${userId}`).emit("export:failed", { | |
| exportJobId, | |
| clipId, | |
| platform, | |
| error, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ User-targeted events (direct to a user's socket) βββ | |
| emitToUser(userId: string, event: string, data: Record<string, unknown>) { | |
| this.server.to(`user:${userId}`).emit(event, { | |
| ...data, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Recording Pipeline Events ββββββββββββββββββββββββββ | |
| notifyRecordingSessionStarted( | |
| podcastId: string, | |
| sessionId: string, | |
| episodeId: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("recording:session-started", { | |
| sessionId, | |
| episodeId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyRecordingSessionCompleted( | |
| podcastId: string, | |
| sessionId: string, | |
| episodeId: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("recording:session-completed", { | |
| sessionId, | |
| episodeId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyRecordingTrackCreated( | |
| podcastId: string, | |
| sessionId: string, | |
| trackId: string, | |
| guestId: string | null, | |
| isHost: boolean, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("recording:track-created", { | |
| sessionId, | |
| trackId, | |
| guestId, | |
| isHost, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Live Stream Events βββββββββββββββββββββββββββββββββ | |
| notifyStreamStarted( | |
| podcastId: string, | |
| room: string, | |
| episodeId: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("stream:started", { | |
| room, | |
| episodeId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyStreamEnded( | |
| podcastId: string, | |
| room: string, | |
| episodeId: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("stream:ended", { | |
| room, | |
| episodeId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyParticipantJoined( | |
| podcastId: string, | |
| room: string, | |
| identity: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("stream:participant-joined", { | |
| room, | |
| identity, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyParticipantLeft( | |
| podcastId: string, | |
| room: string, | |
| identity: string, | |
| ) { | |
| this.server.to(`podcast:${podcastId}`).emit("stream:participant-left", { | |
| room, | |
| identity, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Support Ticket Events βββββββββββββββββββββββββββ | |
| notifyTicketCreated( | |
| workspaceId: string, | |
| ticket: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("ticket:created", { | |
| ticket, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyTicketAssigned( | |
| workspaceId: string, | |
| ticketId: string, | |
| agentId: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("ticket:assigned", { | |
| ticketId, | |
| agentId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| this.server.to(`user:${agentId}`).emit("ticket:assigned", { | |
| ticketId, | |
| agentId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyNewMessage( | |
| workspaceId: string, | |
| ticketId: string, | |
| message: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("ticket:new-message", { | |
| ticketId, | |
| message, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyTicketStatusChanged( | |
| workspaceId: string, | |
| ticketId: string, | |
| status: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("ticket:status-changed", { | |
| ticketId, | |
| status, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyCsatRequested( | |
| userId: string, | |
| ticketId: string, | |
| rating: number, | |
| ) { | |
| this.server.to(`user:${userId}`).emit("ticket:csat-requested", { | |
| ticketId, | |
| rating, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Cal.com Booking Events ββββββββββββββββββββββββββ | |
| notifyCalComBookingCreated( | |
| workspaceId: string, | |
| booking: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:created", { | |
| booking, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyCalComBookingCancelled( | |
| workspaceId: string, | |
| bookingId: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:cancelled", { | |
| bookingId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyCalComBookingRescheduled( | |
| workspaceId: string, | |
| bookingId: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:rescheduled", { | |
| bookingId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Documenso Document Events βββββββββββββββββββββββββ | |
| notifyDocumensoDocumentSent( | |
| workspaceId: string, | |
| document: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("documenso:document:sent", { | |
| document, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyDocumensoDocumentStatusChanged( | |
| workspaceId: string, | |
| documentId: string | number, | |
| status: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("documenso:document:status-changed", { | |
| documentId, | |
| status, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Document Management Events βββββββββββββββββββββββββ | |
| notifyDocumentUploaded( | |
| workspaceId: string, | |
| document: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("document:uploaded", { | |
| document, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyDocumentShared( | |
| workspaceId: string, | |
| share: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("document:shared", { | |
| share, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyDocumentRevoked( | |
| workspaceId: string, | |
| shareId: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("document:revoked", { | |
| shareId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyDocumentTamperingDetected( | |
| workspaceId: string, | |
| documentId: string, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("document:tampering-detected", { | |
| documentId, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| // βββ Listmonk Newsletter Events ββββββββββββββββββββββββ | |
| notifyListmonkSubscriberAdded( | |
| workspaceId: string, | |
| subscriber: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("listmonk:subscriber:added", { | |
| subscriber, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| notifyListmonkCampaignSent( | |
| workspaceId: string, | |
| campaign: Record<string, unknown>, | |
| ) { | |
| this.server.to(`workspace:${workspaceId}`).emit("listmonk:campaign:sent", { | |
| campaign, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| } | |
| } | |