ApiController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Felix Nüsse <Felix.nuesse@t-online.de>
  8. * @author fnuesse <felix.nuesse@t-online.de>
  9. * @author fnuesse <fnuesse@techfak.uni-bielefeld.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ <skjnldsv@protonmail.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Max Kovalenko <mxss1998@yandex.ru>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Nina Pypchenko <22447785+nina-py@users.noreply.github.com>
  17. * @author Richard Steinmetz <richard@steinmetz.cloud>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Tobias Kaminsky <tobias@kaminsky.me>
  21. * @author Vincent Petry <vincent@nextcloud.com>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OCA\Files\Controller;
  39. use OC\Files\Node\Node;
  40. use OCA\Files\Service\TagService;
  41. use OCA\Files\Service\UserConfig;
  42. use OCA\Files\Service\ViewConfig;
  43. use OCP\AppFramework\Controller;
  44. use OCP\AppFramework\Http;
  45. use OCP\AppFramework\Http\Attribute\OpenAPI;
  46. use OCP\AppFramework\Http\ContentSecurityPolicy;
  47. use OCP\AppFramework\Http\DataResponse;
  48. use OCP\AppFramework\Http\FileDisplayResponse;
  49. use OCP\AppFramework\Http\JSONResponse;
  50. use OCP\AppFramework\Http\Response;
  51. use OCP\AppFramework\Http\StreamResponse;
  52. use OCP\Files\File;
  53. use OCP\Files\Folder;
  54. use OCP\Files\NotFoundException;
  55. use OCP\IConfig;
  56. use OCP\IPreview;
  57. use OCP\IRequest;
  58. use OCP\IUserSession;
  59. use OCP\Share\IManager;
  60. use OCP\Share\IShare;
  61. /**
  62. * @package OCA\Files\Controller
  63. */
  64. class ApiController extends Controller {
  65. private TagService $tagService;
  66. private IManager $shareManager;
  67. private IPreview $previewManager;
  68. private IUserSession $userSession;
  69. private IConfig $config;
  70. private ?Folder $userFolder;
  71. private UserConfig $userConfig;
  72. private ViewConfig $viewConfig;
  73. public function __construct(string $appName,
  74. IRequest $request,
  75. IUserSession $userSession,
  76. TagService $tagService,
  77. IPreview $previewManager,
  78. IManager $shareManager,
  79. IConfig $config,
  80. ?Folder $userFolder,
  81. UserConfig $userConfig,
  82. ViewConfig $viewConfig) {
  83. parent::__construct($appName, $request);
  84. $this->userSession = $userSession;
  85. $this->tagService = $tagService;
  86. $this->previewManager = $previewManager;
  87. $this->shareManager = $shareManager;
  88. $this->config = $config;
  89. $this->userFolder = $userFolder;
  90. $this->userConfig = $userConfig;
  91. $this->viewConfig = $viewConfig;
  92. }
  93. /**
  94. * Gets a thumbnail of the specified file
  95. *
  96. * @since API version 1.0
  97. *
  98. * @NoAdminRequired
  99. * @NoCSRFRequired
  100. * @StrictCookieRequired
  101. *
  102. * @param int $x Width of the thumbnail
  103. * @param int $y Height of the thumbnail
  104. * @param string $file URL-encoded filename
  105. * @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, array{message?: string}, array{}>
  106. *
  107. * 200: Thumbnail returned
  108. * 400: Getting thumbnail is not possible
  109. * 404: File not found
  110. */
  111. public function getThumbnail($x, $y, $file) {
  112. if ($x < 1 || $y < 1) {
  113. return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
  114. }
  115. try {
  116. $file = $this->userFolder->get($file);
  117. if ($file instanceof Folder) {
  118. throw new NotFoundException();
  119. }
  120. if ($file->getId() <= 0) {
  121. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  122. }
  123. /** @var File $file */
  124. $preview = $this->previewManager->getPreview($file, $x, $y, true);
  125. return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
  126. } catch (NotFoundException $e) {
  127. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  128. } catch (\Exception $e) {
  129. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  130. }
  131. }
  132. /**
  133. * Updates the info of the specified file path
  134. * The passed tags are absolute, which means they will
  135. * replace the actual tag selection.
  136. *
  137. * @NoAdminRequired
  138. *
  139. * @param string $path path
  140. * @param array|string $tags array of tags
  141. * @return DataResponse
  142. */
  143. public function updateFileTags($path, $tags = null) {
  144. $result = [];
  145. // if tags specified or empty array, update tags
  146. if (!is_null($tags)) {
  147. try {
  148. $this->tagService->updateFileTags($path, $tags);
  149. } catch (\OCP\Files\NotFoundException $e) {
  150. return new DataResponse([
  151. 'message' => $e->getMessage()
  152. ], Http::STATUS_NOT_FOUND);
  153. } catch (\OCP\Files\StorageNotAvailableException $e) {
  154. return new DataResponse([
  155. 'message' => $e->getMessage()
  156. ], Http::STATUS_SERVICE_UNAVAILABLE);
  157. } catch (\Exception $e) {
  158. return new DataResponse([
  159. 'message' => $e->getMessage()
  160. ], Http::STATUS_NOT_FOUND);
  161. }
  162. $result['tags'] = $tags;
  163. }
  164. return new DataResponse($result);
  165. }
  166. /**
  167. * @param \OCP\Files\Node[] $nodes
  168. * @return array
  169. */
  170. private function formatNodes(array $nodes) {
  171. $shareTypesForNodes = $this->getShareTypesForNodes($nodes);
  172. return array_values(array_map(function (Node $node) use ($shareTypesForNodes) {
  173. $shareTypes = $shareTypesForNodes[$node->getId()] ?? [];
  174. $file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
  175. $file['hasPreview'] = $this->previewManager->isAvailable($node);
  176. $parts = explode('/', dirname($node->getPath()), 4);
  177. if (isset($parts[3])) {
  178. $file['path'] = '/' . $parts[3];
  179. } else {
  180. $file['path'] = '/';
  181. }
  182. if (!empty($shareTypes)) {
  183. $file['shareTypes'] = $shareTypes;
  184. }
  185. return $file;
  186. }, $nodes));
  187. }
  188. /**
  189. * Get the share types for each node
  190. *
  191. * @param \OCP\Files\Node[] $nodes
  192. * @return array<int, int[]> list of share types for each fileid
  193. */
  194. private function getShareTypesForNodes(array $nodes): array {
  195. $userId = $this->userSession->getUser()->getUID();
  196. $requestedShareTypes = [
  197. IShare::TYPE_USER,
  198. IShare::TYPE_GROUP,
  199. IShare::TYPE_LINK,
  200. IShare::TYPE_REMOTE,
  201. IShare::TYPE_EMAIL,
  202. IShare::TYPE_ROOM,
  203. IShare::TYPE_DECK,
  204. IShare::TYPE_SCIENCEMESH,
  205. ];
  206. $shareTypes = [];
  207. $nodeIds = array_map(function (Node $node) {
  208. return $node->getId();
  209. }, $nodes);
  210. foreach ($requestedShareTypes as $shareType) {
  211. $nodesLeft = array_combine($nodeIds, array_fill(0, count($nodeIds), true));
  212. $offset = 0;
  213. // fetch shares until we've either found shares for all nodes or there are no more shares left
  214. while (count($nodesLeft) > 0) {
  215. $shares = $this->shareManager->getSharesBy($userId, $shareType, null, false, 100, $offset);
  216. foreach ($shares as $share) {
  217. $fileId = $share->getNodeId();
  218. if (isset($nodesLeft[$fileId])) {
  219. if (!isset($shareTypes[$fileId])) {
  220. $shareTypes[$fileId] = [];
  221. }
  222. $shareTypes[$fileId][] = $shareType;
  223. unset($nodesLeft[$fileId]);
  224. }
  225. }
  226. if (count($shares) < 100) {
  227. break;
  228. } else {
  229. $offset += count($shares);
  230. }
  231. }
  232. }
  233. return $shareTypes;
  234. }
  235. /**
  236. * Returns a list of recently modified files.
  237. *
  238. * @NoAdminRequired
  239. *
  240. * @return DataResponse
  241. */
  242. public function getRecentFiles() {
  243. $nodes = $this->userFolder->getRecent(100);
  244. $files = $this->formatNodes($nodes);
  245. return new DataResponse(['files' => $files]);
  246. }
  247. /**
  248. * Returns the current logged-in user's storage stats.
  249. *
  250. * @NoAdminRequired
  251. *
  252. * @param ?string $dir the directory to get the storage stats from
  253. * @return JSONResponse
  254. */
  255. public function getStorageStats($dir = '/'): JSONResponse {
  256. $storageInfo = \OC_Helper::getStorageInfo($dir ?: '/');
  257. return new JSONResponse(['message' => 'ok', 'data' => $storageInfo]);
  258. }
  259. /**
  260. * Set a user view config
  261. *
  262. * @NoAdminRequired
  263. *
  264. * @param string $view
  265. * @param string $key
  266. * @param string|bool $value
  267. * @return JSONResponse
  268. */
  269. public function setViewConfig(string $view, string $key, $value): JSONResponse {
  270. try {
  271. $this->viewConfig->setConfig($view, $key, (string)$value);
  272. } catch (\InvalidArgumentException $e) {
  273. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  274. }
  275. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfig($view)]);
  276. }
  277. /**
  278. * Get the user view config
  279. *
  280. * @NoAdminRequired
  281. *
  282. * @return JSONResponse
  283. */
  284. public function getViewConfigs(): JSONResponse {
  285. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfigs()]);
  286. }
  287. /**
  288. * Set a user config
  289. *
  290. * @NoAdminRequired
  291. *
  292. * @param string $key
  293. * @param string|bool $value
  294. * @return JSONResponse
  295. */
  296. public function setConfig(string $key, $value): JSONResponse {
  297. try {
  298. $this->userConfig->setConfig($key, (string)$value);
  299. } catch (\InvalidArgumentException $e) {
  300. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  301. }
  302. return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
  303. }
  304. /**
  305. * Get the user config
  306. *
  307. * @NoAdminRequired
  308. *
  309. * @return JSONResponse
  310. */
  311. public function getConfigs(): JSONResponse {
  312. return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
  313. }
  314. /**
  315. * Toggle default for showing/hiding hidden files
  316. *
  317. * @NoAdminRequired
  318. *
  319. * @param bool $value
  320. * @return Response
  321. * @throws \OCP\PreConditionNotMetException
  322. */
  323. public function showHiddenFiles(bool $value): Response {
  324. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
  325. return new Response();
  326. }
  327. /**
  328. * Toggle default for cropping preview images
  329. *
  330. * @NoAdminRequired
  331. *
  332. * @param bool $value
  333. * @return Response
  334. * @throws \OCP\PreConditionNotMetException
  335. */
  336. public function cropImagePreviews(bool $value): Response {
  337. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
  338. return new Response();
  339. }
  340. /**
  341. * Toggle default for files grid view
  342. *
  343. * @NoAdminRequired
  344. *
  345. * @param bool $show
  346. * @return Response
  347. * @throws \OCP\PreConditionNotMetException
  348. */
  349. public function showGridView(bool $show): Response {
  350. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
  351. return new Response();
  352. }
  353. /**
  354. * Get default settings for the grid view
  355. *
  356. * @NoAdminRequired
  357. */
  358. public function getGridView() {
  359. $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
  360. return new JSONResponse(['gridview' => $status]);
  361. }
  362. /**
  363. * @NoAdminRequired
  364. * @NoCSRFRequired
  365. * @PublicPage
  366. */
  367. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  368. public function serviceWorker(): StreamResponse {
  369. $response = new StreamResponse(__DIR__ . '/../../../../dist/preview-service-worker.js');
  370. $response->setHeaders([
  371. 'Content-Type' => 'application/javascript',
  372. 'Service-Worker-Allowed' => '/'
  373. ]);
  374. $policy = new ContentSecurityPolicy();
  375. $policy->addAllowedWorkerSrcDomain("'self'");
  376. $policy->addAllowedScriptDomain("'self'");
  377. $policy->addAllowedConnectDomain("'self'");
  378. $response->setContentSecurityPolicy($policy);
  379. return $response;
  380. }
  381. }