Completed
Push — master ( 72889e...5f25dd )
by Morris
25:38 queued 13:04
created

Generator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 5
dl 13
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, Roeland Jago Douma <[email protected]>
4
 *
5
 * @author Roeland Jago Douma <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OC\Preview;
25
26
use OCP\Files\File;
27
use OCP\Files\IAppData;
28
use OCP\Files\NotFoundException;
29
use OCP\Files\NotPermittedException;
30
use OCP\Files\SimpleFS\ISimpleFile;
31
use OCP\Files\SimpleFS\ISimpleFolder;
32
use OCP\IConfig;
33
use OCP\IImage;
34
use OCP\IPreview;
35
use OCP\Preview\IProvider;
36
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
37
use Symfony\Component\EventDispatcher\GenericEvent;
38
39
class Generator {
40
41
	/** @var IPreview */
42
	private $previewManager;
43
	/** @var IConfig */
44
	private $config;
45
	/** @var IAppData */
46
	private $appData;
47
	/** @var GeneratorHelper */
48
	private $helper;
49
	/** @var EventDispatcherInterface */
50
	private $eventDispatcher;
51
52
	/**
53
	 * @param IConfig $config
54
	 * @param IPreview $previewManager
55
	 * @param IAppData $appData
56
	 * @param GeneratorHelper $helper
57
	 * @param EventDispatcherInterface $eventDispatcher
58
	 */
59 View Code Duplication
	public function __construct(
60
		IConfig $config,
61
		IPreview $previewManager,
62
		IAppData $appData,
63
		GeneratorHelper $helper,
64
		EventDispatcherInterface $eventDispatcher
65
	) {
66
		$this->config = $config;
67
		$this->previewManager = $previewManager;
68
		$this->appData = $appData;
69
		$this->helper = $helper;
70
		$this->eventDispatcher = $eventDispatcher;
71
	}
72
73
	/**
74
	 * Returns a preview of a file
75
	 *
76
	 * The cache is searched first and if nothing usable was found then a preview is
77
	 * generated by one of the providers
78
	 *
79
	 * @param File $file
80
	 * @param int $width
81
	 * @param int $height
82
	 * @param bool $crop
83
	 * @param string $mode
84
	 * @param string $mimeType
85
	 * @return ISimpleFile
86
	 * @throws NotFoundException
87
	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
88
	 */
89
	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
90
		$this->eventDispatcher->dispatch(
91
			IPreview::EVENT,
92
			new GenericEvent($file,[
93
				'width' => $width,
94
				'height' => $height,
95
				'crop' => $crop,
96
				'mode' => $mode
97
			])
98
		);
99
100
		if ($mimeType === null) {
101
			$mimeType = $file->getMimeType();
102
		}
103
		if (!$this->previewManager->isMimeSupported($mimeType)) {
104
			throw new NotFoundException();
105
		}
106
107
		$previewFolder = $this->getPreviewFolder($file);
108
109
		// Get the max preview and infer the max preview sizes from that
110
		$maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
111
		list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
112
113
		// If both width and heigth are -1 we just want the max preview
114
		if ($width === -1 && $height === -1) {
115
			$width = $maxWidth;
116
			$height = $maxHeight;
117
		}
118
119
		// Calculate the preview size
120
		list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
121
122
		// No need to generate a preview that is just the max preview
123
		if ($width === $maxWidth && $height === $maxHeight) {
124
			return $maxPreview;
125
		}
126
127
		// Try to get a cached preview. Else generate (and store) one
128
		try {
129
			$file = $this->getCachedPreview($previewFolder, $width, $height, $crop);
130
		} catch (NotFoundException $e) {
131
			$file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
132
		}
133
134
		return $file;
135
	}
136
137
	/**
138
	 * @param ISimpleFolder $previewFolder
139
	 * @param File $file
140
	 * @param string $mimeType
141
	 * @return ISimpleFile
142
	 * @throws NotFoundException
143
	 */
144
	private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
145
		$nodes = $previewFolder->getDirectoryListing();
146
147
		foreach ($nodes as $node) {
148
			if (strpos($node->getName(), 'max')) {
149
				return $node;
150
			}
151
		}
152
153
		$previewProviders = $this->previewManager->getProviders();
154
		foreach ($previewProviders as $supportedMimeType => $providers) {
155
			if (!preg_match($supportedMimeType, $mimeType)) {
156
				continue;
157
			}
158
159
			foreach ($providers as $provider) {
160
				$provider = $this->helper->getProvider($provider);
161
				if (!($provider instanceof IProvider)) {
162
					continue;
163
				}
164
165
				$maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048);
166
				$maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048);
167
168
				$preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
169
170
				if (!($preview instanceof IImage)) {
171
					continue;
172
				}
173
174
				$path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.png';
175
				try {
176
					$file = $previewFolder->newFile($path);
177
					$file->putContent($preview->data());
178
				} catch (NotPermittedException $e) {
179
					throw new NotFoundException();
180
				}
181
182
				return $file;
183
			}
184
		}
185
186
		throw new NotFoundException();
187
	}
188
189
	/**
190
	 * @param ISimpleFile $file
191
	 * @return int[]
192
	 */
193
	private function getPreviewSize(ISimpleFile $file) {
194
		$size = explode('-', $file->getName());
195
		return [(int)$size[0], (int)$size[1]];
196
	}
