You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

170 lines
5.8 KiB

5 months ago
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Api\Concerns\ResolvesParticipantApplication;
use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\ApplicationFile;
4 months ago
use App\Support\SignupFormFileRules;
5 months ago
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
3 months ago
use Illuminate\Support\Facades\Log;
5 months ago
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
5 months ago
use Symfony\Component\HttpFoundation\StreamedResponse;
5 months ago
class ApplicationFileController extends Controller
{
use ResolvesParticipantApplication;
private function application(Request $request): Application
{
$app = $this->participantApplication($request);
$app->assertMayEditSignup('file');
return $app;
}
public function store(Request $request): JsonResponse
{
$maxKb = (int) config('contest.file_max_kb', 20480);
$data = $request->validate([
'kind' => ['required', 'string', Rule::in(['plan', 'supporting'])],
'file' => ['required', 'file', 'max:'.$maxKb],
]);
$app = $this->application($request);
4 months ago
$app->loadMissing('competition');
5 months ago
$uploaded = $data['file'];
$ext = strtolower($uploaded->getClientOriginalExtension());
4 months ago
$schemaRow = SignupFormFileRules::fileFieldRow($app->competition, $data['kind']);
$allowedExt = SignupFormFileRules::effectiveAllowedExtensions($schemaRow);
if (! in_array($ext, $allowedExt, true)) {
5 months ago
throw ValidationException::withMessages([
4 months ago
'file' => ['仅支持:'.implode('、', $allowedExt)],
5 months ago
]);
}
4 months ago
$maxFiles = SignupFormFileRules::maxCount($schemaRow);
if ($maxFiles !== null) {
$current = $app->files()->where('kind', $data['kind'])->count();
if ($current >= $maxFiles) {
throw ValidationException::withMessages([
'file' => ['最多可上传 '.$maxFiles.' 个文件'],
]);
}
}
// public 磁盘 throw=false 时写失败可能返回 false(落库成 path="0"),目录不可写等场景也会抛异常
try {
$path = $uploaded->store("applications/{$app->id}", 'public');
} catch (\Throwable $e) {
Log::error('application.file.store_exception', [
'application_id' => $app->id,
'kind' => $data['kind'],
'original_name' => $uploaded->getClientOriginalName(),
'error' => $e->getMessage(),
]);
throw ValidationException::withMessages([
'file' => ['文件保存失败,请稍后重试'],
]);
}
if (! is_string($path) || $path === '' || $path === '0' || ! Storage::disk('public')->exists($path)) {
Log::error('application.file.store_failed', [
'application_id' => $app->id,
'kind' => $data['kind'],
'original_name' => $uploaded->getClientOriginalName(),
'path_result' => is_string($path) ? $path : var_export($path, true),
]);
throw ValidationException::withMessages([
'file' => ['文件保存失败,请稍后重试'],
]);
}
5 months ago
$file = ApplicationFile::create([
'application_id' => $app->id,
'kind' => $data['kind'],
'disk' => 'public',
'path' => $path,
'original_name' => $uploaded->getClientOriginalName(),
'size' => $uploaded->getSize(),
'mime' => $uploaded->getClientMimeType(),
]);
return response()->json([
'id' => $file->id,
'kind' => $file->kind,
'original_name' => $file->original_name,
'size' => $file->size,
5 months ago
'url' => $file->participantPreviewSignedUrl(),
5 months ago
], 201);
}
5 months ago
/**
* 选手附件预览(签名 URL,GET 无需 Bearer;由 API 在 json 中下发短期有效链接)。
*/
public function downloadSigned(Request $request, ApplicationFile $file): StreamedResponse
{
$file->assertStoredFileExists();
5 months ago
return Storage::disk($file->disk)->response(
$file->path,
$file->clientDownloadName(),
[
'Cache-Control' => 'private, no-store',
3 months ago
'Connection' => 'close',
5 months ago
],
$file->preferredStreamDisposition(),
);
}
5 months ago
public function destroy(Request $request, ApplicationFile $file): JsonResponse
{
3 months ago
$competition = $this->resolvePublishedCompetitionFromRequest($request);
$application = Application::query()
->where('user_id', $request->user()->id)
->where('competition_id', $competition->id)
->first();
if ($application === null || (int) $file->application_id !== (int) $application->id) {
5 months ago
abort(404);
}
3 months ago
$application->assertMayEditSignup('file');
$disk = $file->disk;
$path = $file->path;
$fileId = $file->id;
5 months ago
$file->delete();
3 months ago
$this->queueStorageFileRemoval($disk, $path, $fileId);
3 months ago
5 months ago
return response()->json(['message' => 'deleted']);
}
3 months ago
private function queueStorageFileRemoval(string $disk, string $path, int $fileId): void
{
dispatch(static function () use ($disk, $path, $fileId): void {
try {
Storage::disk($disk)->delete($path);
} catch (\Throwable $e) {
Log::warning('application.file.storage_delete_failed', [
'file_id' => $fileId,
'disk' => $disk,
'path' => $path,
'error' => $e->getMessage(),
]);
}
})->afterResponse();
}
5 months ago
}