diff --git a/.gitignore b/.gitignore index 293c8aa..90caa8f 100644 --- a/.gitignore +++ b/.gitignore @@ -37,4 +37,5 @@ debian/files ### Certificates certs/ - +.venv/ +.vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md index e3d49e7..398e221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,39 @@ # Changelog +## [1.2.8] - 2026-03-20 +### Added +- Modificado MenuBrowserController para permitir la edición de las plantillas de menú en "raw", permitiendo modificar el código twig en lugar del html ya compilado por twig, de esta forma podemos editar el fichero twig y aplicar cambios para ver el resultado antes de guardar la plantilla. + +## [1.2.7] - 2026-03-17 +### Fixed +- Se ha corregido la lectura de la variable `OGCLIENT_API_KEY` desde `env.json` para inyectarla correctamente en la plantilla PXE generada por `ogBoot`. + +## [1.2.6] - 2026-03-17 +### Added +- Se ha añadido AssetsManagerController para la gestion de assets. + +## [1.2.5] - 2026-03-16 +### Fixed +- Se ha modificado el fichero security.yml para que el acceso a la api lo tenga el ROLE_USER en lugar de IS_AUTHENTICATED_FULLY, ya que de lo contrario cualquier cliente con rol ROLE_OGCLIENT_API podia acceder a la api, de esta forma se asegura que solo los usuarios con rol ROLE_USER puedan acceder a la api y el cliente solo pueda acceder a la ruta commands. + +## [1.2.4] - 2026-03-16 +### Added +- Se ha implementado un nuevo [ApiKeyAuthenticator] para dotar de acceso seguro al endpoint `/commands` mediante la cabecera `X-API-KEY`. +- Incorporación de la variable global de entorno `OGCLIENT_API_KEY` en env.json para gestionar el token de acceso de clientes desde la interfaz gráfica. +### Changed +- Se ha modificado el controlador PostAction de `PxeBootFile` para inyectar y propagar la clave `ogclient_api_key` al payload que se envía a `ogBoot` durante la creación del arranque. + +## [1.2.3] - 2026-03-11 +### Added +- Se ha añadido una nueva funcionalidad en el DTO `MenuInput` (campo `menuHtmlContent`) para recibir la plantilla HTML íntegra del menú codificada en Base64. + +### Improved +- Se ha refactorizado y asegurado la lógica de creación de menús dentro de `MenuProcessor`, para decodificar estrictamente el payload en Base64 y sobreescribir físicamente la plantilla `.twig` descartando la plantilla por defecto. + +## [1.2.2] - 2026-02-27 +### Improved +- Nuevo menú por defecto en el cliente, organizando la información por discos + +--- ## [1.2.1] - 2025-10-22 ### Fixed - Se ha corregido un error en el commando que se encarga de ejecutar tareas pendientes. diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 6466847..a4ce57f 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -22,6 +22,8 @@ security: success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure jwt: ~ + custom_authenticators: + - App\Security\ApiKeyAuthenticator refresh_jwt: check_path: refresh_token @@ -29,6 +31,7 @@ security: - { path: ^/$, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI - { path: ^/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI docs - { path: ^/auth/login, roles: PUBLIC_ACCESS } + - { path: ^/commands, roles: [ROLE_OGCLIENT_API, ROLE_USER] } - { path: ^/opengnsys/rest, roles: PUBLIC_ACCESS } - { path: ^/og-repository/webhook, roles: PUBLIC_ACCESS } - { path: ^/og-lives/install/webhook, roles: PUBLIC_ACCESS } @@ -36,7 +39,7 @@ security: - { path: ^/validate, roles: PUBLIC_ACCESS } - { path: ^/menu-browser, roles: PUBLIC_ACCESS } - { path: ^/menu/, roles: PUBLIC_ACCESS } - - { path: ^/, roles: IS_AUTHENTICATED_FULLY } + - { path: ^/, roles: ROLE_USER } when@test: security: diff --git a/env.json b/env.json index c40cd36..c62e201 100644 --- a/env.json +++ b/env.json @@ -10,6 +10,7 @@ "SSL_ENABLED": "false", "OG_BOOT_IP": "127.0.0.1", "OG_BOOT_API_PORT": "8082", - "OG_BOOT_PXE_PORT": "8082" + "OG_BOOT_PXE_PORT": "8082", + "OGCLIENT_API_KEY": "ogclient-super-secret-token" } } \ No newline at end of file diff --git a/src/Controller/AssetManagerController.php b/src/Controller/AssetManagerController.php new file mode 100644 index 0000000..1b6d194 --- /dev/null +++ b/src/Controller/AssetManagerController.php @@ -0,0 +1,160 @@ +query->get('path', ''); + $targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + $response = null; + + if ($targetPath === null || !is_dir($targetPath)) { + $response = new JsonResponse(['message' => 'Directorio inválido o no encontrado.'], Response::HTTP_NOT_FOUND); + } else { + $items = []; + $iterator = new \DirectoryIterator($targetPath); + foreach ($iterator as $fileinfo) { + if ($fileinfo->isDot()) continue; + + $items[] = [ + 'name' => $fileinfo->getFilename(), + 'type' => $fileinfo->isDir() ? 'folder' : 'file', + 'size' => $fileinfo->isFile() ? $fileinfo->getSize() : null, + 'path' => ltrim($requestedPath . '/' . $fileinfo->getFilename(), '/') + ]; + } + + usort($items, function($a, $b) { + if ($a['type'] === $b['type']) { + return strcasecmp($a['name'], $b['name']); + } + return $a['type'] === 'folder' ? -1 : 1; + }); + + $response = new JsonResponse($items, Response::HTTP_OK); + } + + return $response; + } + + #[Route('/ogassets/upload', name: 'api_assets_upload', methods: ['POST'])] + public function uploadAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse + { + $file = $request->files->get('file'); + $requestedPath = $request->request->get('path', ''); + $extractZip = $request->request->getBoolean('extractZip', false); + $response = null; + + if (!$file) { + $response = new JsonResponse(['message' => 'No file uploaded.'], Response::HTTP_BAD_REQUEST); + } else { + $targetDir = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + + if ($targetDir === null) { + $response = new JsonResponse(['message' => 'Ruta destino inválida.'], Response::HTTP_FORBIDDEN); + } else { + if (!is_dir($targetDir)) { + mkdir($targetDir, 0755, true); + $targetDir = realpath($targetDir); + } + + $originalName = $file->getClientOriginalName(); + $extension = strtolower($file->getClientOriginalExtension()); + + if ($extractZip && $extension === 'zip') { + $safeName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', pathinfo($originalName, PATHINFO_FILENAME)); + $extractDir = $targetDir . '/' . $safeName; + + if (!$filesystem->exists($extractDir)) { + $filesystem->mkdir($extractDir, 0755); + } + + $zip = new ZipArchive(); + if ($zip->open($file->getPathname()) === true) { + $zip->extractTo($extractDir); + $zip->close(); + $response = new JsonResponse(['message' => 'ZIP extraído correctamente.']); + } else { + $response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } else { + try { + $file->move($targetDir, $originalName); + $response = new JsonResponse(['message' => 'Archivo subido correctamente.']); + } catch (\Exception $e) { + $response = new JsonResponse(['message' => 'Error al guardar el archivo.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } + } + } + + return $response; + } + + #[Route('/ogassets/delete', name: 'api_assets_delete', methods: ['DELETE'])] + public function deleteAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse + { + $data = json_decode($request->getContent(), true); + $requestedPath = $data['path'] ?? ''; + $response = null; + + if (empty($requestedPath)) { + $response = new JsonResponse(['message' => 'Ruta requerida.'], Response::HTTP_BAD_REQUEST); + } else { + $realBase = realpath($params->get('kernel.project_dir') . '/public/assets'); + $targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + + if ($targetPath === null || !file_exists($targetPath) || $targetPath === $realBase) { + $response = new JsonResponse(['message' => 'Ruta inválida o prohibida.'], Response::HTTP_FORBIDDEN); + } else { + try { + $filesystem->remove($targetPath); + $response = new JsonResponse(['message' => 'Elemento eliminado correctamente.']); + } catch (\Exception $e) { + $response = new JsonResponse(['message' => 'Error al eliminar el elemento.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } + } + + return $response; + } +} diff --git a/src/Controller/MenuBrowserController.php b/src/Controller/MenuBrowserController.php index 2ca78be..291dcff 100644 --- a/src/Controller/MenuBrowserController.php +++ b/src/Controller/MenuBrowserController.php @@ -9,6 +9,7 @@ use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Attribute\Route; use Twig\Environment; @@ -29,9 +30,42 @@ class MenuBrowserController extends AbstractController $partitions = []; $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]); + + $disks = []; // Array nuevo estructurado if ($client) { - $partitions = $client->getPartitions(); + $rawPartitions = $client->getPartitions()->toArray(); + + foreach ($rawPartitions as $part) { + $diskNum = $part->getDiskNumber(); + $partNum = $part->getPartitionNumber(); + + // Inicializamos el array del disco si no existe + if (!isset($disks[$diskNum])) { + $disks[$diskNum] = [ + 'info' => null, // Aquí guardaremos la partición 0 (tamaño total) + 'parts' => [] // Aquí las particiones reales + ]; + } + + if ($partNum == 0) { + // Es la info del disco completo + $disks[$diskNum]['info'] = $part; + } else { + // Es una partición normal + $disks[$diskNum]['parts'][] = $part; + } + } + + // Ordenamos los discos (1, 2, 3...) + ksort($disks); + + // Ordenamos las particiones dentro de cada disco (1, 2, 3...) + foreach ($disks as &$diskData) { + usort($diskData['parts'], function($a, $b) { + return $a->getPartitionNumber() <=> $b->getPartitionNumber(); + }); + } } $menuName = $client->getMenu()->getPublicUrl(); @@ -39,11 +73,11 @@ class MenuBrowserController extends AbstractController return $this->render('browser/' . $menuName . '.html.twig', [ 'ip' => $host, 'mac' => $client ? $client->getMac() : null, - 'partitions' => $partitions, + 'disks' => $disks, ]); } - #[Route('/menu/{templateName}', name: 'render_menu_template')] + #[Route('/menu/{templateName}', name: 'render_menu_template', requirements: ['templateName' => '.+'])] public function renderMenu(string $templateName, Request $request): Response { $templatePath = 'browser/' . $templateName . '.html.twig'; @@ -54,7 +88,49 @@ class MenuBrowserController extends AbstractController return $this->render($templatePath, [ 'ip' => 'invitado', - 'partitions' => [], + 'disks' => [], ]); } + + #[Route('/menu-raw/{templateName}', name: 'get_raw_menu_template', requirements: ['templateName' => '.+'], methods: ['GET'])] + public function getRawMenu(string $templateName, Request $request): Response + { + $templatePath = 'browser/' . $templateName . '.html.twig'; + + if (!$this->twig->getLoader()->exists($templatePath)) { + throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName)); + } + + $content = $this->twig->getLoader()->getSourceContext($templatePath)->getCode(); + + return new Response($content, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=utf-8']); + } + + #[Route('/menu-preview', name: 'preview_menu_template', methods: ['POST'])] + public function previewMenu(Request $request): Response + { + $data = json_decode($request->getContent(), true); + $base64Template = $data['templateBase64'] ?? ''; + + if (empty($base64Template)) { + return new JsonResponse(['message' => 'Falta el contenido de la plantilla.'], Response::HTTP_BAD_REQUEST); + } + + $content = base64_decode($base64Template); + if ($content === false) { + return new JsonResponse(['message' => 'El contenido Base64 es inválido.'], Response::HTTP_BAD_REQUEST); + } + + try { + $template = $this->twig->createTemplate($content); + $rendered = $template->render([ + 'ip' => '127.0.0.1 (Previsualización)', + 'mac' => '00:00:00:00:00:00', + 'disks' => [], + ]); + return new Response($rendered, Response::HTTP_OK, ['Content-Type' => 'text/html; charset=utf-8']); + } catch (\Exception $e) { + return new JsonResponse(['message' => 'Error al compilar la plantilla Twig: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } } diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index 6d0ae99..4812bf5 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -37,7 +37,7 @@ class RunScriptAction extends AbstractOgAgentController throw new BadRequestHttpException('IP is required'); } - $data = $this->buildRequestData($client, $input->script); + $data = $this->buildRequestData($client, $input->script, $input->runAsAdmin); $response = $this->executeScript($client, $data); if (isset($response['code']) && $response['code'] === 409) { @@ -58,21 +58,14 @@ class RunScriptAction extends AbstractOgAgentController return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK); } - private function buildRequestData(Client $client, string $script): array + private function buildRequestData(Client $client, string $script, bool $runAsAdmin = false): array { $scriptBase64 = base64_encode($script); - if ($this->isLinuxOrWindows($client)) { + if ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) { return [ 'script' => $scriptBase64, - 'client' => 'false' - ]; - } - - if ($this->isLinuxOrWindowsSession($client)) { - return [ - 'script' => $scriptBase64, - 'client' => 'true' + 'client' => $runAsAdmin ? 'false' : 'true' ]; } diff --git a/src/Controller/OgBoot/AbstractOgBootController.php b/src/Controller/OgBoot/AbstractOgBootController.php index 18f6bea..2d3918e 100644 --- a/src/Controller/OgBoot/AbstractOgBootController.php +++ b/src/Controller/OgBoot/AbstractOgBootController.php @@ -41,6 +41,8 @@ abstract class AbstractOgBootController extends AbstractController protected readonly CreateService $createService, protected readonly SimplifyOgLiveFilenameService $simplifyOgLiveFilenameService, protected readonly ExtractOgLiveFilenameDateService $extractOgLiveFilenameDateService, + #[Autowire(env: 'OGCLIENT_API_KEY')] + protected string $ogClientApiKey, protected readonly LoggerInterface $logger, ) diff --git a/src/Controller/OgBoot/PxeBootFile/PostAction.php b/src/Controller/OgBoot/PxeBootFile/PostAction.php index 725dad7..4ca7410 100644 --- a/src/Controller/OgBoot/PxeBootFile/PostAction.php +++ b/src/Controller/OgBoot/PxeBootFile/PostAction.php @@ -58,7 +58,8 @@ class PostAction extends AbstractOgBootController 'ogntp' => $client->getOrganizationalUnit()->getNetworkSettings()?->getNtp(), 'ogdns' => $client->getOrganizationalUnit()->getNetworkSettings()?->getDns(), 'ogProxy' => $client->getOrganizationalUnit()->getNetworkSettings()?->getProxy(), - 'resolution' => $client->getResolution() ?? '791' + 'resolution' => $client->getResolution() ?? '791', + 'ogclient_api_key' => $this->ogClientApiKey ] ]; diff --git a/src/Dto/Input/CommandExecuteInput.php b/src/Dto/Input/CommandExecuteInput.php index 4f71b31..8d8b6f4 100644 --- a/src/Dto/Input/CommandExecuteInput.php +++ b/src/Dto/Input/CommandExecuteInput.php @@ -34,4 +34,11 @@ final class CommandExecuteInput example: false )] public bool $queue = false; + + #[Groups(['command:write'])] + #[ApiProperty( + description: 'Si ejecutar el script en modo administrador', + example: false + )] + public bool $runAsAdmin = false; } \ No newline at end of file diff --git a/src/Dto/Input/MenuInput.php b/src/Dto/Input/MenuInput.php index 5a8c1c1..9835a73 100644 --- a/src/Dto/Input/MenuInput.php +++ b/src/Dto/Input/MenuInput.php @@ -37,6 +37,10 @@ final class MenuInput #[ApiProperty(description: 'The default menu', example: "false")] public ?bool $isDefault = false; + #[Groups(['menu:write'])] + #[ApiProperty(description: 'HTML Content of the menu in Base64', example: "PGh0bWw+PC9odG1sPg==")] + public ?string $menuHtmlContent = null; + public function __construct(?Menu $menu = null) { if (!$menu) { diff --git a/src/Security/ApiKeyAuthenticator.php b/src/Security/ApiKeyAuthenticator.php new file mode 100644 index 0000000..c954021 --- /dev/null +++ b/src/Security/ApiKeyAuthenticator.php @@ -0,0 +1,77 @@ +projectDir = $kernel->getProjectDir(); + } + + /** + * Called on every request to decide if this authenticator should be used for the request. + * Returning `false` will cause this authenticator to be skipped. + */ + public function supports(Request $request): ?bool + { + return $request->headers->has('X-API-KEY'); + } + + public function authenticate(Request $request): Passport + { + $apiToken = $request->headers->get('X-API-KEY'); + + $envFile = $this->projectDir . DIRECTORY_SEPARATOR . 'env.json'; + if (!is_file($envFile)) { + throw new CustomUserMessageAuthenticationException('Configuration file not found.'); + } + + $config = json_decode(file_get_contents($envFile), true); + $expectedToken = $config['vars']['OGCLIENT_API_KEY'] ?? null; + + if (null === $expectedToken || $apiToken !== $expectedToken) { + throw new CustomUserMessageAuthenticationException('Invalid API Token.'); + } + + // Usamos tu propia entidad User para crear un usuario virtual "al vuelo" + return new SelfValidatingPassport(new UserBadge('ogclient_api_user', function() { + $apiUser = new User(); + $apiUser->setUsername('ogclient_api_user'); + $apiUser->setRoles(['ROLE_OGCLIENT_API']); + $apiUser->setPassword(''); // Evitamos nulos en propiedades requeridas si las hay + + return $apiUser; + })); + } + + public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response + { + // on success, let the request continue + return null; + } + + public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response + { + $data = [ + 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()) + ]; + + return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); + } +} diff --git a/src/State/Processor/MenuProcessor.php b/src/State/Processor/MenuProcessor.php index a0722c2..ff9576c 100644 --- a/src/State/Processor/MenuProcessor.php +++ b/src/State/Processor/MenuProcessor.php @@ -12,12 +12,19 @@ use ApiPlatform\Validator\ValidatorInterface; use App\Dto\Input\MenuInput; use App\Dto\Output\MenuOutput; use App\Repository\MenuRepository; +use App\Entity\Menu; +use Symfony\Component\Filesystem\Exception\IOExceptionInterface; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; +use Symfony\Component\Filesystem\Filesystem; + readonly class MenuProcessor implements ProcessorInterface { public function __construct( private MenuRepository $menuRepository, - private ValidatorInterface $validator + private ValidatorInterface $validator, + private ParameterBagInterface $params, + private Filesystem $filesystem ) { } @@ -47,12 +54,24 @@ readonly class MenuProcessor implements ProcessorInterface } $entity = null; + $oldPublicUrl = null; + if (isset($uriVariables['uuid'])) { $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + if ($entity) { + $oldPublicUrl = $entity->getPublicUrl(); + } } $menu = $data->createOrUpdateEntity($entity); $this->validator->validate($menu); + + // Extraemos el contenido base64 (asumiendo que $data es tu MenuInput) + $base64HtmlContent = property_exists($data, 'menuHtmlContent') ? $data->menuHtmlContent : null; + + // Sincronización de ficheros físicos y caché + $this->syncMenuTemplateFile($menu, $operation, $oldPublicUrl, $base64HtmlContent); + $this->menuRepository->save($menu); return new MenuOutput($menu); @@ -60,9 +79,160 @@ readonly class MenuProcessor implements ProcessorInterface private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null { - $user = $this->menuRepository->findOneByUuid($uriVariables['uuid']); - $this->menuRepository->delete($user); + $entity = null; + + if (isset($uriVariables['uuid'])) { + $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + + if ($entity) { + // 1. Borrar el fichero físico y la caché antes de eliminar de BD + $this->removeMenuTemplateFile($entity); + + // 2. Eliminar de la base de datos + $this->menuRepository->delete($entity); + } + } return null; } + + /** + * Creates, renames, and updates the Twig file associated with the menu. + * Throws \RuntimeException if any file system operation fails. + */ + private function syncMenuTemplateFile(Menu $menu, Operation $operation, ?string $oldPublicUrl, ?string $base64HtmlContent = null): void + { + $newPublicUrl = $menu->getPublicUrl(); + + if ($newPublicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = rtrim($projectDir, '/') . '/templates/browser/'; + $newTemplateName = preg_replace('#^/menu/#', '', parse_url($newPublicUrl, PHP_URL_PATH)); + + if (!empty($newTemplateName)) { + $targetFile = $templatesDir . $newTemplateName . '.html.twig'; + $filesChanged = false; + + try { + // 1. RENAME OPERATION (Only for PUT/PATCH if URL changed) + if (($operation instanceof Put || $operation instanceof Patch) && $newPublicUrl !== $oldPublicUrl && $oldPublicUrl) { + $oldTemplateName = preg_replace('#^/menu/#', '', parse_url($oldPublicUrl, PHP_URL_PATH)); + $sourceFile = $templatesDir . $oldTemplateName . '.html.twig'; + + if ($this->filesystem->exists($sourceFile)) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->rename($sourceFile, $targetFile, true); + $this->cleanupEmptyDirectories(dirname($sourceFile), $templatesDir); + $filesChanged = true; + } + } + + // 2. DETERMINE CONTENT + $contentToWrite = "{# Template for menu: {$menu->getName()} #}\n{% extends 'base.html.twig' %}\n{% block body %}\n

