import { NextRequest, NextResponse } from 'next/server' import { writeFile } 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) // 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}` // 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 } ) } }