PreviewManager.php 14 KB

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