Generator.php 20 KB

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