File size: 10,244 Bytes
9470e9f |
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
import { Server } from 'socket.io';
import matchingQueue from './MatchingQueue.js';
import { updateKarma } from './KarmaService.js';
import User from '../models/User.js';
import Message from '../models/Message.js';
import CallSession from '../models/CallSession.js';
let io;
const ICEBREAKERS = [
"What's your most controversial food opinion?",
"If you could teleport anywhere right now, where to?",
"What's the last song you listened to on repeat?",
"Zombie apocalypse team: You + 2 fictional characters. Who?",
"Cats or Dogs? Defend your answer.",
"What's a movie you can watch 100 times?",
"Best Wi-Fi name you've ever seen?",
"If you were a ghost, who would you haunt?",
"What's the weirdest talent you have?",
"Pineapple on pizza: Yes or Criminal?",
"What's something you're oddly passionate about?",
"If your life had a theme song right now, what would it be?",
"What's the most random thing you've learned this semester?",
"What's a hot take you're willing to defend?",
"What's the best late-night food near your campus?",
"What's your go-to comfort show or YouTube channel?",
"What's a hobby you picked up and then immediately dropped?",
"What's something small that instantly makes your day better?",
"What's the most college thing that's happened to you this week?",
"What's your current obsession?",
"What's your major—and do you actually like it?",
"Hardest class you've taken so far?",
"Are you more of a library studier or last-minute grinder?",
"Best campus spot nobody talks about?",
"Most useless class requirement you've had?",
"What's one class everyone should avoid?",
"What's your ideal class schedule: mornings or afternoons?",
"Biggest academic struggle right now?",
"Group projects: blessing or curse?",
"What's one thing you wish freshmen knew?",
"What's a hill you're willing to die on?",
"If sleep were a class, would you pass?",
"What's your most controversial campus opinion?",
"What's something you pretend to enjoy but actually don't?",
"What's the worst fashion phase you went through?",
"What's your most irrational fear?",
"What's a weird habit you have?",
"What's the worst app you still use daily?",
"If procrastination were a sport, how good would you be?",
"What's the dumbest thing you've done this month?",
"If money didn't matter, what would you be doing right now?",
"If you could restart college, what would you do differently?",
"If you could instantly master one skill, what would it be?",
"What would your dream elective be?",
"If you could time-travel to one moment in your life, when?",
"What's a random dream you haven't told many people?",
"What would your perfect day look like?",
"If you had to teach a class, what would it be about?",
"What's something you want to get better at?",
"If you disappeared for a year, what would you do?",
"What's something you're proud of lately?",
"What's been stressing you out recently?",
"What's one thing you're looking forward to?",
"Who's had the biggest influence on you?",
"What's something you're trying to improve about yourself?",
"What's the best advice you've gotten?",
"What's something you're grateful for today?",
"What's one goal you have this semester?",
"What's something that motivates you?",
"What's one thing that always cheers you up?",
"Coffee or energy drinks?",
"Night owl or early bird?",
"Introvert, extrovert, or depends?",
"Study music or silence?",
"Netflix or YouTube?",
"Gym, sports, or neither?",
"Homebody or always out?",
"Texting or calling?",
"Winter or summer?",
"Spontaneous or planned?"
];
const onlineUsers = new Set();
export const initSocket = (httpServer) => {
io = new Server(httpServer, {
cors: {
origin: process.env.CLIENT_URL || "*",
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
console.log(`🔌 Client connected: ${socket.id}`);
socket.on('register_online', (userId) => {
socket.userId = userId.toString();
onlineUsers.add(socket.userId);
io.emit('online_count', { count: onlineUsers.size });
});
// 1. User joins the "Looking for Match" queue
socket.on('join_queue', (user) => {
console.log(`🔍 User ${user.displayName} joined queue`);
socket.userId = user._id.toString();
onlineUsers.add(socket.userId);
// Broadcast correct count
io.emit('online_count', { count: onlineUsers.size });
const match = matchingQueue.findMatch(user);
if (match) {
// MATCH FOUND!
socket.partnerSocketId = match.socketId;
const partnerSocket = io.sockets.sockets.get(match.socketId);
if (partnerSocket) {
partnerSocket.partnerSocketId = socket.id;
}
const createSession = async (userA_id, userB_id) => {
try {
const session = await new CallSession({
participants: [userA_id, userB_id]
}).save();
return session._id;
} catch (err) {
console.error("Session log error", err);
}
};
matchingQueue.remove(match.socketId);
const roomId = `${socket.id}-${match.socketId}`;
socket.join(roomId);
io.to(match.socketId).socketsJoin(roomId);
// PICK RANDOM QUESTION
const question = ICEBREAKERS[Math.floor(Math.random() * ICEBREAKERS.length)];
// NOTIFY USER A (Current Socket)
io.to(socket.id).emit('match_found', {
roomId,
peerId: match.user._id.toString(), // <--- FIX: Ensure String
peerName: match.user.displayName,
peerKarma: match.user.karma,
peerProfile: match.user.profile,
remoteSocketId: match.socketId, // Pass this for social signaling
icebreaker: question
});
// NOTIFY USER B (Target Socket)
io.to(match.socketId).emit('match_found', {
roomId,
peerId: user._id.toString(), // <--- FIX: Ensure String
peerName: user.displayName,
peerKarma: user.karma,
peerProfile: user.profile,
remoteSocketId: socket.id,
icebreaker: question
});
// Tell Initiator (Current Socket) to send Offer
socket.emit('initiate_call', { remoteSocketId: match.socketId });
} else {
// NO MATCH -> Wait in queue
matchingQueue.add(socket.id, user);
}
});
// 2. WebRTC Signaling (The Handshake)
socket.on('offer', (payload) => {
io.to(payload.target).emit('offer', payload);
});
socket.on('answer', (payload) => {
io.to(payload.target).emit('answer', payload);
});
socket.on('ice-candidate', (payload) => {
io.to(payload.target).emit('ice-candidate', payload);
});
// 3. Cleanup
socket.on('disconnect', async () => {
console.log(`🔌 Client disconnected: ${socket.id}`);
if (socket.userId) {
onlineUsers.delete(socket.userId);
}
io.emit('online_count', { count: onlineUsers.size });
if (socket.partnerSocketId) {
io.to(socket.partnerSocketId).emit('call_ended');
}
// 1. Remove from Matching Queue (Critical)
matchingQueue.remove(socket.id);
// 2. Handle Dropped Calls (Phase 10 Logic)
if (socket.activeSessionId) {
await CallSession.findByIdAndUpdate(socket.activeSessionId, {
endTime: Date.now(),
status: 'dropped'
});
// 3. Notify the partner (if they are still there)
// We need to know who the partner was.
// Ideally, store `socket.partnerId` during match.
if (socket.partnerSocketId) {
io.to(socket.partnerSocketId).emit('peer_disconnected');
}
}
});
socket.on('report_violation', async ({ type }) => {
if (!socket.userId) return;
console.log(`🚨 AI REPORT on ${socket.userId}: ${type}`);
if (type === 'NSFW_AUTO') {
// Heavy Penalty for Flashing
await updateKarma(socket.userId, -20, 'NSFW AI Detection');
// Force disconnect
socket.disconnect();
}
});
socket.on('share_social', async ({ targetId, platform }) => {
try {
// 1. Fetch Sender's Profile securely
const sender = await User.findById(socket.userId);
if (!sender) return;
const handle = sender.profile.socials?.[platform];
if (!handle) {
// Notify sender they haven't set this up
socket.emit('error_toast', { message: `No ${platform} handle set in profile.` });
return;
}
// 2. Emit to Target
io.to(targetId).emit('social_received', {
platform,
handle,
senderName: sender.displayName
});
// 3. Confirm to Sender
socket.emit('social_shared_success', { platform });
} catch (err) {
console.error("Share failed", err);
}
});
socket.on('send_message', async ({ receiverId, content }) => {
try {
// 1. Save to DB
const newMsg = await new Message({
sender: socket.userId,
receiver: receiverId,
content
}).save();
// 2. Emit to Receiver (if online)
// We need a way to find Receiver's Socket ID.
// Ideally, maintain a Map: userId -> socketId
// For MVP: We broadcast to a room named after the userId (User joins room "user:ID" on connect)
io.to(`user:${receiverId}`).emit('receive_message', newMsg);
// 3. Emit back to Sender (to confirm sent)
socket.emit('message_sent', newMsg);
} catch (err) {
console.error("Chat error", err);
}
});
socket.on('login_flow', (userId) => {
socket.join(`user:${userId}`);
});
// 4. EXPLICIT END CALL
socket.on('end_call', ({ roomId }) => {
if (socket.partnerSocketId) {
io.to(socket.partnerSocketId).emit('call_ended');
}
socket.leave(roomId);
socket.partnerSocketId = null;
});
});
};
export const getIO = () => io;
|