-
-
Notifications
You must be signed in to change notification settings - Fork 219
/
AssetService.php
403 lines (364 loc) · 14.1 KB
/
AssetService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<?php
declare(strict_types=1);
namespace Neos\Media\Domain\Service;
/*
* This file is part of the Neos.Media package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use GuzzleHttp\Psr7\Uri;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Exception as HttpException;
use Neos\Flow\Log\Utility\LogEnvironment;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Flow\Mvc\Routing\Exception\MissingActionNameException;
use Neos\Flow\Mvc\Routing\UriBuilder;
use Neos\Flow\ObjectManagement\ObjectManagerInterface;
use Neos\Flow\Package\PackageManager;
use Neos\Flow\Persistence\RepositoryInterface;
use Neos\Flow\Reflection\ReflectionService;
use Neos\Flow\ResourceManagement\PersistentResource;
use Neos\Flow\ResourceManagement\ResourceManager;
use Neos\Media\Domain\Model\AssetInterface;
use Neos\Media\Domain\Model\AssetVariantInterface;
use Neos\Media\Domain\Model\ImageInterface;
use Neos\Media\Domain\Model\ImageVariant;
use Neos\Media\Domain\Model\Thumbnail;
use Neos\Media\Domain\Model\ThumbnailConfiguration;
use Neos\Media\Domain\Repository\AssetRepository;
use Neos\Media\Domain\Strategy\AssetUsageStrategyInterface;
use Neos\Media\Exception\AssetServiceException;
use Neos\Media\Exception\AssetVariantGeneratorException;
use Neos\Media\Exception\ThumbnailServiceException;
use Neos\RedirectHandler\Storage\RedirectStorageInterface;
use Neos\Utility\Arrays;
use Neos\Utility\MediaTypes;
use Psr\Log\LoggerInterface;
/**
* An asset service that handles for example commands on assets, retrieves information
* about usage of assets and rendering thumbnails.
*
* @Flow\Scope("singleton")
*/
class AssetService
{
/**
* @Flow\Inject
* @var ResourceManager
*/
protected $resourceManager;
/**
* @Flow\Inject
* @var ThumbnailService
*/
protected $thumbnailService;
/**
* @Flow\Inject
* @var UriBuilder
*/
protected $uriBuilder;
/**
* @Flow\Inject
* @var ObjectManagerInterface
*/
protected $objectManager;
/**
* @Flow\Inject
* @var ReflectionService
*/
protected $reflectionService;
/**
* @var array
*/
protected $usageStrategies;
/**
* @Flow\Inject
* @var PackageManager
*/
protected $packageManager;
/**
* @Flow\Inject
* @var LoggerInterface
*/
protected $logger;
/**
* @Flow\Inject
* @var ImageService
*/
protected $imageService;
/**
* @Flow\Inject
* @var AssetVariantGenerator
*/
protected $assetVariantGenerator;
/**
* Returns the repository for an asset
*
* @param AssetInterface $asset
* @return RepositoryInterface
* @api
*/
public function getRepository(AssetInterface $asset): RepositoryInterface
{
$assetRepositoryClassName = str_replace('\\Model\\', '\\Repository\\', get_class($asset)) . 'Repository';
if (class_exists($assetRepositoryClassName)) {
return $this->objectManager->get($assetRepositoryClassName);
}
return $this->objectManager->get(AssetRepository::class);
}
/**
* Calculates the dimensions of the thumbnail to be generated and returns the thumbnail URI.
* In case of Images this is a thumbnail of the image, in case of other assets an icon representation.
*
* @param AssetInterface $asset
* @param ThumbnailConfiguration $configuration
* @param ActionRequest $request Request argument must be provided for asynchronous thumbnails
* @return array|null Array with keys "width", "height" and "src" if the thumbnail generation work or null
* @throws AssetServiceException
* @throws ThumbnailServiceException
* @throws MissingActionNameException
* @throws HttpException
*/
public function getThumbnailUriAndSizeForAsset(AssetInterface $asset, ThumbnailConfiguration $configuration, ActionRequest $request = null): ?array
{
$thumbnailImage = $this->thumbnailService->getThumbnail($asset, $configuration);
if (!$thumbnailImage instanceof ImageInterface) {
return null;
}
$resource = $thumbnailImage->getResource();
if ($thumbnailImage instanceof Thumbnail) {
$staticResource = $thumbnailImage->getStaticResource();
if ($resource === null && $staticResource === null && $configuration->isAsync() === true) {
if ($request === null) {
throw new AssetServiceException('Request argument must be provided for async thumbnails.', 1447660835);
}
$this->uriBuilder->setRequest($request->getMainRequest());
$uri = $this->uriBuilder
->reset()
->setCreateAbsoluteUri(true)
->uriFor('thumbnail', ['thumbnail' => $thumbnailImage], 'Thumbnail', 'Neos.Media');
} else {
$uri = $this->thumbnailService->getUriForThumbnail($thumbnailImage);
}
} else {
$uri = $this->resourceManager->getPublicPersistentResourceUri($resource);
}
return [
'width' => $thumbnailImage->getWidth(),
'height' => $thumbnailImage->getHeight(),
'src' => $uri
];
}
/**
* Returns all registered asset usage strategies
*
* @return array<\Neos\Media\Domain\Strategy\AssetUsageStrategyInterface>
*/
protected function getUsageStrategies(): array
{
if (is_array($this->usageStrategies)) {
return $this->usageStrategies;
}
$this->usageStrategies = [];
$assetUsageStrategyImplementations = $this->reflectionService->getAllImplementationClassNamesForInterface(AssetUsageStrategyInterface::class);
foreach ($assetUsageStrategyImplementations as $assetUsageStrategyImplementationClassName) {
$this->usageStrategies[] = $this->objectManager->get($assetUsageStrategyImplementationClassName);
}
return $this->usageStrategies;
}
/**
* Returns an array of asset usage references.
*
* @param AssetInterface $asset
* @return array<\Neos\Media\Domain\Model\Dto\UsageReference>
*/
public function getUsageReferences(AssetInterface $asset): array
{
$usages = [];
/** @var AssetUsageStrategyInterface $strategy */
foreach ($this->getUsageStrategies() as $strategy) {
$usages = Arrays::arrayMergeRecursiveOverrule($usages, $strategy->getUsageReferences($asset));
}
return $usages;
}
/**
* Returns the total count of times an asset is used.
*
* @param AssetInterface $asset
* @return integer
*/
public function getUsageCount(AssetInterface $asset): int
{
$usageCount = 0;
/** @var AssetUsageStrategyInterface $strategy */
foreach ($this->getUsageStrategies() as $strategy) {
$usageCount += $strategy->getUsageCount($asset);
}
return $usageCount;
}
/**
* Returns true if the asset is used.
*
* @param AssetInterface $asset
* @return boolean
*/
public function isInUse(AssetInterface $asset): bool
{
/** @var AssetUsageStrategyInterface $strategy */
foreach ($this->getUsageStrategies() as $strategy) {
if ($strategy->isInUse($asset) === true) {
return true;
}
}
return false;
}
/**
* Validates if the asset can be removed
*
* @param AssetInterface $asset
* @return void
* @throws AssetServiceException Thrown if the asset can not be removed
*/
public function validateRemoval(AssetInterface $asset): void
{
if ($asset instanceof ImageVariant) {
return;
}
if ($this->isInUse($asset)) {
throw new AssetServiceException('Asset could not be deleted, because it is still in use.', 1462196420);
}
}
/**
* Replace resource on an asset. Takes variants and redirect handling into account.
*
* @param AssetInterface $asset
* @param PersistentResource $resource
* @param array $options
* @return void
*/
public function replaceAssetResource(AssetInterface $asset, PersistentResource $resource, array $options = []): void
{
$originalAssetResource = $asset->getResource();
$resourceMediaType = $resource->getMediaType();
$asset->setResource($resource);
if (isset($options['keepOriginalFilename']) && (boolean)$options['keepOriginalFilename'] === true) {
$originalFilename = $originalAssetResource->getFilename();
if (MediaTypes::getMediaTypeFromFilename($originalFilename) !== $resourceMediaType) {
$originalFileExtension = $originalAssetResource->getFileExtension();
$fileExtensionForMediaType = MediaTypes::getFilenameExtensionFromMediaType($resourceMediaType);
// filename needs to get new matching extension
$originalFilename = preg_replace(sprintf('/(.*)\.%s$/', $originalFileExtension), '$1.' . $fileExtensionForMediaType, $originalFilename);
}
$asset->getResource()->setFilename($originalFilename);
$asset->getResource()->setMediaType($resourceMediaType);
}
$uriMapping = [];
$redirectHandlerEnabled = isset($options['generateRedirects']) && (boolean)$options['generateRedirects'] === true && $this->packageManager->isPackageAvailable('Neos.RedirectHandler');
if ($redirectHandlerEnabled) {
$originalAssetResourceUri = new Uri($this->resourceManager->getPublicPersistentResourceUri($originalAssetResource));
$newAssetResourceUri = new Uri($this->resourceManager->getPublicPersistentResourceUri($asset->getResource()));
$uriMapping[$originalAssetResourceUri->getPath()] = $newAssetResourceUri->getPath();
}
if (method_exists($asset, 'getVariants')) {
$variants = $asset->getVariants();
/** @var AssetVariantInterface $variant */
foreach ($variants as $variant) {
$originalVariantResource = $variant->getResource();
$presetIdentifier = $variant->getPresetIdentifier();
$variantName = $variant->getPresetVariantName();
if (isset($presetIdentifier, $variantName)) {
try {
$variant = $this->assetVariantGenerator->recreateVariant($asset, $presetIdentifier, $variantName);
if ($variant === null) {
$this->logger->debug(
sprintf('No variant returned when recreating asset variant %s::%s for %s', $presetIdentifier, $variantName, $asset->getTitle()),
LogEnvironment::fromMethodName(__METHOD__)
);
continue;
}
} catch (AssetVariantGeneratorException $exception) {
$this->logger->error(
sprintf('Error when recreating asset variant: %s', $exception->getMessage()),
LogEnvironment::fromMethodName(__METHOD__)
);
continue;
}
} else {
$variant->refresh();
foreach ($variant->getAdjustments() as $adjustment) {
if (method_exists($adjustment, 'refit') && $this->imageService->getImageSize($originalAssetResource) !== $this->imageService->getImageSize($resource)) {
if ($asset instanceof ImageInterface && $asset->getWidth() !== null && $asset->getHeight() !== null) {
$adjustment->refit($asset);
}
}
}
$this->getRepository($variant)->update($variant);
}
if ($redirectHandlerEnabled) {
$originalVariantResourceUri = new Uri($this->resourceManager->getPublicPersistentResourceUri($originalVariantResource));
$newVariantResourceUri = new Uri($this->resourceManager->getPublicPersistentResourceUri($variant->getResource()));
$uriMapping[$originalVariantResourceUri->getPath()] = $newVariantResourceUri->getPath();
}
}
}
if ($redirectHandlerEnabled) {
/** @var RedirectStorageInterface $redirectStorage */
$redirectStorage = $this->objectManager->get(RedirectStorageInterface::class);
foreach ($uriMapping as $originalUri => $newUri) {
$existingRedirect = $redirectStorage->getOneBySourceUriPathAndHost($originalUri);
if ($existingRedirect === null && $originalUri !== $newUri) {
$redirectStorage->addRedirect($originalUri, $newUri, 301);
}
}
}
$this->getRepository($asset)->update($asset);
$this->emitAssetResourceReplaced($asset);
}
/**
* Signals that an asset was added.
*
* @Flow\Signal
* @param AssetInterface $asset
* @return void
*/
public function emitAssetCreated(AssetInterface $asset): void
{
}
/**
* Signals that an asset was removed.
*
* @Flow\Signal
* @param AssetInterface $asset
* @return void
*/
public function emitAssetRemoved(AssetInterface $asset): void
{
}
/**
* Signals that an asset was updated.
*
* @Flow\Signal
* @param AssetInterface $asset
* @return void
*/
public function emitAssetUpdated(AssetInterface $asset): void
{
}
/**
* Signals that a resource on an asset has been replaced
*
* Note: when an asset resource is replaced, the assetUpdated signal is sent anyway
* and can be used instead.
*
* @param AssetInterface $asset
* @return void
* @Flow\Signal
*/
public function emitAssetResourceReplaced(AssetInterface $asset): void
{
}
}