PreviewManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. $this->registerCoreProvider(Preview\ImaginaryPDF::class, Preview\ImaginaryPDF::supportedMimeTypes());
  319. // SVG and Bitmap require imagick
  320. if ($this->imagickSupport->hasExtension()) {
  321. $imagickProviders = [
  322. 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class],
  323. 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class],
  324. 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class],
  325. 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class],
  326. 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class],
  327. 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class],
  328. 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class],
  329. 'HEIC' => ['mimetype' => '/image\/(x-)?hei(f|c)/', 'class' => Preview\HEIC::class],
  330. 'TGA' => ['mimetype' => '/image\/(x-)?t(ar)?ga/', 'class' => Preview\TGA::class],
  331. 'SGI' => ['mimetype' => '/image\/(x-)?sgi/', 'class' => Preview\SGI::class],
  332. ];
  333. foreach ($imagickProviders as $queryFormat => $provider) {
  334. $class = $provider['class'];
  335. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  336. continue;
  337. }
  338. if ($this->imagickSupport->supportsFormat($queryFormat)) {
  339. $this->registerCoreProvider($class, $provider['mimetype']);
  340. }
  341. }
  342. }
  343. $this->registerCoreProvidersOffice();
  344. // Video requires avconv or ffmpeg
  345. if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) {
  346. $movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null);
  347. if (!is_string($movieBinary)) {
  348. $movieBinary = $this->binaryFinder->findBinaryPath('avconv');
  349. if (!is_string($movieBinary)) {
  350. $movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg');
  351. }
  352. }
  353. if (is_string($movieBinary)) {
  354. $this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ['movieBinary' => $movieBinary]);
  355. }
  356. }
  357. }
  358. private function registerCoreProvidersOffice(): void {
  359. $officeProviders = [
  360. ['mimetype' => '/application\/msword/', 'class' => Preview\MSOfficeDoc::class],
  361. ['mimetype' => '/application\/vnd.ms-.*/', 'class' => Preview\MSOffice2003::class],
  362. ['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => Preview\MSOffice2007::class],
  363. ['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => Preview\OpenDocument::class],
  364. ['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => Preview\StarOffice::class],
  365. ['mimetype' => '/image\/emf/', 'class' => Preview\EMF::class],
  366. ];
  367. $findBinary = true;
  368. $officeBinary = false;
  369. foreach ($officeProviders as $provider) {
  370. $class = $provider['class'];
  371. if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
  372. continue;
  373. }
  374. if ($findBinary) {
  375. // Office requires openoffice or libreoffice
  376. $officeBinary = $this->config->getSystemValue('preview_libreoffice_path', false);
  377. if ($officeBinary === false) {
  378. $officeBinary = $this->binaryFinder->findBinaryPath('libreoffice');
  379. }
  380. if ($officeBinary === false) {
  381. $officeBinary = $this->binaryFinder->findBinaryPath('openoffice');
  382. }
  383. $findBinary = false;
  384. }
  385. if ($officeBinary) {
  386. $this->registerCoreProvider($class, $provider['mimetype'], ['officeBinary' => $officeBinary]);
  387. }
  388. }
  389. }
  390. private function registerBootstrapProviders(): void {
  391. $context = $this->bootstrapCoordinator->getRegistrationContext();
  392. if ($context === null) {
  393. // Just ignore for now
  394. return;
  395. }
  396. $providers = $context->getPreviewProviders();
  397. foreach ($providers as $provider) {
  398. $key = $provider->getMimeTypeRegex() . '-' . $provider->getService();
  399. if (array_key_exists($key, $this->loadedBootstrapProviders)) {
  400. // Do not load the provider more than once
  401. continue;
  402. }
  403. $this->loadedBootstrapProviders[$key] = null;
  404. $this->registerProvider($provider->getMimeTypeRegex(), function () use ($provider) {
  405. try {
  406. return $this->container->get($provider->getService());
  407. } catch (QueryException $e) {
  408. return null;
  409. }
  410. });
  411. }
  412. }
  413. /**
  414. * @throws NotFoundException if preview generation is disabled
  415. */
  416. private function throwIfPreviewsDisabled(): void {
  417. if (!$this->enablePreviews) {
  418. throw new NotFoundException('Previews disabled');
  419. }
  420. }
  421. }