Generator.php 17 KB

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