Notifications.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. *
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OCA\FederatedFileSharing;
  25. use OCP\AppFramework\Http;
  26. use OCP\BackgroundJob\IJobList;
  27. use OCP\Federation\ICloudFederationFactory;
  28. use OCP\Federation\ICloudFederationProviderManager;
  29. use OCP\Http\Client\IClientService;
  30. use OCP\OCS\IDiscoveryService;
  31. class Notifications {
  32. const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
  33. /** @var AddressHandler */
  34. private $addressHandler;
  35. /** @var IClientService */
  36. private $httpClientService;
  37. /** @var IDiscoveryService */
  38. private $discoveryService;
  39. /** @var IJobList */
  40. private $jobList;
  41. /** @var ICloudFederationProviderManager */
  42. private $federationProviderManager;
  43. /** @var ICloudFederationFactory */
  44. private $cloudFederationFactory;
  45. /**
  46. * @param AddressHandler $addressHandler
  47. * @param IClientService $httpClientService
  48. * @param IDiscoveryService $discoveryService
  49. * @param IJobList $jobList
  50. * @param ICloudFederationProviderManager $federationProviderManager
  51. * @param ICloudFederationFactory $cloudFederationFactory
  52. */
  53. public function __construct(
  54. AddressHandler $addressHandler,
  55. IClientService $httpClientService,
  56. IDiscoveryService $discoveryService,
  57. IJobList $jobList,
  58. ICloudFederationProviderManager $federationProviderManager,
  59. ICloudFederationFactory $cloudFederationFactory
  60. ) {
  61. $this->addressHandler = $addressHandler;
  62. $this->httpClientService = $httpClientService;
  63. $this->discoveryService = $discoveryService;
  64. $this->jobList = $jobList;
  65. $this->federationProviderManager = $federationProviderManager;
  66. $this->cloudFederationFactory = $cloudFederationFactory;
  67. }
  68. /**
  69. * send server-to-server share to remote server
  70. *
  71. * @param string $token
  72. * @param string $shareWith
  73. * @param string $name
  74. * @param int $remote_id
  75. * @param string $owner
  76. * @param string $ownerFederatedId
  77. * @param string $sharedBy
  78. * @param string $sharedByFederatedId
  79. * @param int $shareType (can be a remote user or group share)
  80. * @return bool
  81. * @throws \OC\HintException
  82. * @throws \OC\ServerNotAvailableException
  83. */
  84. public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
  85. list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
  86. if ($user && $remote) {
  87. $local = $this->addressHandler->generateRemoteURL();
  88. $fields = array(
  89. 'shareWith' => $user,
  90. 'token' => $token,
  91. 'name' => $name,
  92. 'remoteId' => $remote_id,
  93. 'owner' => $owner,
  94. 'ownerFederatedId' => $ownerFederatedId,
  95. 'sharedBy' => $sharedBy,
  96. 'sharedByFederatedId' => $sharedByFederatedId,
  97. 'remote' => $local,
  98. 'shareType' => $shareType
  99. );
  100. $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
  101. $status = json_decode($result['result'], true);
  102. $ocsStatus = isset($status['ocs']);
  103. $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
  104. if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
  105. \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
  106. return true;
  107. }
  108. }
  109. return false;
  110. }
  111. /**
  112. * ask owner to re-share the file with the given user
  113. *
  114. * @param string $token
  115. * @param int $id remote Id
  116. * @param int $shareId internal share Id
  117. * @param string $remote remote address of the owner
  118. * @param string $shareWith
  119. * @param int $permission
  120. * @param string $filename
  121. * @return bool
  122. * @throws \OC\HintException
  123. * @throws \OC\ServerNotAvailableException
  124. */
  125. public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
  126. $fields = array(
  127. 'shareWith' => $shareWith,
  128. 'token' => $token,
  129. 'permission' => $permission,
  130. 'remoteId' => $shareId,
  131. );
  132. $ocmFields = $fields;
  133. $ocmFields['remoteId'] = $id;
  134. $ocmFields['localId'] = $shareId;
  135. $ocmFields['name'] = $filename;
  136. $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
  137. if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
  138. return [$ocmResult['token'], $ocmResult['providerId']];
  139. }
  140. $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
  141. $status = json_decode($result['result'], true);
  142. $httpRequestSuccessful = $result['success'];
  143. $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
  144. $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
  145. $validRemoteId = isset($status['ocs']['data']['remoteId']);
  146. if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
  147. return [
  148. $status['ocs']['data']['token'],
  149. (int)$status['ocs']['data']['remoteId']
  150. ];
  151. }
  152. return false;
  153. }
  154. /**
  155. * send server-to-server unshare to remote server
  156. *
  157. * @param string $remote url
  158. * @param int $id share id
  159. * @param string $token
  160. * @return bool
  161. */
  162. public function sendRemoteUnShare($remote, $id, $token) {
  163. $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
  164. }
  165. /**
  166. * send server-to-server unshare to remote server
  167. *
  168. * @param string $remote url
  169. * @param int $id share id
  170. * @param string $token
  171. * @return bool
  172. */
  173. public function sendRevokeShare($remote, $id, $token) {
  174. $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
  175. }
  176. /**
  177. * send notification to remote server if the permissions was changed
  178. *
  179. * @param string $remote
  180. * @param int $remoteId
  181. * @param string $token
  182. * @param int $permissions
  183. * @return bool
  184. */
  185. public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
  186. $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
  187. }
  188. /**
  189. * forward accept reShare to remote server
  190. *
  191. * @param string $remote
  192. * @param int $remoteId
  193. * @param string $token
  194. */
  195. public function sendAcceptShare($remote, $remoteId, $token) {
  196. $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
  197. }
  198. /**
  199. * forward decline reShare to remote server
  200. *
  201. * @param string $remote
  202. * @param int $remoteId
  203. * @param string $token
  204. */
  205. public function sendDeclineShare($remote, $remoteId, $token) {
  206. $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
  207. }
  208. /**
  209. * inform remote server whether server-to-server share was accepted/declined
  210. *
  211. * @param string $remote
  212. * @param string $token
  213. * @param int $remoteId Share id on the remote host
  214. * @param string $action possible actions: accept, decline, unshare, revoke, permissions
  215. * @param array $data
  216. * @param int $try
  217. * @return boolean
  218. */
  219. public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
  220. $fields = [
  221. 'token' => $token,
  222. 'remoteId' => $remoteId
  223. ];
  224. foreach ($data as $key => $value) {
  225. $fields[$key] = $value;
  226. }
  227. $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
  228. $status = json_decode($result['result'], true);
  229. if ($result['success'] &&
  230. ($status['ocs']['meta']['statuscode'] === 100 ||
  231. $status['ocs']['meta']['statuscode'] === 200
  232. )
  233. ) {
  234. return true;
  235. } elseif ($try === 0) {
  236. // only add new job on first try
  237. $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
  238. [
  239. 'remote' => $remote,
  240. 'remoteId' => $remoteId,
  241. 'token' => $token,
  242. 'action' => $action,
  243. 'data' => json_encode($data),
  244. 'try' => $try,
  245. 'lastRun' => $this->getTimestamp()
  246. ]
  247. );
  248. }
  249. return false;
  250. }
  251. /**
  252. * return current timestamp
  253. *
  254. * @return int
  255. */
  256. protected function getTimestamp() {
  257. return time();
  258. }
  259. /**
  260. * try http post with the given protocol, if no protocol is given we pick
  261. * the secure one (https)
  262. *
  263. * @param string $remoteDomain
  264. * @param string $urlSuffix
  265. * @param array $fields post parameters
  266. * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
  267. * @return array
  268. * @throws \Exception
  269. */
  270. protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
  271. if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
  272. $remoteDomain = 'https://' . $remoteDomain;
  273. }
  274. $result = [
  275. 'success' => false,
  276. 'result' => '',
  277. ];
  278. // if possible we use the new OCM API
  279. $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
  280. if (is_array($ocmResult)) {
  281. $result['success'] = true;
  282. $result['result'] = json_encode([
  283. 'ocs' => ['meta' => ['statuscode' => 200]]]);
  284. return $result;
  285. }
  286. return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
  287. }
  288. /**
  289. * try old federated sharing API if the OCM api doesn't work
  290. *
  291. * @param $remoteDomain
  292. * @param $urlSuffix
  293. * @param array $fields
  294. * @return mixed
  295. * @throws \Exception
  296. */
  297. protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
  298. $result = [
  299. 'success' => false,
  300. 'result' => '',
  301. ];
  302. // Fall back to old API
  303. $client = $this->httpClientService->newClient();
  304. $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
  305. $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
  306. try {
  307. $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
  308. 'body' => $fields,
  309. 'timeout' => 10,
  310. 'connect_timeout' => 10,
  311. ]);
  312. $result['result'] = $response->getBody();
  313. $result['success'] = true;
  314. } catch (\Exception $e) {
  315. // if flat re-sharing is not supported by the remote server
  316. // we re-throw the exception and fall back to the old behaviour.
  317. // (flat re-shares has been introduced in Nextcloud 9.1)
  318. if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
  319. throw $e;
  320. }
  321. }
  322. return $result;
  323. }
  324. /**
  325. * send action regarding federated sharing to the remote server using the OCM API
  326. *
  327. * @param $remoteDomain
  328. * @param $fields
  329. * @param $action
  330. *
  331. * @return bool
  332. */
  333. protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
  334. switch ($action) {
  335. case 'share':
  336. $share = $this->cloudFederationFactory->getCloudFederationShare(
  337. $fields['shareWith'] . '@' . $remoteDomain,
  338. $fields['name'],
  339. '',
  340. $fields['remoteId'],
  341. $fields['ownerFederatedId'],
  342. $fields['owner'],
  343. $fields['sharedByFederatedId'],
  344. $fields['sharedBy'],
  345. $fields['token'],
  346. $fields['shareType'],
  347. 'file'
  348. );
  349. return $this->federationProviderManager->sendShare($share);
  350. case 'reshare':
  351. // ask owner to reshare a file
  352. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  353. $notification->setMessage('REQUEST_RESHARE',
  354. 'file',
  355. $fields['remoteId'],
  356. [
  357. 'sharedSecret' => $fields['token'],
  358. 'shareWith' => $fields['shareWith'],
  359. 'senderId' => $fields['localId'],
  360. 'shareType' => $fields['shareType'],
  361. 'message' => 'Ask owner to reshare the file'
  362. ]
  363. );
  364. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  365. case 'unshare':
  366. //owner unshares the file from the recipient again
  367. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  368. $notification->setMessage('SHARE_UNSHARED',
  369. 'file',
  370. $fields['remoteId'],
  371. [
  372. 'sharedSecret' => $fields['token'],
  373. 'messgage' => 'file is no longer shared with you'
  374. ]
  375. );
  376. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  377. case 'reshare_undo':
  378. // if a reshare was unshared we send the information to the initiator/owner
  379. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  380. $notification->setMessage('RESHARE_UNDO',
  381. 'file',
  382. $fields['remoteId'],
  383. [
  384. 'sharedSecret' => $fields['token'],
  385. 'message' => 'reshare was revoked'
  386. ]
  387. );
  388. return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
  389. }
  390. return false;
  391. }
  392. }