-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
PreviewManager.php
478 lines (432 loc) · 15.1 KB
/
PreviewManager.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Olivier Paroz <github@oparoz.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Sebastian Steinmetz <462714+steiny2k@users.noreply.github.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC;
use OC\AppFramework\Bootstrap\Coordinator;
use OC\Preview\Generator;
use OC\Preview\GeneratorHelper;
use OC\Preview\IMagickSupport;
use OCP\AppFramework\QueryException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\File;
use OCP\Files\IAppData;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\IBinaryFinder;
use OCP\IConfig;
use OCP\IPreview;
use OCP\IServerContainer;
use OCP\Preview\IProviderV2;
use function array_key_exists;
class PreviewManager implements IPreview {
protected IConfig $config;
protected IRootFolder $rootFolder;
protected IAppData $appData;
protected IEventDispatcher $eventDispatcher;
private ?Generator $generator = null;
private GeneratorHelper $helper;
protected bool $providerListDirty = false;
protected bool $registeredCoreProviders = false;
protected array $providers = [];
/** @var array mime type => support status */
protected array $mimeTypeSupportMap = [];
protected ?array $defaultProviders = null;
protected ?string $userId;
private Coordinator $bootstrapCoordinator;
/**
* Hash map (without value) of loaded bootstrap providers
* @psalm-var array<string, null>
*/
private array $loadedBootstrapProviders = [];
private IServerContainer $container;
private IBinaryFinder $binaryFinder;
private IMagickSupport $imagickSupport;
public function __construct(
IConfig $config,
IRootFolder $rootFolder,
IAppData $appData,
IEventDispatcher $eventDispatcher,
GeneratorHelper $helper,
?string $userId,
Coordinator $bootstrapCoordinator,
IServerContainer $container,
IBinaryFinder $binaryFinder,
IMagickSupport $imagickSupport
) {
$this->config = $config;
$this->rootFolder = $rootFolder;
$this->appData = $appData;
$this->eventDispatcher = $eventDispatcher;
$this->helper = $helper;
$this->userId = $userId;
$this->bootstrapCoordinator = $bootstrapCoordinator;
$this->container = $container;
$this->binaryFinder = $binaryFinder;
$this->imagickSupport = $imagickSupport;
}
/**
* In order to improve lazy loading a closure can be registered which will be
* called in case preview providers are actually requested
*
* $callable has to return an instance of \OCP\Preview\IProvider or \OCP\Preview\IProviderV2
*
* @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
* @param \Closure $callable
* @return void
*/
public function registerProvider($mimeTypeRegex, \Closure $callable): void {
if (!$this->config->getSystemValueBool('enable_previews', true)) {
return;
}
if (!isset($this->providers[$mimeTypeRegex])) {
$this->providers[$mimeTypeRegex] = [];
}
$this->providers[$mimeTypeRegex][] = $callable;
$this->providerListDirty = true;
}
/**
* Get all providers
*/
public function getProviders(): array {
if (!$this->config->getSystemValueBool('enable_previews', true)) {
return [];
}
$this->registerCoreProviders();
$this->registerBootstrapProviders();
if ($this->providerListDirty) {
$keys = array_map('strlen', array_keys($this->providers));
array_multisort($keys, SORT_DESC, $this->providers);
$this->providerListDirty = false;
}
return $this->providers;
}
/**
* Does the manager have any providers
*/
public function hasProviders(): bool {
$this->registerCoreProviders();
return !empty($this->providers);
}
private function getGenerator(): Generator {
if ($this->generator === null) {
$this->generator = new Generator(
$this->config,
$this,
$this->appData,
new GeneratorHelper(
$this->rootFolder,
$this->config
),
$this->eventDispatcher
);
}
return $this->generator;
}
/**
* Returns a preview of a file
*
* The cache is searched first and if nothing usable was found then a preview is
* generated by one of the providers
*
* @param File $file
* @param int $width
* @param int $height
* @param bool $crop
* @param string $mode
* @param string $mimeType
* @return ISimpleFile
* @throws NotFoundException
* @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
* @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
*/
public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
$previewConcurrency = $this->getGenerator()->getNumConcurrentPreviews('preview_concurrency_all');
$sem = Generator::guardWithSemaphore(Generator::SEMAPHORE_ID_ALL, $previewConcurrency);
try {
$preview = $this->getGenerator()->getPreview($file, $width, $height, $crop, $mode, $mimeType);
} finally {
Generator::unguardWithSemaphore($sem);
}
return $preview;
}
/**
* Generates previews of a file
*
* @param File $file
* @param array $specifications
* @param string $mimeType
* @return ISimpleFile the last preview that was generated
* @throws NotFoundException
* @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
* @since 19.0.0
*/
public function generatePreviews(File $file, array $specifications, $mimeType = null) {
return $this->getGenerator()->generatePreviews($file, $specifications, $mimeType);
}
/**
* returns true if the passed mime type is supported
*
* @param string $mimeType
* @return boolean
*/
public function isMimeSupported($mimeType = '*') {
if (!$this->config->getSystemValueBool('enable_previews', true)) {
return false;
}
if (isset($this->mimeTypeSupportMap[$mimeType])) {
return $this->mimeTypeSupportMap[$mimeType];
}
$this->registerCoreProviders();
$this->registerBootstrapProviders();
$providerMimeTypes = array_keys($this->providers);
foreach ($providerMimeTypes as $supportedMimeType) {
if (preg_match($supportedMimeType, $mimeType)) {
$this->mimeTypeSupportMap[$mimeType] = true;
return true;
}
}
$this->mimeTypeSupportMap[$mimeType] = false;
return false;
}
/**
* Check if a preview can be generated for a file
*/
public function isAvailable(\OCP\Files\FileInfo $file): bool {
if (!$this->config->getSystemValueBool('enable_previews', true)) {
return false;
}
$this->registerCoreProviders();
if (!$this->isMimeSupported($file->getMimetype())) {
return false;
}
$mount = $file->getMountPoint();
if ($mount and !$mount->getOption('previews', true)) {
return false;
}
foreach ($this->providers as $supportedMimeType => $providers) {
if (preg_match($supportedMimeType, $file->getMimetype())) {
foreach ($providers as $providerClosure) {
$provider = $this->helper->getProvider($providerClosure);
if (!($provider instanceof IProviderV2)) {
continue;
}
if ($provider->isAvailable($file)) {
return true;
}
}
}
}
return false;
}
/**
* List of enabled default providers
*
* The following providers are enabled by default:
* - OC\Preview\PNG
* - OC\Preview\JPEG
* - OC\Preview\GIF
* - OC\Preview\BMP
* - OC\Preview\XBitmap
* - OC\Preview\MarkDown
* - OC\Preview\MP3
* - OC\Preview\TXT
*
* The following providers are disabled by default due to performance or privacy concerns:
* - OC\Preview\Font
* - OC\Preview\HEIC
* - OC\Preview\Illustrator
* - OC\Preview\Movie
* - OC\Preview\MSOfficeDoc
* - OC\Preview\MSOffice2003
* - OC\Preview\MSOffice2007
* - OC\Preview\OpenDocument
* - OC\Preview\PDF
* - OC\Preview\Photoshop
* - OC\Preview\Postscript
* - OC\Preview\StarOffice
* - OC\Preview\SVG
* - OC\Preview\TIFF
*
* @return array
*/
protected function getEnabledDefaultProvider() {
if ($this->defaultProviders !== null) {
return $this->defaultProviders;
}
$imageProviders = [
Preview\PNG::class,
Preview\JPEG::class,
Preview\GIF::class,
Preview\BMP::class,
Preview\XBitmap::class,
Preview\Krita::class,
Preview\WebP::class,
];
$this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
Preview\MarkDown::class,
Preview\MP3::class,
Preview\TXT::class,
Preview\OpenDocument::class,
], $imageProviders));
if (in_array(Preview\Image::class, $this->defaultProviders)) {
$this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
}
$this->defaultProviders = array_unique($this->defaultProviders);
return $this->defaultProviders;
}
/**
* Register the default providers (if enabled)
*
* @param string $class
* @param string $mimeType
*/
protected function registerCoreProvider($class, $mimeType, $options = []) {
if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
$this->registerProvider($mimeType, function () use ($class, $options) {
return new $class($options);
});
}
}
/**
* Register the default providers (if enabled)
*/
protected function registerCoreProviders() {
if ($this->registeredCoreProviders) {
return;
}
$this->registeredCoreProviders = true;
$this->registerCoreProvider(Preview\TXT::class, '/text\/plain/');
$this->registerCoreProvider(Preview\MarkDown::class, '/text\/(x-)?markdown/');
$this->registerCoreProvider(Preview\PNG::class, '/image\/png/');
$this->registerCoreProvider(Preview\JPEG::class, '/image\/jpeg/');
$this->registerCoreProvider(Preview\GIF::class, '/image\/gif/');
$this->registerCoreProvider(Preview\BMP::class, '/image\/bmp/');
$this->registerCoreProvider(Preview\XBitmap::class, '/image\/x-xbitmap/');
$this->registerCoreProvider(Preview\WebP::class, '/image\/webp/');
$this->registerCoreProvider(Preview\Krita::class, '/application\/x-krita/');
$this->registerCoreProvider(Preview\MP3::class, '/audio\/mpeg/');
$this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/');
$this->registerCoreProvider(Preview\Imaginary::class, Preview\Imaginary::supportedMimeTypes());
// SVG and Bitmap require imagick
if ($this->imagickSupport->hasExtension()) {
$imagickProviders = [
'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class],
'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class],
'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class],
'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class],
'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class],
'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class],
'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class],
'HEIC' => ['mimetype' => '/image\/hei(f|c)/', 'class' => Preview\HEIC::class],
'TGA' => ['mimetype' => '/image\/t(ar)?ga/', 'class' => Preview\TGA::class],
'SGI' => ['mimetype' => '/image\/sgi/', 'class' => Preview\SGI::class],
];
foreach ($imagickProviders as $queryFormat => $provider) {
$class = $provider['class'];
if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
continue;
}
if ($this->imagickSupport->supportsFormat($queryFormat)) {
$this->registerCoreProvider($class, $provider['mimetype']);
}
}
}
$this->registerCoreProvidersOffice();
// Video requires avconv or ffmpeg
if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) {
$movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null);
if (!is_string($movieBinary)) {
$movieBinary = $this->binaryFinder->findBinaryPath('avconv');
if (!is_string($movieBinary)) {
$movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg');
}
}
if (is_string($movieBinary)) {
$this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ["movieBinary" => $movieBinary]);
}
}
}
private function registerCoreProvidersOffice(): void {
$officeProviders = [
['mimetype' => '/application\/msword/', 'class' => Preview\MSOfficeDoc::class],
['mimetype' => '/application\/vnd.ms-.*/', 'class' => Preview\MSOffice2003::class],
['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => Preview\MSOffice2007::class],
['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => Preview\OpenDocument::class],
['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => Preview\StarOffice::class],
['mimetype' => '/image\/emf/', 'class' => Preview\EMF::class],
];
$findBinary = true;
$officeBinary = false;
foreach ($officeProviders as $provider) {
$class = $provider['class'];
if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
continue;
}
if ($findBinary) {
// Office requires openoffice or libreoffice
$officeBinary = $this->config->getSystemValue('preview_libreoffice_path', false);
if ($officeBinary === false) {
$officeBinary = $this->binaryFinder->findBinaryPath('libreoffice');
}
if ($officeBinary === false) {
$officeBinary = $this->binaryFinder->findBinaryPath('openoffice');
}
$findBinary = false;
}
if ($officeBinary) {
$this->registerCoreProvider($class, $provider['mimetype'], ['officeBinary' => $officeBinary]);
}
}
}
private function registerBootstrapProviders(): void {
$context = $this->bootstrapCoordinator->getRegistrationContext();
if ($context === null) {
// Just ignore for now
return;
}
$providers = $context->getPreviewProviders();
foreach ($providers as $provider) {
$key = $provider->getMimeTypeRegex() . '-' . $provider->getService();
if (array_key_exists($key, $this->loadedBootstrapProviders)) {
// Do not load the provider more than once
continue;
}
$this->loadedBootstrapProviders[$key] = null;
$this->registerProvider($provider->getMimeTypeRegex(), function () use ($provider) {
try {
return $this->container->get($provider->getService());
} catch (QueryException $e) {
return null;
}
});
}
}
}