ReferenceController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OCP\AppFramework\Controller;
  9. use OCP\AppFramework\Http;
  10. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  11. use OCP\AppFramework\Http\DataDownloadResponse;
  12. use OCP\AppFramework\Http\DataResponse;
  13. use OCP\Collaboration\Reference\IReferenceManager;
  14. use OCP\Files\AppData\IAppDataFactory;
  15. use OCP\Files\NotFoundException;
  16. use OCP\Files\NotPermittedException;
  17. use OCP\IRequest;
  18. class ReferenceController extends Controller {
  19. public function __construct(
  20. string $appName,
  21. IRequest $request,
  22. private IReferenceManager $referenceManager,
  23. private IAppDataFactory $appDataFactory,
  24. ) {
  25. parent::__construct($appName, $request);
  26. }
  27. /**
  28. * @PublicPage
  29. * @NoCSRFRequired
  30. *
  31. * Get a preview for a reference
  32. *
  33. * @param string $referenceId the reference cache key
  34. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_NOT_FOUND, '', array{}>
  35. *
  36. * 200: Preview returned
  37. * 404: Reference not found
  38. */
  39. #[FrontpageRoute(verb: 'GET', url: '/core/references/preview/{referenceId}')]
  40. public function preview(string $referenceId): DataDownloadResponse|DataResponse {
  41. $reference = $this->referenceManager->getReferenceByCacheKey($referenceId);
  42. try {
  43. $appData = $this->appDataFactory->get('core');
  44. $folder = $appData->getFolder('opengraph');
  45. $file = $folder->getFile($referenceId);
  46. $contentType = $reference === null || $reference->getImageContentType() === null
  47. ? $file->getMimeType()
  48. : $reference->getImageContentType();
  49. $response = new DataDownloadResponse(
  50. $file->getContent(),
  51. $referenceId,
  52. $contentType
  53. );
  54. } catch (NotFoundException|NotPermittedException $e) {
  55. $response = new DataResponse('', Http::STATUS_NOT_FOUND);
  56. }
  57. $response->cacheFor(3600, false, true);
  58. return $response;
  59. }
  60. }