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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. * Change the default sort mode
  246. *
  247. * @NoAdminRequired
  248. *
  249. * @param string $mode
  250. * @param string $direction
  251. * @return Response
  252. * @throws \OCP\PreConditionNotMetException
  253. */
  254. public function updateFileSorting($mode, $direction) {
  255. $allowedMode = ['name', 'size', 'mtime'];
  256. $allowedDirection = ['asc', 'desc'];
  257. if (!in_array($mode, $allowedMode) || !in_array($direction, $allowedDirection)) {
  258. $response = new Response();
  259. $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
  260. return $response;
  261. }
  262. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting', $mode);
  263. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting_direction', $direction);
  264. return new Response();
  265. }
  266. /**
  267. * Toggle default files user config
  268. *
  269. * @NoAdminRequired
  270. *
  271. * @param string $key
  272. * @param string|bool $value
  273. * @return JSONResponse
  274. */
  275. public function setConfig(string $key, string|bool $value): JSONResponse {
  276. try {
  277. $this->userConfig->setConfig($key, (string)$value);
  278. } catch (\InvalidArgumentException $e) {
  279. return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  280. }
  281. return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
  282. }
  283. /**
  284. * Get the user config
  285. *
  286. * @NoAdminRequired
  287. *
  288. * @return JSONResponse
  289. */
  290. public function getConfigs(): JSONResponse {
  291. return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
  292. }
  293. /**
  294. * Toggle default for showing/hiding hidden files
  295. *
  296. * @NoAdminRequired
  297. *
  298. * @param bool $value
  299. * @return Response
  300. * @throws \OCP\PreConditionNotMetException
  301. */
  302. public function showHiddenFiles(bool $value): Response {
  303. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
  304. return new Response();
  305. }
  306. /**
  307. * Toggle default for cropping preview images
  308. *
  309. * @NoAdminRequired
  310. *
  311. * @param bool $value
  312. * @return Response
  313. * @throws \OCP\PreConditionNotMetException
  314. */
  315. public function cropImagePreviews(bool $value): Response {
  316. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
  317. return new Response();
  318. }
  319. /**
  320. * Toggle default for files grid view
  321. *
  322. * @NoAdminRequired
  323. *
  324. * @param bool $show
  325. * @return Response
  326. * @throws \OCP\PreConditionNotMetException
  327. */
  328. public function showGridView(bool $show): Response {
  329. $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
  330. return new Response();
  331. }
  332. /**
  333. * Get default settings for the grid view
  334. *
  335. * @NoAdminRequired
  336. */
  337. public function getGridView() {
  338. $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
  339. return new JSONResponse(['gridview' => $status]);
  340. }
  341. /**
  342. * Toggle default for showing/hiding xxx folder
  343. *
  344. * @NoAdminRequired
  345. *
  346. * @param int $show
  347. * @param string $key the key of the folder
  348. *
  349. * @return Response
  350. * @throws \OCP\PreConditionNotMetException
  351. */
  352. public function toggleShowFolder(int $show, string $key): Response {
  353. if ($show !== 0 && $show !== 1) {
  354. return new DataResponse([
  355. 'message' => 'Invalid show value. Only 0 and 1 are allowed.'
  356. ], Http::STATUS_BAD_REQUEST);
  357. }
  358. $userId = $this->userSession->getUser()->getUID();
  359. // Set the new value and return it
  360. // Using a prefix prevents the user from setting arbitrary keys
  361. $this->config->setUserValue($userId, 'files', 'show_' . $key, (string)$show);
  362. return new JSONResponse([$key => $show]);
  363. }
  364. /**
  365. * Get sorting-order for custom sorting
  366. *
  367. * @NoAdminRequired
  368. *
  369. * @param string $folderpath
  370. * @return string
  371. * @throws \OCP\Files\NotFoundException
  372. */
  373. public function getNodeType($folderpath) {
  374. $node = $this->userFolder->get($folderpath);
  375. return $node->getType();
  376. }
  377. }