You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ApiController.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 OCP\AppFramework\Controller;
  43. use OCP\AppFramework\Http;
  44. use OCP\AppFramework\Http\DataResponse;
  45. use OCP\AppFramework\Http\FileDisplayResponse;
  46. use OCP\AppFramework\Http\JSONResponse;
  47. use OCP\AppFramework\Http\Response;
  48. use OCP\Files\File;
  49. use OCP\Files\Folder;
  50. use OCP\Files\NotFoundException;
  51. use OCP\IConfig;
  52. use OCP\IPreview;
  53. use OCP\IRequest;
  54. use OCP\IUserSession;
  55. use OCP\Share\IManager;
  56. use OCP\Share\IShare;
  57. /**
  58. * Class ApiController
  59. *
  60. * @package OCA\Files\Controller
  61. */
  62. class ApiController extends Controller {
  63. private TagService $tagService;
  64. private IManager $shareManager;
  65. private IPreview $previewManager;
  66. private IUserSession $userSession;
  67. private IConfig $config;
  68. private Folder $userFolder;
  69. private UserConfig $userConfig;
  70. /**
  71. * @param string $appName
  72. * @param IRequest $request
  73. * @param IUserSession $userSession
  74. * @param TagService $tagService
  75. * @param IPreview $previewManager
  76. * @param IManager $shareManager
  77. * @param IConfig $config
  78. * @param Folder $userFolder
  79. */
  80. public function __construct($appName,
  81. IRequest $request,
  82. IUserSession $userSession,
  83. TagService $tagService,
  84. IPreview $previewManager,
  85. IManager $shareManager,
  86. IConfig $config,
  87. Folder $userFolder,
  88. UserConfig $userConfig) {
  89. parent::__construct($appName, $request);
  90. $this->userSession = $userSession;
  91. $this->tagService = $tagService;
  92. $this->previewManager = $previewManager;
  93. $this->shareManager = $shareManager;
  94. $this->config = $config;
  95. $this->userFolder = $userFolder;
  96. $this->userConfig = $userConfig;
  97. }
  98. /**
  99. * Gets a thumbnail of the specified file
  100. *
  101. * @since API version 1.0
  102. *
  103. * @NoAdminRequired
  104. * @NoCSRFRequired
  105. * @StrictCookieRequired
  106. *
  107. * @param int $x
  108. * @param int $y
  109. * @param string $file URL-encoded filename
  110. * @return DataResponse|FileDisplayResponse
  111. */
  112. public function getThumbnail($x, $y, $file) {
  113. if ($x < 1 || $y < 1) {
  114. return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
  115. }
  116. try {
  117. $file = $this->userFolder->get($file);
  118. if ($file instanceof Folder) {
  119. throw new NotFoundException();
  120. }
  121. /** @var File $file */
  122. $preview = $this->previewManager->getPreview($file, $x, $y, true);
  123. return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
  124. } catch (NotFoundException $e) {
  125. return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
  126. } catch (\Exception $e) {
  127. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  128. }
  129. }
  130. /**
  131. * Updates the info of the specified file path
  132. * The passed tags are absolute, which means they will
  133. * replace the actual tag selection.
  134. *
  135. * @NoAdminRequired
  136. *
  137. * @param string $path path
  138. * @param array|string $tags array of tags
  139. * @return DataResponse
  140. */
  141. public function updateFileTags($path, $tags = null) {
  142. $result = [];
  143. // if tags specified or empty array, update tags
  144. if (!is_null($tags)) {
  145. try {
  146. $this->tagService->updateFileTags($path, $tags);
  147. } catch (\OCP\Files\NotFoundException $e) {
  148. return new DataResponse([
  149. 'message' => $e->getMessage()
  150. ], Http::STATUS_NOT_FOUND);
  151. } catch (\OCP\Files\StorageNotAvailableException $e) {
  152. return new DataResponse([
  153. 'message' => $e->getMessage()
  154. ], Http::STATUS_SERVICE_UNAVAILABLE);
  155. } catch (\Exception $e) {
  156. return new DataResponse([
  157. 'message' => $e->getMessage()
  158. ], Http::STATUS_NOT_FOUND);
  159. }
  160. $result['tags'] = $tags;
  161. }
  162. return new DataResponse($result);
  163. }
  164. /**
  165. * @param \OCP\Files\Node[] $nodes
  166. * @return array
  167. */
  168. private function formatNodes(array $nodes) {
  169. $shareTypesForNodes = $this->getShareTypesForNodes($nodes);
  170. return array_values(array_map(function (Node $node) use ($shareTypesForNodes) {
  171. $shareTypes = $shareTypesForNodes[$node->getId()] ?? [];
  172. $file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
  173. $file['hasPreview'] = $this->previewManager->isAvailable($node);
  174. $parts = explode('/', dirname($node->getPath()), 4);
  175. if (isset($parts[3])) {
  176. $file['path'] = '/' . $parts[3];
  177. } else {
  178. $file['path'] = '/';
  179. }
  180. if (!empty($shareTypes)) {
  181. $file['shareTypes'] = $shareTypes;
  182. }
  183. return $file;
  184. }, $nodes));
  185. }
  186. /**
  187. * Get the share types for each node
  188. *
  189. * @param \OCP\Files\Node[] $nodes
  190. * @return array<int, int[]> list of share types for each fileid
  191. */
  192. private function getShareTypesForNodes(array $nodes): array {
  193. $userId = $this->userSession->getUser()->getUID();
  194. $requestedShareTypes = [
  195. IShare::TYPE_USER,
  196. IShare::TYPE_GROUP,
  197. IShare::TYPE_LINK,
  198. IShare::TYPE_REMOTE,
  199. IShare::TYPE_EMAIL,
  200. IShare::TYPE_ROOM,
  201. IShare::TYPE_DECK,
  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. * Change the default sort mode
  258. *
  259. * @NoAdminRequired
  260. *
  261. * @param string $mode
  262. * @param string $direction
  263. * @return Response
  264. * @throws \OCP\PreConditionNotMetException
  265. */
  266. public function updateFileSorting($mode, $direction) {
  267. $allowedMode = ['name', 'size', 'mtime'];
  268. $allowedDirection = ['asc', 'desc'];
  269. if (!in_array($mode, $allowedMode) || !in_array($direction, $allowedDirection)) {
  270. $response = new Response();
  271. $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
  272. return $response;
  273. }
  274. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting', $mode);
  275. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting_direction', $direction);
  276. return new Response();
  277. }
  278. /**
  279. * Toggle default files user config
  280. *
  281. * @NoAdminRequired
  282. *
  283. * @param string $key
  284. * @param string|bool $value
  285. * @return JSONResponse
  286. */
  287. public function setConfig(string $key, $value): JSONResponse {
  288. try {
  289. $this->userConfig->setConfig($key, (string)$value);
  290. } catch (\InvalidArgumentException $e) {
  291. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  292. }
  293. return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
  294. }
  295. /**
  296. * Get the user config
  297. *
  298. * @NoAdminRequired
  299. *
  300. * @return JSONResponse
  301. */
  302. public function getConfigs(): JSONResponse {
  303. return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
  304. }
  305. /**
  306. * Toggle default for showing/hiding hidden files
  307. *
  308. * @NoAdminRequired
  309. *
  310. * @param bool $value
  311. * @return Response
  312. * @throws \OCP\PreConditionNotMetException
  313. */
  314. public function showHiddenFiles(bool $value): Response {
  315. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
  316. return new Response();
  317. }
  318. /**
  319. * Toggle default for cropping preview images
  320. *
  321. * @NoAdminRequired
  322. *
  323. * @param bool $value
  324. * @return Response
  325. * @throws \OCP\PreConditionNotMetException
  326. */
  327. public function cropImagePreviews(bool $value): Response {
  328. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
  329. return new Response();
  330. }
  331. /**
  332. * Toggle default for files grid view
  333. *
  334. * @NoAdminRequired
  335. *
  336. * @param bool $show
  337. * @return Response
  338. * @throws \OCP\PreConditionNotMetException
  339. */
  340. public function showGridView(bool $show): Response {
  341. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
  342. return new Response();
  343. }
  344. /**
  345. * Get default settings for the grid view
  346. *
  347. * @NoAdminRequired
  348. */
  349. public function getGridView() {
  350. $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
  351. return new JSONResponse(['gridview' => $status]);
  352. }
  353. /**
  354. * Toggle default for showing/hiding xxx folder
  355. *
  356. * @NoAdminRequired
  357. *
  358. * @param int $show
  359. * @param string $key the key of the folder
  360. *
  361. * @return Response
  362. * @throws \OCP\PreConditionNotMetException
  363. */
  364. public function toggleShowFolder(int $show, string $key): Response {
  365. if ($show !== 0 && $show !== 1) {
  366. return new DataResponse([
  367. 'message' => 'Invalid show value. Only 0 and 1 are allowed.'
  368. ], Http::STATUS_BAD_REQUEST);
  369. }
  370. $userId = $this->userSession->getUser()->getUID();
  371. // Set the new value and return it
  372. // Using a prefix prevents the user from setting arbitrary keys
  373. $this->config->setUserValue($userId, 'files', 'show_' . $key, (string)$show);
  374. return new JSONResponse([$key => $show]);
  375. }
  376. /**
  377. * Get sorting-order for custom sorting
  378. *
  379. * @NoAdminRequired
  380. *
  381. * @param string $folderpath
  382. * @return string
  383. * @throws \OCP\Files\NotFoundException
  384. */
  385. public function getNodeType($folderpath) {
  386. $node = $this->userFolder->get($folderpath);
  387. return $node->getType();
  388. }
  389. }