ReferenceController.php 2.0 KB

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