DirectFile.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 Direct */
  18. private $direct;
  19. /** @var IRootFolder */
  20. private $rootFolder;
  21. /** @var File */
  22. private $file;
  23. private $eventDispatcher;
  24. public function __construct(Direct $direct, IRootFolder $rootFolder, IEventDispatcher $eventDispatcher) {
  25. $this->direct = $direct;
  26. $this->rootFolder = $rootFolder;
  27. $this->eventDispatcher = $eventDispatcher;
  28. }
  29. public function put($data) {
  30. throw new Forbidden();
  31. }
  32. public function get() {
  33. $this->getFile();
  34. $this->eventDispatcher->dispatchTyped(new BeforeFileDirectDownloadedEvent($this->file));
  35. return $this->file->fopen('rb');
  36. }
  37. public function getContentType() {
  38. $this->getFile();
  39. return $this->file->getMimeType();
  40. }
  41. public function getETag() {
  42. $this->getFile();
  43. return $this->file->getEtag();
  44. }
  45. /**
  46. * @psalm-suppress ImplementedReturnTypeMismatch \Sabre\DAV\IFile::getSize signature does not support 32bit
  47. * @return int|float
  48. */
  49. public function getSize() {
  50. $this->getFile();
  51. return $this->file->getSize();
  52. }
  53. public function delete() {
  54. throw new Forbidden();
  55. }
  56. public function getName() {
  57. return $this->direct->getToken();
  58. }
  59. public function setName($name) {
  60. throw new Forbidden();
  61. }
  62. public function getLastModified() {
  63. $this->getFile();
  64. return $this->file->getMTime();
  65. }
  66. private function getFile() {
  67. if ($this->file === null) {
  68. $userFolder = $this->rootFolder->getUserFolder($this->direct->getUserId());
  69. $file = $userFolder->getFirstNodeById($this->direct->getFileId());
  70. if (!$file) {
  71. throw new NotFound();
  72. }
  73. if (!$file instanceof File) {
  74. throw new Forbidden('direct download not allowed on directories');
  75. }
  76. $this->file = $file;
  77. }
  78. return $this->file;
  79. }
  80. }