|
|
|
import * as config from './config';
|
|
|
|
import * as storage from './storage';
|
|
|
|
import * as http_server from './http';
|
|
|
|
import * as des from './deserializer';
|
|
|
|
import * as send from './send';
|
|
|
|
import * as recv from './recv';
|
|
|
|
|
|
|
|
import { MESSAGE, EVENT, SESSION } from './enums';
|
|
|
|
import { sessions, desks } from './storage';
|
|
|
|
|
|
|
|
export function startup() {
|
|
|
|
Bun.serve({
|
|
|
|
hostname: config.HOST,
|
|
|
|
port: config.PORT,
|
|
|
|
|
|
|
|
fetch(req, server) {
|
|
|
|
const url = new URL(req.url);
|
|
|
|
|
|
|
|
if (url.pathname == '/ws/') {
|
|
|
|
const desk_id = url.searchParams.get('deskId') || '0';
|
|
|
|
const session_id = url.searchParams.get('sessionId') || '0';
|
|
|
|
|
|
|
|
if (!(desk_id in desks)) {
|
|
|
|
const desk = {
|
|
|
|
id: desk_id,
|
|
|
|
sn: 0,
|
|
|
|
events: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
storage.queries.insert_desk.run({
|
|
|
|
'$id': desk_id,
|
|
|
|
'$title': `Desk ${desk_id}`
|
|
|
|
});
|
|
|
|
|
|
|
|
desks[desk_id] = desk;
|
|
|
|
}
|
|
|
|
|
|
|
|
server.upgrade(req, {
|
|
|
|
data: {
|
|
|
|
desk_id: desk_id,
|
|
|
|
session_id: session_id,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
return http_server.route(req);
|
|
|
|
},
|
|
|
|
|
|
|
|
websocket: {
|
|
|
|
open(ws) {
|
|
|
|
send.send_init(ws);
|
|
|
|
const userjoin_event = {'type': EVENT.USER_JOINED, 'user_id': ws.data.session_id};
|
|
|
|
send.fire_event(sessions[ws.data.session_id], userjoin_event);
|
|
|
|
},
|
|
|
|
|
|
|
|
async message(ws, u8array) {
|
|
|
|
const dataview = new DataView(u8array.buffer);
|
|
|
|
const d = des.create(dataview);
|
|
|
|
recv.handle_message(ws, d);
|
|
|
|
},
|
|
|
|
|
|
|
|
close(ws, code, message) {
|
|
|
|
if (ws.data.session_id in sessions) {
|
|
|
|
const leave_event = {'type': EVENT.LEAVE, 'user_id': ws.data.session_id};
|
|
|
|
send.fire_event(sessions[ws.data.session_id], leave_event);
|
|
|
|
console.log(`session ${ws.data.session_id} closed`);
|
|
|
|
sessions[ws.data.session_id].state = SESSION.CLOSED;
|
|
|
|
sessions[ws.data.session_id].ws = null;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
error(ws, error) {
|
|
|
|
close(ws, 1000, error); // Treat error as normal close
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
console.log(`Running on ${config.HOST}:${config.PORT}`)
|
|
|
|
}
|