Skip to content

Commit

Permalink
Merge pull request #1944 from MTES-MCT/feature/1322-redimensionnement…
Browse files Browse the repository at this point in the history
…-image-upload

 [BO - Traitement image] Générer des miniatures et redimensionnement lors de l'upload de photos
  • Loading branch information
hmeneuvrier authored Nov 22, 2023
2 parents 5487805 + 8d1eca8 commit 9c04f4c
Show file tree
Hide file tree
Showing 19 changed files with 369 additions and 52 deletions.
4 changes: 3 additions & 1 deletion .docker/php-fpm/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Install Redis
&& pecl install redis \
&& docker-php-ext-enable redis \
# PHP GD
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
# Install others
&& docker-php-ext-install -j2 bcmath ctype iconv pdo pdo_mysql pdo_sqlite zip xsl\
&& docker-php-ext-install -j2 bcmath ctype iconv pdo pdo_mysql pdo_sqlite zip xsl gd\
&& docker-php-ext-enable opcache \
&& rm /usr/src/php/ext/*.tgz \
&& curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer \
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"doctrine/doctrine-bundle": "^2.5",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.10",
"intervention/image": "^2.7",
"knplabs/knp-snappy-bundle": "^1.9",
"league/flysystem-aws-s3-v3": "^3.0",
"league/flysystem-bundle": "^2.3",
Expand Down
86 changes: 85 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ services:
arguments:
$normalizers:
- '@App\Serializer\SignalementDraftRequestNormalizer'
Intervention\Image\ImageManager:

when@test:
parameters:
Expand Down
26 changes: 26 additions & 0 deletions migrations/Version20231114163537.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20231114163537 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add field size to file';
}

public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE file ADD size BIGINT DEFAULT NULL');
}

public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE file DROP size');
}
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 3 additions & 17 deletions src/Controller/Back/SignalementFileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
use App\Messenger\Message\PdfExportMessage;
use App\Repository\FileRepository;
use App\Service\Signalement\SignalementFileProcessor;
use App\Service\UploadHandlerService;
use Doctrine\ORM\EntityManagerInterface;
use League\Flysystem\FilesystemException;
use League\Flysystem\FilesystemOperator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
Expand Down Expand Up @@ -107,25 +107,11 @@ public function deleteFileSignalement(
string $filename,
Request $request,
FileRepository $fileRepository,
FilesystemOperator $fileStorage
UploadHandlerService $uploadHandlerService,
): JsonResponse {
$this->denyAccessUnlessGranted('FILE_DELETE', $signalement);
if ($this->isCsrfTokenValid('signalement_delete_file_'.$signalement->getId(), $request->get('_token'))) {
$fileType = 'documents' === $type ? File::FILE_TYPE_DOCUMENT : File::FILE_TYPE_PHOTO;

$fileCollection = $signalement->getFiles()->filter(
function (File $file) use ($fileStorage, $fileType, $filename) {
return $fileType === $file->getFileType()
&& $filename === $file->getFilename()
&& $fileStorage->fileExists($filename);
}
);

if (!$fileCollection->isEmpty()) {
$file = $fileCollection->current();
$fileStorage->delete($file->getFilename());
$fileRepository->remove($file, true);

if ($uploadHandlerService->deleteFile($signalement, $type, $filename, $fileRepository)) {
return $this->json(['response' => 'success']);
}
}
Expand Down
17 changes: 13 additions & 4 deletions src/Controller/FrontSignalementController.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use App\Repository\TerritoryRepository;
use App\Repository\UserRepository;
use App\Service\Files\DocumentProvider;
use App\Service\ImageManipulationHandler;
use App\Service\Mailer\NotificationMail;
use App\Service\Mailer\NotificationMailerRegistry;
use App\Service\Mailer\NotificationMailerType;
Expand Down Expand Up @@ -88,12 +89,18 @@ public function checkTerritory(Request $request, PostalCodeHomeChecker $postalCo
public function handleUpload(
UploadHandlerService $uploadHandlerService,
Request $request,
LoggerInterface $logger
LoggerInterface $logger,
ImageManipulationHandler $imageManipulationHandler
) {
if (null !== ($files = $request->files->get('signalement'))) {
try {
foreach ($files as $key => $file) {
return $this->json($uploadHandlerService->toTempFolder($file)->setKey($key));
$res = $uploadHandlerService->toTempFolder($file)->setKey($key);
if (!isset($res['error']) && \in_array($file->getMimeType(), ImageManipulationHandler::IMAGE_MIME_TYPES)) {
$imageManipulationHandler->resize($res['filePath'])->thumbnail();
}

return $this->json($res);
}
} catch (\Exception $exception) {
$logger->error($exception->getMessage());
Expand Down Expand Up @@ -139,12 +146,14 @@ public function envoi(
$dataFiles = $data['files'];
foreach ($dataFiles as $key => $files) {
foreach ($files as $titre => $file) {
$filename = $uploadHandlerService->moveFromBucketTempFolder($file);
$file = $fileFactory->createInstanceFrom(
filename: $uploadHandlerService->moveFromBucketTempFolder($file),
filename: $filename,
title: $titre,
type: 'documents' === $key ? File::FILE_TYPE_DOCUMENT : File::FILE_TYPE_PHOTO
type: 'documents' === $key ? File::FILE_TYPE_DOCUMENT : File::FILE_TYPE_PHOTO,
);
if (null !== $file) {
$file->setSize($uploadHandlerService->getFileSize($file->getFilename()));
$signalement->addFile($file);
}
}
Expand Down
26 changes: 21 additions & 5 deletions src/Controller/Security/SecurityController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace App\Controller\Security;

use App\Entity\Signalement;
use App\Service\ImageManipulationHandler;
use League\Flysystem\FilesystemOperator;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
Expand Down Expand Up @@ -45,19 +47,33 @@ public function check()

#[Route('/_up/{filename}/{uuid?}', name: 'show_uploaded_file')]
public function showUploadedFile(
string $filename,
LoggerInterface $logger,
Signalement|null $signalement = null
FilesystemOperator $fileStorage,
string $filename,
?Signalement $signalement = null,
): BinaryFileResponse|RedirectResponse {
$request = Request::createFromGlobals();
$this->denyAccessUnlessGranted(
'FILE_VIEW',
null === $this->getUser() ? $this->isCsrfTokenValid('suivi_signalement_ext_file_view', $request->get('t')) : $signalement
);

$tmpFilepath = $this->getParameter('uploads_tmp_dir').$filename;
$bucketFilepath = $this->getParameter('url_bucket').'/'.$filename;
try {
$variant = $request->query->get('variant');

$pathInfo = pathinfo($filename);
$ext = \array_key_exists('extension', $pathInfo) ? '.'.$pathInfo['extension'] : '';

$resize = $pathInfo['filename'].ImageManipulationHandler::SUFFIX_RESIZE.$ext;
$thumb = $pathInfo['filename'].ImageManipulationHandler::SUFFIX_THUMB.$ext;

if ('thumb' == $variant && $fileStorage->fileExists($thumb)) {
$filename = $thumb;
} elseif ('resize' == $variant && $fileStorage->fileExists($resize)) {
$filename = $resize;
}
$tmpFilepath = $this->getParameter('uploads_tmp_dir').$filename;
$bucketFilepath = $this->getParameter('url_bucket').'/'.$filename;

file_put_contents($tmpFilepath, file_get_contents($bucketFilepath));
$file = new File($tmpFilepath);

Expand Down
16 changes: 16 additions & 0 deletions src/Entity/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Entity\Enum\DocumentType;
use App\Repository\FileRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: FileRepository::class)]
Expand Down Expand Up @@ -42,6 +43,9 @@ class File
#[ORM\JoinColumn(nullable: true)]
private ?Intervention $intervention = null;

#[ORM\Column(type: Types::BIGINT, nullable: true)]
private ?string $size = null;

#[ORM\Column(type: 'string', enumType: DocumentType::class, nullable: true)]
private ?DocumentType $documentType = null;

Expand Down Expand Up @@ -142,6 +146,18 @@ public function setIntervention(?Intervention $intervention): self
return $this;
}

public function getSize(): ?string
{
return $this->size;
}

public function setSize(?string $size): self
{
$this->size = $size;

return $this;
}

public function getDocumentType(): ?DocumentType
{
return $this->documentType;
Expand Down
1 change: 0 additions & 1 deletion src/Factory/FileFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ public function createInstanceFrom(
->setFilename($filename)
->setTitle($title)
->setFileType($type);

if (null !== $signalement) {
$file->setSignalement($signalement);
}
Expand Down
Loading

0 comments on commit 9c04f4c

Please sign in to comment.