DirectFile.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\Direct;
  8. use OCA\DAV\Db\Direct;
  9. use OCA\DAV\Events\BeforeFileDirectDownloadedEvent;
  10. use OCP\EventDispatcher\IEventDispatcher;
  11. use OCP\Files\File;
  12. use OCP\Files\IRootFolder;
  13. use Sabre\DAV\Exception\Forbidden;
  14. use Sabre\DAV\Exception\NotFound;
  15. use Sabre\DAV\IFile;
  16. class DirectFile implements IFile {
  17. /** @var File */
  18. private $file;
  19. public function __construct(
  20. private Direct $direct,
  21. private IRootFolder $rootFolder,
  22. private IEventDispatcher $eventDispatcher,
  23. ) {
  24. }
  25. public function put($data) {
  26. throw new Forbidden();
  27. }
  28. public function get() {
  29. $this->getFile();
  30. $this->eventDispatcher->dispatchTyped(new BeforeFileDirectDownloadedEvent($this->file));
  31. return $this->file->fopen('rb');
  32. }
  33. public function getContentType() {
  34. $this->getFile();
  35. return $this->file->getMimeType();
  36. }
  37. public function getETag() {
  38. $this->getFile();
  39. return $this->file->getEtag();
  40. }
  41. /**
  42. * @psalm-suppress ImplementedReturnTypeMismatch \Sabre\DAV\IFile::getSize signature does not support 32bit
  43. * @return int|float
  44. */
  45. public function getSize() {
  46. $this->getFile();
  47. return $this->file->getSize();
  48. }
  49. public function delete() {
  50. throw new Forbidden();
  51. }
  52. public function getName() {
  53. return $this->direct->getToken();
  54. }
  55. public function setName($name) {
  56. throw new Forbidden();
  57. }
  58. public function getLastModified() {
  59. $this->getFile();
  60. return $this->file->getMTime();
  61. }
  62. private function getFile() {
  63. if ($this->file === null) {
  64. $userFolder = $this->rootFolder->getUserFolder($this->direct->getUserId());
  65. $file = $userFolder->getFirstNodeById($this->direct->getFileId());
  66. if (!$file) {
  67. throw new NotFound();
  68. }
  69. if (!$file instanceof File) {
  70. throw new Forbidden('direct download not allowed on directories');
  71. }
  72. $this->file = $file;
  73. }
  74. return $this->file;
  75. }
  76. }