Generator.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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\EventDispatcher\IEventDispatcher;
  32. use OCP\Files\File;
  33. use OCP\Files\IAppData;
  34. use OCP\Files\InvalidPathException;
  35. use OCP\Files\NotFoundException;
  36. use OCP\Files\NotPermittedException;
  37. use OCP\Files\SimpleFS\ISimpleFile;
  38. use OCP\Files\SimpleFS\ISimpleFolder;
  39. use OCP\IConfig;
  40. use OCP\IImage;
  41. use OCP\IPreview;
  42. use OCP\IStreamImage;
  43. use OCP\Preview\BeforePreviewFetchedEvent;
  44. use OCP\Preview\IProviderV2;
  45. use OCP\Preview\IVersionedPreviewFile;
  46. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  47. use Symfony\Component\EventDispatcher\GenericEvent;
  48. class Generator {
  49. public const SEMAPHORE_ID_ALL = 0x0a11;
  50. public const SEMAPHORE_ID_NEW = 0x07ea;
  51. /** @var IPreview */
  52. private $previewManager;
  53. /** @var IConfig */
  54. private $config;
  55. /** @var IAppData */
  56. private $appData;
  57. /** @var GeneratorHelper */
  58. private $helper;
  59. /** @var EventDispatcherInterface */
  60. private $legacyEventDispatcher;
  61. /** @var IEventDispatcher */
  62. private $eventDispatcher;
  63. public function __construct(
  64. IConfig $config,
  65. IPreview $previewManager,
  66. IAppData $appData,
  67. GeneratorHelper $helper,
  68. EventDispatcherInterface $legacyEventDispatcher,
  69. IEventDispatcher $eventDispatcher
  70. ) {
  71. $this->config = $config;
  72. $this->previewManager = $previewManager;
  73. $this->appData = $appData;
  74. $this->helper = $helper;
  75. $this->legacyEventDispatcher = $legacyEventDispatcher;
  76. $this->eventDispatcher = $eventDispatcher;
  77. }
  78. /**
  79. * Returns a preview of a file
  80. *
  81. * The cache is searched first and if nothing usable was found then a preview is
  82. * generated by one of the providers
  83. *
  84. * @param File $file
  85. * @param int $width
  86. * @param int $height
  87. * @param bool $crop
  88. * @param string $mode
  89. * @param string $mimeType
  90. * @return ISimpleFile
  91. * @throws NotFoundException
  92. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  93. */
  94. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  95. $specification = [
  96. 'width' => $width,
  97. 'height' => $height,
  98. 'crop' => $crop,
  99. 'mode' => $mode,
  100. ];
  101. $this->legacyEventDispatcher->dispatch(
  102. IPreview::EVENT,
  103. new GenericEvent($file, $specification)
  104. );
  105. $this->eventDispatcher->dispatchTyped(new BeforePreviewFetchedEvent(
  106. $file
  107. ));
  108. // since we only ask for one preview, and the generate method return the last one it created, it returns the one we want
  109. return $this->generatePreviews($file, [$specification], $mimeType);
  110. }
  111. /**
  112. * Generates previews of a file
  113. *
  114. * @param File $file
  115. * @param non-empty-array $specifications
  116. * @param string $mimeType
  117. * @return ISimpleFile the last preview that was generated
  118. * @throws NotFoundException
  119. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  120. */
  121. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  122. //Make sure that we can read the file
  123. if (!$file->isReadable()) {
  124. throw new NotFoundException('Cannot read file');
  125. }
  126. if ($mimeType === null) {
  127. $mimeType = $file->getMimeType();
  128. }
  129. $previewFolder = $this->getPreviewFolder($file);
  130. $previewVersion = '';
  131. if ($file instanceof IVersionedPreviewFile) {
  132. $previewVersion = $file->getPreviewVersion() . '-';
  133. }
  134. // If imaginary is enabled, and we request a small thumbnail,
  135. // let's not generate the max preview for performance reasons
  136. if (count($specifications) === 1
  137. && ($specifications[0]['width'] <= 256 || $specifications[0]['height'] <= 256)
  138. && preg_match(Imaginary::supportedMimeTypes(), $mimeType)
  139. && $this->config->getSystemValueString('preview_imaginary_url', 'invalid') !== 'invalid') {
  140. $crop = $specifications[0]['crop'] ?? false;
  141. $preview = $this->getSmallImagePreview($previewFolder, $file, $mimeType, $previewVersion, $crop);
  142. if ($preview->getSize() === 0) {
  143. $preview->delete();
  144. throw new NotFoundException('Cached preview size 0, invalid!');
  145. }
  146. return $preview;
  147. }
  148. // Get the max preview and infer the max preview sizes from that
  149. $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType, $previewVersion);
  150. $maxPreviewImage = null; // only load the image when we need it
  151. if ($maxPreview->getSize() === 0) {
  152. $maxPreview->delete();
  153. throw new NotFoundException('Max preview size 0, invalid!');
  154. }
  155. [$maxWidth, $maxHeight] = $this->getPreviewSize($maxPreview, $previewVersion);
  156. $preview = null;
  157. foreach ($specifications as $specification) {
  158. $width = $specification['width'] ?? -1;
  159. $height = $specification['height'] ?? -1;
  160. $crop = $specification['crop'] ?? false;
  161. $mode = $specification['mode'] ?? IPreview::MODE_FILL;
  162. // If both width and height are -1 we just want the max preview
  163. if ($width === -1 && $height === -1) {
  164. $width = $maxWidth;
  165. $height = $maxHeight;
  166. }
  167. // Calculate the preview size
  168. [$width, $height] = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
  169. // No need to generate a preview that is just the max preview
  170. if ($width === $maxWidth && $height === $maxHeight) {
  171. // ensure correct return value if this was the last one
  172. $preview = $maxPreview;
  173. continue;
  174. }
  175. // Try to get a cached preview. Else generate (and store) one
  176. try {
  177. try {
  178. $preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType(), $previewVersion);
  179. } catch (NotFoundException $e) {
  180. if (!$this->previewManager->isMimeSupported($mimeType)) {
  181. throw new NotFoundException();
  182. }
  183. if ($maxPreviewImage === null) {
  184. $maxPreviewImage = $this->helper->getImage($maxPreview);
  185. }
  186. $preview = $this->generatePreview($previewFolder, $maxPreviewImage, $width, $height, $crop, $maxWidth, $maxHeight, $previewVersion);
  187. }
  188. } catch (\InvalidArgumentException $e) {
  189. throw new NotFoundException("", 0, $e);
  190. }
  191. if ($preview->getSize() === 0) {
  192. $preview->delete();
  193. throw new NotFoundException('Cached preview size 0, invalid!');
  194. }
  195. }
  196. assert($preview !== null);
  197. // Free memory being used by the embedded image resource. Without this the image is kept in memory indefinitely.
  198. // Garbage Collection does NOT free this memory. We have to do it ourselves.
  199. if ($maxPreviewImage instanceof \OCP\Image) {
  200. $maxPreviewImage->destroy();
  201. }
  202. return $preview;
  203. }
  204. /**
  205. * Generate a small image straight away without generating a max preview first
  206. * Preview generated is 256x256
  207. *
  208. * @throws NotFoundException
  209. */
  210. private function getSmallImagePreview(ISimpleFolder $previewFolder, File $file, string $mimeType, string $prefix, bool $crop): ISimpleFile {
  211. $nodes = $previewFolder->getDirectoryListing();
  212. foreach ($nodes as $node) {
  213. $name = $node->getName();
  214. if (($prefix === '' || str_starts_with($name, $prefix))) {
  215. // Prefix match
  216. if (str_starts_with($name, $prefix . '256-256-crop') && $crop) {
  217. // Cropped image
  218. return $node;
  219. }
  220. if (str_starts_with($name, $prefix . '256-256.') && !$crop) {
  221. // Uncropped image
  222. return $node;
  223. }
  224. }
  225. }
  226. $previewProviders = $this->previewManager->getProviders();
  227. foreach ($previewProviders as $supportedMimeType => $providers) {
  228. // Filter out providers that does not support this mime
  229. if (!preg_match($supportedMimeType, $mimeType)) {
  230. continue;
  231. }
  232. foreach ($providers as $providerClosure) {
  233. $provider = $this->helper->getProvider($providerClosure);
  234. if (!($provider instanceof IProviderV2)) {
  235. continue;
  236. }
  237. if (!$provider->isAvailable($file)) {
  238. continue;
  239. }
  240. $preview = $this->helper->getThumbnail($provider, $file, 256, 256, $crop);
  241. if (!($preview instanceof IImage)) {
  242. continue;
  243. }
  244. // Try to get the extension.
  245. try {
  246. $ext = $this->getExtention($preview->dataMimeType());
  247. } catch (\InvalidArgumentException $e) {
  248. // Just continue to the next iteration if this preview doesn't have a valid mimetype
  249. continue;
  250. }
  251. $path = $this->generatePath(256, 256, $crop, $preview->dataMimeType(), $prefix);
  252. try {
  253. $file = $previewFolder->newFile($path);
  254. if ($preview instanceof IStreamImage) {
  255. $file->putContent($preview->resource());
  256. } else {
  257. $file->putContent($preview->data());
  258. }
  259. } catch (NotPermittedException $e) {
  260. throw new NotFoundException();
  261. }
  262. return $file;
  263. }
  264. }
  265. throw new NotFoundException('No provider successfully handled the preview generation');
  266. }
  267. /**
  268. * Acquire a semaphore of the specified id and concurrency, blocking if necessary.
  269. * Return an identifier of the semaphore on success, which can be used to release it via
  270. * {@see Generator::unguardWithSemaphore()}.
  271. *
  272. * @param int $semId
  273. * @param int $concurrency
  274. * @return false|resource the semaphore on success or false on failure
  275. */
  276. public static function guardWithSemaphore(int $semId, int $concurrency) {
  277. if (!extension_loaded('sysvsem')) {
  278. return false;
  279. }
  280. $sem = sem_get($semId, $concurrency);
  281. if ($sem === false) {
  282. return false;
  283. }
  284. if (!sem_acquire($sem)) {
  285. return false;
  286. }
  287. return $sem;
  288. }
  289. /**
  290. * Releases the semaphore acquired from {@see Generator::guardWithSemaphore()}.
  291. *
  292. * @param resource|bool $semId the semaphore identifier returned by guardWithSemaphore
  293. * @return bool
  294. */
  295. public static function unguardWithSemaphore($semId): bool {
  296. if (!is_resource($semId) || !extension_loaded('sysvsem')) {
  297. return false;
  298. }
  299. return sem_release($semId);
  300. }
  301. /**
  302. * Get the number of concurrent threads supported by the host.
  303. *
  304. * @return int number of concurrent threads, or 0 if it cannot be determined
  305. */
  306. public static function getHardwareConcurrency(): int {
  307. static $width;
  308. if (!isset($width)) {
  309. if (is_file("/proc/cpuinfo")) {
  310. $width = substr_count(file_get_contents("/proc/cpuinfo"), "processor");
  311. } else {
  312. $width = 0;
  313. }
  314. }
  315. return $width;
  316. }
  317. /**
  318. * Get number of concurrent preview generations from system config
  319. *
  320. * Two config entries, `preview_concurrency_new` and `preview_concurrency_all`,
  321. * are available. If not set, the default values are determined with the hardware concurrency
  322. * of the host. In case the hardware concurrency cannot be determined, or the user sets an
  323. * invalid value, fallback values are:
  324. * For new images whose previews do not exist and need to be generated, 4;
  325. * For all preview generation requests, 8.
  326. * Value of `preview_concurrency_all` should be greater than or equal to that of
  327. * `preview_concurrency_new`, otherwise, the latter is returned.
  328. *
  329. * @param string $type either `preview_concurrency_new` or `preview_concurrency_all`
  330. * @return int number of concurrent preview generations, or -1 if $type is invalid
  331. */
  332. public function getNumConcurrentPreviews(string $type): int {
  333. static $cached = array();
  334. if (array_key_exists($type, $cached)) {
  335. return $cached[$type];
  336. }
  337. $hardwareConcurrency = self::getHardwareConcurrency();
  338. switch ($type) {
  339. case "preview_concurrency_all":
  340. $fallback = $hardwareConcurrency > 0 ? $hardwareConcurrency * 2 : 8;
  341. $concurrency_all = $this->config->getSystemValueInt($type, $fallback);
  342. $concurrency_new = $this->getNumConcurrentPreviews("preview_concurrency_new");
  343. $cached[$type] = max($concurrency_all, $concurrency_new);
  344. break;
  345. case "preview_concurrency_new":
  346. $fallback = $hardwareConcurrency > 0 ? $hardwareConcurrency : 4;
  347. $cached[$type] = $this->config->getSystemValueInt($type, $fallback);
  348. break;
  349. default:
  350. return -1;
  351. }
  352. return $cached[$type];
  353. }
  354. /**
  355. * @param ISimpleFolder $previewFolder
  356. * @param File $file
  357. * @param string $mimeType
  358. * @param string $prefix
  359. * @return ISimpleFile
  360. * @throws NotFoundException
  361. */
  362. private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType, $prefix) {
  363. $nodes = $previewFolder->getDirectoryListing();
  364. foreach ($nodes as $node) {
  365. $name = $node->getName();
  366. if (($prefix === '' || strpos($name, $prefix) === 0) && strpos($name, 'max')) {
  367. return $node;
  368. }
  369. }
  370. $previewProviders = $this->previewManager->getProviders();
  371. foreach ($previewProviders as $supportedMimeType => $providers) {
  372. // Filter out providers that does not support this mime
  373. if (!preg_match($supportedMimeType, $mimeType)) {
  374. continue;
  375. }
  376. foreach ($providers as $providerClosure) {
  377. $provider = $this->helper->getProvider($providerClosure);
  378. if (!($provider instanceof IProviderV2)) {
  379. continue;
  380. }
  381. if (!$provider->isAvailable($file)) {
  382. continue;
  383. }
  384. $maxWidth = $this->config->getSystemValueInt('preview_max_x', 4096);
  385. $maxHeight = $this->config->getSystemValueInt('preview_max_y', 4096);
  386. $previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');
  387. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  388. try {
  389. $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
  390. } finally {
  391. self::unguardWithSemaphore($sem);
  392. }
  393. if (!($preview instanceof IImage)) {
  394. continue;
  395. }
  396. // Try to get the extention.
  397. try {
  398. $ext = $this->getExtention($preview->dataMimeType());
  399. } catch (\InvalidArgumentException $e) {
  400. // Just continue to the next iteration if this preview doesn't have a valid mimetype
  401. continue;
  402. }
  403. $path = $prefix . (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
  404. try {
  405. $file = $previewFolder->newFile($path);
  406. if ($preview instanceof IStreamImage) {
  407. $file->putContent($preview->resource());
  408. } else {
  409. $file->putContent($preview->data());
  410. }
  411. } catch (NotPermittedException $e) {
  412. throw new NotFoundException();
  413. }
  414. return $file;
  415. }
  416. }
  417. throw new NotFoundException();
  418. }
  419. /**
  420. * @param ISimpleFile $file
  421. * @param string $prefix
  422. * @return int[]
  423. */
  424. private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
  425. $size = explode('-', substr($file->getName(), strlen($prefix)));
  426. return [(int)$size[0], (int)$size[1]];
  427. }
  428. /**
  429. * @param int $width
  430. * @param int $height
  431. * @param bool $crop
  432. * @param string $mimeType
  433. * @param string $prefix
  434. * @return string
  435. */
  436. private function generatePath($width, $height, $crop, $mimeType, $prefix) {
  437. $path = $prefix . (string)$width . '-' . (string)$height;
  438. if ($crop) {
  439. $path .= '-crop';
  440. }
  441. $ext = $this->getExtention($mimeType);
  442. $path .= '.' . $ext;
  443. return $path;
  444. }
  445. /**
  446. * @param int $width
  447. * @param int $height
  448. * @param bool $crop
  449. * @param string $mode
  450. * @param int $maxWidth
  451. * @param int $maxHeight
  452. * @return int[]
  453. */
  454. private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
  455. /*
  456. * If we are not cropping we have to make sure the requested image
  457. * respects the aspect ratio of the original.
  458. */
  459. if (!$crop) {
  460. $ratio = $maxHeight / $maxWidth;
  461. if ($width === -1) {
  462. $width = $height / $ratio;
  463. }
  464. if ($height === -1) {
  465. $height = $width * $ratio;
  466. }
  467. $ratioH = $height / $maxHeight;
  468. $ratioW = $width / $maxWidth;
  469. /*
  470. * Fill means that the $height and $width are the max
  471. * Cover means min.
  472. */
  473. if ($mode === IPreview::MODE_FILL) {
  474. if ($ratioH > $ratioW) {
  475. $height = $width * $ratio;
  476. } else {
  477. $width = $height / $ratio;
  478. }
  479. } elseif ($mode === IPreview::MODE_COVER) {
  480. if ($ratioH > $ratioW) {
  481. $width = $height / $ratio;
  482. } else {
  483. $height = $width * $ratio;
  484. }
  485. }
  486. }
  487. if ($height !== $maxHeight && $width !== $maxWidth) {
  488. /*
  489. * Scale to the nearest power of four
  490. */
  491. $pow4height = 4 ** ceil(log($height) / log(4));
  492. $pow4width = 4 ** ceil(log($width) / log(4));
  493. // Minimum size is 64
  494. $pow4height = max($pow4height, 64);
  495. $pow4width = max($pow4width, 64);
  496. $ratioH = $height / $pow4height;
  497. $ratioW = $width / $pow4width;
  498. if ($ratioH < $ratioW) {
  499. $width = $pow4width;
  500. $height /= $ratioW;
  501. } else {
  502. $height = $pow4height;
  503. $width /= $ratioH;
  504. }
  505. }
  506. /*
  507. * Make sure the requested height and width fall within the max
  508. * of the preview.
  509. */
  510. if ($height > $maxHeight) {
  511. $ratio = $height / $maxHeight;
  512. $height = $maxHeight;
  513. $width /= $ratio;
  514. }
  515. if ($width > $maxWidth) {
  516. $ratio = $width / $maxWidth;
  517. $width = $maxWidth;
  518. $height /= $ratio;
  519. }
  520. return [(int)round($width), (int)round($height)];
  521. }
  522. /**
  523. * @param ISimpleFolder $previewFolder
  524. * @param ISimpleFile $maxPreview
  525. * @param int $width
  526. * @param int $height
  527. * @param bool $crop
  528. * @param int $maxWidth
  529. * @param int $maxHeight
  530. * @param string $prefix
  531. * @return ISimpleFile
  532. * @throws NotFoundException
  533. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  534. */
  535. private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
  536. $preview = $maxPreview;
  537. if (!$preview->valid()) {
  538. throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
  539. }
  540. $previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');
  541. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  542. try {
  543. if ($crop) {
  544. if ($height !== $preview->height() && $width !== $preview->width()) {
  545. //Resize
  546. $widthR = $preview->width() / $width;
  547. $heightR = $preview->height() / $height;
  548. if ($widthR > $heightR) {
  549. $scaleH = $height;
  550. $scaleW = $maxWidth / $heightR;
  551. } else {
  552. $scaleH = $maxHeight / $widthR;
  553. $scaleW = $width;
  554. }
  555. $preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
  556. }
  557. $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
  558. $cropY = (int)floor(abs($height - $preview->height()) * 0.5);
  559. $preview = $preview->cropCopy($cropX, $cropY, $width, $height);
  560. } else {
  561. $preview = $maxPreview->resizeCopy(max($width, $height));
  562. }
  563. } finally {
  564. self::unguardWithSemaphore($sem);
  565. }
  566. $path = $this->generatePath($width, $height, $crop, $preview->dataMimeType(), $prefix);
  567. try {
  568. $file = $previewFolder->newFile($path);
  569. $file->putContent($preview->data());
  570. } catch (NotPermittedException $e) {
  571. throw new NotFoundException();
  572. }
  573. return $file;
  574. }
  575. /**
  576. * @param ISimpleFolder $previewFolder
  577. * @param int $width
  578. * @param int $height
  579. * @param bool $crop
  580. * @param string $mimeType
  581. * @param string $prefix
  582. * @return ISimpleFile
  583. *
  584. * @throws NotFoundException
  585. */
  586. private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType, $prefix) {
  587. $path = $this->generatePath($width, $height, $crop, $mimeType, $prefix);
  588. return $previewFolder->getFile($path);
  589. }
  590. /**
  591. * Get the specific preview folder for this file
  592. *
  593. * @param File $file
  594. * @return ISimpleFolder
  595. *
  596. * @throws InvalidPathException
  597. * @throws NotFoundException
  598. * @throws NotPermittedException
  599. */
  600. private function getPreviewFolder(File $file) {
  601. // Obtain file id outside of try catch block to prevent the creation of an existing folder
  602. $fileId = (string)$file->getId();
  603. try {
  604. $folder = $this->appData->getFolder($fileId);
  605. } catch (NotFoundException $e) {
  606. $folder = $this->appData->newFolder($fileId);
  607. }
  608. return $folder;
  609. }
  610. /**
  611. * @param string $mimeType
  612. * @return null|string
  613. * @throws \InvalidArgumentException
  614. */
  615. private function getExtention($mimeType) {
  616. switch ($mimeType) {
  617. case 'image/png':
  618. return 'png';
  619. case 'image/jpeg':
  620. return 'jpg';
  621. case 'image/gif':
  622. return 'gif';
  623. default:
  624. throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
  625. }
  626. }
  627. }