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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/**
 * @fileoverview Archive controller handling all API endpoint logic.
 * Manages file uploads, extraction, file tree generation, and downloads.
 * @module controllers/archiveController
 */

import fs from 'fs-extra';
import path from 'path';
import { randomInt } from 'crypto';
import archiver from 'archiver';
import { fileURLToPath } from 'url';
import mime from 'mime-types';
import { extractArchive, getExtractionStats } from '../services/extractionService.js';
import { generateFileTree } from '../utils/fileTree.js';
import { validatePath, sanitizeFilename, isArchiveExtension } from '../middleware/security.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Base paths for file storage.
 * @constant {Object}
 */
const PATHS = {
  uploads: path.resolve(__dirname, '../../uploads'),
  extracted: path.resolve(__dirname, '../../extracted'),
};

// Ensure directories exist
await fs.ensureDir(PATHS.uploads);
await fs.ensureDir(PATHS.extracted);

/**
 * Stores active session information for cleanup.
 * @type {Map<string, {createdAt: number, timeout: NodeJS.Timeout}>}
 */
const activeSessions = new Map();

/**
 * Session timeout duration.
 * @constant {number}
 */
const SESSION_TIMEOUT = parseInt(process.env.SESSION_TIMEOUT) || 60000; // 1 minute

/**
 * 8-digit numeric access code pattern used as the public session identifier.
 * @constant {RegExp}
 */
const ACCESS_CODE_PATTERN = /^\d{8}$/;

/**
 * Generates a unique 8-digit numeric code that maps directly to a session folder.
 *
 * @async
 * @returns {Promise<string>} Unique access code
 */
const generateAccessCode = async () => {
  for (let attempt = 0; attempt < 30; attempt++) {
    const code = String(randomInt(0, 100000000)).padStart(8, '0');
    const exists = await fs.pathExists(path.join(PATHS.extracted, code));
    if (!exists && ACCESS_CODE_PATTERN.test(code)) {
      return code;
    }
  }

  throw new Error('Unable to generate a unique access code');
};

/**
 * Schedules automatic cleanup for a session.
 * 
 * @param {string} sessionId - Session ID to schedule cleanup for
 */
const scheduleCleanup = (sessionId) => {
  const createdAt = Date.now();
  const expiresAt = createdAt + SESSION_TIMEOUT;
  const timeout = setTimeout(async () => {
    await cleanupSession(sessionId);
  }, SESSION_TIMEOUT);

  activeSessions.set(sessionId, {
    createdAt,
    expiresAt,
    timeout,
  });

  return { createdAt, expiresAt };
};

/**
 * Gets expiry information for a session.
 *
 * @param {string} sessionId - Session ID
 * @returns {{expiresAt: number|null, timeRemainingMs: number|null}}
 */
const getSessionExpiryInfo = (sessionId) => {
  const session = activeSessions.get(sessionId);
  if (!session?.expiresAt) {
    return {
      expiresAt: null,
      timeRemainingMs: null,
    };
  }

  return {
    expiresAt: session.expiresAt,
    timeRemainingMs: Math.max(0, session.expiresAt - Date.now()),
  };
};

/**
 * Cleans up session files and data.
 * 
 * @async
 * @param {string} sessionId - Session ID to cleanup
 * @returns {Promise<boolean>} True if cleanup succeeded
 */
const cleanupSession = async (sessionId) => {
  try {
    const session = activeSessions.get(sessionId);
    if (session?.timeout) {
      clearTimeout(session.timeout);
    }
    activeSessions.delete(sessionId);

    // Remove extracted files
    const extractedPath = path.join(PATHS.extracted, sessionId);
    await fs.remove(extractedPath);

    // Remove uploaded file
    const uploadPattern = path.join(PATHS.uploads, `${sessionId}*`);
    const uploadFiles = await fs.readdir(PATHS.uploads);
    for (const file of uploadFiles) {
      if (file.startsWith(sessionId)) {
        await fs.remove(path.join(PATHS.uploads, file));
      }
    }

    console.log(`Session cleaned up: ${sessionId}`);
    return true;
  } catch (error) {
    console.error(`Cleanup error for session ${sessionId}:`, error.message);
    return false;
  }
};

