summaryrefslogtreecommitdiff
path: root/frontend/app/api/storage/route.ts
blob: 66f28171f247e4f2dc935d1994cf98dc85eade77 (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
76
77
78
79
80
import { NextResponse } from 'next/server'
import { exec } from 'child_process'
import { promisify } from 'util'

const execAsync = promisify(exec)

// Cache for 10 seconds
let cacheTimestamp = 0
let cachedData: StorageData | null = null

interface StorageData {
  activeDriveUsage: number
  totalDiskCapacity: number
  totalDiskUsed: number
  availableDisk: number
}

async function fetchStorageData(): Promise<StorageData> {
  const now = Date.now()
  
  // Return cached data if less than 10 seconds old
  if (cachedData && now - cacheTimestamp < 10000) {
    return cachedData
  }

  try {
    // Get active drive usage in bytes
    const { stdout: driveSize } = await execAsync('fctdrive drive-size')
    const activeDriveUsage = parseInt(driveSize.trim()) || 0

    // Get disk usage in bytes
    const fctdrivePath = process.env.FCTDRIVE_PATH || '/home/diogo464/dev/fctdrive'
    const { stdout: dfOutput } = await execAsync(`df -B1 "${fctdrivePath}"`)
    
    // Parse df output - second line contains the data
    const lines = dfOutput.trim().split('\n')
    const dataLine = lines[1] // Skip header line
    const columns = dataLine.split(/\s+/)
    
    const totalDiskCapacity = parseInt(columns[1]) || 0
    const totalDiskUsed = parseInt(columns[2]) || 0
    const availableDisk = parseInt(columns[3]) || 0

    const data: StorageData = {
      activeDriveUsage,
      totalDiskCapacity,
      totalDiskUsed,
      availableDisk
    }

    // Update cache
    cachedData = data
    cacheTimestamp = now

    return data
  } catch (error) {
    console.error('Failed to fetch storage data:', error)
    
    // Return zeros on error as requested
    return {
      activeDriveUsage: 0,
      totalDiskCapacity: 0,
      totalDiskUsed: 0,
      availableDisk: 0
    }
  }
}

export async function GET() {
  try {
    const data = await fetchStorageData()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Storage API error:', error)
    return NextResponse.json(
      { error: 'Failed to fetch storage data' },
      { status: 500 }
    )
  }
}