PreviewManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC;
  8. use OC\AppFramework\Bootstrap\Coordinator;
  9. use OC\Preview\Generator;
  10. use OC\Preview\GeneratorHelper;
  11. use OC\Preview\IMagickSupport;
  12. use OCP\AppFramework\QueryException;
  13. use OCP\EventDispatcher\IEventDispatcher;
  14. use OCP\Files\File;
  15. use OCP\Files\IAppData;
  16. use OCP\Files\IRootFolder;
  17. use OCP\Files\NotFoundException;
  18. use OCP\Files\SimpleFS\ISimpleFile;
  19. use OCP\IBinaryFinder;
  20. use OCP\IConfig;
  21. use OCP\IPreview;
  22. use OCP\IServerContainer;
  23. use OCP\Preview\IProviderV2;
  24. use function array_key_exists;
  25. class PreviewManager implements IPreview {
  26. protected IConfig $config;
  27. protected IRootFolder $rootFolder;
  28. protected IAppData $appData;
  29. protected IEventDispatcher $eventDispatcher;
  30. private ?Generator $generator = null;
  31. private GeneratorHelper $helper;
  32. protected bool $providerListDirty = false;
  33. protected bool $registeredCoreProviders = false;
  34. protected array $providers = [];
  35. /** @var array mime type => support status */
  36. protected array $mimeTypeSupportMap = [];
  37. protected ?array $defaultProviders = null;
  38. protected ?string $userId;
  39. private Coordinator $bootstrapCoordinator;
  40. /**
  41. * Hash map (without value) of loaded bootstrap providers
  42. * @psalm-var array<string, null>
  43. */
  44. private array $loadedBootstrapProviders = [];
  45. private IServerContainer $container;
  46. private IBinaryFinder $binaryFinder;
  47. private IMagickSupport $imagickSupport;
  48. private bool $enablePreviews;
  49. public function __construct(
  50. IConfig $config,
  51. IRootFolder $rootFolder,
  52. IAppData $appData,
  53. IEventDispatcher $eventDispatcher,
  54. GeneratorHelper $helper,
  55. ?string $userId,
  56. Coordinator $bootstrapCoordinator,
  57. IServerContainer $container,
  58. IBinaryFinder $binaryFinder,
  59. IMagickSupport $imagickSupport
  60. ) {
  61. $this->config = $config;
  62. $this->rootFolder = $rootFolder;
  63. $this->appData = $appData;
  64. $this->eventDispatcher = $eventDispatcher;
  65. $this->helper = $helper;
  66. $this->userId = $userId;
  67. $this->bootstrapCoordinator = $bootstrapCoordinator;
  68. $this->container = $container;
  69. $this->binaryFinder = $binaryFinder;
  70. $this->imagickSupport = $imagickSupport;
  71. $this->enablePreviews = $config->getSystemValueBool('enable_previews', true);
  72. }
  73. /**
  74. * In order to improve lazy loading a closure can be registered which will be
  75. * called in case preview providers are actually requested
  76. *
  77. * $callable has to return an instance of \OCP\Preview\IProvider or \OCP\Preview\IProviderV2
  78. *
  79. * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
  80. * @param \Closure $callable
  81. * @return void
  82. */
  83. public function registerProvider($mimeTypeRegex, \Closure $callable): void {
  84. if (!$this->enablePreviews) {
  85. return;
  86. }
  87. if (!isset($this->providers[$mimeTypeRegex])) {
  88. $this->providers[$mimeTypeRegex] = [];
  89. }
  90. $this->providers[$mimeTypeRegex][] = $callable;
  91. $this->providerListDirty = true;
  92. }
  93. /**
  94. * Get all providers
  95. */
  96. public function getProviders(): array {
  97. if (!$this->enablePreviews) {
  98. return [];
  99. }
  100. $this->registerCoreProviders();
  101. $this->registerBootstrapProviders();
  102. if ($this->providerListDirty) {
  103. $keys = array_map('strlen', array_keys($this->providers));
  104. array_multisort($keys, SORT_DESC, $this->providers);
  105. $this->providerListDirty = false;
  106. }
  107. return $this->providers;
  108. }
  109. /**
  110. * Does the manager have any providers
  111. */
  112. public function hasProviders(): bool {
  113. $this->registerCoreProviders();
  114. return !empty($this->providers);
  115. }
  116. private function getGenerator(): Generator {
  117. if ($this->generator === null) {
  118. $this->generator = new Generator(
  119. $this->config,
  120. $this,
  121. $this->appData,
  122. new GeneratorHelper(
  123. $this->rootFolder,
  124. $this->config
  125. ),
  126. $this->eventDispatcher
  127. );
  128. }
  129. return $this->generator;
  130. }
  131. /**
  132. * Returns a preview of a file
  133. *
  134. * The cache is searched first and if nothing usable was found then a preview is
  135. * generated by one of the providers
  136. *
  137. * @param File $file
  138. * @param int $width
  139. * @param int $height
  140. * @param bool $crop
  141. * @param string $mode
  142. * @param string $mimeType
  143. * @return ISimpleFile
  144. * @throws NotFoundException
  145. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  146. * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
  147. */
  148. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  149. $this->throwIfPreviewsDisabled();
  150. $previewConcurrency = $this->getGenerator()->getNumConcurrentPreviews('preview_concurrency_all');
  151. $sem = Generator::guardWithSemaphore(Generator::SEMAPHORE_ID_ALL, $previewConcurrency);
  152. try {
  153. $preview = $this->getGenerator()->getPreview($file, $width, $height, $crop, $mode, $mimeType);
  154. } finally {
  155. Generator::unguardWithSemaphore($sem);
  156. }
  157. return $preview;
  158. }
  159. /**
  160. * Generates previews of a file
  161. *
  162. * @param File $file
  163. * @param array $specifications
  164. * @param string $mimeType
  165. * @return ISimpleFile the last preview that was generated
  166. * @throws NotFoundException
  167. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  168. * @since 19.0.0
  169. */
  170. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  171. $this->throwIfPreviewsDisabled();
  172. return $this->getGenerator()->generatePreviews($file, $specifications, $mimeType);
  173. }
  174. /**
  175. * returns true if the passed mime type is supported
  176. *
  177. * @param string $mimeType
  178. * @return boolean
  179. */
  180. public function isMimeSupported($mimeType = '*') {
  181. if (!$this->enablePreviews) {
  182. return false;
  183. }
  184. if (isset($this->mimeTypeSupportMap[$mimeType])) {
  185. return $this->mimeTypeSupportMap[$mimeType];
  186. }
  187. $this->registerCoreProviders();
  188. $this->registerBootstrapProviders();
  189. $providerMimeTypes = array_keys($this->providers);
  190. foreach ($providerMimeTypes as $supportedMimeType) {
  191. if (preg_match($supportedMimeType, $mimeType)) {
  192. $this->mimeTypeSupportMap[$mimeType] = true;
  193. return true;
  194. }
  195. }
  196. $this->mimeTypeSupportMap[$mimeType] = false;
  197. return false;
  198. }
  199. /**
  200. * Check if a preview can be generated for a file
  201. */
  202. public function isAvailable(\OCP\Files\FileInfo $file): bool {
  203. if (!$this->enablePreviews) {
  204. return false;
  205. }
  206. $this->registerCoreProviders();
  207. if (!$this->isMimeSupported($file->getMimetype())) {
  208. return false;
  209. }
  210. $mount = $file->getMountPoint();
  211. if ($mount and !$mount->getOption('previews', true)) {
  212. return false;
  213. }
  214. foreach ($this->providers as $supportedMimeType => $providers) {
  215. if (preg_match($supportedMimeType, $file->getMimetype())) {
  216. foreach ($providers as $providerClosure) {
  217. $provider = $this->helper->getProvider($providerClosure);
  218. if (!($provider instanceof IProviderV2)) {
  219. continue;
  220. }
  221. if ($provider->isAvailable($file)) {
  222. return true;
  223. }
  224. }
  225. }
  226. }
  227. return false;
  228. }
  229. /**
  230. * List of enabled default providers
  231. *
  232. * The following providers are enabled by default:
  233. * - OC\Preview\PNG
  234. * - OC\Preview\JPEG
  235. * - OC\Preview\GIF
  236. * - OC\Preview\BMP
  237. * - OC\Preview\XBitmap
  238. * - OC\Preview\MarkDown
  239. * - OC\Preview\MP3
  240. * - OC\Preview\TXT
  241. *
  242. * The following providers are disabled by default due to performance or privacy concerns:
  243. * - OC\Preview\Font
  244. * - OC\Preview\HEIC
  245. * - OC\Preview\Illustrator
  246. * - OC\Preview\Movie
  247. * - OC\Preview\MSOfficeDoc
  248. * - OC\Preview\MSOffice2003
  249. * - OC\Preview\MSOffice2007
  250. * - OC\Preview\OpenDocument
  251. * - OC\Preview\PDF
  252. * - OC\Preview\Photoshop
  253. * - OC\Preview\Postscript
  254. * - OC\Preview\StarOffice
  255. * - OC\Preview\SVG
  256. * - OC\Preview\TIFF
  257. *
  258. * @return array
  259. */
  260. protected function getEnabledDefaultProvider() {
  261. if ($this->defaultProviders !== null) {
  262. return $this->defaultProviders;
  263. }
  264. $imageProviders = [
  265. Preview\PNG::class,
  266. Preview\JPEG::class,
  267. Preview\GIF::class,
  268. Preview\BMP::class,
  269. Preview\XBitmap::class,
  270. Preview\Krita::class,
  271. Preview\WebP::class,
  272. ];
  273. $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
  274. Preview\MarkDown::class,
  275. Preview\MP3::class,
  276. Preview\TXT::class,
  277. Preview\OpenDocument::class,
  278. ], $imageProviders));
  279. if (in_array(Preview\Image::class, $this->defaultProviders)) {
  280. $this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
  281. }
  282. $this->defaultProviders = array_unique($this->defaultProviders);
  283. return $this->defaultProviders;
  284. }
  285. /**
  286. * Register the default providers (if enabled)
  287. *
  288. * @param string $class
  289. * @param string $mimeType
  290. */
  291. protected function registerCoreProvider($class, $mimeType, $options = []) {
  292. if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  293. $this->registerProvider($mimeType, function () use ($class, $options) {
  294. return new $class($options);
  295. });
  296. }
  297. }
  298. /**
  299. * Register the default providers (if enabled)
  300. */
  301. protected function registerCoreProviders() {
  302. if ($this->registeredCoreProviders) {
  303. return;
  304. }
  305. $this->registeredCoreProviders = true;
  306. $this->registerCoreProvider(Preview\TXT::class, '/text\/plain/');
  307. $this->registerCoreProvider(Preview\MarkDown::class, '/text\/(x-)?markdown/');
  308. $this->registerCoreProvider(Preview\PNG::class, '/image\/png/');
  309. $this->registerCoreProvider(Preview\JPEG::class, '/image\/jpeg/');
  310. $this->registerCoreProvider(Preview\GIF::class, '/image\/gif/');
  311. $this->registerCoreProvider(Preview\BMP::class, '/image\/bmp/');
  312. $this->registerCoreProvider(Preview\XBitmap::class, '/image\/x-xbitmap/');
  313. $this->registerCoreProvider(Preview\WebP::class, '/image\/webp/');
  314. $this->registerCoreProvider(Preview\Krita::class, '/application\/x-krita/');
  315. $this->registerCoreProvider(Preview\MP3::class, '/audio\/mpeg/');
  316. $this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/');
  317. $this->registerCoreProvider(Preview\Imaginary::class, Preview\Imaginary::supportedMimeTypes());
  318. // SVG and Bitmap require imagick
  319. if ($this->imagickSupport->hasExtension()) {
  320. $imagickProviders = [
  321. 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class],
  322. 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class],
  323. 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class],
  324. 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class],
  325. 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class],
  326. 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class],
  327. 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class],
  328. 'HEIC' => ['mimetype' => '/image\/(x-)?hei(f|c)/', 'class' => Preview\HEIC::class],
  329. 'TGA' => ['mimetype' => '/image\/(x-)?t(ar)?ga/', 'class' => Preview\TGA::class],
  330. 'SGI' => ['mimetype' => '/image\/(x-)?sgi/', 'class' => Preview\SGI::class],
  331. ];
  332. foreach ($imagickProviders as $queryFormat => $provider) {
  333. $class = $provider['class'];
  334. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  335. continue;
  336. }
  337. if ($this->imagickSupport->supportsFormat($queryFormat)) {
  338. $this->registerCoreProvider($class, $provider['mimetype']);
  339. }
  340. }
  341. }
  342. $this->registerCoreProvidersOffice();
  343. // Video requires avconv or ffmpeg
  344. if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) {
  345. $movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null);
  346. if (!is_string($movieBinary)) {
  347. $movieBinary = $this->binaryFinder->findBinaryPath('avconv');
  348. if (!is_string($movieBinary)) {
  349. $movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg');
  350. }
  351. }
  352. if (is_string($movieBinary)) {
  353. $this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ["movieBinary" => $movieBinary]);
  354. }
  355. }
  356. }
  357. private function registerCoreProvidersOffice(): void {
  358. $officeProviders = [
  359. ['mimetype' => '/application\/msword/', 'class' => Preview\MSOfficeDoc::class],
  360. ['mimetype' => '/application\/vnd.ms-.*/', 'class' => Preview\MSOffice2003::class],
  361. ['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => Preview\MSOffice2007::class],
  362. ['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => Preview\OpenDocument::class],
  363. ['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => Preview\StarOffice::class],
  364. ['mimetype' => '/image\/emf/', 'class' => Preview\EMF::class],
  365. ];
  366. $findBinary = true;
  367. $officeBinary = false;
  368. foreach ($officeProviders as $provider) {
  369. $class = $provider['class'];
  370. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  371. continue;
  372. }
  373. if ($findBinary) {
  374. // Office requires openoffice or libreoffice
  375. $officeBinary = $this->config->getSystemValue('preview_libreoffice_path', false);
  376. if ($officeBinary === false) {
  377. $officeBinary = $this->binaryFinder->findBinaryPath('libreoffice');
  378. }
  379. if ($officeBinary === false) {
  380. $officeBinary = $this->binaryFinder->findBinaryPath('openoffice');
  381. }
  382. $findBinary = false;
  383. }
  384. if ($officeBinary) {
  385. $this->registerCoreProvider($class, $provider['mimetype'], ['officeBinary' => $officeBinary]);
  386. }
  387. }
  388. }
  389. private function registerBootstrapProviders(): void {
  390. $context = $this->bootstrapCoordinator->getRegistrationContext();
  391. if ($context === null) {
  392. // Just ignore for now
  393. return;
  394. }
  395. $providers = $context->getPreviewProviders();
  396. foreach ($providers as $provider) {
  397. $key = $provider->getMimeTypeRegex() . '-' . $provider->getService();
  398. if (array_key_exists($key, $this->loadedBootstrapProviders)) {
  399. // Do not load the provider more than once
  400. continue;
  401. }
  402. $this->loadedBootstrapProviders[$key] = null;
  403. $this->registerProvider($provider->getMimeTypeRegex(), function () use ($provider) {
  404. try {
  405. return $this->container->get($provider->getService());
  406. } catch (QueryException $e) {
  407. return null;
  408. }
  409. });
  410. }
  411. }
  412. /**
  413. * @throws NotFoundException if preview generation is disabled
  414. */
  415. private function throwIfPreviewsDisabled(): void {
  416. if (!$this->enablePreviews) {
  417. throw new NotFoundException('Previews disabled');
  418. }
  419. }
  420. }