/**
 * Handles file upload and extraction.
 * Supports both single and multiple file uploads.
 * POST /api/upload
 * 
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const uploadArchive = async (req, res) => {
  const createdSessions = [];
  const uploadPaths = [];

  try {
    // Support both single file (req.file) and multiple files (req.files)
    const files = req.files || (req.file ? [req.file] : []);
    
    if (files.length === 0) {
      return res.status(400).json({
        error: true,
        message: 'No file uploaded',
        code: 'NO_FILE',
      });
    }

    // Get password from request body (optional)
    const password = req.body?.password || null;
    
    const results = [];
    
    // Process each file
    for (const file of files) {
      const sessionId = await generateAccessCode();
      const uploadPath = file.path;
      
      createdSessions.push(sessionId);
      uploadPaths.push(uploadPath);

      // Create session extraction directory
      const extractionPath = path.join(PATHS.extracted, sessionId);
      await fs.ensureDir(extractionPath, { mode: 0o755 });

      const safeFilename = sanitizeFilename(file.originalname);
      const isArchive = isArchiveExtension(file.originalname);

      if (isArchive) {
        // Extract the archive (with password if provided)
        console.log(`Extracting ${file.originalname} to session ${sessionId}${password ? ' (with password)' : ''}`);
        const result = await extractArchive(uploadPath, extractionPath, { password });

        if (!result.success) {
          // Clean up on extraction failure
          await fs.remove(extractionPath);
          await fs.remove(uploadPath);

          const statusCode = result.code === 'PASSWORD_PROTECTED' ||
                            result.code === 'INCORRECT_PASSWORD' ||
                            result.code === 'CORRUPTED_ARCHIVE' ? 422 : 500;

          return res.status(statusCode).json({
            error: true,
            message: `${file.originalname}: ${result.error}`,
            code: result.code,
          });
        }

        // Clean up uploaded archive (no longer needed)
        await fs.remove(uploadPath);
      } else {
        // Plain files do not need extraction. Store them directly in the session folder.
        await fs.move(uploadPath, path.join(extractionPath, safeFilename), { overwrite: false });
      }

      // Get extraction stats
      const stats = await getExtractionStats(extractionPath);

      // Schedule automatic cleanup
      const expiryInfo = scheduleCleanup(sessionId);

      results.push({
        sessionId,
        accessCode: sessionId,
        filename: safeFilename,
        type: isArchive ? 'archive' : 'file',
        expiresAt: expiryInfo.expiresAt,
        timeRemainingMs: Math.max(0, expiryInfo.expiresAt - Date.now()),
        stats: {
          totalFiles: stats.totalFiles,
          totalSize: stats.totalSize,
        },
      });
    }

    // Return response based on single or multiple files
    if (results.length === 1) {
      res.status(200).json({
        success: true,
        ...results[0],
      });
    } else {
      res.status(200).json({
        success: true,
        count: results.length,
        archives: results,
      });
    }
  } catch (error) {
    console.error('Upload error:', error);

    // Clean up on error
    for (const sessionId of createdSessions) {
      await fs.remove(path.join(PATHS.extracted, sessionId)).catch(() => {});
    }
    for (const uploadPath of uploadPaths) {
      await fs.remove(uploadPath).catch(() => {});
    }

    res.status(500).json({
      error: true,
      message: 'Failed to process archive',
      code: 'INTERNAL_ERROR',
    });
  }
};

/**
 * Returns the file tree for a session.
 * GET /api/files/:sessionId
 * 
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const getFileTree = async (req, res) => {
  try {
    const { sessionId } = req.params;
    const sessionPath = path.join(PATHS.extracted, sessionId);

    // Check if session exists
    const exists = await fs.pathExists(sessionPath);
    if (!exists) {
      return res.status(404).json({
        error: true,
        message: 'Session not found or expired',
        code: 'SESSION_NOT_FOUND',
      });
    }

    // Generate file tree
    const tree = await generateFileTree(sessionPath);

    const expiryInfo = getSessionExpiryInfo(sessionId);

    res.status(200).json({
      success: true,
      sessionId,
      expiresAt: expiryInfo.expiresAt,
      timeRemainingMs: expiryInfo.timeRemainingMs,
      tree,
    });
  } catch (error) {
    console.error('Get file tree error:', error);
    res.status(500).json({
      error: true,
      message: 'Failed to retrieve file structure',
      code: 'INTERNAL_ERROR',
    });
  }
};

/**
 * Downloads an individual file.
 * GET /api/download/:sessionId/file?path=<filepath>
 * 
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const downloadFile = async (req, res) => {
  try {
    const { sessionId } = req.params;
    const filePath = req.query.path;

    // Path validation is done in middleware, but double-check
    const pathValidation = validatePath(filePath);
    if (!pathValidation.valid) {
      return res.status(400).json({
        error: true,
        message: pathValidation.error,
        code: 'INVALID_PATH',
      });
    }

    const sessionPath = path.join(PATHS.extracted, sessionId);
    const fullPath = path.join(sessionPath, filePath);

    // SECURITY: Ensure path stays within session directory
    const normalizedPath = path.normalize(fullPath);
    if (!normalizedPath.startsWith(path.normalize(sessionPath))) {
      return res.status(400).json({
        error: true,
        message: 'Invalid file path',
        code: 'INVALID_PATH',
      });
    }

    // Check if file exists
    const exists = await fs.pathExists(fullPath);
    if (!exists) {
      return res.status(404).json({
        error: true,
        message: 'File not found',
        code: 'FILE_NOT_FOUND',
      });
    }

    // Check if it's a file (not directory)
    const stats = await fs.stat(fullPath);
    if (stats.isDirectory()) {
      return res.status(400).json({
        error: true,
        message: 'Cannot download a directory. Use folder download endpoint.',
        code: 'IS_DIRECTORY',
      });
    }

    // Set headers and send file
    const filename = sanitizeFilename(path.basename(fullPath));
    const contentType = mime.lookup(fullPath) || 'application/octet-stream';
    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.setHeader('Content-Length', stats.size);

    const readStream = fs.createReadStream(fullPath);
    readStream.pipe(res);
  } catch (error) {
    console.error('Download file error:', error);
    res.status(500).json({
      error: true,
      message: 'Failed to download file',
      code: 'INTERNAL_ERROR',
    });
  }
};

/**
 * Views an individual file inline when the browser supports the content type.
 * GET /api/view/:sessionId/file?path=<filepath>
 *
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const viewFile = async (req, res) => {
  try {
    const { sessionId } = req.params;
    const filePath = req.query.path;

    const pathValidation = validatePath(filePath);
    if (!pathValidation.valid) {
      return res.status(400).json({
        error: true,
        message: pathValidation.error,
        code: 'INVALID_PATH',
      });
    }

    const sessionPath = path.join(PATHS.extracted, sessionId);
    const fullPath = path.join(sessionPath, filePath);

    const normalizedPath = path.normalize(fullPath);
    if (!normalizedPath.startsWith(path.normalize(sessionPath))) {
      return res.status(400).json({
        error: true,
        message: 'Invalid file path',
        code: 'INVALID_PATH',
      });
    }

    const exists = await fs.pathExists(fullPath);
    if (!exists) {
      return res.status(404).json({
        error: true,
        message: 'File not found',
        code: 'FILE_NOT_FOUND',
      });
    }

    const stats = await fs.stat(fullPath);
    if (stats.isDirectory()) {
      return res.status(400).json({
        error: true,
        message: 'Cannot view a directory. Open or download a file instead.',
        code: 'IS_DIRECTORY',
      });
    }

    const filename = sanitizeFilename(path.basename(fullPath));
    const contentType = mime.lookup(fullPath) || 'application/octet-stream';
    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Disposition', `inline; filename="${filename}"`);
    res.setHeader('Content-Length', stats.size);
    res.setHeader('X-Content-Type-Options', 'nosniff');

    const readStream = fs.createReadStream(fullPath);
    readStream.pipe(res);
  } catch (error) {
    console.error('View file error:', error);
    res.status(500).json({
      error: true,
      message: 'Failed to view file',
      code: 'INTERNAL_ERROR',
    });
  }
};

/**
 * Downloads a folder as a ZIP archive.
 * GET /api/download/:sessionId/folder?path=<folderpath>
 * 
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const downloadFolder = async (req, res) => {
  try {
    const { sessionId } = req.params;
    const folderPath = req.query.path || '/';

    // Path validation
    if (folderPath !== '/') {
      const pathValidation = validatePath(folderPath);
      if (!pathValidation.valid) {
        return res.status(400).json({
          error: true,
          message: pathValidation.error,
          code: 'INVALID_PATH',
        });
      }
    }

    const sessionPath = path.join(PATHS.extracted, sessionId);
    const fullPath = folderPath === '/' ? sessionPath : path.join(sessionPath, folderPath);

    // SECURITY: Ensure path stays within session directory
    const normalizedPath = path.normalize(fullPath);
    if (!normalizedPath.startsWith(path.normalize(sessionPath))) {
      return res.status(400).json({
        error: true,
        message: 'Invalid folder path',
        code: 'INVALID_PATH',
      });
    }

    // Check if folder exists
    const exists = await fs.pathExists(fullPath);
    if (!exists) {
      return res.status(404).json({
        error: true,
        message: 'Folder not found',
        code: 'FILE_NOT_FOUND',
      });
    }

    // Check if it's a directory
    const stats = await fs.stat(fullPath);
    if (!stats.isDirectory()) {
      return res.status(400).json({
        error: true,
        message: 'Path is not a folder. Use file download endpoint.',
        code: 'NOT_DIRECTORY',
      });
    }

    // Create ZIP archive
    const folderName = folderPath === '/' ? 'archive' : sanitizeFilename(path.basename(fullPath));
    const zipFilename = `${folderName}.zip`;

    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', `attachment; filename="${zipFilename}"`);

    const archive = archiver('zip', {
      zlib: { level: 6 }, // Balanced compression
    });

    archive.on('error', (err) => {
      console.error('Archiver error:', err);
      if (!res.headersSent) {
        res.status(500).json({
          error: true,
          message: 'Failed to create archive',
          code: 'ARCHIVE_ERROR',
        });
      }
    });

    archive.pipe(res);
    archive.directory(fullPath, false);
    await archive.finalize();
  } catch (error) {
    console.error('Download folder error:', error);
    if (!res.headersSent) {
      res.status(500).json({
        error: true,
        message: 'Failed to download folder',
        code: 'INTERNAL_ERROR',
      });
    }
  }
};

/**
 * Manually deletes a session.
 * DELETE /api/session/:sessionId
 * 
 * @async
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
export const deleteSession = async (req, res) => {
  try {
    const { sessionId } = req.params;
    const sessionPath = path.join(PATHS.extracted, sessionId);

    // Check if session exists
    const exists = await fs.pathExists(sessionPath);
    if (!exists) {
      return res.status(404).json({
        error: true,
        message: 'Session not found',
        code: 'SESSION_NOT_FOUND',
      });
    }

    // Clean up the session
    const success = await cleanupSession(sessionId);

    if (success) {
      res.status(200).json({
        success: true,
        message: 'Session deleted successfully',
      });
    } else {
      res.status(500).json({
        error: true,
        message: 'Failed to delete session',
        code: 'CLEANUP_ERROR',
      });
    }
  } catch (error) {
    console.error('Delete session error:', error);
    res.status(500).json({
      error: true,
      message: 'Failed to delete session',
      code: 'INTERNAL_ERROR',
    });
  }
};

/**
 * Gets session information.
 * Used internally for monitoring.
 * 
 * @param {string} sessionId - Session ID
 * @returns {Object|null} Session info or null
 */
export const getSessionInfo = (sessionId) => {
  return activeSessions.get(sessionId) || null;
};

/**
 * Gets count of active sessions.
 * 
 * @returns {number} Number of active sessions
 */
export const getActiveSessionCount = () => {
  return activeSessions.size;
};