File size: 11,642 Bytes
521a9b6
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1fca8b
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
e1fca8b
16e3957
 
 
 
 
 
 
 
 
 
521a9b6
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
 
 
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
16e3957
521a9b6
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
 
 
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
521a9b6
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1fca8b
 
 
 
 
 
 
 
521a9b6
e1fca8b
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
16e3957
 
 
 
 
 
521a9b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as fs from 'fs';
import * as path from 'path';
import { supabase } from './client';
import { config } from '../config';
import { logger } from '../utils/logger';
import {
  createR2SignedDownloadUrl,
  deleteR2Object,
  downloadR2File,
  isR2ObjectRef,
  putR2Buffer,
  putR2File,
  readR2Text,
} from './r2';

/**
 * Upload a user's input file to the turnitin-inputs bucket.
 * Returns the storage path within the bucket.
 */
export async function uploadInputFile(
  userId: string,
  storageKey: string,
  fileName: string,
  fileBuffer: Buffer,
  upsert = false,
): Promise<string> {
  const ext = path.extname(fileName);
  const storagePath = `${userId}/${storageKey}/input${ext}`;

  if (config.storageProvider === 'r2') {
    try {
      return await putR2Buffer(
        config.inputBucket,
        storagePath,
        fileBuffer,
        getMimeType(ext),
      );
    } catch (error) {
      logger.error('Failed to upload input file to R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const { error } = await supabase.storage
    .from(config.supabaseInputBucket)
    .upload(storagePath, fileBuffer, {
      contentType: getMimeType(ext),
      upsert,
    });

  if (error) {
    logger.error('Failed to upload input file', { storagePath, error: error.message });
    throw error;
  }

  return storagePath;
}

/**
 * Upload an input file from disk. R2 receives a stream so a 100 MB user upload
 * does not need a second full-size in-memory copy inside the worker.
 */
export async function uploadInputFileFromPath(
  userId: string,
  storageKey: string,
  fileName: string,
  localPath: string,
  upsert = false,
): Promise<string> {
  const ext = path.extname(fileName);
  const storagePath = `${userId}/${storageKey}/input${ext}`;

  if (config.storageProvider === 'r2') {
    try {
      return await putR2File(
        config.inputBucket,
        storagePath,
        localPath,
        getMimeType(ext),
      );
    } catch (error) {
      logger.error('Failed to upload input file to R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  // Supabase Storage's Node client expects a buffer. This fallback only serves
  // legacy objects/deployments; R2 is the configured destination for new jobs.
  const fileBuffer = await fs.promises.readFile(localPath);
  const { error } = await supabase.storage
    .from(config.supabaseInputBucket)
    .upload(storagePath, fileBuffer, {
      contentType: getMimeType(ext),
      upsert,
    });

  if (error) {
    logger.error('Failed to upload input file', { storagePath, error: error.message });
    throw error;
  }

  return storagePath;
}

/**
 * Download a file from Supabase Storage to a local path.
 */
export async function downloadInputFile(storagePath: string, localPath: string): Promise<void> {
  if (isR2ObjectRef(storagePath)) {
    try {
      await downloadR2File(storagePath, localPath);
      return;
    } catch (error) {
      logger.error('Failed to download input file from R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const { data, error } = await supabase.storage
    .from(config.supabaseInputBucket)
    .download(storagePath);

  if (error) {
    logger.error('Failed to download input file', { storagePath, error: error.message });
    throw error;
  }

  const buffer = Buffer.from(await data.arrayBuffer());
  const dir = path.dirname(localPath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  fs.writeFileSync(localPath, buffer);
}

/** Delete a staged input when atomic job creation definitively did not happen. */
export async function deleteInputFile(storagePath: string): Promise<void> {
  if (isR2ObjectRef(storagePath)) {
    await deleteR2Object(storagePath);
    return;
  }

  const { error } = await supabase.storage
    .from(config.supabaseInputBucket)
    .remove([storagePath]);
  if (error) {
    logger.error('Failed to delete staged input file', {
      storagePath,
      error: error.message,
    });
    throw error;
  }
}

/**
 * Upload a generated report PDF to the turnitin-reports bucket.
 * Returns the storage path and expiry timestamp.
 */
export async function uploadReportPdf(
  userId: string,
  jobId: string,
  localPdfPath: string,
): Promise<{ storagePath: string; expiresAt: string }> {
  const storagePath = `${userId}/${jobId}/report.pdf`;

  if (config.storageProvider === 'r2') {
    try {
      const objectRef = await putR2File(
        config.reportBucket,
        storagePath,
        localPdfPath,
        'application/pdf',
      );
      return {
        storagePath: objectRef,
        expiresAt: createReportExpiry(),
      };
    } catch (error) {
      logger.error('Failed to upload report PDF to R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const fileBuffer = fs.readFileSync(localPdfPath);

  const { error } = await supabase.storage
    .from(config.supabaseReportBucket)
    .upload(storagePath, fileBuffer, {
      contentType: 'application/pdf',
      upsert: true,
    });

  if (error) {
    logger.error('Failed to upload report PDF', { storagePath, error: error.message });
    throw error;
  }

  return { storagePath, expiresAt: createReportExpiry() };
}

/**
 * Upload a legacy Turnitin Digital Receipt PDF with the same retention policy
 * as the similarity report.
 */
export async function uploadReceiptPdf(
  userId: string,
  jobId: string,
  localPdfPath: string,
): Promise<{ storagePath: string; expiresAt: string }> {
  const storagePath = `${userId}/${jobId}/receipt.pdf`;

  if (config.storageProvider === 'r2') {
    try {
      const objectRef = await putR2File(
        config.reportBucket,
        storagePath,
        localPdfPath,
        'application/pdf',
      );
      return {
        storagePath: objectRef,
        expiresAt: createReportExpiry(),
      };
    } catch (error) {
      logger.error('Failed to upload Digital Receipt PDF to R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const fileBuffer = fs.readFileSync(localPdfPath);

  const { error } = await supabase.storage
    .from(config.supabaseReportBucket)
    .upload(storagePath, fileBuffer, {
      contentType: 'application/pdf',
      upsert: true,
    });

  if (error) {
    logger.error('Failed to upload Digital Receipt PDF', {
      storagePath,
      error: error.message,
    });
    throw error;
  }

  return { storagePath, expiresAt: createReportExpiry() };
}

/**
 * Delete a report PDF from Supabase Storage.
 */
export async function deleteReportPdf(storagePath: string): Promise<void> {
  if (isR2ObjectRef(storagePath)) {
    try {
      await deleteR2Object(storagePath);
      return;
    } catch (error) {
      logger.error('Failed to delete report PDF from R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const { error } = await supabase.storage
    .from(config.supabaseReportBucket)
    .remove([storagePath]);

  if (error) {
    logger.error('Failed to delete report PDF', { storagePath, error: error.message });
    throw error;
  }
}

/**
 * Upload a Playwright browser storage state to the sessions bucket.
 * Returns the storage path.
 */
export async function uploadStorageState(
  accountId: string,
  stateJson: string,
): Promise<string> {
  const storagePath = `${accountId}/state.json`;

  if (config.storageProvider === 'r2') {
    try {
      return await putR2Buffer(
        config.sessionBucket,
        storagePath,
        Buffer.from(stateJson, 'utf-8'),
        'application/json',
      );
    } catch (error) {
      logger.error('Failed to upload storage state to R2', {
        accountId,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const { error } = await supabase.storage
    .from(config.supabaseSessionBucket)
    .upload(storagePath, Buffer.from(stateJson, 'utf-8'), {
      contentType: 'application/json',
      upsert: true,
    });

  if (error) {
    logger.error('Failed to upload storage state', { accountId, error: error.message });
    throw error;
  }

  return storagePath;
}

/**
 * Download a previously saved storage state.
 * Returns the JSON string, or null if not found.
 */
export async function downloadStorageState(storagePath: string): Promise<string | null> {
  if (isR2ObjectRef(storagePath)) {
    try {
      return await readR2Text(storagePath);
    } catch (error) {
      logger.error('Failed to download storage state from R2', {
        storagePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const { data, error } = await supabase.storage
    .from(config.supabaseSessionBucket)
    .download(storagePath);

  if (error) {
    // Not found is not fatal — the account may not have a saved session
    if (error.message?.includes('not found') || error.message?.includes('Object not found')) {
      return null;
    }
    logger.error('Failed to download storage state', { storagePath, error: error.message });
    throw error;
  }

  return await data.text();
}

/**
 * Create a time-limited signed URL for a file in any bucket.
 */
export async function createSignedUrl(
  bucket: string,
  filePath: string,
  expiresInSeconds: number,
  downloadFileName?: string,
): Promise<string> {
  if (isR2ObjectRef(filePath)) {
    try {
      return await createR2SignedDownloadUrl(
        filePath,
        expiresInSeconds,
        downloadFileName,
      );
    } catch (error) {
      logger.error('Failed to create R2 signed URL', {
        bucket,
        filePath,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  const legacyBucket =
    bucket === config.reportBucket
      ? config.supabaseReportBucket
      : bucket === config.inputBucket
        ? config.supabaseInputBucket
        : bucket === config.sessionBucket
          ? config.supabaseSessionBucket
          : bucket;
  const { data, error } = await supabase.storage
    .from(legacyBucket)
    .createSignedUrl(
      filePath,
      expiresInSeconds,
      downloadFileName ? { download: downloadFileName } : undefined,
    );

  if (error) {
    logger.error('Failed to create signed URL', { bucket, filePath, error: error.message });
    throw error;
  }

  return data.signedUrl;
}

function createReportExpiry(): string {
  return new Date(
    Date.now() + config.reportRetentionHours * 60 * 60 * 1000,
  ).toISOString();
}

/** Map file extensions to MIME types */
function getMimeType(ext: string): string {
  const mimeTypes: Record<string, string> = {
    '.pdf': 'application/pdf',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    '.ps': 'application/postscript',
    '.html': 'text/html',
    '.txt': 'text/plain',
    '.rtf': 'application/rtf',
    '.odt': 'application/vnd.oasis.opendocument.text',
    '.hwp': 'application/x-hwp',
  };
  return mimeTypes[ext.toLowerCase()] || 'application/octet-stream';
}