StoragesController.php 11 KB

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