Spaces:
Running
Running
File size: 2,593 Bytes
8a6248c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | import Appointment from "../models/appointmentModel.js";
const videoCallSocket = (io) => {
io.on('connection', (socket) => {
console.log('A user connected');
// Handle the join-call event
socket.on('join-call', async ({ appointmentId, role }) => {
console.log(`User with role ${role} is joining call for appointment ${appointmentId}`);
const appointment = await Appointment.findById(appointmentId).populate('farmerId expertId');
if (!appointment) {
console.log(`Appointment not found: ${appointmentId}`);
return;
}
if (role === 'farmer') {
io.to(appointment.expertId.socketId).emit('join-call', {
appointmentId,
role: 'expert',
message: 'Farmer is ready to join the call!',
});
socket.join(appointmentId); // Join the socket room
} else if (role === 'expert') {
io.to(appointment.farmerId.socketId).emit('join-call', {
appointmentId,
role: 'farmer',
message: 'Expert is ready to join the call!',
});
socket.join(appointmentId); // Join the socket room
}
});
// Handle the video call offer (from farmer to expert)
socket.on('video-call-offer', (offerData) => {
const { appointmentId, offer, role } = offerData;
const targetRole = role === 'farmer' ? 'expert' : 'farmer';
// Send the offer to the other user (expert or farmer)
io.to(appointmentId).emit('video-call-offer', {
offer,
appointmentId,
role: targetRole,
});
});
// Handle the video call answer (from expert to farmer)
socket.on('video-call-answer', (answerData) => {
const { appointmentId, answer, role } = answerData;
const targetRole = role === 'farmer' ? 'expert' : 'farmer';
// Send the answer to the other user (expert or farmer)
io.to(appointmentId).emit('video-call-answer', {
answer,
appointmentId,
role: targetRole,
});
});
// Handle ICE candidates
socket.on('ice-candidate', (candidateData) => {
const { appointmentId, candidate, role } = candidateData;
const targetRole = role === 'farmer' ? 'expert' : 'farmer';
// Send the ICE candidate to the other user (expert or farmer)
io.to(appointmentId).emit('ice-candidate', {
candidate,
appointmentId,
role: targetRole,
});
});
// Handle disconnect event
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
};
export default videoCallSocket;
|