Generator.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Elijah Martin-Merrill <elijah@nyp-itsours.com>
  7. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Scott Dutton <scott@exussum.co.uk>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OC\Preview;
  30. use OCP\Files\File;
  31. use OCP\Files\IAppData;
  32. use OCP\Files\NotFoundException;
  33. use OCP\Files\NotPermittedException;
  34. use OCP\Files\SimpleFS\ISimpleFile;
  35. use OCP\Files\SimpleFS\ISimpleFolder;
  36. use OCP\IConfig;
  37. use OCP\IImage;
  38. use OCP\IPreview;
  39. use OCP\Preview\IProviderV2;
  40. use OCP\Preview\IVersionedPreviewFile;
  41. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  42. use Symfony\Component\EventDispatcher\GenericEvent;
  43. class Generator {
  44. /** @var IPreview */
  45. private $previewManager;
  46. /** @var IConfig */
  47. private $config;
  48. /** @var IAppData */
  49. private $appData;
  50. /** @var GeneratorHelper */
  51. private $helper;
  52. /** @var EventDispatcherInterface */
  53. private $eventDispatcher;
  54. /**
  55. * @param IConfig $config
  56. * @param IPreview $previewManager
  57. * @param IAppData $appData
  58. * @param GeneratorHelper $helper
  59. * @param EventDispatcherInterface $eventDispatcher
  60. */
  61. public function __construct(
  62. IConfig $config,
  63. IPreview $previewManager,
  64. IAppData $appData,
  65. GeneratorHelper $helper,
  66. EventDispatcherInterface $eventDispatcher
  67. ) {
  68. $this->config = $config;
  69. $this->previewManager = $previewManager;
  70. $this->appData = $appData;
  71. $this->helper = $helper;
  72. $this->eventDispatcher = $eventDispatcher;
  73. }
  74. /**
  75. * Returns a preview of a file
  76. *
  77. * The cache is searched first and if nothing usable was found then a preview is
  78. * generated by one of the providers
  79. *
  80. * @param File $file
  81. * @param int $width
  82. * @param int $height
  83. * @param bool $crop
  84. * @param string $mode
  85. * @param string $mimeType
  86. * @return ISimpleFile
  87. * @throws NotFoundException
  88. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  89. */
  90. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  91. $specification = [
  92. 'width' => $width,
  93. 'height' => $height,
  94. 'crop' => $crop,
  95. 'mode' => $mode,
  96. ];
  97. $this->eventDispatcher->dispatch(
  98. IPreview::EVENT,
  99. new GenericEvent($file, $specification)
  100. );
  101. // since we only ask for one preview, and the generate method return the last one it created, it returns the one we want
  102. return $this->generatePreviews($file, [$specification], $mimeType);
  103. }
  104. /**
  105. * Generates previews of a file
  106. *
  107. * @param File $file
  108. * @param array $specifications
  109. * @param string $mimeType
  110. * @return ISimpleFile the last preview that was generated
  111. * @throws NotFoundException
  112. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  113. */
  114. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  115. //Make sure that we can read the file
  116. if (!$file->isReadable()) {
  117. throw new NotFoundException('Cannot read file');
  118. }
  119. if ($mimeType === null) {
  120. $mimeType = $file->getMimeType();
  121. }
  122. $previewFolder = $this->getPreviewFolder($file);
  123. $previewVersion = '';
  124. if ($file instanceof IVersionedPreviewFile) {
  125. $previewVersion = $file->getPreviewVersion() . '-';
  126. }
  127. // Get the max preview and infer the max preview sizes from that
  128. $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType, $previewVersion);
  129. $maxPreviewImage = null; // only load the image when we need it
  130. if ($maxPreview->getSize() === 0) {
  131. $maxPreview->delete();
  132. throw new NotFoundException('Max preview size 0, invalid!');
  133. }
  134. [$maxWidth, $maxHeight] = $this->getPreviewSize($maxPreview, $previewVersion);
  135. $preview = null;
  136. foreach ($specifications as $specification) {
  137. $width = $specification['width'] ?? -1;
  138. $height = $specification['height'] ?? -1;
  139. $crop = $specification['crop'] ?? false;
  140. $mode = $specification['mode'] ?? IPreview::MODE_FILL;
  141. // If both width and height are -1 we just want the max preview
  142. if ($width === -1 && $height === -1) {
  143. $width = $maxWidth;
  144. $height = $maxHeight;
  145. }
  146. // Calculate the preview size
  147. [$width, $height] = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
  148. // No need to generate a preview that is just the max preview
  149. if ($width === $maxWidth && $height === $maxHeight) {
  150. // ensure correct return value if this was the last one
  151. $preview = $maxPreview;
  152. continue;
  153. }
  154. // Try to get a cached preview. Else generate (and store) one
  155. try {
  156. try {
  157. $preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType(), $previewVersion);
  158. } catch (NotFoundException $e) {
  159. if (!$this->previewManager->isMimeSupported($mimeType)) {
  160. throw new NotFoundException();
  161. }
  162. if ($maxPreviewImage === null) {
  163. $maxPreviewImage = $this->helper->getImage($maxPreview);
  164. }
  165. $preview = $this->generatePreview($previewFolder, $maxPreviewImage, $width, $height, $crop, $maxWidth, $maxHeight, $previewVersion);
  166. }
  167. } catch (\InvalidArgumentException $e) {
  168. throw new NotFoundException("", 0, $e);
  169. }
  170. if ($preview->getSize() === 0) {
  171. $preview->delete();
  172. throw new NotFoundException('Cached preview size 0, invalid!');
  173. }
  174. }
  175. // Free memory being used by the embedded image resource. Without this the image is kept in memory indefinitely.
  176. // Garbage Collection does NOT free this memory. We have to do it ourselves.
  177. if ($maxPreviewImage instanceof \OC_Image) {
  178. $maxPreviewImage->destroy();
  179. }
  180. return $preview;
  181. }
  182. /**
  183. * @param ISimpleFolder $previewFolder
  184. * @param File $file
  185. * @param string $mimeType
  186. * @param string $prefix
  187. * @return ISimpleFile
  188. * @throws NotFoundException
  189. */
  190. private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType, $prefix) {
  191. $nodes = $previewFolder->getDirectoryListing();
  192. foreach ($nodes as $node) {
  193. $name = $node->getName();
  194. if (($prefix === '' || strpos($name, $prefix) === 0) && strpos($name, 'max')) {
  195. return $node;
  196. }
  197. }
  198. $previewProviders = $this->previewManager->getProviders();
  199. foreach ($previewProviders as $supportedMimeType => $providers) {
  200. if (!preg_match($supportedMimeType, $mimeType)) {
  201. continue;
  202. }
  203. foreach ($providers as $providerClosure) {
  204. $provider = $this->helper->getProvider($providerClosure);
  205. if (!($provider instanceof IProviderV2)) {
  206. continue;
  207. }
  208. if (!$provider->isAvailable($file)) {
  209. continue;
  210. }
  211. $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 4096);
  212. $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 4096);
  213. $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
  214. if (!($preview instanceof IImage)) {
  215. continue;
  216. }
  217. // Try to get the extention.
  218. try {
  219. $ext = $this->getExtention($preview->dataMimeType());
  220. } catch (\InvalidArgumentException $e) {
  221. // Just continue to the next iteration if this preview doesn't have a valid mimetype
  222. continue;
  223. }
  224. $path = $prefix . (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
  225. try {
  226. $file = $previewFolder->newFile($path);
  227. $file->putContent($preview->data());
  228. } catch (NotPermittedException $e) {
  229. throw new NotFoundException();
  230. }
  231. return $file;
  232. }
  233. }
  234. throw new NotFoundException();
  235. }
  236. /**
  237. * @param ISimpleFile $file
  238. * @param string $prefix
  239. * @return int[]
  240. */
  241. private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
  242. $size = explode('-', substr($file->getName(), strlen($prefix)));
  243. return [(int)$size[0], (int)$size[1]];
  244. }
  245. /**
  246. * @param int $width
  247. * @param int $height
  248. * @param bool $crop
  249. * @param string $mimeType
  250. * @param string $prefix
  251. * @return string
  252. */
  253. private function generatePath($width, $height, $crop, $mimeType, $prefix) {
  254. $path = $prefix . (string)$width . '-' . (string)$height;
  255. if ($crop) {
  256. $path .= '-crop';
  257. }
  258. $ext = $this->getExtention($mimeType);
  259. $path .= '.' . $ext;
  260. return $path;
  261. }
  262. /**
  263. * @param int $width
  264. * @param int $height
  265. * @param bool $crop
  266. * @param string $mode
  267. * @param int $maxWidth
  268. * @param int $maxHeight
  269. * @return int[]
  270. */
  271. private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
  272. /*
  273. * If we are not cropping we have to make sure the requested image
  274. * respects the aspect ratio of the original.
  275. */
  276. if (!$crop) {
  277. $ratio = $maxHeight / $maxWidth;
  278. if ($width === -1) {
  279. $width = $height / $ratio;
  280. }
  281. if ($height === -1) {
  282. $height = $width * $ratio;
  283. }
  284. $ratioH = $height / $maxHeight;
  285. $ratioW = $width / $maxWidth;
  286. /*
  287. * Fill means that the $height and $width are the max
  288. * Cover means min.
  289. */
  290. if ($mode === IPreview::MODE_FILL) {
  291. if ($ratioH > $ratioW) {
  292. $height = $width * $ratio;
  293. } else {
  294. $width = $height / $ratio;
  295. }
  296. } elseif ($mode === IPreview::MODE_COVER) {
  297. if ($ratioH > $ratioW) {
  298. $width = $height / $ratio;
  299. } else {
  300. $height = $width * $ratio;
  301. }
  302. }
  303. }
  304. if ($height !== $maxHeight && $width !== $maxWidth) {
  305. /*
  306. * Scale to the nearest power of four
  307. */
  308. $pow4height = 4 ** ceil(log($height) / log(4));
  309. $pow4width = 4 ** ceil(log($width) / log(4));
  310. // Minimum size is 64
  311. $pow4height = max($pow4height, 64);
  312. $pow4width = max($pow4width, 64);
  313. $ratioH = $height / $pow4height;
  314. $ratioW = $width / $pow4width;
  315. if ($ratioH < $ratioW) {
  316. $width = $pow4width;
  317. $height /= $ratioW;
  318. } else {
  319. $height = $pow4height;
  320. $width /= $ratioH;
  321. }
  322. }
  323. /*
  324. * Make sure the requested height and width fall within the max
  325. * of the preview.
  326. */
  327. if ($height > $maxHeight) {
  328. $ratio = $height / $maxHeight;
  329. $height = $maxHeight;
  330. $width /= $ratio;
  331. }
  332. if ($width > $maxWidth) {
  333. $ratio = $width / $maxWidth;
  334. $width = $maxWidth;
  335. $height /= $ratio;
  336. }
  337. return [(int)round($width), (int)round($height)];
  338. }
  339. /**
  340. * @param ISimpleFolder $previewFolder
  341. * @param ISimpleFile $maxPreview
  342. * @param int $width
  343. * @param int $height
  344. * @param bool $crop
  345. * @param int $maxWidth
  346. * @param int $maxHeight
  347. * @param string $prefix
  348. * @return ISimpleFile
  349. * @throws NotFoundException
  350. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  351. */
  352. private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
  353. $preview = $maxPreview;
  354. if (!$preview->valid()) {
  355. throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
  356. }
  357. if ($crop) {
  358. if ($height !== $preview->height() && $width !== $preview->width()) {
  359. //Resize
  360. $widthR = $preview->width() / $width;
  361. $heightR = $preview->height() / $height;
  362. if ($widthR > $heightR) {
  363. $scaleH = $height;
  364. $scaleW = $maxWidth / $heightR;
  365. } else {
  366. $scaleH = $maxHeight / $widthR;
  367. $scaleW = $width;
  368. }
  369. $preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
  370. }
  371. $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
  372. $cropY = (int)floor(abs($height - $preview->height()) * 0.5);
  373. $preview = $preview->cropCopy($cropX, $cropY, $width, $height);
  374. } else {
  375. $preview = $maxPreview->resizeCopy(max($width, $height));
  376. }
  377. $path = $this->generatePath($width, $height, $crop, $preview->dataMimeType(), $prefix);
  378. try {
  379. $file = $previewFolder->newFile($path);
  380. $file->putContent($preview->data());
  381. } catch (NotPermittedException $e) {
  382. throw new NotFoundException();
  383. }
  384. return $file;
  385. }
  386. /**
  387. * @param ISimpleFolder $previewFolder
  388. * @param int $width
  389. * @param int $height
  390. * @param bool $crop
  391. * @param string $mimeType
  392. * @param string $prefix
  393. * @return ISimpleFile
  394. *
  395. * @throws NotFoundException
  396. */
  397. private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType, $prefix) {
  398. $path = $this->generatePath($width, $height, $crop, $mimeType, $prefix);
  399. return $previewFolder->getFile($path);
  400. }
  401. /**
  402. * Get the specific preview folder for this file
  403. *
  404. * @param File $file
  405. * @return ISimpleFolder
  406. */
  407. private function getPreviewFolder(File $file) {
  408. try {
  409. $folder = $this->appData->getFolder($file->getId());
  410. } catch (NotFoundException $e) {
  411. $folder = $this->appData->newFolder($file->getId());
  412. }
  413. return $folder;
  414. }
  415. /**
  416. * @param string $mimeType
  417. * @return null|string
  418. * @throws \InvalidArgumentException
  419. */
  420. private function getExtention($mimeType) {
  421. switch ($mimeType) {
  422. case 'image/png':
  423. return 'png';
  424. case 'image/jpeg':
  425. return 'jpg';
  426. case 'image/gif':
  427. return 'gif';
  428. default:
  429. throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
  430. }
  431. }
  432. }