Skip to content

Commit

Permalink
remove unused code: rooms, log, d3, call
Browse files Browse the repository at this point in the history
  • Loading branch information
dankoster committed Dec 17, 2024
1 parent be332d6 commit f7b4bea
Show file tree
Hide file tree
Showing 9 changed files with 12 additions and 828 deletions.
205 changes: 5 additions & 200 deletions server/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request } from "jsr:@oak/oak@17/request";
import { Router } from "jsr:@oak/oak@17/router";
import * as db from "./db.ts";
import type { SSEvent, AuthTokenName, ApiRoute, Room, Connection, Identity, Update, DM, DMRequest } from "./types.ts";
import type { SSEvent, AuthTokenName, ApiRoute, Connection, Identity, Update, DM, DMRequest } from "./types.ts";
import { onLocalBuild } from "./localHelper.ts";

export { api }
Expand All @@ -10,15 +10,12 @@ const sseEvent: { [Property in SSEvent]: Property } = {
pk: "pk",
id: "id",
webRTC: "webRTC",
rooms: "rooms",
connections: "connections",
refresh: "refresh",
reconnect: "reconnect",
new_connection: "new_connection",
delete_connection: "delete_connection",
update: "update",
new_room: "new_room",
delete_room: "delete_room",
friendRequest: "friendRequest",
friendList: "friendList",
friendRequests: "friendRequests",
Expand All @@ -35,8 +32,6 @@ const apiRoute: { [Property in ApiRoute]: Property } = {
clear: "clear",
discardKey: "discardKey",
webRTC: "webRTC",
room: "room",
"room/join": "room/join",
becomeAnonymous: "becomeAnonymous",
log: "log",
friendRequest: "friendRequest",
Expand All @@ -51,16 +46,13 @@ const apiRoute: { [Property in ApiRoute]: Property } = {

//server is starting up... cleanup and then get persisted data
db.serverInitAndCleanup()
const roomByUUID = db.getRoomsByUUID() ?? new Map<string, Room>()
const connectionByUUID = db.getConnectionsByUUID() ?? new Map<string, Connection>()
const wsByUUID = new Map<string, WebSocket>()
const updateFunctionByUUID = new Map<string, {
isLocal: boolean,
update: (event: SSEvent, value?: string) => void,
}>()

// console.log('got rooms', roomByUUID)
// console.log('got connections', connectionByUUID)

if (Deno.env.get('ENVIRONMENT') === 'local') {
console.log('LOCAL BUILD watching for frontend changes...')
Expand All @@ -71,8 +63,6 @@ if (Deno.env.get('ENVIRONMENT') === 'local') {
})
}

db.log({ action: 'INIT', note: `${connectionByUUID.size} connections, ${roomByUUID.size} rooms` })

export function validateConnectionByUUID(uuid: string) {
return connectionByUUID.has(uuid)
}
Expand All @@ -82,7 +72,6 @@ export async function addConnectionIdentity(uuid: string, identity: Identity) {
con.identity = identity

const result = db.persistConnection(uuid, con)
db.log({ action: "addConnectionIdentity", uuid, identityId: result?.identity?.id })

con.identity.id = result?.identity?.id
console.log("addConnectionIdentity", con)
Expand All @@ -105,7 +94,7 @@ function sseMessage(event: SSEvent, data?: string, id?: string) {
return new TextEncoder().encode(msg);
}

function notifyAllConnections(event: SSEvent, update: Update | Room | Connection, options?: { excludeUUID?: string }) {
function notifyAllConnections(event: SSEvent, update: Update | Connection, options?: { excludeUUID?: string }) {
updateFunctionByUUID.forEach((fn, uuidToUpdate) => {
if (!options?.excludeUUID || options?.excludeUUID !== uuidToUpdate) {
console.log(event.toUpperCase(), uuidToUpdate, update)
Expand Down Expand Up @@ -149,26 +138,6 @@ function objectFrom<V>(map: Map<string, V>) {
return obj;
}

function deleteRoom(room: Room) {
//kick all users from the room
console.log("deleteRoom: kick all users!")
connectionByUUID.forEach((con, uuid) => {
if (con.roomId === room.id) {
delete con.roomId;
db.persistConnection(uuid, con)
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: "roomId",
value: ""
});
}
});

db.deleteRoom(room)
roomByUUID.delete(room.id)
notifyAllConnections(sseEvent.delete_room, room)
}

function event(req: Request) {
return `${req.method} ${req.url.pathname}`.toUpperCase()
}
Expand Down Expand Up @@ -253,114 +222,6 @@ api.post(`/${apiRoute.webRTC}/:userId`, async (ctx) => {
ctx.response.status = 200 //success!
})

//Join room by id
api.post(`/${apiRoute["room/join"]}/:id`, async (ctx) => {
const roomId = ctx.params.id
console.log("[JOIN ROOM] POST", apiRoute.room.toUpperCase(), roomId)
const uuid = ctx.request.headers.get(AUTH_TOKEN_HEADER_NAME);
if (!uuid) throw new Error(`Missing ${AUTH_TOKEN_HEADER_NAME} header`);

const con = connectionByUUID.get(uuid)
if (!con) {
ctx.response.status = 401 //unauthenticated
return
}

const room = roomByUUID.get(roomId)
if (!room) {
ctx.response.status = 404
return
}

con.roomId = room?.id
db.persistConnection(uuid, con)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: room.id })
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: "roomId",
value: room.id
})

ctx.response.status = 200
})

//Create a room
api.post(`/${apiRoute.room}`, async (ctx) => {

console.log("POST", apiRoute.room.toUpperCase())
const uuid = ctx.request.headers.get(AUTH_TOKEN_HEADER_NAME);
if (!uuid) throw new Error(`Missing ${AUTH_TOKEN_HEADER_NAME} header`);

const con = connectionByUUID.get(uuid)
if (!con) throw new Error(`${uuid} not found in ${[...connectionByUUID.keys()]}`)

const room: Room = {
id: crypto.randomUUID(),
ownerId: con.id,
}

con.roomId = room.id
db.persistRoom(room)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: room.id })
roomByUUID.set(room.id, room)

db.persistConnection(uuid, con)
notifyAllConnections(sseEvent.new_room, room)
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: "roomId",
value: room.id
})

