-
Notifications
You must be signed in to change notification settings - Fork 17
IBX-8344: Added endpoint for download images #1271
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
5c52878
Added DownloadImageController
ciastektk 9a4250b
Added routing
ciastektk c348ae1
[Composer] Added ext-zip
ciastektk 5920633
Update src/bundle/Controller/DownloadImageController.php
ciastektk 79b727b
Update src/bundle/Controller/DownloadImageController.php
ciastektk dc48c63
[Composer] Mover ext-zip to require-dev
ciastektk 066e995
Code cleanup & added extension check for downloading multiple images
ciastektk 2bb0281
Added enableMultipleDownload option in DamWidget Config provider
ciastektk 86a754f
Fixed ZIP extension is not loaded exception message
ciastektk 802d3e8
Fixed archive name and extension
ciastektk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,320 @@ | ||
<?php | ||
|
||
/** | ||
* @copyright Copyright (C) Ibexa AS. All rights reserved. | ||
* @license For full copyright and license information view LICENSE file distributed with this source code. | ||
*/ | ||
declare(strict_types=1); | ||
|
||
namespace Ibexa\Bundle\AdminUi\Controller; | ||
|
||
use DateTimeImmutable; | ||
use Ibexa\Contracts\Core\Repository\SearchService; | ||
use Ibexa\Contracts\Core\Repository\Values\Content\Content; | ||
use Ibexa\Contracts\Core\Repository\Values\Content\Query; | ||
use Ibexa\Contracts\Core\Repository\Values\Content\Search\SearchResult; | ||
use Ibexa\Core\FieldType\Image\Value; | ||
use Ibexa\Rest\Server\Controller; | ||
use Ibexa\User\UserSetting\DateTimeFormat\FormatterInterface; | ||
use RuntimeException; | ||
use Symfony\Component\HttpFoundation\HeaderUtils; | ||
use Symfony\Component\HttpFoundation\Response; | ||
use ZipArchive; | ||
|
||
final class DownloadImageController extends Controller | ||
{ | ||
private const EXTENSION_ZIP = '.zip'; | ||
|
||
private const ARCHIVE_NAME_PATTERN = 'images_%s' . self::EXTENSION_ZIP; | ||
|
||
private int $downloadLimit; | ||
|
||
private FormatterInterface $formatter; | ||
|
||
/** @var array<string, mixed> */ | ||
private array $imageMappings; | ||
|
||
private SearchService $searchService; | ||
|
||
/** | ||
* @param array<string, mixed> $imageMappings | ||
*/ | ||
public function __construct( | ||
int $downloadLimit, | ||
FormatterInterface $formatter, | ||
array $imageMappings, | ||
SearchService $searchService | ||
) { | ||
$this->downloadLimit = $downloadLimit; | ||
$this->formatter = $formatter; | ||
$this->imageMappings = $imageMappings; | ||
$this->searchService = $searchService; | ||
} | ||
|
||
/** | ||
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\InvalidArgumentException | ||
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\InvalidCriterionArgumentException | ||
* @throws \Exception | ||
*/ | ||
public function downloadAction(string $contentIdList): Response | ||
{ | ||
$splitContentIdList = array_map( | ||
static fn (string $value): int => (int)$value, | ||
explode(',', $contentIdList) | ||
); | ||
|
||
$this->assertDownloadLimitNotExceeded($splitContentIdList); | ||
|
||
$images = $this->loadImages($splitContentIdList); | ||
if (0 === $images->totalCount) { | ||
return new Response( | ||
'No results found.', | ||
Response::HTTP_NOT_FOUND | ||
); | ||
} | ||
|
||
return $this->processDownloading($images); | ||
} | ||
|
||
/** | ||
* @param array<int> $contentIdList | ||
*/ | ||
private function assertDownloadLimitNotExceeded(array $contentIdList): void | ||
{ | ||
if (count($contentIdList) > $this->downloadLimit) { | ||
throw new RuntimeException( | ||
sprintf( | ||
'Total download limit in one request is %d.', | ||
$this->downloadLimit | ||
) | ||
); | ||
} | ||
} | ||
|
||
/** | ||
* @throws \Random\RandomException | ||
* @throws \Exception | ||
*/ | ||
private function processDownloading(SearchResult $result): Response | ||
{ | ||
if (1 === $result->totalCount) { | ||
return $this->downloadSingleImage( | ||
$result->getIterator()->current()->valueObject | ||
); | ||
} | ||
|
||
if (!extension_loaded('zip')) { | ||
throw new RuntimeException( | ||
'ZIP extension is not loaded. Enable the extension or use single download instead.' | ||
); | ||
} | ||
|
||
$contentList = []; | ||
|
||
/** @var \Ibexa\Contracts\Core\Repository\Values\Content\Search\SearchHit $image */ | ||
foreach ($result as $image) { | ||
/** @var \Ibexa\Contracts\Core\Repository\Values\Content\Content $content */ | ||
$content = $image->valueObject; | ||
$contentList[] = $content; | ||
} | ||
|
||
return $this->downloadArchiveWithImages($contentList); | ||
} | ||
|
||
/** | ||
* @throws \Random\RandomException | ||
*/ | ||
private function downloadSingleImage(Content $content): Response | ||
{ | ||
$value = $this->getImageValue($content); | ||
$uri = $this->getImageUri($value); | ||
|
||
$content = file_get_contents($uri); | ||
if (false === $content) { | ||
throw new RuntimeException( | ||
sprintf( | ||
'Failed to read data from "%s"', | ||
$uri | ||
) | ||
); | ||
} | ||
|
||
$response = $this->createResponse( | ||
$content, | ||
$this->getImageFileName($value) | ||
); | ||
|
||
$response->headers->set('Content-Type', $value->mime); | ||
|
||
return $response; | ||
} | ||
|
||
/** | ||
* @param array<\Ibexa\Contracts\Core\Repository\Values\Content\Content> $contentList | ||
* | ||
* @throws \Random\RandomException | ||
*/ | ||
private function downloadArchiveWithImages(array $contentList): Response | ||
{ | ||
$archiveName = sprintf( | ||
self::ARCHIVE_NAME_PATTERN, | ||
$this->generateRandomFileName() | ||
); | ||
|
||
$this->createArchive($archiveName, $contentList); | ||
|
||
$content = file_get_contents($archiveName); | ||
if (false === $content) { | ||
throw new RuntimeException('Failed to read archive with images.'); | ||
} | ||
|
||
$fileName = $this->formatter->format(new DateTimeImmutable()) . self::EXTENSION_ZIP; | ||
$response = $this->createResponse($content, $fileName); | ||
$response->headers->set('Content-Type', 'application/zip'); | ||
|
||
unlink($archiveName); | ||
|
||
return $response; | ||
} | ||
|
||
private function getImageValue(Content $content): Value | ||
{ | ||
$imageFieldIdentifier = $this->getImageFieldIdentifier($content->getContentType()->identifier); | ||
$value = $content->getFieldValue($imageFieldIdentifier); | ||
|
||
if (null === $value) { | ||
throw new RuntimeException( | ||
sprintf( | ||
'Missing field with identifier: "%s"', | ||
$imageFieldIdentifier | ||
) | ||
); | ||
} | ||
|
||
if (!$value instanceof Value) { | ||
throw new RuntimeException( | ||
sprintf( | ||
'Field value should be of type %s. "%s" given.', | ||
Value::class, | ||
get_debug_type($value) | ||
) | ||
); | ||
} | ||
|
||
return $value; | ||
} | ||
|
||
private function getImageFieldIdentifier(string $contentTypeIdentifier): string | ||
{ | ||
$imageFieldIdentifier = $this->imageMappings[$contentTypeIdentifier]['imageFieldIdentifier']; | ||
if (null === $imageFieldIdentifier) { | ||
throw new RuntimeException( | ||
sprintf( | ||
'Missing key imageFieldIdentifier for content type mapping "%s".', | ||
$contentTypeIdentifier | ||
) | ||
); | ||
} | ||
|
||
return $imageFieldIdentifier; | ||
} | ||
|
||
private function getImageUri(Value $value): string | ||
{ | ||
$uri = $value->uri; | ||
if (null === $uri) { | ||
throw new RuntimeException('Missing image uri'); | ||
} | ||
|
||
return ltrim($uri, '/'); | ||
} | ||
|
||
/** | ||
* @throws \Random\RandomException | ||
*/ | ||
private function getImageFileName(Value $value): string | ||
{ | ||
return $value->fileName ?? 'image_' . $this->generateRandomFileName(); | ||
} | ||
|
||
/** | ||
* @param array<int> $contentIdList | ||
* | ||
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\InvalidArgumentException; | ||
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\InvalidCriterionArgumentException; | ||
*/ | ||
private function loadImages(array $contentIdList): SearchResult | ||
{ | ||
$query = new Query(); | ||
$query->filter = new Query\Criterion\LogicalAnd( | ||
[ | ||
new Query\Criterion\ContentId($contentIdList), | ||
new Query\Criterion\ContentTypeIdentifier($this->getContentTypeIdentifiers()), | ||
] | ||
); | ||
$query->limit = $this->downloadLimit; | ||
|
||
return $this->searchService->findContent($query, [], false); | ||
} | ||
|
||
/** | ||
* @return array<string> | ||
*/ | ||
private function getContentTypeIdentifiers(): array | ||
{ | ||
$contentTypeIdentifiers = []; | ||
foreach ($this->imageMappings as $contentTypeIdentifier => $mapping) { | ||
$contentTypeIdentifiers[] = $contentTypeIdentifier; | ||
} | ||
|
||
return $contentTypeIdentifiers; | ||
} | ||
|
||
private function createResponse( | ||
string $content, | ||
string $fileName | ||
): Response { | ||
$disposition = HeaderUtils::makeDisposition( | ||
HeaderUtils::DISPOSITION_ATTACHMENT, | ||
$fileName | ||
); | ||
|
||
return new Response( | ||
$content, | ||
200, | ||
[ | ||
'Content-Disposition' => $disposition, | ||
'Content-Length' => strlen($content), | ||
] | ||
); | ||
} | ||
|
||
/** | ||
* @param array<\Ibexa\Contracts\Core\Repository\Values\Content\Content> $contentList | ||
* | ||
* @throws \Random\RandomException | ||
*/ | ||
private function createArchive(string $name, array $contentList): void | ||
{ | ||
$zipArchive = new ZipArchive(); | ||
$zipArchive->open($name, ZipArchive::CREATE); | ||
|
||
foreach ($contentList as $content) { | ||
$value = $this->getImageValue($content); | ||
$zipArchive->addFile( | ||
$this->getImageUri($value), | ||
$this->getImageFileName($value) | ||
); | ||
} | ||
|
||
$zipArchive->close(); | ||
} | ||
|
||
/** | ||
* @throws \Random\RandomException | ||
*/ | ||
private function generateRandomFileName(): string | ||
{ | ||
return bin2hex(random_bytes(12)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.