summaryrefslogtreecommitdiff
path: root/app/Console/Commands/CleanupOrphanedChunks.php
blob: 6c54aaab84cddbcecaafeba475fe46643fe71961 (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
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class CleanupOrphanedChunks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'files:cleanup-chunks';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete orphaned upload chunks older than 24 hours';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $cutoff = now()->subHours(config('fileupload.chunk_cleanup_hours', 24));

        $orphanedChunks = DB::table('upload_chunks')
            ->where('created_at', '<', $cutoff)
            ->get();

        $this->info("Found {$orphanedChunks->count()} orphaned chunks");

        $uploadIds = $orphanedChunks->pluck('upload_id')->unique();

        foreach ($uploadIds as $uploadId) {
            // Delete directory for this upload_id
            $chunkPath = 'chunks/' . $uploadId;

            if (Storage::exists($chunkPath)) {
                Storage::deleteDirectory($chunkPath);
                $this->info("Deleted chunk directory: {$chunkPath}");
            }

            // Delete database records
            DB::table('upload_chunks')->where('upload_id', $uploadId)->delete();
        }

        $this->info("Cleanup complete. Removed chunks for {$uploadIds->count()} uploads.");

        return 0;
    }
}