ctx.response.body = JSON.stringify(room)
})

//exit room (the room is deleted if the owner leaves)
api.delete(`/${apiRoute.room}/:id`, async (ctx) => {
console.log("DELETE", apiRoute.room.toUpperCase(), ctx.params)
const uuid = ctx.request.headers.get(AUTH_TOKEN_HEADER_NAME);
if (!uuid) throw new Error(`Missing ${AUTH_TOKEN_HEADER_NAME} header`);

const con = connectionByUUID.get(uuid)
if (!con) {
ctx.response.status = 401 //unauthenticated
return
}

//remove the room reference regardless (we're leaving the room)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
delete con.roomId
db.persistConnection(uuid, con)
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: "roomId",
value: ""
})
ctx.response.status = 200 //but we did successfully leave the room

//are we the owner? Nuke it!
const room = roomByUUID.get(ctx.params.id)
if (room && room.ownerId == con.id) {
deleteRoom(room);
ctx.response.body = room
ctx.response.status = 200
}
})

//Get room by id
api.get(`/${apiRoute.room}/:id`, async (ctx) => {
const uuid = ctx.request.headers.get(AUTH_TOKEN_HEADER_NAME);
if (!uuid) throw new Error(`Missing ${AUTH_TOKEN_HEADER_NAME} header`);

const con = connectionByUUID.get(uuid)
if (!con) {
ctx.response.status = 401 //unauthenticated
return
}

ctx.response.body = roomByUUID.get(ctx.params.id)
})

