Generator.php 20 KB

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