File size: 14,799 Bytes
179db97
 
 
 
 
 
 
 
 
fdd8ef0
179db97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7e4d54
 
179db97
 
 
f7e4d54
179db97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7e4d54
 
 
 
 
 
 
bf40519
f7e4d54
 
 
 
 
 
 
 
 
 
 
 
 
 
1edabae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7e4d54
 
 
1edabae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179db97
 
 
 
 
 
 
 
 
 
 
 
01d5160
f7e4d54
 
 
 
 
1edabae
 
 
 
 
 
f7e4d54
179db97
 
 
 
 
 
 
 
 
01d5160
179db97
01d5160
 
 
 
 
559451d
1edabae
01d5160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179db97
 
01d5160
179db97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01d5160
179db97
 
 
 
 
 
 
 
 
 
 
01d5160
 
 
559451d
1edabae
01d5160
 
 
 
 
 
 
 
 
 
 
 
179db97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1edabae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179db97
 
1edabae
179db97
 
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// ═══════════════════════════════════════════════════════════════════════════
// SESSION API - Create, Join, End, Get sessions
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: { action: 'create' | 'join' | 'end' | 'get', ... }
// ═══════════════════════════════════════════════════════════════════════════

import { NextRequest, NextResponse } from 'next/server';
import { sessionManager } from '@/lib/session-manager';
export { OPTIONS } from '@/lib/cors';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;

    switch (action) {
      case 'create':
        return handleCreate(body);
      case 'join':
        return handleJoin(body);
      case 'end':
        return handleEnd(body);
      case 'get':
        return handleGet(body);
      case 'list':
        return handleList();
      case 'lookup':
        return handleLookup(body);
      default:
        return NextResponse.json({
          success: false,
          error: `Invalid action: ${action}. Valid actions: create, join, end, get, list, lookup`
        }, { status: 400 });
    }
  } catch (error) {
    return NextResponse.json({
      success: false,
      error: 'Invalid JSON body'
    }, { status: 400 });
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// CREATE SESSION
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: {
//   action: 'create',
//   teacherId: string,       // Required: Unique teacher ID
//   teacherName: string,     // Required: Teacher's display name
//   sessionName: string,     // Required: Name of the session
//   description?: string,    // Optional: Session description
//   slideUrls?: string[]     // Optional: Array of slide image URLs
// }
// ═══════════════════════════════════════════════════════════════════════════

function handleCreate(body: any) {
  const { teacherId, teacherName, sessionName, description, slideUrls } = body;

  // Validate required fields
  if (!teacherId || !teacherName || !sessionName) {
    return NextResponse.json({
      success: false,
      error: 'Missing required fields: teacherId, teacherName, sessionName'
    }, { status: 400 });
  }

  // Create session
  const session = sessionManager.createSession(
    teacherId,
    teacherName,
    sessionName,
    description,
    slideUrls || []
  );

  return NextResponse.json({
    success: true,
    data: session,
    message: 'Session created successfully'
  });
}

// ═══════════════════════════════════════════════════════════════════════════
// LOOKUP SESSION BY ROOM CODE
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: { action: 'lookup', roomCode: string }
// ═══════════════════════════════════════════════════════════════════════════

async function handleLookup(body: any) {
  const { roomCode } = body;
  if (!roomCode) {
    return NextResponse.json({ success: false, error: 'Missing roomCode' }, { status: 400 });
  }
  // Try exact room code first
  const byCode = sessionManager.getSessionByRoomCode(String(roomCode));
  if (byCode) {
    return NextResponse.json({ success: true, data: byCode });
  }
  // Fallback: treat as full session ID
  const byId = sessionManager.getSession(String(roomCode));
  if (byId) {
    return NextResponse.json({ success: true, data: byId });
  }

  // Try to find on disk if server restarted
  try {
    const diskId = await findSessionIdByRoomCode(String(roomCode));
    if (diskId) {
      // Just return the lookup info, not the full session tree, or fetch it?
      // handleLookup usually returns the session object.
      const fs = await import('fs/promises');
      const path = await import('path');
      const storageRoot = process.env.SPACE_ID ? '/data' : path.join(process.cwd(), 'data');
      const filePath = path.join(storageRoot, 'sessions', diskId, 'session_url.json');
      const dataStr = await fs.readFile(filePath, 'utf-8');
      const oldState = JSON.parse(dataStr);
      return NextResponse.json({ success: true, data: oldState.session });
    }
  } catch (err) {}

  return NextResponse.json({ success: false, error: 'Session not found' }, { status: 404 });
}

// Helper to scan disk for room codes after restart
async function findSessionIdByRoomCode(roomCode: string): Promise<string | null> {
  try {
    const fs = await import('fs/promises');
    const path = await import('path');
    const storageRoot = process.env.SPACE_ID ? '/data' : path.join(process.cwd(), 'data');
    const sessionsDir = path.join(storageRoot, 'sessions');
    const folders = await fs.readdir(sessionsDir);
    
    for (const folder of folders) {
      try {
        const filePath = path.join(sessionsDir, folder, 'session_url.json');
        const dataStr = await fs.readFile(filePath, 'utf-8');
        const state = JSON.parse(dataStr);
        if (state?.session?.roomCode === roomCode) {
          return folder;
        }
      } catch (err) { }
    }
  } catch (err) {}
  return null;
}

// ═══════════════════════════════════════════════════════════════════════════
// JOIN SESSION
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: {
//   action: 'join',
//   sessionId: string,       // Required: Session ID to join
//   userId: string,          // Required: Unique user ID
//   userName: string         // Required: User's display name
// }
// ═══════════════════════════════════════════════════════════════════════════

async function handleJoin(body: any) {
  let { sessionId, userId, userName } = body;

  // Support joining by 4-digit room code
  if (sessionId && sessionId.length <= 6) {
    const byCode = sessionManager.getSessionByRoomCode(sessionId);
    if (byCode) {
      sessionId = byCode.id;
    } else {
      const diskId = await findSessionIdByRoomCode(sessionId);
      if (diskId) sessionId = diskId;
    }
  }

  // Validate required fields
  if (!sessionId || !userId || !userName) {
    return NextResponse.json({
      success: false,
      error: 'Missing required fields: sessionId, userId, userName'
    }, { status: 400 });
  }

  // Check if session exists in memory
  const session = sessionManager.getSession(sessionId);
  if (!session || !session.isActive) {
    // Try to load from disk
    try {
      const fs = await import('fs/promises');
      const path = await import('path');
      const storageRoot = process.env.SPACE_ID ? '/data' : path.join(process.cwd(), 'data');
      const filePath = path.join(storageRoot, 'sessions', sessionId, 'session_url.json');
      const dataStr = await fs.readFile(filePath, 'utf-8');
      const oldState = JSON.parse(dataStr);
      
      const user = {
        id: userId,
        name: userName,
        role: 'student',
        sessionId,
        joinedAt: new Date().toISOString()
      };

      return NextResponse.json({
        success: true,
        data: {
          user,
          ...oldState
        },
        message: 'Joined past session'
      });
    } catch (err) {
      return NextResponse.json({
        success: false,
        error: 'Session not found or has ended'
      }, { status: 404 });
    }
  }



  // Join session
  const user = sessionManager.joinSession(sessionId, userId, userName, 'student');

  // Get current session state
  const state = sessionManager.getSessionState(sessionId);

  return NextResponse.json({
    success: true,
    data: {
      user,
      session: state?.session,
      currentSlide: state?.currentSlide,
      whiteboardStrokes: state?.whiteboardStrokes,
      reactions: state?.reactions,
      activePoll: state?.activePoll
    },
    message: 'Joined session successfully'
  });
}

// ═══════════════════════════════════════════════════════════════════════════
// END SESSION
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: {
//   action: 'end',
//   sessionId: string        // Required: Session ID to end
// }
// ═══════════════════════════════════════════════════════════════════════════

async function handleEnd(body: any) {
  const { sessionId } = body;

  if (!sessionId) {
    return NextResponse.json({
      success: false,
      error: 'Missing required field: sessionId'
    }, { status: 400 });
  }

  const session = sessionManager.getSession(sessionId);
  if (!session) {
    return NextResponse.json({
      success: false,
      error: 'Session not found'
    }, { status: 404 });
  }

  await sessionManager.endSession(sessionId);

  return NextResponse.json({
    success: true,
    message: 'Session ended successfully'
  });
}

// ═══════════════════════════════════════════════════════════════════════════
// GET SESSION
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: {
//   action: 'get',
//   sessionId: string        // Required: Session ID to get
// }
// ═══════════════════════════════════════════════════════════════════════════

async function handleGet(body: any) {
  const { sessionId } = body;

  if (!sessionId) {
    return NextResponse.json({
      success: false,
      error: 'Missing required field: sessionId'
    }, { status: 400 });
  }

  const state = sessionManager.getSessionState(sessionId);
  if (!state) {
    try {
      const fs = await import('fs/promises');
      const path = await import('path');
      const storageRoot = process.env.SPACE_ID ? '/data' : path.join(process.cwd(), 'data');
      const filePath = path.join(storageRoot, 'sessions', sessionId, 'session_url.json');
      const dataStr = await fs.readFile(filePath, 'utf-8');
      const oldState = JSON.parse(dataStr);
      return NextResponse.json({
        success: true,
        data: oldState
      });
    } catch (err) {
      return NextResponse.json({
        success: false,
        error: 'Session not found'
      }, { status: 404 });
    }
  }

  return NextResponse.json({
    success: true,
    data: state
  });
}

// ═══════════════════════════════════════════════════════════════════════════
// LIST ALL SESSIONS
// ═══════════════════════════════════════════════════════════════════════════
// POST /api/session
// Body: { action: 'list' }
// ═══════════════════════════════════════════════════════════════════════════

async function handleList() {
  const activeSessions = sessionManager.getAllSessions();
  const allSessions = [...activeSessions];

  // Also read older sessions from disk
  try {
    const fs = await import('fs/promises');
    const path = await import('path');
    const storageRoot = process.env.SPACE_ID ? '/data' : path.join(process.cwd(), 'data');
    const sessionsDir = path.join(storageRoot, 'sessions');
    const folders = await fs.readdir(sessionsDir).catch(() => []);
    
    for (const folder of folders) {
      // Skip if already active in memory
      if (activeSessions.some(s => s.id === folder)) continue;
      
      try {
        const filePath = path.join(sessionsDir, folder, 'session_url.json');
        const dataStr = await fs.readFile(filePath, 'utf-8');
        const state = JSON.parse(dataStr);
        if (state?.session) {
          allSessions.push(state.session);
        }
      } catch (err) {}
    }
  } catch (err) {}

  return NextResponse.json({
    success: true,
    data: allSessions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
  });
}