import io from "socket.io-client";
import { useParams } from "react-router-dom";
import Peer from "peerjs";
import Video from "../components/Video";
import Navbar from "../components/Navbar";
import { useMedia } from "../components/MediaContext";
const Room = () => {
const { room } = useParams();
const [users, setUsers] = useState([]);
const socket = useRef();
const myPeer = useRef();
const screenSharePeer = useRef();
const myVideoStream = useRef();
const { webcamOn, audioOn } = useMedia();
const [stream, setStream] = useState(null);
const [positions, setPositions] = useState({});
const [sizes, setSizes] = useState({});
const [screenShareActive, setScreenShareActive] = useState(false);
const startScreenShareRef = useRef(null); // Step 1: Create a ref to store the function
useEffect(() => {
socket.current = io("http://localhost:3000");
myPeer.current = new Peer(undefined, {
host: "/",
port: "3001",
});
navigator.mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then((stream) => {
setStream(stream);
myVideoStream.current = stream;
addVideoStream(myPeer.current.id, stream);
myPeer.current.on("call", (call) => {
call.answer(stream);
call.on("stream", (userVideoStream) => {
addVideoStream(call.peer, userVideoStream);
});
});
socket.current.emit("join-room", room, myPeer.current.id);
socket.current.on("user-connected", (userId) => {
connectToNewUser(userId, stream);
});
socket.current.on("user-disconnected", (userId) => {
setUsers((prevUsers) =>
prevUsers.filter((user) => user.id !== userId)
);
});
socket.current.on("initialPositions", (positions) => {
setPositions(positions);
});
socket.current.on("initialSizes", (sizes) => {
setSizes(sizes);
});
socket.current.on("positionChanged", ({ userId, position }) => {
setPositions((prevPositions) => ({
...prevPositions,
[userId]: position,
}));
});
socket.current.on("sizeChanged", ({ userId, size }) => {
setSizes((prevSizes) => ({
...prevSizes,
[userId]: size,
}));
});
// Define the startScreenShare function inside the useEffect
const startScreenShare = () => {
if (screenShareActive) return;
navigator.mediaDevices
.getDisplayMedia({ video: true, audio: true })
.then((screenStream) => {
console.log("Screen stream obtained:", screenStream);
if (screenStream) {
console.log(screenStream);
screenSharePeer.current = new Peer(undefined, {
host: "/",
port: "3001",
});
screenSharePeer.current.on("open", (screenShareId) => {
console.log(
"Screen Share Peer created:",
screenSharePeer.current.id
);
setScreenShareActive(true);
addVideoStream(screenShareId, screenStream, true);
socket.current.emit("screen-share-started", {
userId: screenShareId,
});
console.log("Screen share started and event emitted");
screenStream.getVideoTracks()[0].onended = () => {
setScreenShareActive(false);
setUsers((prevUsers) =>
prevUsers.filter((user) => user.id !== screenShareId)
);
socket.current.emit("screen-share-stopped", {
userId: screenShareId,
});
screenSharePeer.current.destroy();
};
});
}
})
.catch((err) => {
console.error("Error starting screen share:", err);
});
};
startScreenShareRef.current = startScreenShare; // Store the function in the ref
// Move these socket listeners outside the function to avoid adding them multiple times
socket.current.on("user-screen-share-started", ({ userId }) => {
connectToScreenShare(userId, stream);
});
socket.current.on("user-screen-share-stopped", ({ userId }) => {
setUsers((prevUsers) =>
prevUsers.filter((user) => user.id !== userId)
);
});
});
return () => {
socket.current.disconnect();
myPeer.current.destroy();
if (screenSharePeer.current) {
screenSharePeer.current.destroy();
}
};
}, [room]);
useEffect(() => {
if (stream) {
stream.getVideoTracks()[0].enabled = webcamOn;
}
}, [webcamOn, stream]);
useEffect(() => {
if (stream) {
stream.getAudioTracks()[0].enabled = audioOn;
}
}, [audioOn, stream]);
const addVideoStream = (id, stream, isScreen = false) => {
setUsers((prevUsers) => {
if (prevUsers.some((user) => user.id === id)) {
return prevUsers;
}
return [...prevUsers, { id, stream, isScreen }];
});
};
const connectToNewUser = (userId, stream) => {
const call = myPeer.current.call(userId, stream);
call.on("stream", (userVideoStream) => {
addVideoStream(userId, userVideoStream);
});
};
const handlePositionChange = (userId, position) => {
socket.current.emit("updatePosition", { userId, position });
};
const handleSizeChange = (userId, size) => {
socket.current.emit("updateSize", { userId, size });
};
const connectToScreenShare = (userId, stream) => {
const call = screenSharePeer.current.call(userId, stream);
call.on("stream", (userVideoStream) => {
addVideoStream(userId, userVideoStream, true);
});
};
return (
<div className="bg-cover bg-[url('./backgrounds/night-room.jpg')] min-h-screen">
<Navbar startScreenShare={startScreenShareRef.current} />{" "}
{/* Step 3: Pass the ref */}
<h1 className="font-bold">Room ID: {room}</h1>
<div className="grid grid-row-4 grid-flow-col gap-4">
{users.map((user) => (
<Video
key={user.id}
stream={user.stream}
userId={user.id}
roomId={room}
initialPosition={positions[user.id] || { x: 0, y: 0 }}
initialSize={sizes[user.id] || { width: 200, height: 200 }}
onPositionChange={handlePositionChange}
onSizeChange={handleSizeChange}
isScreen={user.isScreen}
/>
))}
</div>
</div>
);
};
export default Room;
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { v4: uuidV4 } = require("uuid");
const path = require("path");
const io = require("socket.io")(server);
const buildPath = path.join(__dirname, "build");
app.use(express.static(buildPath));
console.log(buildPath);
app.get("/getRoom", (req, res) => {
const newRoomId = uuidV4();
console.log("Generated Room ID:", newRoomId);
res.redirect(`/${newRoomId}`);
});
app.get("/:room", (req, res) => {
console.log("Serving room:", req.params.room);
res.sendFile(path.join(buildPath, "index.html"));
});
server.listen(3000, () => {
console.log("Server is running on port 3000");
});
let positions = {};
let sizes = {};
io.on("connection", (socket) => {
socket.on("join-room", (roomId, userId) => {
socket.join(roomId);
socket.to(roomId).emit("user-connected", userId);
// Send initial positions and sizes
socket.emit("initialPositions", positions[roomId] || {});
socket.emit("initialSizes", sizes[roomId] || {});
socket.on("disconnect", () => {
socket.to(roomId).emit("user-disconnected", userId);
if (positions[roomId]) {
delete positions[roomId][userId];
}
if (sizes[roomId]) {
delete sizes[roomId][userId];
}
});
socket.on("updatePosition", ({ userId, position }) => {
if (!positions[roomId]) {
positions[roomId] = {};
}
positions[roomId][userId] = position;
socket.to(roomId).emit("positionChanged", { userId, position });
});
socket.on("updateSize", ({ userId, size }) => {
if (!sizes[roomId]) {
sizes[roomId] = {};
}
sizes[roomId][userId] = size;
socket.to(roomId).emit("sizeChanged", { userId, size });
});
// Handle screen share start
socket.on("screen-share-started", ({ userId, stream }) => {
if (roomId) {
socket.to(roomId).emit("user-screen-share-started", { userId });
console.log(stream);
}
});
// Handle screen share stop
socket.on("screen-share-stopped", ({ userId }) => {
if (roomId) {
socket.to(roomId).emit("user-screen-share-stopped", { userId });
}
});
});
});
these are my room and server components. the screen sharing feature refuses to work at all. multiple logs show that the MediaStream is being created for screen share as well as a separate id for it but it does not show up in my room.
if im right about the Room component, the screen share stream should be treated as another user joining the room and their mediastream should be displayed as usual, however that is not the case. a blank video pops up for the user initiating the screen share but it does not pop up for another users in the room.
keebee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.