PreviewManager.php 14 KB

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