1
0

ProviderV2.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Preview;
  8. use OCP\Files\File;
  9. use OCP\Files\FileInfo;
  10. use OCP\IImage;
  11. use OCP\Preview\IProviderV2;
  12. abstract class ProviderV2 implements IProviderV2 {
  13. /** @var array */
  14. protected $options;
  15. /** @var array */
  16. protected $tmpFiles = [];
  17. /**
  18. * Constructor
  19. *
  20. * @param array $options
  21. */
  22. public function __construct(array $options = []) {
  23. $this->options = $options;
  24. }
  25. /**
  26. * @return string Regex with the mimetypes that are supported by this provider
  27. */
  28. abstract public function getMimeType(): string ;
  29. /**
  30. * Check if a preview can be generated for $path
  31. *
  32. * @param FileInfo $file
  33. * @return bool
  34. */
  35. public function isAvailable(FileInfo $file): bool {
  36. return true;
  37. }
  38. /**
  39. * get thumbnail for file at path $path
  40. *
  41. * @param File $file
  42. * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image
  43. * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image
  44. * @return null|\OCP\IImage false if no preview was generated
  45. * @since 17.0.0
  46. */
  47. abstract public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage;
  48. protected function useTempFile(File $file): bool {
  49. return $file->isEncrypted() || !$file->getStorage()->isLocal();
  50. }
  51. /**
  52. * Get a path to either the local file or temporary file
  53. *
  54. * @param File $file
  55. * @param int $maxSize maximum size for temporary files
  56. * @return string|false
  57. */
  58. protected function getLocalFile(File $file, ?int $maxSize = null) {
  59. if ($this->useTempFile($file)) {
  60. $absPath = \OC::$server->getTempManager()->getTemporaryFile();
  61. $content = $file->fopen('r');
  62. if ($maxSize) {
  63. $content = stream_get_contents($content, $maxSize);
  64. }
  65. file_put_contents($absPath, $content);
  66. $this->tmpFiles[] = $absPath;
  67. return $absPath;
  68. } else {
  69. $path = $file->getStorage()->getLocalFile($file->getInternalPath());
  70. if (is_string($path)) {
  71. return $path;
  72. } else {
  73. return false;
  74. }
  75. }
  76. }
  77. /**
  78. * Clean any generated temporary files
  79. */
  80. protected function cleanTmpFiles(): void {
  81. foreach ($this->tmpFiles as $tmpFile) {
  82. unlink($tmpFile);
  83. }
  84. $this->tmpFiles = [];
  85. }
  86. }