{$menu->getName()}

\n{% endblock %}\n"; + $hasCustomContent = false; + + if (!empty($base64HtmlContent)) { + $decodedContent = base64_decode($base64HtmlContent, true); // true = strict mode + if ($decodedContent !== false) { + $contentToWrite = $decodedContent; + $hasCustomContent = true; + } + } + + // 3. WRITE OPERATION (If file doesn't exist, OR if we received explicit HTML content) + if (!$this->filesystem->exists($targetFile) || $hasCustomContent) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->dumpFile($targetFile, $contentToWrite); + + $filesChanged = true; + } + + // 4. TWIG CACHE INVALIDATION + if ($filesChanged) { + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure synchronizing menu template file. Reason: %s', $exception->getMessage()), + 0, + $exception + ); + } + } + } + } + + /** + * Removes the Twig file associated with the menu, cleans up empty parent directories, + * and clears the cache. Throws \RuntimeException if any file system operation fails. + */ + private function removeMenuTemplateFile(Menu $menu): void + { + $publicUrl = $menu->getPublicUrl(); + + if ($publicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = $projectDir . '/templates/browser/'; + $templateName = preg_replace('#^/menu/#', '', parse_url($publicUrl, PHP_URL_PATH)); + + if (!empty($templateName)) { + $targetFile = $templatesDir . $templateName . '.html.twig'; + + try { + if ($this->filesystem->exists($targetFile)) { + // 1. Delete the actual file + $this->filesystem->remove($targetFile); + + $this->cleanupEmptyDirectories(dirname($targetFile), $templatesDir); + + // 3. TWIG CACHE INVALIDATION + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure removing menu template file or directories. Reason: %s', $exception->getMessage()), 0, $exception); + } + } + } + } + + /** + * Traverses upwards from a starting directory to a base directory, removing empty folders. + */ + private function cleanupEmptyDirectories(string $startDir, string $baseDir): void + { + $currentDir = $startDir; + $baseDirExact = rtrim($baseDir, '/'); + $continueCleaning = true; + + // La condición del while tiene el control absoluto del flujo + while ($continueCleaning && $currentDir !== $baseDirExact && str_starts_with($currentDir, $baseDirExact)) { + // Asumimos que pararemos, a menos que encontremos una carpeta vacía + $continueCleaning = false; + + if (is_dir($currentDir)) { + $dirContents = array_diff(scandir($currentDir), ['.', '..']); + + if (empty($dirContents)) { + $this->filesystem->remove($currentDir); + $currentDir = dirname($currentDir); + + // Como hemos borrado esta, le decimos al bucle que siga mirando arriba + $continueCleaning = true; + } + } + } + } + + } diff --git a/templates/browser/main.html.twig b/templates/browser/main.html.twig index ed786ed..69ac50f 100644 --- a/templates/browser/main.html.twig +++ b/templates/browser/main.html.twig @@ -34,7 +34,7 @@ background-color: var(--background-color); color: var(--text-color); line-height: 1.5; - background-image: + background-image: radial-gradient(at 0% 0%, rgba(37, 99, 235, 0.1) 0px, transparent 50%), radial-gradient(at 100% 100%, rgba(5, 150, 105, 0.1) 0px, transparent 50%); min-height: 100vh; @@ -210,15 +210,15 @@ .linux i { color: var(--success-color); } .apagar i { color: var(--danger-color); } - .windows a:hover { + .windows a:hover { background-color: rgba(37, 99, 235, 0.1); color: var(--primary-color); } - .linux a:hover { + .linux a:hover { background-color: rgba(5, 150, 105, 0.1); color: var(--success-color); } - .apagar a:hover { + .apagar a:hover { background-color: rgba(220, 38, 38, 0.1); color: var(--danger-color); } @@ -393,7 +393,6 @@ border: 2px dashed #cbd5e1; } - /* Estados especiales para diferentes tipos de particiones */ .partition-os { font-weight: 600; color: var(--success-color); @@ -444,6 +443,57 @@ font-size: 0.8rem; } } + + /* --- NUEVOS ESTILOS PARA LA AGRUPACIÓN POR DISCOS --- */ + .disk-container { + margin-bottom: 2.5rem; + border: 1px solid #e2e8f0; + border-radius: var(--border-radius); + overflow: hidden; + background: white; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.02); + } + + .disk-header { + background: #f8fafc; + padding: 1rem 1.5rem; + border-bottom: 1px solid #e2e8f0; + display: flex; + justify-content: space-between; + align-items: center; + } + + .disk-header h3 { + margin: 0; + font-size: 1.1rem; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.5rem; + } + + .disk-total-badge { + background: linear-gradient(135deg, var(--primary-color), var(--primary-light)); + color: white; + padding: 0.35rem 0.85rem; + border-radius: 20px; + font-size: 0.85rem; + font-weight: 600; + box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2); + } + + .empty-disk { + text-align: center; + padding: 2rem; + color: #64748b; + font-style: italic; + } + + .partition-number { + font-weight: bold; + font-size: 1.1rem; + color: var(--text-color); + } @@ -475,48 +525,81 @@
-

