StoragesController.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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\DataResponse;
  39. use OCP\Files\StorageNotAvailableException;
  40. use OCP\IConfig;
  41. use OCP\IGroupManager;
  42. use OCP\IL10N;
  43. use OCP\IRequest;
  44. use OCP\IUserSession;
  45. use Psr\Log\LoggerInterface;
  46. /**
  47. * Base class for storages controllers
  48. */
  49. abstract class StoragesController extends Controller {
  50. /**
  51. * Creates a new storages controller.
  52. *
  53. * @param string $AppName application name
  54. * @param IRequest $request request object
  55. * @param IL10N $l10n l10n service
  56. * @param StoragesService $storagesService storage service
  57. * @param LoggerInterface $logger
  58. */
  59. public function __construct(
  60. $AppName,
  61. IRequest $request,
  62. protected IL10N $l10n,
  63. protected StoragesService $service,
  64. protected LoggerInterface $logger,
  65. protected IUserSession $userSession,
  66. protected IGroupManager $groupManager,
  67. protected IConfig $config
  68. ) {
  69. parent::__construct($AppName, $request);
  70. }
  71. /**
  72. * Create a storage from its parameters
  73. *
  74. * @param string $mountPoint storage mount point
  75. * @param string $backend backend identifier
  76. * @param string $authMechanism authentication mechanism identifier
  77. * @param array $backendOptions backend-specific options
  78. * @param array|null $mountOptions mount-specific options
  79. * @param array|null $applicableUsers users for which to mount the storage
  80. * @param array|null $applicableGroups groups for which to mount the storage
  81. * @param int|null $priority priority
  82. *
  83. * @return StorageConfig|DataResponse
  84. */
  85. protected function createStorage(
  86. $mountPoint,
  87. $backend,
  88. $authMechanism,
  89. $backendOptions,
  90. $mountOptions = null,
  91. $applicableUsers = null,
  92. $applicableGroups = null,
  93. $priority = null
  94. ) {
  95. $canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);
  96. if (!$canCreateNewLocalStorage && $backend === 'local') {
  97. return new DataResponse(
  98. [
  99. 'message' => $this->l10n->t('Forbidden to manage local mounts')
  100. ],
  101. Http::STATUS_FORBIDDEN
  102. );
  103. }
  104. try {
  105. return $this->service->createStorage(
  106. $mountPoint,
  107. $backend,
  108. $authMechanism,
  109. $backendOptions,
  110. $mountOptions,
  111. $applicableUsers,
  112. $applicableGroups,
  113. $priority
  114. );
  115. } catch (\InvalidArgumentException $e) {
  116. $this->logger->error($e->getMessage(), ['exception' => $e]);
  117. return new DataResponse(
  118. [
  119. 'message' => $this->l10n->t('Invalid backend or authentication mechanism class')
  120. ],
  121. Http::STATUS_UNPROCESSABLE_ENTITY
  122. );
  123. }
  124. }
  125. /**
  126. * Validate storage config
  127. *
  128. * @param StorageConfig $storage storage config
  129. *1
  130. * @return DataResponse|null returns response in case of validation error
  131. */
  132. protected function validate(StorageConfig $storage) {
  133. $mountPoint = $storage->getMountPoint();
  134. if ($mountPoint === '') {
  135. return new DataResponse(
  136. [
  137. 'message' => $this->l10n->t('Invalid mount point'),
  138. ],
  139. Http::STATUS_UNPROCESSABLE_ENTITY
  140. );
  141. }
  142. if ($storage->getBackendOption('objectstore')) {
  143. // objectstore must not be sent from client side
  144. return new DataResponse(
  145. [
  146. 'message' => $this->l10n->t('Objectstore forbidden'),
  147. ],
  148. Http::STATUS_UNPROCESSABLE_ENTITY
  149. );
  150. }
  151. /** @var Backend */
  152. $backend = $storage->getBackend();
  153. /** @var AuthMechanism */
  154. $authMechanism = $storage->getAuthMechanism();
  155. if ($backend->checkDependencies()) {
  156. // invalid backend
  157. return new DataResponse(
  158. [
  159. 'message' => $this->l10n->t('Invalid storage backend "%s"', [
  160. $backend->getIdentifier(),
  161. ]),
  162. ],
  163. Http::STATUS_UNPROCESSABLE_ENTITY
  164. );
  165. }
  166. if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
  167. // not permitted to use backend
  168. return new DataResponse(
  169. [
  170. 'message' => $this->l10n->t('Not permitted to use backend "%s"', [
  171. $backend->getIdentifier(),
  172. ]),
  173. ],
  174. Http::STATUS_UNPROCESSABLE_ENTITY
  175. );
  176. }
  177. if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
  178. // not permitted to use auth mechanism
  179. return new DataResponse(
  180. [
  181. 'message' => $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
  182. $authMechanism->getIdentifier(),
  183. ]),
  184. ],
  185. Http::STATUS_UNPROCESSABLE_ENTITY
  186. );
  187. }
  188. if (!$backend->validateStorage($storage)) {
  189. // unsatisfied parameters
  190. return new DataResponse(
  191. [
  192. 'message' => $this->l10n->t('Unsatisfied backend parameters'),
  193. ],
  194. Http::STATUS_UNPROCESSABLE_ENTITY
  195. );
  196. }
  197. if (!$authMechanism->validateStorage($storage)) {
  198. // unsatisfied parameters
  199. return new DataResponse(
  200. [
  201. 'message' => $this->l10n->t('Unsatisfied authentication mechanism parameters'),
  202. ],
  203. Http::STATUS_UNPROCESSABLE_ENTITY
  204. );
  205. }
  206. return null;
  207. }
  208. protected function manipulateStorageConfig(StorageConfig $storage) {
  209. /** @var AuthMechanism */
  210. $authMechanism = $storage->getAuthMechanism();
  211. $authMechanism->manipulateStorageConfig($storage);
  212. /** @var Backend */
  213. $backend = $storage->getBackend();
  214. $backend->manipulateStorageConfig($storage);
  215. }
  216. /**
  217. * Check whether the given storage is available / valid.
  218. *
  219. * Note that this operation can be time consuming depending
  220. * on whether the remote storage is available or not.
  221. *
  222. * @param StorageConfig $storage storage configuration
  223. * @param bool $testOnly whether to storage should only test the connection or do more things
  224. */
  225. protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
  226. try {
  227. $this->manipulateStorageConfig($storage);
  228. /** @var Backend */
  229. $backend = $storage->getBackend();
  230. // update status (can be time-consuming)
  231. $storage->setStatus(
  232. \OCA\Files_External\MountConfig::getBackendStatus(
  233. $backend->getStorageClass(),
  234. $storage->getBackendOptions(),
  235. false,
  236. $testOnly
  237. )
  238. );
  239. } catch (InsufficientDataForMeaningfulAnswerException $e) {
  240. $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
  241. $storage->setStatus(
  242. (int)$status,
  243. $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
  244. );
  245. } catch (StorageNotAvailableException $e) {
  246. $storage->setStatus(
  247. (int)$e->getCode(),
  248. $this->l10n->t('%s', [$e->getMessage()])
  249. );
  250. } catch (\Exception $e) {
  251. // FIXME: convert storage exceptions to StorageNotAvailableException
  252. $storage->setStatus(
  253. StorageNotAvailableException::STATUS_ERROR,
  254. get_class($e) . ': ' . $e->getMessage()
  255. );
  256. }
  257. }
  258. /**
  259. * Get all storage entries
  260. *
  261. * @return DataResponse
  262. */
  263. public function index() {
  264. $storages = array_map(static fn ($storage) => $storage->jsonSerialize(true), $this->service->getStorages());
  265. return new DataResponse(
  266. $storages,
  267. Http::STATUS_OK
  268. );
  269. }
  270. /**
  271. * Get an external storage entry.
  272. *
  273. * @param int $id storage id
  274. * @param bool $testOnly whether to storage should only test the connection or do more things
  275. *
  276. * @return DataResponse
  277. */
  278. public function show($id, $testOnly = true) {
  279. try {
  280. $storage = $this->service->getStorage($id);
  281. $this->updateStorageStatus($storage, $testOnly);
  282. } catch (NotFoundException $e) {
  283. return new DataResponse(
  284. [
  285. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  286. ],
  287. Http::STATUS_NOT_FOUND
  288. );
  289. }
  290. $data = $storage->jsonSerialize(true);
  291. $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
  292. $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAL || $isAdmin;
  293. return new DataResponse(
  294. $data,
  295. Http::STATUS_OK
  296. );
  297. }
  298. /**
  299. * Deletes the storage with the given id.
  300. *
  301. * @param int $id storage id
  302. *
  303. * @return DataResponse
  304. */
  305. public function destroy($id) {
  306. try {
  307. $this->service->removeStorage($id);
  308. } catch (NotFoundException $e) {
  309. return new DataResponse(
  310. [
  311. 'message' => $this->l10n->t('Storage with ID "%d" not found', [$id]),
  312. ],
  313. Http::STATUS_NOT_FOUND
  314. );
  315. }
  316. return new DataResponse([], Http::STATUS_NO_CONTENT);
  317. }
  318. }