summaryrefslogtreecommitdiff
path: root/frontend/app/api/upload/route.ts
blob: 5ce06405b9b8a169a454a27464f2d05658eb186a (plain)
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
import { NextRequest, NextResponse } from 'next/server'
import { writeFile, unlink } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { randomUUID } from 'crypto'
import { Auth_get_user } from '@/lib/auth'
import { Auth_user_can_upload } from '@/lib/auth_shared'
import { Drive_import } from '@/lib/drive_server'
import { UPLOAD_MAX_FILE_SIZE } from '@/lib/constants'

// POST /api/upload - Simple file upload endpoint
export async function POST(request: NextRequest) {
  try {
    // Check user authentication and permissions
    const user = await Auth_get_user()
    if (!user.isLoggedIn) {
      return NextResponse.json({ error: 'User not authenticated' }, { status: 401 })
    }

    if (!Auth_user_can_upload(user)) {
      return NextResponse.json({ error: 'User does not have upload permissions' }, { status: 403 })
    }

    // Get the target path from query parameters
    const url = new URL(request.url)
    const rawPath = url.searchParams.get('path') || '/'
    const targetPath = decodeURIComponent(rawPath)
    console.log(`targetPath = ${targetPath}`)

    // Handle multipart form data
    const formData = await request.formData()
    const file = formData.get('file') as File

    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 })
    }

    if (file.size > UPLOAD_MAX_FILE_SIZE) {
      return NextResponse.json({
        error: `File exceeds maximum size of ${UPLOAD_MAX_FILE_SIZE / (1024 * 1024)}MB`
      }, { status: 400 })
    }

    const bytes = await file.arrayBuffer()
    const fileBuffer = Buffer.from(bytes)

    // Create temporary file
    const tempFileName = `${randomUUID()}-${file.name}`
    const tempFilePath = join(tmpdir(), tempFileName)

    // Save file to temporary location
    await writeFile(tempFilePath, fileBuffer)

    // Construct the final drive path
    const finalPath = `${targetPath}/${file.name}`
    console.log(`finalPath = ${finalPath}`)

    // Import file using Drive_import (uses --mode move, so temp file is automatically deleted)
    await Drive_import(tempFilePath, finalPath, user.email)

    return NextResponse.json({
      success: true,
      message: 'File uploaded successfully',
      path: finalPath,
      filename: file.name
    })

  } catch (error) {
    console.error('Upload error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal server error' },
      { status: 500 }
    )
  }
}