PreviewController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Files_Versions\Controller;
  7. use OCA\Files_Versions\Versions\IVersionManager;
  8. use OCP\AppFramework\Controller;
  9. use OCP\AppFramework\Http;
  10. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  11. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  12. use OCP\AppFramework\Http\DataResponse;
  13. use OCP\AppFramework\Http\FileDisplayResponse;
  14. use OCP\Files\IRootFolder;
  15. use OCP\Files\NotFoundException;
  16. use OCP\IPreview;
  17. use OCP\IRequest;
  18. use OCP\IUserSession;
  19. class PreviewController extends Controller {
  20. public function __construct(
  21. string $appName,
  22. IRequest $request,
  23. private IRootFolder $rootFolder,
  24. private IUserSession $userSession,
  25. private IVersionManager $versionManager,
  26. private IPreview $previewManager,
  27. ) {
  28. parent::__construct($appName, $request);
  29. }
  30. /**
  31. * Get the preview for a file version
  32. *
  33. * @param string $file Path of the file
  34. * @param int $x Width of the preview
  35. * @param int $y Height of the preview
  36. * @param string $version Version of the file to get the preview for
  37. * @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, list<empty>, array{}>
  38. *
  39. * 200: Preview returned
  40. * 400: Getting preview is not possible
  41. * 404: Preview not found
  42. */
  43. #[NoAdminRequired]
  44. #[NoCSRFRequired]
  45. public function getPreview(
  46. string $file = '',
  47. int $x = 44,
  48. int $y = 44,
  49. string $version = '',
  50. ) {
  51. if ($file === '' || $version === '' || $x === 0 || $y === 0) {
  52. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  53. }
  54. try {
  55. $user = $this->userSession->getUser();
  56. $userFolder = $this->rootFolder->getUserFolder($user->getUID());
  57. $file = $userFolder->get($file);
  58. $versionFile = $this->versionManager->getVersionFile($user, $file, $version);
  59. $preview = $this->previewManager->getPreview($versionFile, $x, $y, true, IPreview::MODE_FILL, $versionFile->getMimetype());
  60. return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
  61. } catch (NotFoundException $e) {
  62. return new DataResponse([], Http::STATUS_NOT_FOUND);
  63. } catch (\InvalidArgumentException $e) {
  64. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  65. }
  66. }
  67. }