197
198
	/**
199
	 * @param int $width
200
	 * @param int $height
201
	 * @param bool $crop
202
	 * @return string
203
	 */
204
	private function generatePath($width, $height, $crop) {
205
		$path = (string)$width . '-' . (string)$height;
206
		if ($crop) {
207
			$path .= '-crop';
208
		}
209
		$path .= '.png';
210
		return $path;
211
	}
212
213
214
215
	/**
216
	 * @param int $width
217
	 * @param int $height
218
	 * @param bool $crop
219
	 * @param string $mode
220
	 * @param int $maxWidth
221
	 * @param int $maxHeight
222
	 * @return int[]
223
	 */
224
	private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
225
226
		/*
227
		 * If we are not cropping we have to make sure the requested image
228
		 * respects the aspect ratio of the original.
229
		 */
230
		if (!$crop) {
231
			$ratio = $maxHeight / $maxWidth;
232
233
			if ($width === -1) {
234
				$width = $height / $ratio;
235
			}
236
			if ($height === -1) {
237
				$height = $width * $ratio;
238
			}
239
240
			$ratioH = $height / $maxHeight;
241
			$ratioW = $width / $maxWidth;
242
243
			/*
244
			 * Fill means that the $height and $width are the max
245
			 * Cover means min.
246
			 */
247
			if ($mode === IPreview::MODE_FILL) {
248
				if ($ratioH > $ratioW) {
249
					$height = $width * $ratio;
250
				} else {
251
					$width = $height / $ratio;
252
				}
253
			} else if ($mode === IPreview::MODE_COVER) {
254
				if ($ratioH > $ratioW) {
255
					$width = $height / $ratio;
256
				} else {
257
					$height = $width * $ratio;
258
				}
259
			}
260
		}
261
262
		if ($height !== $maxHeight && $width !== $maxWidth) {
263
			/*
264
			 * Scale to the nearest power of two
265
			 */
266
			$pow2height = 2 ** ceil(log($height) / log(2));
267
			$pow2width = 2 ** ceil(log($width) / log(2));
268
269
			$ratioH = $height / $pow2height;
270
			$ratioW = $width / $pow2width;
271
272
			if ($ratioH < $ratioW) {
273
				$width = $pow2width;
274
				$height /= $ratioW;
275
			} else {
276
				$height = $pow2height;
277
				$width /= $ratioH;
278
			}
279
		}
280
281
		/*
282
 		 * Make sure the requested height and width fall within the max
283
 		 * of the preview.
284
 		 */
285
		if ($height > $maxHeight) {
286
			$ratio = $height / $maxHeight;
287
			$height = $maxHeight;
288
			$width /= $ratio;
289
		}
290
		if ($width > $maxWidth) {
291
			$ratio = $width / $maxWidth;
292
			$width = $maxWidth;
293
			$height /= $ratio;
294
		}
295
296
		return [(int)round($width), (int)round($height)];
297
	}
298
299
	/**
300
	 * @param ISimpleFolder $previewFolder
301
	 * @param ISimpleFile $maxPreview
302
	 * @param int $width
303
	 * @param int $height
304
	 * @param bool $crop
305
	 * @param int $maxWidth
306
	 * @param int $maxHeight
307
	 * @return ISimpleFile
308
	 * @throws NotFoundException
309
	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
310
	 */
311
	private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
312
		$preview = $this->helper->getImage($maxPreview);
313
314
		if (!$preview->valid()) {
315
			throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
316
		}
317
318
		if ($crop) {
319
			if ($height !== $preview->height() && $width !== $preview->width()) {
320
				//Resize
321
				$widthR = $preview->width() / $width;
322
				$heightR = $preview->height() / $height;
323
324
				if ($widthR > $heightR) {
325
					$scaleH = $height;
326
					$scaleW = $maxWidth / $heightR;
327
				} else {
328
					$scaleH = $maxHeight / $widthR;
329
					$scaleW = $width;
330
				}
331
				$preview->preciseResize(round($scaleW), round($scaleH));
332
			}
333
			$cropX = floor(abs($width - $preview->width()) * 0.5);
334
			$cropY = 0;
335
			$preview->crop($cropX, $cropY, $width, $height);
336
		} else {
337
			$preview->resize(max($width, $height));
338
		}
339
340
341
		$path = $this->generatePath($width, $height, $crop);
342
		try {
343
			$file = $previewFolder->newFile($path);
344
			$file->putContent($preview->data());
345
		} catch (NotPermittedException $e) {
346
			throw new NotFoundException();
347
		}
348
349
		return $file;
350
	}
351
352
	/**
353
	 * @param ISimpleFolder $previewFolder
354
	 * @param int $width
355
	 * @param int $height
356
	 * @param bool $crop
357
	 * @return ISimpleFile
358
	 *
359
	 * @throws NotFoundException
360
	 */
361
	private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) {
362
		$path = $this->generatePath($width, $height, $crop);
363
364
		return $previewFolder->getFile($path);
365
	}
366
367
	/**
368
	 * Get the specific preview folder for this file
369
	 *
370
	 * @param File $file
371
	 * @return ISimpleFolder
372
	 */
373
	private function getPreviewFolder(File $file) {
374
		try {
375
			$folder = $this->appData->getFolder($file->getId());
376
		} catch (NotFoundException $e) {
377
			$folder = $this->appData->newFolder($file->getId());
378
		}
379
380
		return $folder;
381
	}
382
}
383