94 lines
2.8 KiB
PHP
94 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Features\Uploads\Controllers;
|
|
|
|
use App\Features\Consoles\Models\Console;
|
|
use App\Features\Games\Repositories\GameRepository;
|
|
use App\Features\Games\Repositories\RomFileRepository;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Jobs\ScrapeCoverJob;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Str;
|
|
use Inertia\Inertia;
|
|
use Inertia\Response;
|
|
|
|
class UploadController extends Controller
|
|
{
|
|
public function __construct(
|
|
private GameRepository $gameRepository,
|
|
private RomFileRepository $romFileRepository
|
|
) {}
|
|
|
|
public function index(): Response
|
|
{
|
|
return Inertia::render('Upload/Index', [
|
|
'consoles' => Console::orderBy('name')->get(),
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request): RedirectResponse
|
|
{
|
|
$request->validate([
|
|
'console_id' => 'required|exists:consoles,id',
|
|
'rom_files' => 'required|array|min:1',
|
|
'rom_files.*' => 'file|max:102400',
|
|
]);
|
|
|
|
$console = Console::findOrFail($request->console_id);
|
|
$allowedExtensions = $console->rom_extensions;
|
|
|
|
foreach ($request->file('rom_files') as $file) {
|
|
$extension = strtolower($file->getClientOriginalExtension());
|
|
|
|
if (! in_array($extension, $allowedExtensions)) {
|
|
continue;
|
|
}
|
|
|
|
$filename = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
|
|
$filename = "{$filename}.{$extension}";
|
|
|
|
$hash = hash_file('sha256', $file->getRealPath());
|
|
|
|
$existing = $this->romFileRepository->findByHash($hash);
|
|
if ($existing) {
|
|
continue;
|
|
}
|
|
|
|
$path = $file->storeAs(
|
|
"roms/{$console->slug}",
|
|
$filename,
|
|
'local'
|
|
);
|
|
|
|
$gameTitle = Str::title(str_replace(['-', '_'], ' ', pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)));
|
|
$gameSlug = Str::slug($gameTitle);
|
|
|
|
$game = $this->gameRepository->firstOrCreate(
|
|
[
|
|
'console_id' => $console->id,
|
|
'slug' => $gameSlug,
|
|
],
|
|
[
|
|
'title' => $gameTitle,
|
|
]
|
|
);
|
|
|
|
$this->romFileRepository->create([
|
|
'game_id' => $game->id,
|
|
'file_path' => $path,
|
|
'file_name' => $file->getClientOriginalName(),
|
|
'file_size' => $file->getSize(),
|
|
'file_hash' => $hash,
|
|
]);
|
|
|
|
if (! $game->cover_path) {
|
|
ScrapeCoverJob::dispatch($game);
|
|
}
|
|
}
|
|
|
|
return redirect()->route('dashboard')
|
|
->with('success', 'ROMs uploaded successfully.');
|
|
}
|
|
}
|