1
0

Generator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. * @param ISimpleFolder $previewFolder
  268. * @param ISimpleFile[] $previewFiles
  269. * @param File $file
  270. * @param string $mimeType
  271. * @param string $prefix
  272. * @return ISimpleFile
  273. * @throws NotFoundException
  274. */
  275. private function getMaxPreview(ISimpleFolder $previewFolder, array $previewFiles, File $file, $mimeType, $prefix) {
  276. // We don't know the max preview size, so we can't use getCachedPreview.
  277. // It might have been generated with a higher resolution than the current value.
  278. foreach ($previewFiles as $node) {
  279. $name = $node->getName();
  280. if (($prefix === '' || str_starts_with($name, $prefix)) && strpos($name, 'max')) {
  281. return $node;
  282. }
  283. }
  284. $maxWidth = $this->config->getSystemValueInt('preview_max_x', 4096);
  285. $maxHeight = $this->config->getSystemValueInt('preview_max_y', 4096);
  286. return $this->generateProviderPreview($previewFolder, $file, $maxWidth, $maxHeight, false, true, $mimeType, $prefix);
  287. }
  288. private function generateProviderPreview(ISimpleFolder $previewFolder, File $file, int $width, int $height, bool $crop, bool $max, string $mimeType, string $prefix) {
  289. $previewProviders = $this->previewManager->getProviders();
  290. foreach ($previewProviders as $supportedMimeType => $providers) {
  291. // Filter out providers that does not support this mime
  292. if (!preg_match($supportedMimeType, $mimeType)) {
  293. continue;
  294. }
  295. foreach ($providers as $providerClosure) {
  296. $provider = $this->helper->getProvider($providerClosure);
  297. if (!($provider instanceof IProviderV2)) {
  298. continue;
  299. }
  300. if (!$provider->isAvailable($file)) {
  301. continue;
  302. }
  303. $previewConcurrency = $this->config->getSystemValueInt('preview_concurrency_new', 4);
  304. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  305. try {
  306. $preview = $this->helper->getThumbnail($provider, $file, $width, $height);
  307. } finally {
  308. self::unguardWithSemaphore($sem);
  309. }
  310. if (!($preview instanceof IImage)) {
  311. continue;
  312. }
  313. $path = $this->generatePath($preview->width(), $preview->height(), $crop, $max, $preview->dataMimeType(), $prefix);
  314. try {
  315. $file = $previewFolder->newFile($path);
  316. if ($preview instanceof IStreamImage) {
  317. $file->putContent($preview->resource());
  318. } else {
  319. $file->putContent($preview->data());
  320. }
  321. } catch (NotPermittedException $e) {
  322. throw new NotFoundException();
  323. }
  324. return $file;
  325. }
  326. }
  327. throw new NotFoundException('No provider successfully handled the preview generation');
  328. }
  329. /**
  330. * @param ISimpleFile $file
  331. * @param string $prefix
  332. * @return int[]
  333. */
  334. private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
  335. $size = explode('-', substr($file->getName(), strlen($prefix)));
  336. return [(int)$size[0], (int)$size[1]];
  337. }
  338. /**
  339. * @param int $width
  340. * @param int $height
  341. * @param bool $crop
  342. * @param bool $max
  343. * @param string $mimeType
  344. * @param string $prefix
  345. * @return string
  346. */
  347. private function generatePath($width, $height, $crop, $max, $mimeType, $prefix) {
  348. $path = $prefix . (string)$width . '-' . (string)$height;
  349. if ($crop) {
  350. $path .= '-crop';
  351. }
  352. if ($max) {
  353. $path .= '-max';
  354. }
  355. $ext = $this->getExtension($mimeType);
  356. $path .= '.' . $ext;
  357. return $path;
  358. }
  359. /**
  360. * @param int $width
  361. * @param int $height
  362. * @param bool $crop
  363. * @param string $mode
  364. * @param int $maxWidth
  365. * @param int $maxHeight
  366. * @return int[]
  367. */
  368. private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
  369. /*
  370. * If we are not cropping we have to make sure the requested image
  371. * respects the aspect ratio of the original.
  372. */
  373. if (!$crop) {
  374. $ratio = $maxHeight / $maxWidth;
  375. if ($width === -1) {
  376. $width = $height / $ratio;
  377. }
  378. if ($height === -1) {
  379. $height = $width * $ratio;
  380. }
  381. $ratioH = $height / $maxHeight;
  382. $ratioW = $width / $maxWidth;
  383. /*
  384. * Fill means that the $height and $width are the max
  385. * Cover means min.
  386. */
  387. if ($mode === IPreview::MODE_FILL) {
  388. if ($ratioH > $ratioW) {
  389. $height = $width * $ratio;
  390. } else {
  391. $width = $height / $ratio;
  392. }
  393. } elseif ($mode === IPreview::MODE_COVER) {
  394. if ($ratioH > $ratioW) {
  395. $width = $height / $ratio;
  396. } else {
  397. $height = $width * $ratio;
  398. }
  399. }
  400. }
  401. if ($height !== $maxHeight && $width !== $maxWidth) {
  402. /*
  403. * Scale to the nearest power of four
  404. */
  405. $pow4height = 4 ** ceil(log($height) / log(4));
  406. $pow4width = 4 ** ceil(log($width) / log(4));
  407. // Minimum size is 64
  408. $pow4height = max($pow4height, 64);
  409. $pow4width = max($pow4width, 64);
  410. $ratioH = $height / $pow4height;
  411. $ratioW = $width / $pow4width;
  412. if ($ratioH < $ratioW) {
  413. $width = $pow4width;
  414. $height /= $ratioW;
  415. } else {
  416. $height = $pow4height;
  417. $width /= $ratioH;
  418. }
  419. }
  420. /*
  421. * Make sure the requested height and width fall within the max
  422. * of the preview.
  423. */
  424. if ($height > $maxHeight) {
  425. $ratio = $height / $maxHeight;
  426. $height = $maxHeight;
  427. $width /= $ratio;
  428. }
  429. if ($width > $maxWidth) {
  430. $ratio = $width / $maxWidth;
  431. $width = $maxWidth;
  432. $height /= $ratio;
  433. }
  434. return [(int)round($width), (int)round($height)];
  435. }
  436. /**
  437. * @param ISimpleFolder $previewFolder
  438. * @param ISimpleFile $maxPreview
  439. * @param int $width
  440. * @param int $height
  441. * @param bool $crop
  442. * @param int $maxWidth
  443. * @param int $maxHeight
  444. * @param string $prefix
  445. * @return ISimpleFile
  446. * @throws NotFoundException
  447. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  448. */
  449. private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
  450. $preview = $maxPreview;
  451. if (!$preview->valid()) {
  452. throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
  453. }
  454. $previewConcurrency = $this->config->getSystemValueInt('preview_concurrency_new', 4);
  455. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  456. try {
  457. if ($crop) {
  458. if ($height !== $preview->height() && $width !== $preview->width()) {
  459. //Resize
  460. $widthR = $preview->width() / $width;
  461. $heightR = $preview->height() / $height;
  462. if ($widthR > $heightR) {
  463. $scaleH = $height;
  464. $scaleW = $maxWidth / $heightR;
  465. } else {
  466. $scaleH = $maxHeight / $widthR;
  467. $scaleW = $width;
  468. }
  469. $preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
  470. }
  471. $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
  472. $cropY = (int)floor(abs($height - $preview->height()) * 0.5);
  473. $preview = $preview->cropCopy($cropX, $cropY, $width, $height);
  474. } else {
  475. $preview = $maxPreview->resizeCopy(max($width, $height));
  476. }
  477. } finally {
  478. self::unguardWithSemaphore($sem);
  479. }
  480. $path = $this->generatePath($width, $height, $crop, false, $preview->dataMimeType(), $prefix);
  481. try {
  482. $file = $previewFolder->newFile($path);
  483. $file->putContent($preview->data());
  484. } catch (NotPermittedException $e) {
  485. throw new NotFoundException();
  486. }
  487. return $file;
  488. }
  489. /**
  490. * @param ISimpleFile[] $files Array of FileInfo, as the result of getDirectoryListing()
  491. * @param int $width
  492. * @param int $height
  493. * @param bool $crop
  494. * @param string $mimeType
  495. * @param string $prefix
  496. * @return ISimpleFile
  497. *
  498. * @throws NotFoundException
  499. */
  500. private function getCachedPreview($files, $width, $height, $crop, $mimeType, $prefix) {
  501. $path = $this->generatePath($width, $height, $crop, false, $mimeType, $prefix);
  502. foreach ($files as $file) {
  503. if ($file->getName() === $path) {
  504. return $file;
  505. }
  506. }
  507. throw new NotFoundException();
  508. }
  509. /**
  510. * Get the specific preview folder for this file
  511. *
  512. * @param File $file
  513. * @return ISimpleFolder
  514. *
  515. * @throws InvalidPathException
  516. * @throws NotFoundException
  517. * @throws NotPermittedException
  518. */
  519. private function getPreviewFolder(File $file) {
  520. // Obtain file id outside of try catch block to prevent the creation of an existing folder
  521. $fileId = (string)$file->getId();
  522. try {
  523. $folder = $this->appData->getFolder($fileId);
  524. } catch (NotFoundException $e) {
  525. $folder = $this->appData->newFolder($fileId);
  526. }
  527. return $folder;
  528. }
  529. /**
  530. * @param string $mimeType
  531. * @return null|string
  532. * @throws \InvalidArgumentException
  533. */
  534. private function getExtension($mimeType) {
  535. switch ($mimeType) {
  536. case 'image/png':
  537. return 'png';
  538. case 'image/jpeg':
  539. return 'jpg';
  540. case 'image/gif':
  541. return 'gif';
  542. default:
  543. throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
  544. }
  545. }
  546. }