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 // 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 // repeatedly and trace data back and forth
export default class MasterLineData { 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( constructor(
// full line object // full line object
public lineDetails: Line, public lineDetails: Line,
+3
View File
@@ -12,6 +12,9 @@ enum SocketChannels {
SEND_SIGNAL = "SEND_SIGNAL", SEND_SIGNAL = "SEND_SIGNAL",
RECEIVE_SIGNAL = "RECEIVE_SIGNAL", RECEIVE_SIGNAL = "RECEIVE_SIGNAL",
// v3
CONNECT = "CONNECT",
} }
export default SocketChannels; export default SocketChannels;
+1
View File
@@ -0,0 +1 @@
export default class Connect {}
@@ -105,7 +105,7 @@ export default function LineRow({
<div <div
onClick={handleSelectLine} 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 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() && selectedLineId === masterLineData.lineDetails._id.toString() &&
"bg-gray-200 scale-110 shadow-2xl translate-x-3" "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 SocketChannels from "@nirvana/core/sockets/channels";
import { UserStatus } from "../../../core/models/user.model"; import { io } from "socket.io-client";
import { socket } from "../pages/nirvanaApp";
// import { useGetAllContactBasicDetails } from "./index"; const $ws = io("http://localhost:5000");
export default function useSocketData() { export default $ws;
// 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 };
}
@@ -32,29 +32,27 @@ export default function LineDetailsTerminal() {
return ( return (
<> <>
<GlobalHotKeys handlers={handlers} keyMap={keyMap} allowChanges /> <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 { RecoilRoot } from "recoil";
import { Toaster } from "react-hot-toast"; import { Toaster } from "react-hot-toast";
import { configure } from "react-hotkeys"; import { configure } from "react-hotkeys";
import io from "socket.io-client";
import testConnection from "@nirvana/core"; import testConnection from "@nirvana/core";
testConnection(); testConnection();
@@ -35,8 +34,6 @@ configure({
// Create a client // Create a client
export const queryClient = new QueryClient(); export const queryClient = new QueryClient();
export const socket = io("http://localhost:5000");
function NirvanaApp() { function NirvanaApp() {
return ( return (
<> <>
+103 -104
View File
@@ -8,7 +8,6 @@ import Peer from "simple-peer";
import ReceiveSignal from "@nirvana/core/sockets/receiveSignal"; import ReceiveSignal from "@nirvana/core/sockets/receiveSignal";
import SendSignal from "@nirvana/core/sockets/sendSignal"; import SendSignal from "@nirvana/core/sockets/sendSignal";
import SocketChannels from "@nirvana/core/sockets/channels"; import SocketChannels from "@nirvana/core/sockets/channels";
import { socket } from "../nirvanaApp";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
@@ -65,132 +64,132 @@ export default function Overlay() {
useState<MediaStream>(null); useState<MediaStream>(null);
// initially, have these set to default // initially, have these set to default
useEffect(() => { // useEffect(() => {
// POC: nirvana all connected users call // // POC: nirvana all connected users call
// send signal to all peers through ws // // 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 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 // // -> 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... // // -> entails me sending my signal data to all other users...
// the other users will get pinged with my signal data // // the other users will get pinged with my signal data
// -> now they have to take that signal data for new x user // // -> now they have to take that signal data for new x user
// and create their local peer object sending their stream to it // // 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 // // 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 // // 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 // navigator.mediaDevices
.getUserMedia({ video: false, audio: true }) // .getUserMedia({ video: false, audio: true })
.then((localStream: MediaStream) => { // .then((localStream: MediaStream) => {
setLocalUserVideoStream(localStream); // setLocalUserVideoStream(localStream);
// show user video // // show user video
if (localVideoRef?.current) // if (localVideoRef?.current)
localVideoRef.current.srcObject = localStream; // localVideoRef.current.srcObject = localStream;
socket.emit(SocketChannels.JOIN_LIVE_ROOM); // socket.emit(SocketChannels.JOIN_LIVE_ROOM);
socket.on( // socket.on(
SocketChannels.GET_ALL_ACTIVE_SOCKET_IDS, // SocketChannels.GET_ALL_ACTIVE_SOCKET_IDS,
(data: GetAllSocketClients) => { // (data: GetAllSocketClients) => {
console.log("all socket client connections", data); // console.log("all socket client connections", data);
const peers = []; // const peers = [];
data?.socketIds.map((userSocketId) => { // data?.socketIds.map((userSocketId) => {
if (userSocketId === socket.id) return; // if (userSocketId === socket.id) return;
// need one for each user I want to connect to // // need one for each user I want to connect to
var localPeerInitiator = new Peer({ // var localPeerInitiator = new Peer({
initiator: true, // initiator: true,
stream: localStream, // stream: localStream,
trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times // trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
}); // });
localPeerInitiator.on("signal", (signal) => { // localPeerInitiator.on("signal", (signal) => {
console.log( // console.log(
"created local initiator peer and sending signal to: ", // "created local initiator peer and sending signal to: ",
userSocketId // userSocketId
); // );
// send the local peer-peer signal to other users // // send the local peer-peer signal to other users
socket.emit(SocketChannels.SEND_SIGNAL, { // socket.emit(SocketChannels.SEND_SIGNAL, {
userSocketIdToSignal: userSocketId, // userSocketIdToSignal: userSocketId,
simplePeerSignal: signal, // simplePeerSignal: signal,
isAnswerer: false, // isAnswerer: false,
} as SendSignal); // } as SendSignal);
}); // });
peersRefs.current.push({ // peersRefs.current.push({
peer: localPeerInitiator, // peer: localPeerInitiator,
socketUserId: userSocketId, // socketUserId: userSocketId,
}); // });
peers.push(localPeerInitiator); // peers.push(localPeerInitiator);
}); // });
setLocalPeerConnections(peers); // setLocalPeerConnections(peers);
} // }
); // );
// incoming calls, accept them and send back // // incoming calls, accept them and send back
// hits this when I am sending and receiving // // hits this when I am sending and receiving
socket.on(SocketChannels.RECEIVE_SIGNAL, (payload: ReceiveSignal) => { // socket.on(SocketChannels.RECEIVE_SIGNAL, (payload: ReceiveSignal) => {
if (payload.isGoingBackToInitiator) { // if (payload.isGoingBackToInitiator) {
// from the list of peers here locally, we want to accept the answers signal // // from the list of peers here locally, we want to accept the answers signal
const localPeerRefToAnswerer = peersRefs.current.find( // const localPeerRefToAnswerer = peersRefs.current.find(
(peerRef) => peerRef.socketUserId === payload.senderUserSocketId // (peerRef) => peerRef.socketUserId === payload.senderUserSocketId
); // );
console.log( // console.log(
"got back answerers signal, going to signal the right peer now: ", // "got back answerers signal, going to signal the right peer now: ",
localPeerRefToAnswerer // localPeerRefToAnswerer
); // );
localPeerRefToAnswerer.peer.signal(payload.simplePeerSignal); // localPeerRefToAnswerer.peer.signal(payload.simplePeerSignal);
} else { // } else {
console.log("ooo newbie joined room, I guess I will accept it "); // console.log("ooo newbie joined room, I guess I will accept it ");
// if we are answering a received signal // // if we are answering a received signal
var peerToCallerPeer = new Peer({ // var peerToCallerPeer = new Peer({
initiator: false, // initiator: false,
trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times // trickle: false, // prevents the multiple tries on different ice servers and signal from getting called a bunch of times
stream: localStream, // stream: localStream,
}); // });
peerToCallerPeer.on("signal", (signal) => { // peerToCallerPeer.on("signal", (signal) => {
console.log( // console.log(
"as the answerer, I am going to send back my signal so that the newbie can update his local peer for me" // "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, { // socket.emit(SocketChannels.SEND_SIGNAL, {
userSocketIdToSignal: payload.senderUserSocketId, // userSocketIdToSignal: payload.senderUserSocketId,
simplePeerSignal: signal, // simplePeerSignal: signal,
isAnswerer: true, // isAnswerer: true,
} as SendSignal); // } as SendSignal);
}); // });
peerToCallerPeer.signal(payload.simplePeerSignal); // peerToCallerPeer.signal(payload.simplePeerSignal);
peersRefs.current.push({ // peersRefs.current.push({
peer: peerToCallerPeer, // peer: peerToCallerPeer,
socketUserId: payload.senderUserSocketId, // socketUserId: payload.senderUserSocketId,
}); // });
setLocalPeerConnections((prevPeers) => [ // setLocalPeerConnections((prevPeers) => [
...prevPeers, // ...prevPeers,
peerToCallerPeer, // peerToCallerPeer,
]); // ]);
} // }
}); // });
}) // })
.catch((err: Error) => { // .catch((err: Error) => {
console.error(err); // console.error(err);
toast.error(err.message); // toast.error(err.message);
}); // });
}, []); // }, []);
// TODO: get all of the toggle tuned in lines and any line that I am toggle broadcasting to // 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 // loop through and send lineId to the x child stream overlay components who will do the work