Particiones del sistema

- - {% if partitions|length > 0 %} -
- - - - - - - - - - - - - {% for partition in partitions %} - - - - - - - - - {% endfor %} - -
DiscoParticiónTamañoTipoSOAcciones
{{ partition.diskNumber }}{{ partition.partitionNumber }}{{ (partition.size / 1024)|number_format(2) }} MB{{ partition.filesystem }}{{ partition.operativeSystem ? partition.operativeSystem.name : '-' }} - {% if partition.operativeSystem %} - - - Arrancar {{ partition.operativeSystem.name }} - - {% endif %} -
-
+

Almacenamiento del sistema

+ + {% if disks is defined and disks|length > 0 %} + + {% for diskNum, data in disks %} +
+ +
+

+ Disco {{ diskNum }} +

+ {% if data.info %} + + Total: {{ (data.info.size / 1024 / 1024)|number_format(2) }} GB + + {% endif %} +
+ +
+ + + + + + + + + + + + {% for partition in data.parts %} + + + + + + + + + + + + {% else %} + + + + {% endfor %} + +
ParticiónTamañoTipoSistema OperativoAcciones
+ {{ partition.partitionNumber }} + + {{ (partition.size / 1024)|number_format(0) }} MB + + {{ partition.filesystem|default('-') }} + + {{ partition.operativeSystem ? partition.operativeSystem.name : '-' }} + + {% if partition.operativeSystem %} + + Arrancar {{ partition.operativeSystem.name }} + + {% endif %} +
+ No hay particiones utilizables en este disco. +
+
+
+ {% endfor %} + {% else %} -

No hay particiones disponibles.

+

No hay discos detectados en el sistema.

{% endif %}
- + \ No newline at end of file