//nuke it from orbit
api.post(`/${apiRoute.clear}/:key`, async (ctx) => {
//do we have the correct bearer token for this?
Expand All @@ -371,24 +232,20 @@ api.post(`/${apiRoute.clear}/:key`, async (ctx) => {

//here's what we're deleting...
const oldData = objectFrom(connectionByUUID);
console.log("CLEAR", oldData, roomByUUID)
console.log("CLEAR", oldData)
ctx.response.body = oldData

roomByUUID.forEach(room => db.deleteRoom(room))
connectionByUUID.forEach((con, uuid) => db.deleteConnection(uuid))
db.log({ action: event(ctx.request), note: 'key:' + ctx.params.key })

//reinit with empty everything
connectionByUUID.clear()
roomByUUID.clear()

//tell all clients to reconnect
updateFunctionByUUID.forEach(updater => updater.update(sseEvent.reconnect))
})

api.post(`/${apiRoute.friendRequest}`, async (ctx) => {
const { uuid, con: requestor } = getConnection(ctx.request);
db.log({ action: event(ctx.request), uuid, identityId: requestor.identity?.id })

const requesteeId = await ctx.request.body.text()
let requestee = getConnectionById(requesteeId);
Expand Down Expand Up @@ -422,8 +279,6 @@ api.post(`/${apiRoute.acceptFriendRequest}`, async (ctx) => {
const { uuid: requesteeUuid, con } = getConnection(ctx.request);
const friendRequestId = await ctx.request.body.text()

db.log({ action: event(ctx.request), uuid: requesteeUuid, identityId: con.identity?.id, note: friendRequestId })

if (!friendRequestId) throw new Error(`friend request id ${friendRequestId} not found`)

const result = db.acceptFriendRequest(friendRequestId)
Expand Down Expand Up @@ -451,7 +306,6 @@ api.post(`/${apiRoute.acceptFriendRequest}`, async (ctx) => {
api.post(`/${apiRoute.becomeAnonymous}`, async (ctx) => {
try {
const { uuid, con } = getConnection(ctx.request);
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id })
delete con.identity
db.persistConnection(uuid, con)
notifyAllConnections(sseEvent.update, {
Expand All @@ -475,7 +329,6 @@ api.post(`/${apiRoute.setText}`, async (ctx) => {
const { uuid, con } = getConnection(ctx.request)
con.text = text
db.persistConnection(uuid, con)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: 'text',
Expand All @@ -497,7 +350,6 @@ api.post(`/${apiRoute.setColor}`, async (ctx) => {
const { uuid, con } = getConnection(ctx.request)
con.color = color
db.persistConnection(uuid, con)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
notifyAllConnections(sseEvent.update, {
connectionId: con.id,
field: 'color',
Expand All @@ -513,7 +365,6 @@ api.post(`/${apiRoute.setColor}`, async (ctx) => {

api.post(`/${apiRoute.publicKey}`, async (ctx) => {
const { uuid, con } = getConnection(ctx.request)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
const publicKey = await ctx.request.body.text()

if (!publicKey) {
Expand All @@ -534,8 +385,7 @@ api.post(`/${apiRoute.publicKey}`, async (ctx) => {
})

api.post(`/${apiRoute.dmHistory}`, async (ctx) => {
const { uuid, con } = getConnection(ctx.request)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
const { uuid } = getConnection(ctx.request)

const dmRequest = await ctx.request.body.json() as DMRequest
//a null timestamp converts to 0 which is 1970-01-01T00:00:00.000Z
Expand All @@ -562,8 +412,7 @@ api.post(`/${apiRoute.dmHistory}`, async (ctx) => {
})

api.post(`/${apiRoute.dmUnread}`, async (ctx) => {
const { uuid, con } = getConnection(ctx.request)
db.log({ action: event(ctx.request), uuid, identityId: con.identity?.id, roomId: con.roomId })
const { uuid } = getConnection(ctx.request)

const dmRequest = await ctx.request.body.json() as DMRequest

Expand All @@ -589,13 +438,8 @@ api.post(`/${apiRoute.dmUnread}`, async (ctx) => {

api.post(`/${apiRoute.dm}`, async (ctx) => {
try {
const action = event(ctx.request)
console.log(action)
const { uuid: fromUuid, con: fromCon } = getConnection(ctx.request)
db.log({ action, uuid: fromUuid, identityId: fromCon.identity?.id, roomId: fromCon.roomId })

const message = await ctx.request.body.json() as DM

const toCon = getConnectionById(message.toId)
if (!toCon) {
ctx.response.status = 404
Expand Down Expand Up @@ -636,7 +480,6 @@ api.post(`/${apiRoute.dm}`, async (ctx) => {
message.fromId = fromCon.id
message.fromName = fromCon.identity?.name
message.timestamp = (persistedDm.timestamp ?? 0) * 1000 //we don't need a subsecond timestamp on the frontend
// console.log('DM SAVED', `${message.timestamp}: ${message.fromId} -> ${message.toId}`)

ctx.response.status = 200
ctx.response.body = message
Expand All @@ -653,7 +496,6 @@ api.post(`/${apiRoute.dm}`, async (ctx) => {
const updateFn = updateFunctionByUUID.get(uuid)
if (updateFn) {
updateFn.update(sseEvent.dm, JSON.stringify(message))
console.log('DM updating', con.identity?.name, con.kind)
}
}
})
Expand Down Expand Up @@ -692,14 +534,6 @@ api.get(`/${apiRoute.sse}`, async (context) => {

try {
db.persistConnection(uuid, connection)
db.log({
action: event(context.request),
uuid,
identityId: connection?.identity?.id,
ip: context.request.ip,
userAgent: context.request.userAgent.os.name,
note: `CONNECT (${old ? "known" : "new"})`
})
} catch (error) {
console.error(error)
return
Expand All @@ -720,7 +554,6 @@ api.get(`/${apiRoute.sse}`, async (context) => {
controller.enqueue(sseMessage(sseEvent.id, connection.id))
controller.enqueue(sseMessage(sseEvent.pk, uuid))
controller.enqueue(sseMessage(sseEvent.connections, JSON.stringify(Array.from(connectionByUUID.values()))))
controller.enqueue(sseMessage(sseEvent.rooms, JSON.stringify(Array.from(roomByUUID.values()))))

if (connection.identity?.id) {
const friends = db.getFriendsByIdentityId(connection.identity?.id)
Expand Down Expand Up @@ -749,34 +582,6 @@ api.get(`/${apiRoute.sse}`, async (context) => {
if (!connection)
throw new Error(`orphan disconnected! ${uuid}}`)

//are we disconnecting while we have a room open?
if (connection.roomId) {
const room = roomByUUID.get(connection.roomId)

//do we own the room? Nuke it!
if (room && room.ownerId === connection.id) {
console.log('owner disconnected from room', room.id)
deleteRoom(room)
}

//we're also leaving the room
delete connection.roomId
db.persistConnection(uuid, connection)
db.log({
action: event(context.request),
uuid,
identityId: connection?.identity?.id,
ip: context.request.ip,
userAgent: context.request.userAgent.toString(),
note: `DISCONNECT`
})
notifyAllConnections(sseEvent.update, {
connectionId: connection.id,
field: "roomId",
value: ""
})
}

//console.log("SSE Disconnect ", uuid, connection)
connection.status = ""

Expand Down
Loading

0 comments on commit f7b4bea

Please sign in to comment.