Helper.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files\Activity;
  8. use OCP\Files\Folder;
  9. use OCP\Files\IRootFolder;
  10. use OCP\Files\Node;
  11. use OCP\ITagManager;
  12. class Helper {
  13. /** If a user has a lot of favorites the query might get too slow and long */
  14. public const FAVORITE_LIMIT = 50;
  15. public function __construct(
  16. protected ITagManager $tagManager,
  17. protected IRootFolder $rootFolder,
  18. ) {
  19. }
  20. /**
  21. * Return an array with nodes marked as favorites
  22. *
  23. * @param string $user User ID
  24. * @param bool $foldersOnly Only return folders (default false)
  25. * @return Node[]
  26. * @psalm-return ($foldersOnly is true ? Folder[] : Node[])
  27. * @throws \RuntimeException when too many or no favorites where found
  28. */
  29. public function getFavoriteNodes(string $user, bool $foldersOnly = false): array {
  30. $tags = $this->tagManager->load('files', [], false, $user);
  31. $favorites = $tags->getFavorites();
  32. if (empty($favorites)) {
  33. throw new \RuntimeException('No favorites', 1);
  34. } elseif (isset($favorites[self::FAVORITE_LIMIT])) {
  35. throw new \RuntimeException('Too many favorites', 2);
  36. }
  37. // Can not DI because the user is not known on instantiation
  38. $userFolder = $this->rootFolder->getUserFolder($user);
  39. $favoriteNodes = [];
  40. foreach ($favorites as $favorite) {
  41. $node = $userFolder->getFirstNodeById($favorite);
  42. if ($node) {
  43. if (!$foldersOnly || $node instanceof Folder) {
  44. $favoriteNodes[] = $node;
  45. }
  46. }
  47. }
  48. if (empty($favoriteNodes)) {
  49. throw new \RuntimeException('No favorites', 1);
  50. }
  51. return $favoriteNodes;
  52. }
  53. /**
  54. * Returns an array with the favorites
  55. *
  56. * @param string $user
  57. * @return array
  58. * @throws \RuntimeException when too many or no favorites where found
  59. */
  60. public function getFavoriteFilePaths(string $user): array {
  61. $userFolder = $this->rootFolder->getUserFolder($user);
  62. $nodes = $this->getFavoriteNodes($user);
  63. $folders = $items = [];
  64. foreach ($nodes as $node) {
  65. $path = $userFolder->getRelativePath($node->getPath());
  66. $items[] = $path;
  67. if ($node instanceof Folder) {
  68. $folders[] = $path;
  69. }
  70. }
  71. return [
  72. 'items' => $items,
  73. 'folders' => $folders,
  74. ];
  75. }
  76. }