cleaning a bunch and adding in the right handlers for sockets much cleaner

This commit is contained in:
talksik
2022-05-14 08:15:34 -05:00
parent ad01220628
commit 7b70c4b023
8 changed files with 257 additions and 330 deletions
+62 -61
View File
@@ -1,24 +1,21 @@
import { JwtClaims, authCheck } from "../middleware/auth";
import {
Line,
LineMember,
LineMemberState,
} from "@nirvana/core/models/line.model";
import express, { Application, Request, Response } from "express";
import { JwtClaims, authCheck } from '../middleware/auth';
import { Line, LineMember, LineMemberState } from '@nirvana/core/models/line.model';
import express, { Application, Request, Response } from 'express';
import Content from "@nirvana/core/models/content.model";
import CreateLineRequest from "@nirvana/core/requests/createLine.request";
import GetConversationDetailsResponse from "@nirvana/core/responses/getConversationDetails.response";
import GetDmConversationByOtherUserIdResponse from "@nirvana/core/responses/getDmConversationByOtherUserId.response";
import GetUserLinesResponse from "@nirvana/core/responses/getUserLines.response";
import { LineService } from "../services/line.service";
import MasterLineData from "@nirvana/core/models/masterLineData.model";
import NirvanaResponse from "../../core/responses/nirvanaResponse";
import { ObjectId } from "mongodb";
import Relationship from "@nirvana/core/models/relationship.model";
import { User } from "@nirvana/core/models/user.model";
import { UserService } from "../services/user.service";
import { collections } from "../services/database.service";
import Content from '@nirvana/core/models/content.model';
import CreateLineRequest from '@nirvana/core/requests/createLine.request';
import GetConversationDetailsResponse from '@nirvana/core/responses/getConversationDetails.response';
import GetDmConversationByOtherUserIdResponse from '@nirvana/core/responses/getDmConversationByOtherUserId.response';
import GetUserLinesResponse from '@nirvana/core/responses/getUserLines.response';
import { LineService } from '../services/line.service';
import MasterLineData from '@nirvana/core/models/masterLineData.model';
import NirvanaResponse from '@nirvana/core/responses/nirvanaResponse';
import { ObjectId } from 'mongodb';
import Relationship from '@nirvana/core/models/relationship.model';
import { User } from '@nirvana/core/models/user.model';
import { UserService } from '../services/user.service';
import { collections } from '../services/database.service';
import UpdateLineMemberState from '@nirvana/core/requests/updateLineMemberState.request';
export default function getLineRoutes() {
const router = express.Router();
@@ -29,13 +26,16 @@ export default function getLineRoutes() {
// router.get("/:otherUserGoogleUserId", authCheck, getConversationDetails);
// create a line
router.post("/", authCheck, createLine);
router.post('/', authCheck, createLine);
// get all of user's lines
router.get("/", authCheck, getUserLines);
router.get('/', authCheck, getUserLines);
// toggle tune into a line
router.post('/:lineId/state', authCheck, updateLineMemberState);
// get conversation between user and other user
router.get("/dm/:otherUserId", authCheck, getDmByOtherUserId);
router.get('/dm/:otherUserId', authCheck, getDmByOtherUserId);
return router;
}
@@ -54,7 +54,7 @@ async function getDmByOtherUserId(req: Request, res: Response) {
res.status(200).json();
return;
res.status(205).json("no such conversation between you two");
res.status(205).json('no such conversation between you two');
} catch (error) {
res.status(500).json(error);
}
@@ -66,7 +66,7 @@ async function createLine(req: Request, res: Response) {
console.log(req.body);
if (!reqObj?.otherMemberIds.length) {
res.status(400).json("must provide member Ids");
res.status(400).json('must provide member Ids');
return;
}
@@ -77,7 +77,7 @@ async function createLine(req: Request, res: Response) {
reqObj.lineName ?? undefined,
new Date(),
new Date(),
new ObjectId()
new ObjectId(),
);
// TODO: validate that users exists before creating line members
@@ -86,67 +86,74 @@ async function createLine(req: Request, res: Response) {
const newLineMember = new LineMember(
newLine._id!,
new ObjectId(memId),
LineMemberState.INBOX
LineMemberState.INBOX,
);
return newLineMember;
}) ?? [];
lineMembers.push(
new LineMember(
newLine._id!,
new ObjectId(userInfo.userId),
LineMemberState.INBOX
)
new LineMember(newLine._id!, new ObjectId(userInfo.userId), LineMemberState.INBOX),
);
const transactionResult = await LineService.createLine(
newLine,
lineMembers
);
const transactionResult = await LineService.createLine(newLine, lineMembers);
transactionResult
? res.status(200).json(new NirvanaResponse(newLine))
: res
.status(400)
.json(
new NirvanaResponse(undefined, new Error("unable to create line"))
);
: res.status(400).json(new NirvanaResponse(undefined, new Error('unable to create line')));
} catch (error) {
console.log(error);
res.status(500).json(error);
}
}
async function updateLineMemberState(req: Request, res: Response) {
try {
const userInfo = res.locals.userInfo as JwtClaims;
const { lineId } = req.params;
const request = req.body as UpdateLineMemberState;
// TODO: validation to check if user is actually a member of the line
const result = await LineService.updateLineMemberState(
lineId,
userInfo.userId,
request.newState,
);
return result?.ok
? res.status(200).json(new NirvanaResponse("successfully updated line member's state"))
: res
.status(400)
.json(new NirvanaResponse(undefined, new Error('not updated...something went wrong')));
} catch (error) {
res.status(500).json(new NirvanaResponse(undefined, error as Error));
}
}
async function getUserLines(req: Request, res: Response) {
try {
const userInfo = res.locals.userInfo as JwtClaims;
// get all of user's lineMember entries
const userLineMembers = await LineService.getLineMembersByUserId(
userInfo.userId
);
const userLineMembers = await LineService.getLineMembersByUserId(userInfo.userId);
if (!userLineMembers?.length) {
const resObj = new GetUserLinesResponse([]);
res.json(
new NirvanaResponse(resObj, undefined, "this user is not in any lines")
);
res.json(new NirvanaResponse(resObj, undefined, 'this user is not in any lines'));
return;
}
const lineIds =
userLineMembers?.map((lineMember) => lineMember.lineId) ?? [];
const lineIds = userLineMembers?.map((lineMember) => lineMember.lineId) ?? [];
// this will include the current user lineMember association to the line
const allLineMembers = await LineService.getLineMembersInLines(lineIds);
const allLinesUsersIds: ObjectId[] = [];
allLineMembers?.map((currentLineMember) => {
if (currentLineMember?.userId)
allLinesUsersIds.push(currentLineMember.userId);
if (currentLineMember?.userId) allLinesUsersIds.push(currentLineMember.userId);
}) ?? [];
// get all users relevant here
@@ -174,34 +181,28 @@ async function getUserLines(req: Request, res: Response) {
// get the user lineMember assoc out of the list of the lineMembers for this line
const userLineMember = associatedLineMembersForLine?.find(
(currentLineMemberForLine) =>
currentLineMemberForLine.userId.toString() === userInfo.userId
currentLineMemberForLine.userId.toString() === userInfo.userId,
);
if (userLineMember) {
// take out the current user from the "other" line members list now
associatedLineMembersForLine = associatedLineMembersForLine.filter(
(currentLineMember) =>
currentLineMember.userId.toString() !== userInfo.userId
(currentLineMember) => currentLineMember.userId.toString() !== userInfo.userId,
);
// get the user objects for all of the other members
const otherUsers: User[] = [];
associatedLineMembersForLine.forEach((currentLineMember) => {
const foundUserObject = allRelevantUsers?.find((currentUser) =>
currentUser._id?.equals(currentLineMember.userId)
currentUser._id?.equals(currentLineMember.userId),
);
if (foundUserObject) otherUsers.push(foundUserObject);
});
masterLines.push(
new MasterLineData(
currentLine,
userLineMember,
associatedLineMembersForLine,
otherUsers
)
new MasterLineData(currentLine, userLineMember, associatedLineMembersForLine, otherUsers),
);
}
});
+16 -114
View File
@@ -7,6 +7,7 @@ import {
ServerRequestChannels,
ServerResponseChannels,
SomeoneConnectedResponse,
SomeoneDisconnectedResponse,
SomeoneTunedResponse,
SomeoneUntunedFromLineResponse,
StartBroadcastingRequest,
@@ -84,23 +85,12 @@ export default function InitializeWs(io: any) {
const roomName = `connectedLine:${req.lineId}`;
socket.join(roomName);
console.log(`${socket.id} now in rooms ${socket.rooms}`);
const clientUserIdsInRoom = [...(io.sockets.adapter.rooms.get(roomName) ?? [])].map(
(otherUserSocketId: string) => socketIdsToUserIds[otherUserSocketId],
);
io.in(roomName).emit(
ServerResponseChannels.SOMEONE_CONNECTED_TO_LINE,
new SomeoneConnectedResponse(req.lineId, userInfo.userId, clientUserIdsInRoom),
new SomeoneConnectedResponse(req.lineId, userInfo.userId),
);
});
/**
* TODO: handle when user wants to completely leave a line (delete or removed from one)
*/
socket.on(ServerRequestChannels.DISCONNECT_FROM_LINE, () => console.log('not implemented'));
/** TUNE | User tunes into the line either temporarily or toggled in */
socket.on(ServerRequestChannels.TUNE_INTO_LINE, async (req: TuneToLineRequest) => {
console.log(`${socket.id} user TUNED into room for line ${req.lineId}`);
@@ -108,38 +98,12 @@ export default function InitializeWs(io: any) {
const roomName = `tunedLine:${req.lineId}`;
socket.join(roomName);
console.log(`${socket.id} now in rooms ${Object.keys(socket.rooms)}`);
// persist tuning in if user is toggle tuning in
if (req.keepTunedIn) {
await LineService.updateLineMemberState(
req.lineId,
userInfo.userId,
LineMemberState.TUNED,
);
} else {
await LineService.updateLineMemberState(
req.lineId,
userInfo.userId,
LineMemberState.INBOX,
);
}
const clientUserIdsInRoom = [...(io.sockets.adapter.rooms.get(roomName) ?? [])].map(
(otherUserSocketId: string) => socketIdsToUserIds[otherUserSocketId],
);
// we want to notify everyone connected to the line even if they are not tuned in
const connectedLineRoomName = `connectedLine:${req.lineId}`;
io.in(connectedLineRoomName).emit(
ServerResponseChannels.SOMEONE_TUNED_INTO_LINE,
new SomeoneTunedResponse(
req.lineId,
userInfo.userId,
clientUserIdsInRoom,
req.keepTunedIn,
),
new SomeoneTunedResponse(req.lineId, userInfo.userId),
);
});
@@ -151,18 +115,14 @@ export default function InitializeWs(io: any) {
const roomName = `tunedLine:${req.lineId}`;
socket.leave(roomName);
console.log('someone left room');
const clientUserIdsInRoom = [...(io.sockets.adapter.rooms.get(roomName) ?? [])].map(
(otherUserSocketId: string) => socketIdsToUserIds[otherUserSocketId],
);
console.log(`${userInfo.userId} left room: ${roomName}`);
// we want to notify everyone connected to the line even if they are not tuned in
const connectedLineRoomName = `connectedLine:${req.lineId}`;
io.in(connectedLineRoomName).emit(
ServerResponseChannels.SOMEONE_UNTUNED_FROM_LINE,
new SomeoneUntunedFromLineResponse(req.lineId, userInfo.userId, clientUserIdsInRoom),
new SomeoneUntunedFromLineResponse(req.lineId, userInfo.userId),
);
});
@@ -186,21 +146,6 @@ export default function InitializeWs(io: any) {
);
});
// socket.on(SocketChannels.SEND_SIGNAL, async (payload: SendSignal) => {
// console.log(payload);
// const sendingBackData: ReceiveSignal = {
// simplePeerSignal: payload.simplePeerSignal,
// senderUserSocketId: socket.id,
// isGoingBackToInitiator: payload.isAnswerer ? true : false,
// };
// io.to(payload.userSocketIdToSignal).emit(
// SocketChannels.RECEIVE_SIGNAL,
// sendingBackData
// );
// });
// tell the proper other user to create a local peer object for the one on one mesh connection
socket.on(ServerRequestChannels.RTC_CALL_REQUEST, (req: RtcCallRequest) => {
const userSocketId = userIdsToSocketIds[req.userIdToCall];
@@ -220,58 +165,25 @@ export default function InitializeWs(io: any) {
);
});
// TODO: not complete
socket.on(ServerRequestChannels.GOING_INTO_FLOW_STATE, () => {
// change user object to persist this state
// get all of the connectedLine rooms of this person, and tell them that user is going into flow state
for (const roomName of socket.rooms) {
if (roomName !== socket.id) {
const lineId = roomName.split(':')[1];
if (roomName.includes('connectedLine')) {
// get fresh list of tuned in folks without me
const clientUserIdsInRoom = [...(io.sockets.adapter.rooms.get(roomName) ?? [])]
.filter((mappedSocketId) => mappedSocketId !== socket.id)
.map((otherUserSocketId: string) => socketIdsToUserIds[otherUserSocketId]);
// io.in(roomName).emit(
// ServerResponseChannels.SOMEONE_GOING_INTO_FLOW_STATE,
// new SomeoneGoingIntoFlowState(
// userInfo.userId
// )
// );
}
}
}
});
// tell all connected people that I am disconnecting
// tell tuned in folks that I am leaving the room
// tell all people in all my lines that I am disconnecting or untuning
// tell the tuned in folks the new list of
socket.on('disconnecting', (reason: any) => {
console.log(reason);
console.log(`someone disconnecting: ${reason}`);
console.log(socket.rooms);
for (const roomName of socket.rooms) {
if (roomName !== socket.id) {
const lineId = roomName.split(':')[1];
if (roomName.includes('tunedLine')) {
// get fresh list of tuned in folks without me
const clientUserIdsInRoom = [...(io.sockets.adapter.rooms.get(roomName) ?? [])]
.filter((mappedSocketId) => mappedSocketId !== socket.id)
.map((otherUserSocketId: string) => socketIdsToUserIds[otherUserSocketId]);
io.in(roomName).emit(
ServerResponseChannels.SOMEONE_UNTUNED_FROM_LINE,
new SomeoneUntunedFromLineResponse(lineId, userInfo.userId, clientUserIdsInRoom),
);
} else if (roomName.includes('connectedLine')) {
//TODO: p3: client doesn't really to know right now in our flow as this list is not really used
// io.in(roomName).emit(ServerResponseChannels.SOMEONE_UNTUNED_FROM_LINE, new SomeoneDisconnected(lineId, userInfo.userId, clientUserIdsInRoom));
}
const roomToTell = roomName.includes('tunedLine')
? `connectedLine:${lineId}`
: roomName;
io.in(roomToTell).emit(
ServerResponseChannels.SOMEONE_DISCONNECTED_FROM_LINE,
new SomeoneDisconnectedResponse(lineId, userInfo.userId),
);
}
}
});
@@ -280,16 +192,6 @@ export default function InitializeWs(io: any) {
socket.on('disconnect', () => {
delete socketIdsToUserIds[socket.id];
delete userIdsToSocketIds[userInfo.userId];
// get all of the rooms of this socket
// notify everyone of this disconnection
console.log('user disconnected');
console.log(`list of sockets mappings in memory: ${socketIdsToUserIds}`);
console.log(socket.rooms);
// ! NOTIFY ALL CONNECTED LINES SO THAT THEY CAN REMOVE FROM THEIR SESSION CONNECTED USERS ARRAY AND TUNED IN ARRAY
});
});
}