feat: add Sveden update feature

- SvedenController: upload zip and extract to public/sveden
- UpdateSvedenAction: orchestrates temp file handling and extraction
- ExtractSvedenArchiveTask: validates and extracts sveden/abitur folders with security checks
- Sveden.vue: upload UI with progress indicator
- Added routes: GET/POST /dashboard/sveden
- Added quick action: Обновить Sveden
This commit is contained in:
F4ilji
2026-06-30 16:12:16 +05:00
parent 20f615365b
commit c9fca0bf29
6 changed files with 512 additions and 0 deletions
@@ -0,0 +1,42 @@
<?php
namespace App\Containers\Dashboard\Actions\Sveden;
use App\Containers\Dashboard\Tasks\Sveden\ExtractSvedenArchiveTask;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
class UpdateSvedenAction
{
public function __construct(
private readonly ExtractSvedenArchiveTask $extractTask,
) {}
public function run(UploadedFile $file): array
{
$tempPath = storage_path('app/temp/sveden_' . Str::random(16) . '.zip');
$this->ensureTempDirectory();
try {
$file->move(dirname($tempPath), basename($tempPath));
$result = $this->extractTask->run($tempPath);
return $result;
} finally {
if (file_exists($tempPath)) {
unlink($tempPath);
}
}
}
private function ensureTempDirectory(): void
{
$tempDir = storage_path('app/temp');
if (!is_dir($tempDir)) {
mkdir($tempDir, 0755, true);
}
}
}
@@ -0,0 +1,153 @@
<?php
namespace App\Containers\Dashboard\Tasks\Sveden;
use ZipArchive;
class ExtractSvedenArchiveTask
{
private const ALLOWED_FOLDERS = ['sveden', 'abitur'];
private const PUBLIC_PATH = 'public';
private const DANGEROUS_EXTENSIONS = [
'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml',
'asp', 'aspx', 'jsp', 'cgi', 'pl',
'sh', 'bash', 'zsh', 'exe', 'bat', 'cmd',
'env', 'conf', 'ini', 'htaccess',
];
public function run(string $zipPath): array
{
if (!file_exists($zipPath)) {
throw new \RuntimeException("ZIP file not found: {$zipPath}");
}
$zip = new ZipArchive();
$openResult = $zip->open($zipPath);
if ($openResult !== true) {
throw new \RuntimeException("Failed to open ZIP archive (code: {$openResult})");
}
$this->validateZipEntries($zip);
$rootFolders = $this->getRootFolders($zip);
$allowedFolders = array_intersect($rootFolders, self::ALLOWED_FOLDERS);
if (empty($allowedFolders)) {
$zip->close();
throw new \RuntimeException(
'Archive does not contain sveden or abitur folders. Found: ' . implode(', ', $rootFolders ?: ['none'])
);
}
$updated = [];
foreach ($allowedFolders as $folder) {
$this->extractFolder($zip, $folder);
$updated[] = $folder;
}
$zip->close();
return [
'success' => true,
'updated' => $updated,
'skipped' => array_diff($rootFolders, self::ALLOWED_FOLDERS),
];
}
private function getRootFolders(ZipArchive $zip): array
{
$folders = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
$parts = explode('/', $name);
if (count($parts) > 1 && !empty($parts[0])) {
$folders[$parts[0]] = true;
}
}
return array_keys($folders);
}
private function extractFolder(ZipArchive $zip, string $folderName): void
{
$destination = public_path($folderName);
if (!is_dir($destination)) {
mkdir($destination, 0755, true);
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if (strpos($name, $folderName . '/') !== 0) {
continue;
}
$relativePath = substr($name, strlen($folderName . '/'));
if (empty($relativePath)) {
continue;
}
$targetPath = $destination . '/' . $relativePath;
$this->validateFileExtension($relativePath);
if (substr($name, -1) === '/') {
if (!is_dir($targetPath)) {
mkdir($targetPath, 0755, true);
}
} else {
$parentDir = dirname($targetPath);
if (!is_dir($parentDir)) {
mkdir($parentDir, 0755, true);
}
$content = $zip->getFromIndex($i);
file_put_contents($targetPath, $content);
}
}
}
private function validateFileExtension(string $filePath): void
{
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if (in_array($extension, self::DANGEROUS_EXTENSIONS, true)) {
throw new \RuntimeException(
"Potentially dangerous file detected: {$filePath}"
);
}
}
private function validateZipEntries(ZipArchive $zip): void
{
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
if (strpos($filename, '..') !== false) {
throw new \RuntimeException(
"Potentially malicious ZIP entry detected: {$filename}"
);
}
if (preg_match('/^[a-zA-Z]:/', $filename)) {
throw new \RuntimeException(
"Potentially malicious ZIP entry detected: {$filename}"
);
}
if (strpos($filename, '/') === 0) {
throw new \RuntimeException(
"Potentially malicious ZIP entry detected: {$filename}"
);
}
}
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Containers\Dashboard\UI\WEB\Controllers;
use App\Containers\Dashboard\Actions\Sveden\UpdateSvedenAction;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
class SvedenController extends Controller
{
public function __construct(
private readonly UpdateSvedenAction $updateAction,
) {}
public function index(): \Inertia\Response
{
return Inertia::render('Dashboard/Sveden');
}
public function store(Request $request): JsonResponse
{
$request->validate([
'archive' => ['required', 'file', 'mimes:zip', 'max:102400'],
]);
try {
$result = $this->updateAction->run($request->file('archive'));
return response()->json($result);
} catch (\Throwable $e) {
report($e);
return response()->json([
'success' => false,
'message' => 'Ошибка при обновлении: ' . $e->getMessage(),
], 500);
}
}
}
@@ -27,6 +27,7 @@ use App\Containers\Dashboard\UI\WEB\Controllers\EditSliderController;
use App\Containers\Dashboard\UI\WEB\Controllers\FacultyController;
use App\Containers\Dashboard\UI\WEB\Controllers\FacultyWorkerController;
use App\Containers\Dashboard\UI\WEB\Controllers\IndexDashboardController;
use App\Containers\Dashboard\UI\WEB\Controllers\IntegrationCredentialsController;
use App\Containers\Dashboard\UI\WEB\Controllers\JournalIssueController;
use App\Containers\Dashboard\UI\WEB\Controllers\MainSectionController;
use App\Containers\Dashboard\UI\WEB\Controllers\PageController;
@@ -36,6 +37,7 @@ use App\Containers\Dashboard\UI\WEB\Controllers\ProcessMixedFilesController;
use App\Containers\Dashboard\UI\WEB\Controllers\PublishPostController;
use App\Containers\Dashboard\UI\WEB\Controllers\QuickUploadController;
use App\Containers\Dashboard\UI\WEB\Controllers\ScheduleController;
use App\Containers\Dashboard\UI\WEB\Controllers\SvedenController;
use App\Containers\Dashboard\UI\WEB\Controllers\SliderController;
use App\Containers\Dashboard\UI\WEB\Controllers\StoreFilesController;
use App\Containers\Dashboard\UI\WEB\Controllers\StoreSlideController;
@@ -61,10 +63,16 @@ Route::post('/dashboard/logout', [AuthenticatedSessionController::class, 'destro
// Authenticated dashboard routes
Route::middleware(['access-check', 'dashboard.auth'])->group(function () {
Route::get('/dashboard', IndexDashboardController::class)->name('dashboard.index');
Route::get('/dashboard/deploy', [DeployController::class, 'index'])->name('dashboard.deploy.index');
Route::post('/dashboard/deploy', [DeployController::class, 'deploy'])->name('dashboard.deploy');
Route::get('/dashboard/deploy/status', [DeployController::class, 'status'])->name('dashboard.deploy.status');
Route::get('/dashboard/deploy/log', [DeployController::class, 'log'])->name('dashboard.deploy.log');
Route::get('/dashboard/deploy/history', [DeployController::class, 'history'])->name('dashboard.deploy.history');
Route::post('/dashboard/deploy/clear', [DeployController::class, 'clear'])->name('dashboard.deploy.clear');
Route::get('/dashboard/sveden', [SvedenController::class, 'index'])->name('dashboard.sveden');
Route::post('/dashboard/sveden', [SvedenController::class, 'store'])->name('dashboard.sveden.store');
// CRUD постов
Route::prefix('/dashboard/posts')->name('dashboard.posts.')->group(function () {
Route::get('/', [PostController::class, 'index'])->name('index');
@@ -406,6 +414,16 @@ Route::middleware(['access-check', 'dashboard.auth'])->group(function () {
Route::put('/{pageReferenceList}', [PageReferenceListController::class, 'update'])->name('update');
Route::delete('/{pageReferenceList}', [PageReferenceListController::class, 'destroy'])->name('destroy');
});
// CRUD интеграционных ключей
Route::prefix('/dashboard/integration-credentials')->name('dashboard.integration-credentials.')->group(function () {
Route::get('/', [IntegrationCredentialsController::class, 'index'])->name('index');
Route::get('/create', [IntegrationCredentialsController::class, 'create'])->name('create');
Route::post('/', [IntegrationCredentialsController::class, 'store'])->name('store');
Route::get('/{credential}/edit', [IntegrationCredentialsController::class, 'edit'])->name('edit');
Route::put('/{credential}', [IntegrationCredentialsController::class, 'update'])->name('update');
Route::delete('/{credential}', [IntegrationCredentialsController::class, 'destroy'])->name('destroy');
});
});
@@ -25,4 +25,10 @@ export const quickActions = [
href: null,
icon: 'upload',
},
{
label: 'Обновить Sveden',
route: 'dashboard.sveden',
href: null,
icon: 'cog',
},
];
+252
View File
@@ -0,0 +1,252 @@
<template>
<DashboardLayout>
<template #header-title>Обновить Sveden</template>
<template #header-subtitle>Загрузите ZIP-архив для обновления данных</template>
<template #header-icon>
<DashboardIcon name="arrow-path" size="5" class="text-primary" />
</template>
<div class="max-w-2xl mx-auto">
<!-- Flash Messages -->
<transition
enter-active-class="transition duration-200"
enter-from-class="opacity-0 -translate-y-2"
enter-to-class="opacity-100 translate-y-0"
leave-active-class="transition duration-150"
leave-from-class="opacity-100 translate-y-0"
leave-to-class="opacity-0 -translate-y-2"
>
<div v-if="successMessage" class="mb-4 p-4 bg-emerald-50 border border-emerald-200 rounded-lg">
<div class="flex items-start gap-3">
<DashboardIcon name="check-circle" size="5" class="text-emerald-600 flex-shrink-0 mt-0.5" />
<p class="text-sm font-medium text-emerald-800">{{ successMessage }}</p>
</div>
</div>
</transition>
<transition
enter-active-class="transition duration-200"
enter-from-class="opacity-0 -translate-y-2"
enter-to-class="opacity-100 translate-y-0"
leave-active-class="transition duration-150"
leave-from-class="opacity-100 translate-y-0"
leave-to-class="opacity-0 -translate-y-2"
>
<div v-if="errorMessage" class="mb-4 p-4 bg-rose-50 border border-rose-200 rounded-lg">
<div class="flex items-start gap-3">
<DashboardIcon name="x-circle" size="5" class="text-rose-600 flex-shrink-0 mt-0.5" />
<p class="text-sm font-medium text-rose-800">{{ errorMessage }}</p>
</div>
</div>
</transition>
<!-- Upload Card -->
<div class="bg-layer border border-layer-line rounded-lg shadow-sm">
<div class="p-6">
<h2 class="text-lg font-medium text-foreground mb-4">Загрузка архива</h2>
<p class="text-sm text-muted-foreground-1 mb-6">
Загрузите ZIP-архив containing папки <code class="px-1.5 py-0.5 bg-background-2 rounded text-xs">sveden</code> и/или <code class="px-1.5 py-0.5 bg-background-2 rounded text-xs">abitur</code>.
Архив будет распакован, а содержимое папок заменит текущие файлы в <code class="px-1.5 py-0.5 bg-background-2 rounded text-xs">public/</code>.
</p>
<!-- Dropzone -->
<div
class="relative border-2 border-dashed rounded-lg p-8 text-center transition-all duration-200"
:class="[
isDragging
? 'border-primary bg-primary/5'
: 'border-layer-line hover:border-primary/50 hover:bg-primary/5'
]"
@dragover.prevent="isDragging = true"
@dragleave.prevent="isDragging = false"
@drop.prevent="handleDrop"
>
<input
ref="fileInput"
type="file"
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
@change="handleFileSelect"
accept=".zip"
/>
<div v-if="!selectedFile" class="space-y-3">
<DashboardIcon name="cloud-arrow-up" size="12" class="mx-auto text-muted-foreground-1" />
<div>
<p class="text-sm font-medium text-foreground">
<span class="text-primary">Нажмите для загрузки</span> или перетащите ZIP-архив
</p>
<p class="text-xs text-muted-foreground-1 mt-1">
Только ZIP-файлы (макс. 100 МБ)
</p>
</div>
</div>
<div v-else class="space-y-3">
<DashboardIcon name="check-circle" size="12" class="mx-auto text-primary" />
<div>
<p class="text-sm font-medium text-foreground">{{ selectedFile.name }}</p>
<p class="text-xs text-muted-foreground-1 mt-1">{{ formatFileSize(selectedFile.size) }}</p>
</div>
<button
type="button"
class="text-xs text-primary hover:text-primary/80"
@click.stop="clearFile"
>
Удалить и выбрать другой файл
</button>
</div>
</div>
<!-- Upload Button -->
<div class="mt-6 flex justify-end">
<button
type="button"
:disabled="!selectedFile || uploading"
class="inline-flex items-center gap-2 px-4 py-2 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
@click="upload"
>
<DashboardIcon v-if="uploading" name="spinner" size="4" class="animate-spin" />
<DashboardIcon v-else name="arrow-path" size="4" />
{{ uploading ? 'Загрузка...' : 'Обновить' }}
</button>
</div>
</div>
</div>
<!-- Result Card -->
<div v-if="result" class="mt-6 bg-layer border border-layer-line rounded-lg shadow-sm">
<div class="p-6">
<h2 class="text-lg font-medium text-foreground mb-4">Результат обновления</h2>
<div class="space-y-4">
<div v-if="result.updated && result.updated.length > 0">
<label class="block text-sm font-medium text-muted-foreground-1 mb-2">Обновлено:</label>
<div class="flex flex-wrap gap-2">
<span
v-for="folder in result.updated"
:key="folder"
class="inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-100 text-emerald-800 text-sm font-medium rounded-lg"
>
<DashboardIcon name="check-circle" size="3" class="text-emerald-600" />
{{ folder }}
</span>
</div>
</div>
<div v-if="result.skipped && result.skipped.length > 0">
<label class="block text-sm font-medium text-muted-foreground-1 mb-2">Пропущено (не sveden/abitur):</label>
<div class="flex flex-wrap gap-2">
<span
v-for="folder in result.skipped"
:key="folder"
class="inline-flex items-center gap-1 px-2.5 py-1 bg-amber-100 text-amber-800 text-sm font-medium rounded-lg"
>
<DashboardIcon name="exclamation-triangle" size="3" class="text-amber-600" />
{{ folder }}
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</DashboardLayout>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import DashboardLayout from './Components/DashboardLayout.vue';
import DashboardIcon from './Components/DashboardIcon.vue';
defineOptions({
name: 'Sveden',
});
onMounted(() => {
document.title = 'Обновить Sveden | Dashboard';
});
const fileInput = ref(null);
const selectedFile = ref(null);
const isDragging = ref(false);
const uploading = ref(false);
const successMessage = ref(null);
const errorMessage = ref(null);
const result = ref(null);
const handleFileSelect = (event) => {
const file = event.target.files[0];
if (file) {
selectedFile.value = file;
errorMessage.value = null;
result.value = null;
}
};
const handleDrop = (event) => {
isDragging.value = false;
const file = event.dataTransfer.files[0];
if (file) {
selectedFile.value = file;
errorMessage.value = null;
result.value = null;
}
};
const clearFile = () => {
selectedFile.value = null;
result.value = null;
if (fileInput.value) {
fileInput.value.value = '';
}
};
const upload = async () => {
if (!selectedFile.value) return;
uploading.value = true;
errorMessage.value = null;
successMessage.value = null;
result.value = null;
const formData = new FormData();
formData.append('archive', selectedFile.value);
try {
const response = await fetch(route('dashboard.sveden.store'), {
method: 'POST',
body: formData,
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
'X-Requested-With': 'XMLHttpRequest',
},
});
const data = await response.json();
if (data.success) {
result.value = data;
successMessage.value = 'Архив успешно обновлён';
selectedFile.value = null;
if (fileInput.value) {
fileInput.value.value = '';
}
} else {
errorMessage.value = data.message || 'Ошибка при обновлении';
}
} catch (error) {
errorMessage.value = 'Ошибка при загрузке файла. Попробуйте ещё раз.';
console.error('Upload error:', error);
} finally {
uploading.value = false;
}
};
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Б';
const k = 1024;
const sizes = ['Б', 'КБ', 'МБ', 'ГБ'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
};
</script>