StoragesController.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Jesús Macias <jmacias@solidgear.es>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Robin McCorkell <robin@mccorkell.me.uk>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Vincent Petry <vincent@nextcloud.com>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\Files_External\Controller;
  30. use OCA\Files_External\Lib\Auth\AuthMechanism;
  31. use OCA\Files_External\Lib\Backend\Backend;
  32. use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
  33. use OCA\Files_External\Lib\StorageConfig;
  34. use OCA\Files_External\NotFoundException;
  35. use OCA\Files_External\Service\StoragesService;
  36. use OCP\AppFramework\Controller;
  37. use OCP\AppFramework\Http;
  38. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  39. use OCP\AppFramework\Http\DataResponse;
  40. use OCP\Files\StorageNotAvailableException;
  41. use OCP\IConfig;
  42. use OCP\IGroupManager;
  43. use OCP\IL10N;
  44. use OCP\IRequest;
  45. use OCP\IUserSession;
  46. use Psr\Log\LoggerInterface;
  47. /**
  48. * Base class for storages controllers
  49. */
  50. abstract class StoragesController extends Controller {
  51. /**
  52. * Creates a new storages controller.
  53. *
  54. * @param string $AppName application name
  55. * @param IRequest $request request object
  56. * @param IL10N $l10n l10n service
  57. * @param StoragesService $storagesService storage service
  58. * @param LoggerInterface $logger
  59. */
  60. public function __construct(
  61. $AppName,
  62. IRequest $request,
  63. protected IL10N $l10n,
  64. protected StoragesService $service,
  65. protected LoggerInterface $logger,
  66. protected IUserSession $userSession,
  67. protected IGroupManager $groupManager,
  68. protected IConfig $config
  69. ) {
  70. parent::__construct($AppName, $request);
  71. }
  72. /**
  73. * Create a storage from its parameters
  74. *
  75. * @param string $mountPoint storage mount point
  76. * @param string $backend backend identifier
  77. * @param string $authMechanism authentication mechanism identifier
  78. * @param array $backendOptions backend-specific options
  79. * @param array|null $mountOptions mount-specific options
  80. * @param array|null $applicableUsers users for which to mount the storage
  81. * @param array|null $applicableGroups groups for which to mount the storage
  82. * @param int|null $priority priority
  83. *
  84. * @return StorageConfig|DataResponse
  85. */
  86. protected function createStorage(
  87. $mountPoint,
  88. $backend,
  89. $authMechanism,
  90. $backendOptions,
  91. $mountOptions = null,
  92. $applicableUsers = null,
  93. $applicableGroups = null,
  94. $priority = null
  95. ) {
  96. $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
  97. if (!$canCreateNewLocalStorage && $backend === 'local') {
  98. return new DataResponse(
  99. [
  100. 'message' => $this->l10n->t('Forbidden to manage local mounts')
  101. ],
  102. Http::STATUS_FORBIDDEN
  103. );
  104. }
  105. try {
  106. return $this->service->createStorage(
  107. $mountPoint,
  108. $backend,
  109. $authMechanism,
  110. $backendOptions,
  111. $mountOptions,
  112. $applicableUsers,
  113. $applicableGroups,
  114. $priority
  115. );
  116. } catch (\InvalidArgumentException $e) {
  117. $this->logger->error($e->getMessage(), ['exception' => $e]);
  118. return new DataResponse(
  119. [
  120. 'message' => $this->l10n->t('Invalid backend or authentication mechanism class')
  121. ],
  122. Http::STATUS_UNPROCESSABLE_ENTITY
  123. );
  124. }
  125. }
  126. /**
  127. * Validate storage config
  128. *
  129. * @param StorageConfig $storage storage config
  130. *1
  131. * @return DataResponse|null returns response in case of validation error
  132. */
  133. protected function validate(StorageConfig $storage) {
  134. $mountPoint = $storage->getMountPoint();
  135. if ($mountPoint === '') {
  136. return new DataResponse(
  137. [
  138. 'message' => $this->l10n->t('Invalid mount point'),
  139. ],
  140. Http::STATUS_UNPROCESSABLE_ENTITY
  141. );
  142. }
  143. if ($storage->getBackendOption('objectstore')) {
  144. // objectstore must not be sent from client side
  145. return new DataResponse(
  146. [
  147. 'message' => $this->l10n->t('Objectstore forbidden'),
  148. ],
  149. Http::STATUS_UNPROCESSABLE_ENTITY
  150. );
  151. }
  152. /** @var Backend */
  153. $backend = $storage->getBackend();
  154. /** @var AuthMechanism */
  155. $authMechanism = $storage->getAuthMechanism();
  156. if ($backend->checkDependencies()) {
  157. // invalid backend
  158. return new DataResponse(
  159. [
  160. 'message' => $this->l10n->t('Invalid storage backend "%s"', [
  161. $backend->getIdentifier(),
  162. ]),
  163. ],
  164. Http::STATUS_UNPROCESSABLE_ENTITY
  165. );
  166. }
  167. if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
  168. // not permitted to use backend
  169. return new DataResponse(
  170. [
  171. 'message' => $this->l10n->t('Not permitted to use backend "%s"', [
  172. $backend->getIdentifier(),
  173. ]),
  174. ],
  175. Http::STATUS_UNPROCESSABLE_ENTITY
  176. );
  177. }
  178. if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
  179. // not permitted to use auth mechanism
  180. return new DataResponse(
  181. [
  182. 'message' => $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
  183. $authMechanism->getIdentifier(),
  184. ]),
  185. ],
  186. Http::STATUS_UNPROCESSABLE_ENTITY
  187. );
  188. }
  189. if (!$backend->validateStorage($storage)) {
  190. // unsatisfied parameters
  191. return new DataResponse(
  192. [
  193. 'message' => $this->l10n->t('Unsatisfied backend parameters'),
  194. ],
  195. Http::STATUS_UNPROCESSABLE_ENTITY
  196. );
  197. }
  198. if (!$authMechanism->validateStorage($storage)) {
  199. // unsatisfied parameters
  200. return new DataResponse(
  201. [
  202. 'message' => $this->l10n->t('Unsatisfied authentication mechanism parameters'),
  203. ],
  204. Http::STATUS_UNPROCESSABLE_ENTITY
  205. );
  206. }
  207. return null;
  208. }
  209. protected function manipulateStorageConfig(StorageConfig $storage) {
  210. /** @var AuthMechanism */
  211. $authMechanism = $storage->getAuthMechanism();
  212. $authMechanism->manipulateStorageConfig($storage);
  213. /** @var Backend */
  214. $backend = $storage->getBackend();
  215. $backend->manipulateStorageConfig($storage);
  216. }
  217. /**
  218. * Check whether the given storage is available / valid.
  219. *
  220. * Note that this operation can be time consuming depending
  221. * on whether the remote storage is available or not.
  222. *
  223. * @param StorageConfig $storage storage configuration
  224. * @param bool $testOnly whether to storage should only test the connection or do more things
  225. */
  226. protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
  227. try {
  228. $this->manipulateStorageConfig($storage);
  229. /** @var Backend */
  230. $backend = $storage->getBackend();
  231. // update status (can be time-consuming)
  232. $storage->setStatus(
  233. \OCA\Files_External\MountConfig::getBackendStatus(
  234. $backend->getStorageClass(),
  235. $storage->getBackendOptions(),
  236. false,
  237. $testOnly
  238. )
  239. );
  240. } catch (InsufficientDataForMeaningfulAnswerException $e) {
  241. $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
  242. $storage->setStatus(
  243. (int)$status,
  244. $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
  245. );
  246. } catch (StorageNotAvailableException $e) {
  247. $storage->setStatus(
  248. (int)$e->getCode(),
  249. $this->l10n->t('%s', [$e->getMessage()])
  250. );
  251. } catch (\Exception $e) {
  252. // FIXME: convert storage exceptions to StorageNotAvailableException
  253. $storage->setStatus(
  254. StorageNotAvailableException::STATUS_ERROR,
  255. get_class($e) . ': ' . $e->getMessage()
  256. );
  257. }
  258. }
  259. /**
  260. * Get all storage entries
  261. *
  262. * @return DataResponse
  263. */
  264. public function index() {
  265. $storages = array_map(static fn ($storage) => $storage->jsonSerialize(true), $this->service->getStorages());
  266. return new DataResponse(
  267. $storages,
  268. Http::STATUS_OK
  269. );
  270. }
  271. /**
  272. * Get an external storage entry.
  273. *
  274. * @param int $id storage id
  275. * @param bool $testOnly whether to storage should only test the connection or do more things
  276. *
  277. * @return DataResponse
  278. */
  279. public function show(int $id, $testOnly = true) {
  280. try {
  281. $storage = $this->service->getStorage($id);
  282. $this->updateStorageStatus($storage, $testOnly);
  283. } catch (NotFoundException $e) {
  284. return new DataResponse(
  285. [
  286. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  287. ],
  288. Http::STATUS_NOT_FOUND
  289. );
  290. }
  291. $data = $storage->jsonSerialize(true);
  292. $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
  293. $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAl || $isAdmin;
  294. return new DataResponse(
  295. $data,
  296. Http::STATUS_OK
  297. );
  298. }
  299. /**
  300. * Deletes the storage with the given id.
  301. *
  302. * @param int $id storage id
  303. *
  304. * @return DataResponse
  305. */
  306. #[PasswordConfirmationRequired]
  307. public function destroy(int $id) {
  308. try {
  309. $this->service->removeStorage($id);
  310. } catch (NotFoundException $e) {
  311. return new DataResponse(
  312. [
  313. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  314. ],
  315. Http::STATUS_NOT_FOUND
  316. );
  317. }
  318. return new DataResponse([], Http::STATUS_NO_CONTENT);
  319. }
  320. }