Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | /** * Presence Manager Module * * Manages ephemeral "in classroom" state: * - Enter student into classroom * - Leave classroom * - Query current presence * * Presence is different from enrollment: * - Enrollment: persistent registration in a classroom * - Presence: currently active in the classroom for a live session * * A student can only be present in one classroom at a time. */ import { and, eq, inArray } from 'drizzle-orm' import { db } from '@/db' import { classroomEnrollments, classroomPresence, classrooms, players, type ClassroomPresence, type Classroom, type Player, } from '@/db/schema' import { getSocketIO } from '@/lib/socket-io' import { syncPresence, removePresence } from '@/lib/auth/sync-relationships' // ============================================================================ // Enter/Leave Classroom // ============================================================================ export interface EnterClassroomParams { playerId: string classroomId: string enteredBy: string } export interface EnterClassroomResult { success: boolean presence?: ClassroomPresence error?: string } /** * Enter a student into a classroom * * Requirements: * - Student must be enrolled in the classroom * - Student cannot be in another classroom (must leave first) * * If student is already in this classroom, the timestamp is updated. */ export async function enterClassroom(params: EnterClassroomParams): Promise<EnterClassroomResult> { const { playerId, classroomId, enteredBy } = params // Check if student is enrolled const enrollment = await db.query.classroomEnrollments.findFirst({ where: and( eq(classroomEnrollments.classroomId, classroomId), eq(classroomEnrollments.playerId, playerId) ), }) if (!enrollment) { return { success: false, error: 'Student not enrolled in this classroom' } } // Check if already in another classroom const currentPresence = await db.query.classroomPresence.findFirst({ where: eq(classroomPresence.playerId, playerId), }) if (currentPresence && currentPresence.classroomId !== classroomId) { return { success: false, error: 'Student is in another classroom. Must leave first.', } } // Helper: sync presence to Casbin (non-fatal) const syncPresenceToCasbin = () => { db.query.classrooms .findFirst({ where: eq(classrooms.id, classroomId) }) .then((classroom) => { if (classroom) { syncPresence(classroom.teacherId, playerId).catch((err) => console.error('[auth-sync] Failed to sync presence:', err) ) } }) .catch((err) => console.error('[auth-sync] Failed to look up classroom:', err)) } // Upsert presence if (currentPresence) { // Already in this classroom, update timestamp const [updated] = await db .update(classroomPresence) .set({ enteredAt: new Date(), enteredBy }) .where(eq(classroomPresence.playerId, playerId)) .returning() syncPresenceToCasbin() return { success: true, presence: updated } } // Insert new presence const [inserted] = await db .insert(classroomPresence) .values({ playerId, classroomId, enteredBy, }) .returning() // Emit socket event for real-time updates to teacher const io = await getSocketIO() if (io) { // Get player name for the event const player = await db.query.players.findFirst({ where: eq(players.id, playerId), }) io.to(`classroom:${classroomId}`).emit('student-entered', { playerId, playerName: player?.name ?? 'Unknown', enteredBy, }) } syncPresenceToCasbin() return { success: true, presence: inserted } } /** * Remove a student from their current classroom */ export async function leaveClassroom(playerId: string): Promise<void> { // Get current presence before deleting (need classroomId for socket event) const presence = await db.query.classroomPresence.findFirst({ where: eq(classroomPresence.playerId, playerId), }) if (!presence) return await db.delete(classroomPresence).where(eq(classroomPresence.playerId, playerId)) // Emit socket event for real-time updates to teacher const io = await getSocketIO() if (io) { const player = await db.query.players.findFirst({ where: eq(players.id, playerId), }) io.to(`classroom:${presence.classroomId}`).emit('student-left', { playerId, playerName: player?.name ?? 'Unknown', }) } // Sync to Casbin — downgrade teacher-present back to teacher-enrolled (non-fatal) const classroom = await db.query.classrooms.findFirst({ where: eq(classrooms.id, presence.classroomId), }) if (classroom) { removePresence(classroom.teacherId, playerId).catch((err) => console.error('[auth-sync] Failed to remove presence:', err) ) } } /** * Remove a student from a specific classroom (if they're in it) * * @param removedBy - Who initiated the removal: 'teacher' or 'self' */ export async function leaveSpecificClassroom( playerId: string, classroomId: string, removedBy: 'teacher' | 'self' = 'self' ): Promise<void> { const deleted = await db .delete(classroomPresence) .where( and(eq(classroomPresence.playerId, playerId), eq(classroomPresence.classroomId, classroomId)) ) .returning() // Only emit if something was actually deleted if (deleted.length > 0) { const io = await getSocketIO() if (io) { const player = await db.query.players.findFirst({ where: eq(players.id, playerId), }) // Notify the classroom (for teacher's view) io.to(`classroom:${classroomId}`).emit('student-left', { playerId, playerName: player?.name ?? 'Unknown', }) // Notify the player (for student's view) io.to(`player:${playerId}`).emit('presence-removed', { classroomId, removedBy, }) } } } /** * Remove all students from a classroom * * Useful for "end class" functionality. */ export async function clearClassroomPresence(classroomId: string): Promise<number> { const result = await db .delete(classroomPresence) .where(eq(classroomPresence.classroomId, classroomId)) .returning() return result.length } // ============================================================================ // Query Presence // ============================================================================ export interface PresenceWithClassroom extends ClassroomPresence { classroom?: Classroom } export interface PresenceWithPlayer extends ClassroomPresence { player?: Player } /** * Get a student's current presence (which classroom they're in) */ export async function getStudentPresence(playerId: string): Promise<PresenceWithClassroom | null> { const map = await batchGetStudentPresence([playerId]) return map.get(playerId) ?? null } /** * Batch-fetch presence for multiple players in two queries. * * Returns a Map<playerId, PresenceWithClassroom>. * Players not present in any classroom are omitted from the map. */ export async function batchGetStudentPresence( playerIds: string[] ): Promise<Map<string, PresenceWithClassroom>> { const result = new Map<string, PresenceWithClassroom>() if (playerIds.length === 0) return result // Single query: all presence records for these players const presences = await db.query.classroomPresence.findMany({ where: inArray(classroomPresence.playerId, playerIds), }) if (presences.length === 0) return result // Collect unique classroom IDs const classroomIds = [...new Set(presences.map((p) => p.classroomId))] // Single query: all classrooms const classroomList = await db.query.classrooms.findMany({ where: (c, { inArray: inArr }) => inArr(c.id, classroomIds), }) const classroomMap = new Map(classroomList.map((c) => [c.id, c])) // Assemble results for (const presence of presences) { result.set(presence.playerId, { ...presence, classroom: classroomMap.get(presence.classroomId), }) } return result } /** * Check if a student is present in any classroom */ export async function isStudentPresent(playerId: string): Promise<boolean> { const presence = await db.query.classroomPresence.findFirst({ where: eq(classroomPresence.playerId, playerId), }) return !!presence } /** * Check if a student is present in a specific classroom */ export async function isStudentPresentIn(playerId: string, classroomId: string): Promise<boolean> { const presence = await db.query.classroomPresence.findFirst({ where: and( eq(classroomPresence.playerId, playerId), eq(classroomPresence.classroomId, classroomId) ), }) return !!presence } /** * Get all students currently present in a classroom */ export async function getClassroomPresence(classroomId: string): Promise<PresenceWithPlayer[]> { const presences = await db.query.classroomPresence.findMany({ where: eq(classroomPresence.classroomId, classroomId), }) if (presences.length === 0) return [] const playerIds = presences.map((p) => p.playerId) const players = await db.query.players.findMany({ where: (players, { inArray }) => inArray(players.id, playerIds), }) const playerMap = new Map(players.map((p) => [p.id, p])) return presences.map((p) => ({ ...p, player: playerMap.get(p.playerId), })) } /** * Get count of students present in a classroom */ export async function getPresenceCount(classroomId: string): Promise<number> { const presences = await db.query.classroomPresence.findMany({ where: eq(classroomPresence.classroomId, classroomId), }) return presences.length } /** * Get all player IDs present in a classroom */ export async function getPresentPlayerIds(classroomId: string): Promise<string[]> { const presences = await db.query.classroomPresence.findMany({ where: eq(classroomPresence.classroomId, classroomId), }) return presences.map((p) => p.playerId) } |