2023-03-05 19:57:05 +01:00
|
|
|
import authorized from "../middleware/authorized"
|
|
|
|
import Socket from "./websocket"
|
|
|
|
import { permissions } from "@budibase/backend-core"
|
|
|
|
import http from "http"
|
|
|
|
import Koa from "koa"
|
|
|
|
|
2023-04-20 09:02:49 +02:00
|
|
|
export default class GridSocket extends Socket {
|
2023-03-05 19:57:05 +01:00
|
|
|
constructor(app: Koa, server: http.Server) {
|
2023-04-20 09:02:49 +02:00
|
|
|
super(app, server, "/socket/grid", [authorized(permissions.BUILDER)])
|
2023-03-05 19:57:05 +01:00
|
|
|
|
|
|
|
this.io.on("connection", socket => {
|
|
|
|
const user = socket.data.user
|
2023-04-18 11:46:35 +02:00
|
|
|
console.log(`Spreadsheet user connected: ${user?.id}`)
|
2023-03-06 08:43:45 +01:00
|
|
|
|
|
|
|
// Socket state
|
|
|
|
let currentRoom: string
|
2023-03-05 19:57:05 +01:00
|
|
|
|
2023-04-18 11:46:35 +02:00
|
|
|
// Initial identification of connected spreadsheet
|
|
|
|
socket.on("select-table", async (tableId, callback) => {
|
2023-03-06 12:20:47 +01:00
|
|
|
// Leave current room
|
2023-03-06 08:43:45 +01:00
|
|
|
if (currentRoom) {
|
2023-03-06 12:20:47 +01:00
|
|
|
socket.to(currentRoom).emit("user-disconnect", socket.data.user)
|
2023-03-06 08:43:45 +01:00
|
|
|
socket.leave(currentRoom)
|
|
|
|
}
|
2023-03-06 12:20:47 +01:00
|
|
|
|
|
|
|
// Join new room
|
2023-03-06 08:43:45 +01:00
|
|
|
currentRoom = tableId
|
2023-03-06 12:20:47 +01:00
|
|
|
socket.join(currentRoom)
|
|
|
|
socket.to(currentRoom).emit("user-update", socket.data.user)
|
2023-03-06 08:43:45 +01:00
|
|
|
|
2023-03-06 12:20:47 +01:00
|
|
|
// Reply with all users in current room
|
|
|
|
const sockets = await this.io.in(currentRoom).fetchSockets()
|
2023-03-06 08:43:45 +01:00
|
|
|
callback({
|
|
|
|
users: sockets.map(socket => socket.data.user),
|
|
|
|
id: user.id,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2023-03-06 12:20:47 +01:00
|
|
|
// Handle users selecting a new cell
|
2023-03-06 08:43:45 +01:00
|
|
|
socket.on("select-cell", cellId => {
|
|
|
|
socket.data.user.selectedCellId = cellId
|
2023-03-06 12:20:47 +01:00
|
|
|
if (currentRoom) {
|
|
|
|
socket.to(currentRoom).emit("user-update", socket.data.user)
|
|
|
|
}
|
2023-03-05 19:57:05 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
// Disconnection cleanup
|
2023-03-06 12:20:47 +01:00
|
|
|
socket.on("disconnect", () => {
|
|
|
|
if (currentRoom) {
|
|
|
|
socket.to(currentRoom).emit("user-disconnect", socket.data.user)
|
|
|
|
}
|
2023-03-05 19:57:05 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|