good progress with server and client back and forth
- getting there slowly with console logs and understanding the steps along the way
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import express, { Application, Request, Response } from "express";
|
||||
|
||||
const webrtc = require("wrtc");
|
||||
|
||||
export default function getRtcRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// get user details based on id token
|
||||
router.post("/join/:lineId", handleJoin);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
// a mapping between a certain line and the streams for it
|
||||
const linesStreams: {
|
||||
[lineId: string]: any[];
|
||||
} = {};
|
||||
|
||||
async function handleJoin(req: Request, res: Response) {
|
||||
try {
|
||||
const { lineId } = req.params;
|
||||
const { sdp } = req.body;
|
||||
|
||||
const peer = new webrtc.RTCPeerConnection({
|
||||
iceServers: [
|
||||
{
|
||||
urls: "stun:stun.stunprotocol.org",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// allow this peer connection to receive other peoples' streams
|
||||
peer.ontrack = (e: any) => handleStreams(e, peer, lineId);
|
||||
|
||||
// allow this peer connection for this specific line to get tracks for this line already
|
||||
linesStreams[lineId]?.forEach((stream: any) => {
|
||||
stream.getTracks().forEach((track: any) => {
|
||||
console.log(`have tracks in this line`, track, stream);
|
||||
peer.addTrack(track, stream);
|
||||
});
|
||||
});
|
||||
|
||||
// create connection between server and client who hit this endpoint
|
||||
const desc = new webrtc.RTCSessionDescription(sdp);
|
||||
await peer.setRemoteDescription(desc);
|
||||
const answer = await peer.createAnswer();
|
||||
await peer.setLocalDescription(answer);
|
||||
|
||||
const payload = {
|
||||
sdp: peer.localDescription,
|
||||
};
|
||||
|
||||
res
|
||||
.status(200)
|
||||
.json({ message: `You can now broadcast to ${lineId}!`, data: payload });
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
res.status(500).json({
|
||||
message: "Problem in setting up peer connection with media server",
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function handleStreams(e: any, peer: any, lineId: string) {
|
||||
// if the room/line exists already, then add to the list of streams
|
||||
if (lineId in linesStreams) {
|
||||
const newStreamsForLine = [...(linesStreams[lineId] ?? []), ...e.streams];
|
||||
|
||||
linesStreams[lineId] = newStreamsForLine;
|
||||
} else {
|
||||
// create a new list of streams
|
||||
linesStreams[lineId] = [...e.streams];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user