1
0

ApiController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. /** @var File $file */
  121. $preview = $this->previewManager->getPreview($file, $x, $y, true);
  122. return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
  123. } catch (NotFoundException $e) {
  124. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  125. } catch (\Exception $e) {
  126. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  127. }
  128. }
  129. /**
  130. * Updates the info of the specified file path
  131. * The passed tags are absolute, which means they will
  132. * replace the actual tag selection.
  133. *
  134. * @NoAdminRequired
  135. *
  136. * @param string $path path
  137. * @param array|string $tags array of tags
  138. * @return DataResponse
  139. */
  140. public function updateFileTags($path, $tags = null) {
  141. $result = [];
  142. // if tags specified or empty array, update tags
  143. if (!is_null($tags)) {
  144. try {
  145. $this->tagService->updateFileTags($path, $tags);
  146. } catch (\OCP\Files\NotFoundException $e) {
  147. return new DataResponse([
  148. 'message' => $e->getMessage()
  149. ], Http::STATUS_NOT_FOUND);
  150. } catch (\OCP\Files\StorageNotAvailableException $e) {
  151. return new DataResponse([
  152. 'message' => $e->getMessage()
  153. ], Http::STATUS_SERVICE_UNAVAILABLE);
  154. } catch (\Exception $e) {
  155. return new DataResponse([
  156. 'message' => $e->getMessage()
  157. ], Http::STATUS_NOT_FOUND);
  158. }
  159. $result['tags'] = $tags;
  160. }
  161. return new DataResponse($result);
  162. }
  163. /**
  164. * @param \OCP\Files\Node[] $nodes
  165. * @return array
  166. */
  167. private function formatNodes(array $nodes) {
  168. $shareTypesForNodes = $this->getShareTypesForNodes($nodes);
  169. return array_values(array_map(function (Node $node) use ($shareTypesForNodes) {
  170. $shareTypes = $shareTypesForNodes[$node->getId()] ?? [];
  171. $file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
  172. $file['hasPreview'] = $this->previewManager->isAvailable($node);
  173. $parts = explode('/', dirname($node->getPath()), 4);
  174. if (isset($parts[3])) {
  175. $file['path'] = '/' . $parts[3];
  176. } else {
  177. $file['path'] = '/';
  178. }
  179. if (!empty($shareTypes)) {
  180. $file['shareTypes'] = $shareTypes;
  181. }
  182. return $file;
  183. }, $nodes));
  184. }
  185. /**
  186. * Get the share types for each node
  187. *
  188. * @param \OCP\Files\Node[] $nodes
  189. * @return array<int, int[]> list of share types for each fileid
  190. */
  191. private function getShareTypesForNodes(array $nodes): array {
  192. $userId = $this->userSession->getUser()->getUID();
  193. $requestedShareTypes = [
  194. IShare::TYPE_USER,
  195. IShare::TYPE_GROUP,
  196. IShare::TYPE_LINK,
  197. IShare::TYPE_REMOTE,
  198. IShare::TYPE_EMAIL,
  199. IShare::TYPE_ROOM,
  200. IShare::TYPE_DECK,
  201. IShare::TYPE_SCIENCEMESH,
  202. ];
  203. $shareTypes = [];
  204. $nodeIds = array_map(function (Node $node) {
  205. return $node->getId();
  206. }, $nodes);
  207. foreach ($requestedShareTypes as $shareType) {
  208. $nodesLeft = array_combine($nodeIds, array_fill(0, count($nodeIds), true));
  209. $offset = 0;
  210. // fetch shares until we've either found shares for all nodes or there are no more shares left
  211. while (count($nodesLeft) > 0) {
  212. $shares = $this->shareManager->getSharesBy($userId, $shareType, null, false, 100, $offset);
  213. foreach ($shares as $share) {
  214. $fileId = $share->getNodeId();
  215. if (isset($nodesLeft[$fileId])) {
  216. if (!isset($shareTypes[$fileId])) {
  217. $shareTypes[$fileId] = [];
  218. }
  219. $shareTypes[$fileId][] = $shareType;
  220. unset($nodesLeft[$fileId]);
  221. }
  222. }
  223. if (count($shares) < 100) {
  224. break;
  225. } else {
  226. $offset += count($shares);
  227. }
  228. }
  229. }
  230. return $shareTypes;
  231. }
  232. /**
  233. * Returns a list of recently modified files.
  234. *
  235. * @NoAdminRequired
  236. *
  237. * @return DataResponse
  238. */
  239. public function getRecentFiles() {
  240. $nodes = $this->userFolder->getRecent(100);
  241. $files = $this->formatNodes($nodes);
  242. return new DataResponse(['files' => $files]);
  243. }
  244. /**
  245. * Returns the current logged-in user's storage stats.
  246. *
  247. * @NoAdminRequired
  248. *
  249. * @param ?string $dir the directory to get the storage stats from
  250. * @return JSONResponse
  251. */
  252. public function getStorageStats($dir = '/'): JSONResponse {
  253. $storageInfo = \OC_Helper::getStorageInfo($dir ?: '/');
  254. return new JSONResponse(['message' => 'ok', 'data' => $storageInfo]);
  255. }
  256. /**
  257. * Set a user view config
  258. *
  259. * @NoAdminRequired
  260. *
  261. * @param string $view
  262. * @param string $key
  263. * @param string|bool $value
  264. * @return JSONResponse
  265. */
  266. public function setViewConfig(string $view, string $key, $value): JSONResponse {
  267. try {
  268. $this->viewConfig->setConfig($view, $key, (string)$value);
  269. } catch (\InvalidArgumentException $e) {
  270. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  271. }
  272. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfig($view)]);
  273. }
  274. /**
  275. * Get the user view config
  276. *
  277. * @NoAdminRequired
  278. *
  279. * @return JSONResponse
  280. */
  281. public function getViewConfigs(): JSONResponse {
  282. return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfigs()]);
  283. }
  284. /**
  285. * Set a user config
  286. *
  287. * @NoAdminRequired
  288. *
  289. * @param string $key
  290. * @param string|bool $value
  291. * @return JSONResponse
  292. */
  293. public function setConfig(string $key, $value): JSONResponse {
  294. try {
  295. $this->userConfig->setConfig($key, (string)$value);
  296. } catch (\InvalidArgumentException $e) {
  297. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  298. }
  299. return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
  300. }
  301. /**
  302. * Get the user config
  303. *
  304. * @NoAdminRequired
  305. *
  306. * @return JSONResponse
  307. */
  308. public function getConfigs(): JSONResponse {
  309. return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
  310. }
  311. /**
  312. * Toggle default for showing/hiding hidden files
  313. *
  314. * @NoAdminRequired
  315. *
  316. * @param bool $value
  317. * @return Response
  318. * @throws \OCP\PreConditionNotMetException
  319. */
  320. public function showHiddenFiles(bool $value): Response {
  321. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
  322. return new Response();
  323. }
  324. /**
  325. * Toggle default for cropping preview images
  326. *
  327. * @NoAdminRequired
  328. *
  329. * @param bool $value
  330. * @return Response
  331. * @throws \OCP\PreConditionNotMetException
  332. */
  333. public function cropImagePreviews(bool $value): Response {
  334. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
  335. return new Response();
  336. }
  337. /**
  338. * Toggle default for files grid view
  339. *
  340. * @NoAdminRequired
  341. *
  342. * @param bool $show
  343. * @return Response
  344. * @throws \OCP\PreConditionNotMetException
  345. */
  346. public function showGridView(bool $show): Response {
  347. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
  348. return new Response();
  349. }
  350. /**
  351. * Get default settings for the grid view
  352. *
  353. * @NoAdminRequired
  354. */
  355. public function getGridView() {
  356. $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
  357. return new JSONResponse(['gridview' => $status]);
  358. }
  359. /**
  360. * @NoAdminRequired
  361. * @NoCSRFRequired
  362. * @PublicPage
  363. */
  364. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  365. public function serviceWorker(): StreamResponse {
  366. $response = new StreamResponse(__DIR__ . '/../../../../dist/preview-service-worker.js');
  367. $response->setHeaders([
  368. 'Content-Type' => 'application/javascript',
  369. 'Service-Worker-Allowed' => '/'
  370. ]);
  371. $policy = new ContentSecurityPolicy();
  372. $policy->addAllowedWorkerSrcDomain("'self'");
  373. $policy->addAllowedScriptDomain("'self'");
  374. $policy->addAllowedConnectDomain("'self'");
  375. $response->setContentSecurityPolicy($policy);
  376. return $response;
  377. }
  378. }