ApiController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-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\Controller;
  8. use OC\Files\Node\Node;
  9. use OCA\Files\Helper;
  10. use OCA\Files\ResponseDefinitions;
  11. use OCA\Files\Service\TagService;
  12. use OCA\Files\Service\UserConfig;
  13. use OCA\Files\Service\ViewConfig;
  14. use OCP\AppFramework\Controller;
  15. use OCP\AppFramework\Http;
  16. use OCP\AppFramework\Http\Attribute\ApiRoute;
  17. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  18. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  19. use OCP\AppFramework\Http\Attribute\OpenAPI;
  20. use OCP\AppFramework\Http\Attribute\PublicPage;
  21. use OCP\AppFramework\Http\Attribute\StrictCookiesRequired;
  22. use OCP\AppFramework\Http\ContentSecurityPolicy;
  23. use OCP\AppFramework\Http\DataResponse;
  24. use OCP\AppFramework\Http\FileDisplayResponse;
  25. use OCP\AppFramework\Http\JSONResponse;
  26. use OCP\AppFramework\Http\Response;
  27. use OCP\AppFramework\Http\StreamResponse;
  28. use OCP\Files\File;
  29. use OCP\Files\Folder;
  30. use OCP\Files\IRootFolder;
  31. use OCP\Files\NotFoundException;
  32. use OCP\Files\StorageNotAvailableException;
  33. use OCP\IConfig;
  34. use OCP\IL10N;
  35. use OCP\IPreview;
  36. use OCP\IRequest;
  37. use OCP\IUser;
  38. use OCP\IUserSession;
  39. use OCP\PreConditionNotMetException;
  40. use OCP\Share\IManager;
  41. use OCP\Share\IShare;
  42. use Psr\Log\LoggerInterface;
  43. use Throwable;
  44. /**
  45. * @psalm-import-type FilesFolderTree from ResponseDefinitions
  46. *
  47. * @package OCA\Files\Controller
  48. */
  49. class ApiController extends Controller {
  50. public function __construct(
  51. string $appName,
  52. IRequest $request,
  53. private IUserSession $userSession,
  54. private TagService $tagService,
  55. private IPreview $previewManager,
  56. private IManager $shareManager,
  57. private IConfig $config,
  58. private ?Folder $userFolder,
  59. private UserConfig $userConfig,
  60. private ViewConfig $viewConfig,
  61. private IL10N $l10n,
  62. private IRootFolder $rootFolder,
  63. private LoggerInterface $logger,
  64. ) {
  65. parent::__construct($appName, $request);
  66. }
  67. /**
  68. * Gets a thumbnail of the specified file
  69. *
  70. * @since API version 1.0
  71. *
  72. * @param int $x Width of the thumbnail
  73. * @param int $y Height of the thumbnail
  74. * @param string $file URL-encoded filename
  75. * @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, array{message?: string}, array{}>
  76. *
  77. * 200: Thumbnail returned
  78. * 400: Getting thumbnail is not possible
  79. * 404: File not found
  80. */
  81. #[NoAdminRequired]
  82. #[NoCSRFRequired]
  83. #[StrictCookiesRequired]
  84. public function getThumbnail($x, $y, $file) {
  85. if ($x < 1 || $y < 1) {
  86. return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
  87. }
  88. try {
  89. $file = $this->userFolder->get($file);
  90. if ($file instanceof Folder) {
  91. throw new NotFoundException();
  92. }
  93. if ($file->getId() <= 0) {
  94. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  95. }
  96. /** @var File $file */
  97. $preview = $this->previewManager->getPreview($file, $x, $y, true);
  98. return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
  99. } catch (NotFoundException $e) {
  100. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  101. } catch (\Exception $e) {
  102. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  103. }
  104. }
  105. /**
  106. * Updates the info of the specified file path
  107. * The passed tags are absolute, which means they will
  108. * replace the actual tag selection.
  109. *
  110. * @param string $path path
  111. * @param array|string $tags array of tags
  112. * @return DataResponse
  113. */
  114. #[NoAdminRequired]
  115. public function updateFileTags($path, $tags = null) {
  116. $result = [];
  117. // if tags specified or empty array, update tags
  118. if (!is_null($tags)) {
  119. try {
  120. $this->tagService->updateFileTags($path, $tags);
  121. } catch (NotFoundException $e) {
  122. return new DataResponse([
  123. 'message' => $e->getMessage()
  124. ], Http::STATUS_NOT_FOUND);
  125. } catch (StorageNotAvailableException $e) {
  126. return new DataResponse([
  127. 'message' => $e->getMessage()
  128. ], Http::STATUS_SERVICE_UNAVAILABLE);
  129. } catch (\Exception $e) {
  130. return new DataResponse([
  131. 'message' => $e->getMessage()
  132. ], Http::STATUS_NOT_FOUND);
  133. }
  134. $result['tags'] = $tags;
  135. }
  136. return new DataResponse($result);
  137. }
  138. /**
  139. * @param \OCP\Files\Node[] $nodes
  140. * @return array
  141. */
  142. private function formatNodes(array $nodes) {
  143. $shareTypesForNodes = $this->getShareTypesForNodes($nodes);
  144. return array_values(array_map(function (Node $node) use ($shareTypesForNodes) {
  145. $shareTypes = $shareTypesForNodes[$node->getId()] ?? [];
  146. $file = Helper::formatFileInfo($node->getFileInfo());
  147. $file['hasPreview'] = $this->previewManager->isAvailable($node);
  148. $parts = explode('/', dirname($node->getPath()), 4);
  149. if (isset($parts[3])) {
  150. $file['path'] = '/' . $parts[3];
  151. } else {
  152. $file['path'] = '/';
  153. }
  154. if (!empty($shareTypes)) {
  155. $file['shareTypes'] = $shareTypes;
  156. }
  157. return $file;
  158. }, $nodes));
  159. }
  160. /**
  161. * Get the share types for each node
  162. *
  163. * @param \OCP\Files\Node[] $nodes
  164. * @return array<int, int[]> list of share types for each fileid
  165. */
  166. private function getShareTypesForNodes(array $nodes): array {
  167. $userId = $this->userSession->getUser()->getUID();
  168. $requestedShareTypes = [
  169. IShare::TYPE_USER,
  170. IShare::TYPE_GROUP,
  171. IShare::TYPE_LINK,
  172. IShare::TYPE_REMOTE,
  173. IShare::TYPE_EMAIL,
  174. IShare::TYPE_ROOM,
  175. IShare::TYPE_DECK,
  176. IShare::TYPE_SCIENCEMESH,
  177. ];
  178. $shareTypes = [];
  179. $nodeIds = array_map(function (Node $node) {
  180. return $node->getId();
  181. }, $nodes);
  182. foreach ($requestedShareTypes as $shareType) {
  183. $nodesLeft = array_combine($nodeIds, array_fill(0, count($nodeIds), true));
  184. $offset = 0;
  185. // fetch shares until we've either found shares for all nodes or there are no more shares left
  186. while (count($nodesLeft) > 0) {
  187. $shares = $this->shareManager->getSharesBy($userId, $shareType, null, false, 100, $offset);
  188. foreach ($shares as $share) {
  189. $fileId = $share->getNodeId();
  190. if (isset($nodesLeft[$fileId])) {
  191. if (!isset($shareTypes[$fileId])) {
  192. $shareTypes[$fileId] = [];
  193. }
  194. $shareTypes[$fileId][] = $shareType;
  195. unset($nodesLeft[$fileId]);
  196. }
  197. }
  198. if (count($shares) < 100) {
  199. break;
  200. } else {
  201. $offset += count($shares);
  202. }
  203. }
  204. }
  205. return $shareTypes;
  206. }
  207. /**
  208. * Returns a list of recently modified files.
  209. *
  210. * @return DataResponse
  211. */
  212. #[NoAdminRequired]
  213. public function getRecentFiles() {
  214. $nodes = $this->userFolder->getRecent(100);
  215. $files = $this->formatNodes($nodes);
  216. return new DataResponse(['files' => $files]);
  217. }
  218. /**
  219. * @param \OCP\Files\Node[] $nodes
  220. * @param int $depth The depth to traverse into the contents of each node
  221. */
  222. private function getChildren(array $nodes, int $depth = 1, int $currentDepth = 0): array {
  223. if ($currentDepth >= $depth) {
  224. return [];
  225. }
  226. $children = [];
  227. foreach ($nodes as $node) {
  228. if (!($node instanceof Folder)) {
  229. continue;
  230. }
  231. $basename = basename($node->getPath());
  232. $entry = [
  233. 'id' => $node->getId(),
  234. 'basename' => $basename,
  235. 'children' => $this->getChildren($node->getDirectoryListing(), $depth, $currentDepth + 1),
  236. ];
  237. $displayName = $node->getName();
  238. if ($basename !== $displayName) {
  239. $entry['displayName'] = $displayName;
  240. }
  241. $children[] = $entry;
  242. }
  243. return $children;
  244. }
  245. /**
  246. * Returns the folder tree of the user
  247. *
  248. * @param string $path The path relative to the user folder
  249. * @param int $depth The depth of the tree
  250. *
  251. * @return JSONResponse<Http::STATUS_OK, FilesFolderTree, array{}>|JSONResponse<Http::STATUS_UNAUTHORIZED|Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  252. *
  253. * 200: Folder tree returned successfully
  254. * 400: Invalid folder path
  255. * 401: Unauthorized
  256. * 404: Folder not found
  257. */
  258. #[NoAdminRequired]
  259. #[ApiRoute(verb: 'GET', url: '/api/v1/folder-tree')]
  260. public function getFolderTree(string $path = '/', int $depth = 1): JSONResponse {
  261. $user = $this->userSession->getUser();
  262. if (!($user instanceof IUser)) {
  263. return new JSONResponse([
  264. 'message' => $this->l10n->t('Failed to authorize'),
  265. ], Http::STATUS_UNAUTHORIZED);
  266. }
  267. try {
  268. $userFolder = $this->rootFolder->getUserFolder($user->getUID());
  269. $userFolderPath = $userFolder->getPath();
  270. $fullPath = implode('/', [$userFolderPath, trim($path, '/')]);
  271. $node = $this->rootFolder->get($fullPath);
  272. if (!($node instanceof Folder)) {
  273. return new JSONResponse([
  274. 'message' => $this->l10n->t('Invalid folder path'),
  275. ], Http::STATUS_BAD_REQUEST);
  276. }
  277. $nodes = $node->getDirectoryListing();
  278. $tree = $this->getChildren($nodes, $depth);
  279. } catch (NotFoundException $e) {
  280. return new JSONResponse([
  281. 'message' => $this->l10n->t('Folder not found'),
  282. ], Http::STATUS_NOT_FOUND);
  283. } catch (Throwable $th) {
  284. $this->logger->error($th->getMessage(), ['exception' => $th]);
  285. $tree = [];
  286. }
  287. return new JSONResponse($tree);
  288. }
  289. /**
  290. * Returns the current logged-in user's storage stats.
  291. *
  292. * @param ?string $dir the directory to get the storage stats from
  293. * @return JSONResponse
  294. */
  295. #[NoAdminRequired]
  296. public function getStorageStats($dir = '/'): JSONResponse {
  297. $storageInfo = \OC_Helper::getStorageInfo($dir ?: '/');
  298. $response = new JSONResponse(['message' => 'ok', 'data' => $storageInfo]);
  299. $response->cacheFor(5 * 60);
  300. return $response;
  301. }
  302. /**
  303. * Set a user view config
  304. *
  305. * @param string $view
  306. * @param string $key
  307. * @param string|bool $value
  308. * @return JSONResponse
  309. */
  310. #[NoAdminRequired]
  311. public function setViewConfig(string $view, string $key, $value): JSONResponse {
  312. try {
  313. $this->viewConfig->setConfig($view, $key, (string)$value);
  314. } catch (\InvalidArgumentException $e) {
  315. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  316. }
  317. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfig($view)]);
  318. }
  319. /**
  320. * Get the user view config
  321. *
  322. * @return JSONResponse
  323. */
  324. #[NoAdminRequired]
  325. public function getViewConfigs(): JSONResponse {
  326. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfigs()]);
  327. }
  328. /**
  329. * Set a user config
  330. *
  331. * @param string $key
  332. * @param string|bool $value
  333. * @return JSONResponse
  334. */
  335. #[NoAdminRequired]
  336. public function setConfig(string $key, $value): JSONResponse {
  337. try {
  338. $this->userConfig->setConfig($key, (string)$value);
  339. } catch (\InvalidArgumentException $e) {
  340. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  341. }
  342. return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
  343. }
  344. /**
  345. * Get the user config
  346. *
  347. * @return JSONResponse
  348. */
  349. #[NoAdminRequired]
  350. public function getConfigs(): JSONResponse {
  351. return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
  352. }
  353. /**
  354. * Toggle default for showing/hiding hidden files
  355. *
  356. * @param bool $value
  357. * @return Response
  358. * @throws PreConditionNotMetException
  359. */
  360. #[NoAdminRequired]
  361. public function showHiddenFiles(bool $value): Response {
  362. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
  363. return new Response();
  364. }
  365. /**
  366. * Toggle default for cropping preview images
  367. *
  368. * @param bool $value
  369. * @return Response
  370. * @throws PreConditionNotMetException
  371. */
  372. #[NoAdminRequired]
  373. public function cropImagePreviews(bool $value): Response {
  374. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
  375. return new Response();
  376. }
  377. /**
  378. * Toggle default for files grid view
  379. *
  380. * @param bool $show
  381. * @return Response
  382. * @throws PreConditionNotMetException
  383. */
  384. #[NoAdminRequired]
  385. public function showGridView(bool $show): Response {
  386. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
  387. return new Response();
  388. }
  389. /**
  390. * Get default settings for the grid view
  391. */
  392. #[NoAdminRequired]
  393. public function getGridView() {
  394. $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
  395. return new JSONResponse(['gridview' => $status]);
  396. }
  397. #[PublicPage]
  398. #[NoCSRFRequired]
  399. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  400. public function serviceWorker(): StreamResponse {
  401. $response = new StreamResponse(__DIR__ . '/../../../../dist/preview-service-worker.js');
  402. $response->setHeaders([
  403. 'Content-Type' => 'application/javascript',
  404. 'Service-Worker-Allowed' => '/'
  405. ]);
  406. $policy = new ContentSecurityPolicy();
  407. $policy->addAllowedWorkerSrcDomain("'self'");
  408. $policy->addAllowedScriptDomain("'self'");
  409. $policy->addAllowedConnectDomain("'self'");
  410. $response->setContentSecurityPolicy($policy);
  411. return $response;
  412. }
  413. }