79 lines
2.5 KiB
PHP
79 lines
2.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Controller\Share;
|
|
|
|
use App\Service\Share\Exception\InvalidPathException;
|
|
use App\Service\Share\Exception\ShareConnectionException;
|
|
use App\Service\Share\Exception\ShareNotConfiguredException;
|
|
use App\Service\Share\FileEntry;
|
|
use App\Service\Share\FileSource;
|
|
use App\Service\Share\SharePathResolver;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
|
|
class ShareBrowseController extends AbstractController
|
|
{
|
|
public function __construct(
|
|
private readonly FileSource $fileSource,
|
|
private readonly SharePathResolver $pathResolver,
|
|
) {}
|
|
|
|
#[Route('/api/share/browse', name: 'share_browse', methods: ['GET'], priority: 1)]
|
|
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
|
public function __invoke(Request $request): JsonResponse
|
|
{
|
|
$rawPath = (string) $request->query->get('path', '');
|
|
|
|
try {
|
|
$path = $this->pathResolver->normalizeRelative($rawPath);
|
|
} catch (InvalidPathException) {
|
|
return new JsonResponse(['error' => 'Invalid path.'], 400);
|
|
}
|
|
|
|
try {
|
|
$entries = $this->fileSource->dir($path);
|
|
} catch (ShareNotConfiguredException) {
|
|
return new JsonResponse(['error' => 'Share not configured.'], 409);
|
|
} catch (ShareConnectionException) {
|
|
return new JsonResponse(['error' => 'Unable to reach the file share.'], 502);
|
|
}
|
|
|
|
return new JsonResponse([
|
|
'path' => $path,
|
|
'breadcrumb' => $this->breadcrumb($path),
|
|
'entries' => array_map(static fn (FileEntry $e): array => [
|
|
'name' => $e->name,
|
|
'path' => $e->path,
|
|
'isDir' => $e->isDir,
|
|
'size' => $e->size,
|
|
'modifiedAt' => $e->modifiedAt,
|
|
'mimeType' => $e->mimeType,
|
|
], $entries),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @return array<int, array{name: string, path: string}>
|
|
*/
|
|
private function breadcrumb(string $path): array
|
|
{
|
|
if ('' === $path) {
|
|
return [];
|
|
}
|
|
|
|
$crumbs = [];
|
|
$acc = '';
|
|
foreach (explode('/', $path) as $segment) {
|
|
$acc = '' === $acc ? $segment : $acc.'/'.$segment;
|
|
$crumbs[] = ['name' => $segment, 'path' => $acc];
|
|
}
|
|
|
|
return $crumbs;
|
|
}
|
|
}
|