starting socket organizations

This commit is contained in:
talksik
2022-05-06 05:28:52 -05:00
parent abf28c8820
commit 0f8902b47d
9 changed files with 177 additions and 219 deletions
@@ -8,6 +8,15 @@ import { User } from "./user.model";
// speed...I'm developing full stack and I just want all of the data and don't want to change this model
// repeatedly and trace data back and forth
export default class MasterLineData {
// if someone else is buzzing on the line
isOtherBroadcasting?: boolean = false;
// if I am buzzing in the line
isUserBroadcasting?: boolean = false;
// list of user Ids of everyone who is buzzing in this line
currentBroadcasters: string[] = [];
// ?current people tuned into the line...not sure if this is a product decision but can support it
tunedInMemberIds: string[] = [];
constructor(
// full line object
public lineDetails: Line,
+3
View File
@@ -12,6 +12,9 @@ enum SocketChannels {
SEND_SIGNAL = "SEND_SIGNAL",
RECEIVE_SIGNAL = "RECEIVE_SIGNAL",
// v3
CONNECT = "CONNECT",
}
export default SocketChannels;
+1
View File
@@ -0,0 +1 @@
export default class Connect {}
@@ -105,7 +105,7 @@ export default function LineRow({
<div
onClick={handleSelectLine}
className={`flex flex-row items-center justify-start gap-2 p-2 px-4 h-14 hover:bg-gray-200 cursor-pointer transition-all
last:border-b-0 border-b border-b-gray-200 ${
last:border-b-0 border-b border-b-gray-200 relative ${
selectedLineId === masterLineData.lineDetails._id.toString() &&
"bg-gray-200 scale-110 shadow-2xl translate-x-3"
}`}
@@ -0,0 +1,36 @@
import React, { useContext } from "react";
import $ws from "./sockets";
import MasterLineData from "@nirvana/core/models/masterLineData.model";
import SocketChannels from "@nirvana/core/sockets/channels";
import { User } from "@nirvana/core/models";
import { io } from "socket.io-client";
import { useEffect } from "react";
import { useUserLines } from "./index";
interface ILineDataContext {
// represents the modified and up to date lines data with availability from session
lines: MasterLineData[];
relevantUsers: User[];
}
const lineDataContext = React.createContext<ILineDataContext>({
lines: [],
relevantUsers: [],
});
export function LineDataProvider() {
// persistent store of lines
const { data: basicUserLinesData } = useUserLines();
// connect through ws to enrich basic lines data
useEffect(() => {
// $ws.on(SocketChannels.CONNECT, );
}, [basicUserLinesData]);
// get updated associations with certain lines
}
export function useLineDataProvider() {
return useContext(lineDataContext);
}
+3 -88
View File
@@ -1,91 +1,6 @@
import { useEffect, useState } from "react";
import SocketChannels from "@nirvana/core/sockets/channels";
import { UserStatus } from "../../../core/models/user.model";
import { socket } from "../pages/nirvanaApp";
import { io } from "socket.io-client";
// import { useGetAllContactBasicDetails } from "./index";
const $ws = io("http://localhost:5000");
export default function useSocketData() {
// relationshipId's of the conversations where there is someone speaking
const [speakingRooms, setSpeakingRooms] = useState<string[]>([]);
// const { data: allConvosDetsResponse, isFetched } =
// useGetAllContactBasicDetails();
// useEffect(() => {
// if (allConvosDetsResponse) {
// allConvosDetsResponse.contactsDetails.map((contactDet) => {
// // join the right rooms based on the relevant contacts/conversations returned here
// socket.emit(
// SocketChannels.JOIN_ROOM,
// contactDet.relationship._id.toString()
// );
// });
// }
// }, [isFetched]);
useEffect(() => {
socket.on(
SocketChannels.SEND_STARTED_SPEAKING,
(relationshipId: string) => {
console.log(`yayaya someone started speaking in ${relationshipId}!!!!`);
setSpeakingRooms((prevSpeakingRooms) => [
...prevSpeakingRooms,
relationshipId,
]);
}
);
socket.on(
SocketChannels.SEND_STOPPED_SPEAKING,
(relationshipId: string) => {
console.log(`stopped speaking in ${relationshipId}!!!!`);
setSpeakingRooms((prevSpeakingRooms) =>
prevSpeakingRooms.filter(
(relationshipRoomId) => relationshipRoomId !== relationshipId
)
);
}
);
socket.on(
SocketChannels.SEND_AUDIO_CLIP,
(relationshipId: string, audioChunks: any) => {
console.log(relationshipId);
console.log(audioChunks);
const audioBlob = new Blob(audioChunks);
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
}
);
socket.on(
SocketChannels.SEND_USER_STATUS_UPDATE,
(userGoogleId: string, newStatus: UserStatus) => {
console.log(`${userGoogleId} updated their status...hmmm`);
}
);
return () => {
socket.removeAllListeners(SocketChannels.SEND_STARTED_SPEAKING);
socket.removeAllListeners(SocketChannels.SEND_STOPPED_SPEAKING);
socket.removeAllListeners(SocketChannels.SEND_AUDIO_CLIP);
socket.removeAllListeners(SocketChannels.SEND_USER_STATUS_UPDATE);
};
}, []);
// todo: go through all content and add in the socket messages
// find out which convos have new content for user
// sort and get rid of duplicate messages for the clip timeline
// set the latest link for the view component
// sort the conversations according to this:
// live -> new messages -> speaking -> incoming requests
return { speakingRooms };
}
export default $ws;
@@ -32,29 +32,27 @@ export default function LineDetailsTerminal() {
return (
<>
<GlobalHotKeys handlers={handlers} keyMap={keyMap} allowChanges />
<div className="flex flex-col bg-gray-100 w-[400px]">
{/* line overview header */}
<div className="flex flex-row p-3 items-center gap-1">
{/* <LineIcon sourceImages={selectedLine.profilePictures} />
<span className="flex flex-col items-start gap-1">
<h2
className={`text-inherit text-md truncate ${
selectedLine.hasNewActivity ? "font-semibold" : ""
}`}
>
{selectedLine.name}
</h2>
<span className="text-xs text-gray-300">
{`${selectedLine.numberMembers} members`}
</span>
</span> */}
</div>
</div>
</>
// <div
// id={`${selectedLine.lineId}-lineDetailsTerminal`}
// className="flex flex-col bg-gray-100 w-[400px]"
// >
// {/* line overview header */}
// <div className="flex flex-row p-3 items-center gap-1">
// <LineIcon sourceImages={selectedLine.profilePictures} />
// <span className="flex flex-col items-start gap-1">
// <h2
// className={`text-inherit text-md truncate ${
// selectedLine.hasNewActivity ? "font-semibold" : ""
// }`}
// >
// {selectedLine.name}
// </h2>
// <span className="text-xs text-gray-300">
// {`${selectedLine.numberMembers} members`}
// </span>
// </span>
// </div>
// </div>
);
}
@@ -7,7 +7,6 @@ import { ReactQueryDevtools } from "react-query/devtools";
import { RecoilRoot } from "recoil";
import { Toaster } from "react-hot-toast";
import { configure } from "react-hotkeys";
import io from "socket.io-client";
import testConnection from "@nirvana/core";
testConnection();
@@ -35,8 +34,6 @@ configure({
// Create a client
export const queryClient = new QueryClient();
export const socket = io("http://localhost:5000");
function NirvanaApp() {
return (
<>
+103 -104
View File
@@ -8,7 +8,6 @@ import Peer from "simple-peer";
import ReceiveSignal from "@nirvana/core/sockets/receiveSignal";
import SendSignal from "@nirvana/core/sockets/sendSignal";
import SocketChannels from "@nirvana/core/sockets/channels";
import { socket } from "../nirvanaApp";
import toast from "react-hot-toast";
import { useRecoilState } from "recoil";
@@ -65,132 +64,132 @@ export default function Overlay() {
useState<MediaStream>(null);
// initially, have these set to default
useEffect(() => {
// POC: nirvana all connected users call
// send signal to all peers through ws
// useEffect(() => {
// // POC: nirvana all connected users call
// // send signal to all peers through ws
// I join x room
// // I join x room
// I need to do the work of sending my signal to all others in the room
// -> I create a local peer object for my connection to all other people in the room
// -> entails me sending my signal data to all other users...
// // I need to do the work of sending my signal to all others in the room
// // -> I create a local peer object for my connection to all other people in the room
// // -> entails me sending my signal data to all other users...
// the other users will get pinged with my signal data
// -> now they have to take that signal data for new x user
// and create their local peer object sending their stream to it
// and accept/answer the signal after creating this local peer connection between them and the newbie user
// send back their signal now so that the initiator can get it and accept it
// // the other users will get pinged with my signal data
// // -> now they have to take that signal data for new x user
// // and create their local peer object sending their stream to it
// // and accept/answer the signal after creating this local peer connection between them and the newbie user
// // send back their signal now so that the initiator can get it and accept it
console.log("socket id", socket.id);
// console.log("socket id", socket.id);
navigator.mediaDevices
.getUserMedia({ video: false, audio: true })
.then((localStream: MediaStream) => {
setLocalUserVideoStream(localStream);
// navigator.mediaDevices
// .getUserMedia({ video: false, audio: true })
// .then((localStream: MediaStream) => {
// setLocalUserVideoStream(localStream);
// show user video
if (localVideoRef?.current)
localVideoRef.current.srcObject = localStream;
// // show user video
// if (localVideoRef?.current)
// localVideoRef.current.srcObject = localStream;
socket.emit(SocketChannels.JOIN_LIVE_ROOM);
// socket.emit(SocketChannels.JOIN_LIVE_ROOM);
socket.on(
SocketChannels.GET_ALL_ACTIVE_SOCKET_IDS,
(data: GetAllSocketClients) => {
console.log("all socket client connections", data);
// socket.on(
// SocketChannels.GET_ALL_ACTIVE_SOCKET_IDS,
// (data: GetAllSocketClients) => {
// console.log("all socket client connections", data);
const peers = [];
data?.socketIds.map((userSocketId) => {
if (userSocketId === socket.id) return;
// const peers = [];
// data?.socketIds.map((userSocketId) => {
// if (userSocketId === socket.id) return;
// need one for each user I want to connect to
var localPeerInitiator = new Peer({
initiator: true,
stream: localStream,
trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
});
// // need one for each user I want to connect to
// var localPeerInitiator = new Peer({
// initiator: true,
// stream: localStream,
// trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
// });
localPeerInitiator.on("signal", (signal) => {
console.log(
"created local initiator peer and sending signal to: ",
userSocketId
);
// localPeerInitiator.on("signal", (signal) => {
// console.log(
// "created local initiator peer and sending signal to: ",
// userSocketId
// );
// send the local peer-peer signal to other users
socket.emit(SocketChannels.SEND_SIGNAL, {
userSocketIdToSignal: userSocketId,
simplePeerSignal: signal,
isAnswerer: false,
} as SendSignal);
});
// // send the local peer-peer signal to other users
// socket.emit(SocketChannels.SEND_SIGNAL, {
// userSocketIdToSignal: userSocketId,
// simplePeerSignal: signal,
// isAnswerer: false,
// } as SendSignal);
// });
peersRefs.current.push({
peer: localPeerInitiator,
socketUserId: userSocketId,
});
// peersRefs.current.push({
// peer: localPeerInitiator,
// socketUserId: userSocketId,
// });
peers.push(localPeerInitiator);
});
// peers.push(localPeerInitiator);
// });
setLocalPeerConnections(peers);
}
);
// setLocalPeerConnections(peers);
// }
// );
// incoming calls, accept them and send back
// hits this when I am sending and receiving
socket.on(SocketChannels.RECEIVE_SIGNAL, (payload: ReceiveSignal) => {
if (payload.isGoingBackToInitiator) {
// from the list of peers here locally, we want to accept the answers signal
const localPeerRefToAnswerer = peersRefs.current.find(
(peerRef) => peerRef.socketUserId === payload.senderUserSocketId
);
// // incoming calls, accept them and send back
// // hits this when I am sending and receiving
// socket.on(SocketChannels.RECEIVE_SIGNAL, (payload: ReceiveSignal) => {
// if (payload.isGoingBackToInitiator) {
// // from the list of peers here locally, we want to accept the answers signal
// const localPeerRefToAnswerer = peersRefs.current.find(
// (peerRef) => peerRef.socketUserId === payload.senderUserSocketId
// );
console.log(
"got back answerers signal, going to signal the right peer now: ",
localPeerRefToAnswerer
);
// console.log(
// "got back answerers signal, going to signal the right peer now: ",
// localPeerRefToAnswerer
// );
localPeerRefToAnswerer.peer.signal(payload.simplePeerSignal);
} else {
console.log("ooo newbie joined room, I guess I will accept it ");
// localPeerRefToAnswerer.peer.signal(payload.simplePeerSignal);
// } else {
// console.log("ooo newbie joined room, I guess I will accept it ");
// if we are answering a received signal
var peerToCallerPeer = new Peer({
initiator: false,
trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
stream: localStream,
});
// // if we are answering a received signal
// var peerToCallerPeer = new Peer({
// initiator: false,
// trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
// stream: localStream,
// });
peerToCallerPeer.on("signal", (signal) => {
console.log(
"as the answerer, I am going to send back my signal so that the newbie can update his local peer for me"
);
socket.emit(SocketChannels.SEND_SIGNAL, {
userSocketIdToSignal: payload.senderUserSocketId,
simplePeerSignal: signal,
isAnswerer: true,
} as SendSignal);
});
// peerToCallerPeer.on("signal", (signal) => {
// console.log(
// "as the answerer, I am going to send back my signal so that the newbie can update his local peer for me"
// );
// socket.emit(SocketChannels.SEND_SIGNAL, {
// userSocketIdToSignal: payload.senderUserSocketId,
// simplePeerSignal: signal,
// isAnswerer: true,
// } as SendSignal);
// });
peerToCallerPeer.signal(payload.simplePeerSignal);
// peerToCallerPeer.signal(payload.simplePeerSignal);
peersRefs.current.push({
peer: peerToCallerPeer,
socketUserId: payload.senderUserSocketId,
});
// peersRefs.current.push({
// peer: peerToCallerPeer,
// socketUserId: payload.senderUserSocketId,
// });
setLocalPeerConnections((prevPeers) => [
...prevPeers,
peerToCallerPeer,
]);
}
});
})
.catch((err: Error) => {
console.error(err);
toast.error(err.message);
});
}, []);
// setLocalPeerConnections((prevPeers) => [
// ...prevPeers,
// peerToCallerPeer,
// ]);
// }
// });
// })
// .catch((err: Error) => {
// console.error(err);
// toast.error(err.message);
// });
// }, []);
// TODO: get all of the toggle tuned in lines and any line that I am toggle broadcasting to
// loop through and send lineId to the x child stream overlay components who will do the work