]> source.dussan.org Git - nextcloud-server.git/commitdiff
Move federated sharing routes to the federatedfilesharingapp 974/head
authorRoeland Jago Douma <roeland@famdouma.nl>
Fri, 19 Aug 2016 10:01:13 +0000 (12:01 +0200)
committerRoeland Jago Douma <roeland@famdouma.nl>
Sun, 28 Aug 2016 19:26:33 +0000 (21:26 +0200)
* Move routes to app
* Move routes over to the AppFramework
* Fix tests

There is plenty of stuff to fix properly here. But out of scope for now.

apps/federatedfilesharing/appinfo/routes.php
apps/federatedfilesharing/lib/AppInfo/Application.php
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php [new file with mode: 0644]
apps/federatedfilesharing/lib/RequestHandler.php [deleted file]
apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php [new file with mode: 0644]
apps/federatedfilesharing/tests/RequestHandlerTest.php [deleted file]
ocs/routes.php

index a4f56e372c941a81dea9a812a610b14f0c190fc9..9caaa93934812ccb5e0e841ed39f4584c9f94163 100644 (file)
@@ -26,5 +26,14 @@ return [
        'routes' => [
                ['name' => 'MountPublicLink#createFederatedShare', 'url' => '/createFederatedShare', 'verb' => 'POST'],
                ['name' => 'MountPublicLink#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'],
-       ]
+       ],
+       'ocs' => [
+               ['root' => '/cloud', 'name' => 'RequestHandler#createShare', 'url' => '/shares', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#reShare', 'url' => '/shares/{id}/reshare', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#updatePermissions', 'url' => '/shares/{id}/permissions', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#acceptShare', 'url' => '/shares/{id}/accept', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#declineShare', 'url' => '/shares/{id}/decline', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#unshare', 'url' => '/shares/{id}/unshare', 'verb' => 'POST'],
+               ['root' => '/cloud', 'name' => 'RequestHandler#revoke', 'url' => '/shares/{id}/revoke', 'verb' => 'POST'],
+       ],
 ];
index b767a322505b26aa8a63d69ef6f1099ee73956b1..b470bb3e58435171bb5bb0ca33fb048fa5ea37dc 100644 (file)
 namespace OCA\FederatedFileSharing\AppInfo;
 
 
+use OC\AppFramework\Utility\SimpleContainer;
+use OCA\FederatedFileSharing\AddressHandler;
+use OCA\FederatedFileSharing\Controller\RequestHandlerController;
 use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCA\FederatedFileSharing\Notifications;
+use OCA\FederatedFileSharing\RequestHandler;
 use OCP\AppFramework\App;
 
 class Application extends App {
@@ -34,6 +39,35 @@ class Application extends App {
 
        public function __construct() {
                parent::__construct('federatedfilesharing');
+
+               $container = $this->getContainer();
+               $server = $container->getServer();
+
+               $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
+                       $addressHandler = new AddressHandler(
+                               $server->getURLGenerator(),
+                               $server->getL10N('federatedfilesharing')
+                       );
+                       $notification = new Notifications(
+                               $addressHandler,
+                               $server->getHTTPClientService(),
+                               new \OCA\FederatedFileSharing\DiscoveryManager(
+                                       $server->getMemCacheFactory(),
+                                       $server->getHTTPClientService()
+                               ),
+                               \OC::$server->getJobList()
+                       );
+                       return new RequestHandlerController(
+                               $c->query('AppName'),
+                               $server->getRequest(),
+                               $this->getFederatedShareProvider(),
+                               $server->getDatabaseConnection(),
+                               $server->getShareManager(),
+                               $notification,
+                               $addressHandler,
+                               $server->getUserManager()
+                       );
+               });
        }
 
        /**
diff --git a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php
new file mode 100644 (file)
index 0000000..9a41962
--- /dev/null
@@ -0,0 +1,608 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016, ownCloud, Inc.
+ *
+ * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
+ * @author Björn Schießle <bjoern@schiessle.org>
+ * @author Joas Schilling <coding@schilljs.com>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @author Morris Jobke <hey@morrisjobke.de>
+ *
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+namespace OCA\FederatedFileSharing\Controller;
+
+use OCA\FederatedFileSharing\DiscoveryManager;
+use OCA\Files_Sharing\Activity;
+use OCA\FederatedFileSharing\AddressHandler;
+use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCA\FederatedFileSharing\Notifications;
+use OCP\AppFramework\Http;
+use OCP\AppFramework\OCS\OCSBadRequestException;
+use OCP\AppFramework\OCS\OCSException;
+use OCP\AppFramework\OCS\OCSForbiddenException;
+use OCP\AppFramework\OCS\OCSNotFoundException;
+use OCP\AppFramework\OCSController;
+use OCP\Constants;
+use OCP\Files\NotFoundException;
+use OCP\IDBConnection;
+use OCP\IRequest;
+use OCP\IUserManager;
+use OCP\Share;
+use OCP\Share\IShare;
+
+class RequestHandlerController extends OCSController {
+
+       /** @var FederatedShareProvider */
+       private $federatedShareProvider;
+
+       /** @var IDBConnection */
+       private $connection;
+
+       /** @var Share\IManager */
+       private $shareManager;
+
+       /** @var Notifications */
+       private $notifications;
+
+       /** @var AddressHandler */
+       private $addressHandler;
+
+       /** @var  IUserManager */
+       private $userManager;
+
+       /** @var string */
+       private $shareTable = 'share';
+
+       /**
+        * Server2Server constructor.
+        *
+        * @param string $appName
+        * @param IRequest $request
+        * @param FederatedShareProvider $federatedShareProvider
+        * @param IDBConnection $connection
+        * @param Share\IManager $shareManager
+        * @param Notifications $notifications
+        * @param AddressHandler $addressHandler
+        * @param IUserManager $userManager
+        */
+       public function __construct($appName,
+                                                               IRequest $request,
+                                                               FederatedShareProvider $federatedShareProvider,
+                                                               IDBConnection $connection,
+                                                               Share\IManager $shareManager,
+                                                               Notifications $notifications,
+                                                               AddressHandler $addressHandler,
+                                                               IUserManager $userManager
+       ) {
+               parent::__construct($appName, $request);
+
+               $this->federatedShareProvider = $federatedShareProvider;
+               $this->connection = $connection;
+               $this->shareManager = $shareManager;
+               $this->notifications = $notifications;
+               $this->addressHandler = $addressHandler;
+               $this->userManager = $userManager;
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * create a new share
+        *
+        * @return Http\DataResponse
+        * @throws OCSException
+        */
+       public function createShare() {
+
+               if (!$this->isS2SEnabled(true)) {
+                       throw new OCSException('Server does not support federated cloud sharing', 503);
+               }
+
+               $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
+               $token = isset($_POST['token']) ? $_POST['token'] : null;
+               $name = isset($_POST['name']) ? $_POST['name'] : null;
+               $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
+               $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
+               $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
+               $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
+               $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
+               $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
+
+               if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
+
+                       if(!\OCP\Util::isValidFileName($name)) {
+                               throw new OCSException('The mountpoint name contains invalid characters.', 400);
+                       }
+
+                       // FIXME this should be a method in the user management instead
+                       \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
+                       \OCP\Util::emitHook(
+                               '\OCA\Files_Sharing\API\Server2Server',
+                               'preLoginNameUsedAsUserName',
+                               array('uid' => &$shareWith)
+                       );
+                       \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
+
+                       if (!\OCP\User::userExists($shareWith)) {
+                               throw new OCSException('User does not exists', 400);
+                       }
+
+                       \OC_Util::setupFS($shareWith);
+
+                       $discoveryManager = new DiscoveryManager(
+                               \OC::$server->getMemCacheFactory(),
+                               \OC::$server->getHTTPClientService()
+                       );
+                       $externalManager = new \OCA\Files_Sharing\External\Manager(
+                                       \OC::$server->getDatabaseConnection(),
+                                       \OC\Files\Filesystem::getMountManager(),
+                                       \OC\Files\Filesystem::getLoader(),
+                                       \OC::$server->getHTTPClientService(),
+                                       \OC::$server->getNotificationManager(),
+                                       $discoveryManager,
+                                       $shareWith
+                               );
+
+                       try {
+                               $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
+                               $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
+
+                               if ($ownerFederatedId === null) {
+                                       $ownerFederatedId = $owner . '@' . $this->cleanupRemote($remote);
+                               }
+                               // if the owner of the share and the initiator are the same user
+                               // we also complete the federated share ID for the initiator
+                               if ($sharedByFederatedId === null && $owner === $sharedBy) {
+                                       $sharedByFederatedId = $ownerFederatedId;
+                               }
+
+                               \OC::$server->getActivityManager()->publishActivity(
+                                       Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_RECEIVED, array($ownerFederatedId, trim($name, '/')), '', array(),
+                                       '', '', $shareWith, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_LOW);
+
+                               $urlGenerator = \OC::$server->getURLGenerator();
+
+                               $notificationManager = \OC::$server->getNotificationManager();
+                               $notification = $notificationManager->createNotification();
+                               $notification->setApp('files_sharing')
+                                       ->setUser($shareWith)
+                                       ->setDateTime(new \DateTime())
+                                       ->setObject('remote_share', $shareId)
+                                       ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
+
+                               $declineAction = $notification->createAction();
+                               $declineAction->setLabel('decline')
+                                       ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
+                               $notification->addAction($declineAction);
+
+                               $acceptAction = $notification->createAction();
+                               $acceptAction->setLabel('accept')
+                                       ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
+                               $notification->addAction($acceptAction);
+
+                               $notificationManager->notify($notification);
+
+                               return new Http\DataResponse();
+                       } catch (\Exception $e) {
+                               \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
+                               throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
+                       }
+               }
+
+               throw new OCSException('server can not add remote share, missing parameter', 400);
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * create re-share on behalf of another user
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSBadRequestException
+        * @throws OCSForbiddenException
+        * @throws OCSNotFoundException
+        */
+       public function reShare($id) {
+
+               $token = $this->request->getParam('token', null);
+               $shareWith = $this->request->getParam('shareWith', null);
+               $permission = (int)$this->request->getParam('permission', null);
+               $remoteId = (int)$this->request->getParam('remoteId', null);
+
+               if ($id === null ||
+                       $token === null ||
+                       $shareWith === null ||
+                       $permission === null ||
+                       $remoteId === null
+               ) {
+                       throw new OCSBadRequestException();
+               }
+
+               try {
+                       $share = $this->federatedShareProvider->getShareById($id);
+               } catch (Share\Exceptions\ShareNotFound $e) {
+                       throw new OCSNotFoundException();
+               }
+
+               // don't allow to share a file back to the owner
+               list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
+               $owner = $share->getShareOwner();
+               $currentServer = $this->addressHandler->generateRemoteURL();
+               if ($this->addressHandler->compareAddresses($user, $remote,$owner , $currentServer)) {
+                       throw new OCSForbiddenException();
+               }
+
+               if ($this->verifyShare($share, $token)) {
+
+                       // check if re-sharing is allowed
+                       if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
+                               $share->setPermissions($share->getPermissions() & $permission);
+                               // the recipient of the initial share is now the initiator for the re-share
+                               $share->setSharedBy($share->getSharedWith());
+                               $share->setSharedWith($shareWith);
+                               try {
+                                       $result = $this->federatedShareProvider->create($share);
+                                       $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
+                                       return new Http\DataResponse([
+                                               'token' => $result->getToken(),
+                                               'remoteId' => $result->getId()
+                                       ]);
+                               } catch (\Exception $e) {
+                                       throw new OCSBadRequestException();
+                               }
+                       } else {
+                               throw new OCSForbiddenException();
+                       }
+               }
+               throw new OCSBadRequestException();
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * accept server-to-server share
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSException
+        */
+       public function acceptShare($id) {
+
+               if (!$this->isS2SEnabled()) {
+                       throw new OCSException('Server does not support federated cloud sharing', 503);
+               }
+
+               $token = isset($_POST['token']) ? $_POST['token'] : null;
+
+               try {
+                       $share = $this->federatedShareProvider->getShareById($id);
+               } catch (Share\Exceptions\ShareNotFound $e) {
+                       return new Http\DataResponse();
+               }
+
+               if ($this->verifyShare($share, $token)) {
+                       $this->executeAcceptShare($share);
+                       if ($share->getShareOwner() !== $share->getSharedBy()) {
+                               list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
+                               $remoteId = $this->federatedShareProvider->getRemoteId($share);
+                               $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
+                       }
+               }
+
+               return new Http\DataResponse();
+       }
+
+       protected function executeAcceptShare(Share\IShare $share) {
+               list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
+
+               $event = \OC::$server->getActivityManager()->generateEvent();
+               $event->setApp(Activity::FILES_SHARING_APP)
+                       ->setType(Activity::TYPE_REMOTE_SHARE)
+                       ->setAffectedUser($this->getCorrectUid($share))
+                       ->setSubject(Activity::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), basename($file)])
+                       ->setObject('files', $share->getNode()->getId(), $file)
+                       ->setLink($link);
+               \OC::$server->getActivityManager()->publish($event);
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * decline server-to-server share
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSException
+        */
+       public function declineShare($id) {
+
+               if (!$this->isS2SEnabled()) {
+                       throw new OCSException('Server does not support federated cloud sharing', 503);
+               }
+
+               $token = isset($_POST['token']) ? $_POST['token'] : null;
+
+               try {
+                       $share = $this->federatedShareProvider->getShareById($id);
+               } catch (Share\Exceptions\ShareNotFound $e) {
+                       return new Http\DataResponse();
+               }
+
+               if($this->verifyShare($share, $token)) {
+                       if ($share->getShareOwner() !== $share->getSharedBy()) {
+                               list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
+                               $remoteId = $this->federatedShareProvider->getRemoteId($share);
+                               $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
+                       }
+                       $this->executeDeclineShare($share);
+               }
+
+               return new Http\DataResponse();
+       }
+
+       /**
+        * delete declined share and create a activity
+        *
+        * @param Share\IShare $share
+        */
+       protected function executeDeclineShare(Share\IShare $share) {
+               $this->federatedShareProvider->removeShareFromTable($share);
+               list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
+
+               $event = \OC::$server->getActivityManager()->generateEvent();
+               $event->setApp(Activity::FILES_SHARING_APP)
+                       ->setType(Activity::TYPE_REMOTE_SHARE)
+                       ->setAffectedUser($this->getCorrectUid($share))
+                       ->setSubject(Activity::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), basename($file)])
+                       ->setObject('files', $share->getNode()->getId(), $file)
+                       ->setLink($link);
+               \OC::$server->getActivityManager()->publish($event);
+
+       }
+
+       /**
+        * check if we are the initiator or the owner of a re-share and return the correct UID
+        *
+        * @param Share\IShare $share
+        * @return string
+        */
+       protected function getCorrectUid(Share\IShare $share) {
+               if($this->userManager->userExists($share->getShareOwner())) {
+                       return $share->getShareOwner();
+               }
+
+               return $share->getSharedBy();
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * remove server-to-server share if it was unshared by the owner
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSException
+        */
+       public function unshare($id) {
+
+               if (!$this->isS2SEnabled()) {
+                       throw new OCSException('Server does not support federated cloud sharing', 503);
+               }
+
+               $token = isset($_POST['token']) ? $_POST['token'] : null;
+
+               $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
+               $query->execute(array($id, $token));
+               $share = $query->fetchRow();
+
+               if ($token && $id && !empty($share)) {
+
+                       $remote = $this->cleanupRemote($share['remote']);
+
+                       $owner = $share['owner'] . '@' . $remote;
+                       $mountpoint = $share['mountpoint'];
+                       $user = $share['user'];
+
+                       $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
+                       $query->execute(array($id, $token));
+
+                       if ($share['accepted']) {
+                               $path = trim($mountpoint, '/');
+                       } else {
+                               $path = trim($share['name'], '/');
+                       }
+
+                       $notificationManager = \OC::$server->getNotificationManager();
+                       $notification = $notificationManager->createNotification();
+                       $notification->setApp('files_sharing')
+                               ->setUser($share['user'])
+                               ->setObject('remote_share', (int) $share['id']);
+                       $notificationManager->markProcessed($notification);
+
+                       \OC::$server->getActivityManager()->publishActivity(
+                               Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_UNSHARED, array($owner, $path), '', array(),
+                               '', '', $user, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_MEDIUM);
+               }
+
+               return new Http\DataResponse();
+       }
+
+       private function cleanupRemote($remote) {
+               $remote = substr($remote, strpos($remote, '://') + 3);
+
+               return rtrim($remote, '/');
+       }
+
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * federated share was revoked, either by the owner or the re-sharer
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSBadRequestException
+        */
+       public function revoke($id) {
+               $token = $this->request->getParam('token');
+               
+               $share = $this->federatedShareProvider->getShareById($id);
+               
+               if ($this->verifyShare($share, $token)) {
+                       $this->federatedShareProvider->removeShareFromTable($share);
+                       return new Http\DataResponse();
+               }
+
+               throw new OCSBadRequestException();
+       }
+       
+       /**
+        * get share
+        *
+        * @param int $id
+        * @param string $token
+        * @return array|bool
+        */
+       protected function getShare($id, $token) {
+               $query = $this->connection->getQueryBuilder();
+               $query->select('*')->from($this->shareTable)
+                       ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
+                       ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
+                       ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
+
+               $result = $query->execute()->fetchAll();
+
+               if (!empty($result) && isset($result[0])) {
+                       return $result[0];
+               }
+
+               return false;
+       }
+
+       /**
+        * get file
+        *
+        * @param string $user
+        * @param int $fileSource
+        * @return array with internal path of the file and a absolute link to it
+        */
+       private function getFile($user, $fileSource) {
+               \OC_Util::setupFS($user);
+
+               try {
+                       $file = \OC\Files\Filesystem::getPath($fileSource);
+               } catch (NotFoundException $e) {
+                       $file = null;
+               }
+               $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
+               $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
+
+               return array($file, $link);
+
+       }
+
+       /**
+        * check if server-to-server sharing is enabled
+        *
+        * @param bool $incoming
+        * @return bool
+        */
+       private function isS2SEnabled($incoming = false) {
+
+               $result = \OCP\App::isEnabled('files_sharing');
+
+               if ($incoming) {
+                       $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
+               } else {
+                       $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
+               }
+
+               return $result;
+       }
+
+       /**
+        * check if we got the right share
+        *
+        * @param Share\IShare $share
+        * @param string $token
+        * @return bool
+        */
+       protected function verifyShare(Share\IShare $share, $token) {
+               if (
+                       $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
+                       $share->getToken() === $token
+               ) {
+                       return true;
+               }
+
+               return false;
+       }
+
+       /**
+        * @NoCSRFRequired
+        * @PublicPage
+        *
+        * update share information to keep federated re-shares in sync
+        *
+        * @param int $id
+        * @return Http\DataResponse
+        * @throws OCSBadRequestException
+        */
+       public function updatePermissions($id) {
+               $token = $this->request->getParam('token', null);
+               $permissions = $this->request->getParam('permissions', null);
+
+               try {
+                       $share = $this->federatedShareProvider->getShareById($id);
+               } catch (Share\Exceptions\ShareNotFound $e) {
+                       throw new OCSBadRequestException();
+               }
+
+               $validPermission = ctype_digit($permissions);
+               $validToken = $this->verifyShare($share, $token);
+               if ($validPermission && $validToken) {
+                       $this->updatePermissionsInDatabase($share, (int)$permissions);
+               } else {
+                       throw new OCSBadRequestException();
+               }
+
+               return new Http\DataResponse();
+       }
+
+       /**
+        * update permissions in database
+        *
+        * @param IShare $share
+        * @param int $permissions
+        */
+       protected function updatePermissionsInDatabase(IShare $share, $permissions) {
+               $query = $this->connection->getQueryBuilder();
+               $query->update('share')
+                       ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
+                       ->set('permissions', $query->createNamedParameter($permissions))
+                       ->execute();
+       }
+
+}
diff --git a/apps/federatedfilesharing/lib/RequestHandler.php b/apps/federatedfilesharing/lib/RequestHandler.php
deleted file mode 100644 (file)
index f531c7b..0000000
+++ /dev/null
@@ -1,581 +0,0 @@
-<?php
-/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program.  If not, see <http://www.gnu.org/licenses/>
- *
- */
-
-namespace OCA\FederatedFileSharing;
-
-use OCA\Files_Sharing\Activity;
-use OCP\AppFramework\Http;
-use OCP\Constants;
-use OCP\Files\NotFoundException;
-use OCP\IDBConnection;
-use OCP\IRequest;
-use OCP\IUserManager;
-use OCP\Share;
-
-/**
- * Class RequestHandler
- * 
- * handles OCS Request to the federated share API
- *
- * @package OCA\FederatedFileSharing\API
- */
-class RequestHandler {
-
-       /** @var FederatedShareProvider */
-       private $federatedShareProvider;
-
-       /** @var IDBConnection */
-       private $connection;
-
-       /** @var Share\IManager */
-       private $shareManager;
-
-       /** @var IRequest */
-       private $request;
-
-       /** @var Notifications */
-       private $notifications;
-
-       /** @var AddressHandler */
-       private $addressHandler;
-
-       /** @var  IUserManager */
-       private $userManager;
-
-       /** @var string */
-       private $shareTable = 'share';
-
-       /**
-        * Server2Server constructor.
-        *
-        * @param FederatedShareProvider $federatedShareProvider
-        * @param IDBConnection $connection
-        * @param Share\IManager $shareManager
-        * @param IRequest $request
-        * @param Notifications $notifications
-        * @param AddressHandler $addressHandler
-        * @param IUserManager $userManager
-        */
-       public function __construct(FederatedShareProvider $federatedShareProvider,
-                                                               IDBConnection $connection,
-                                                               Share\IManager $shareManager,
-                                                               IRequest $request,
-                                                               Notifications $notifications,
-                                                               AddressHandler $addressHandler,
-                                                               IUserManager $userManager
-       ) {
-               $this->federatedShareProvider = $federatedShareProvider;
-               $this->connection = $connection;
-               $this->shareManager = $shareManager;
-               $this->request = $request;
-               $this->notifications = $notifications;
-               $this->addressHandler = $addressHandler;
-               $this->userManager = $userManager;
-       }
-
-       /**
-        * create a new share
-        *
-        * @param array $params
-        * @return \OC_OCS_Result
-        */
-       public function createShare($params) {
-
-               if (!$this->isS2SEnabled(true)) {
-                       return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing');
-               }
-
-               $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
-               $token = isset($_POST['token']) ? $_POST['token'] : null;
-               $name = isset($_POST['name']) ? $_POST['name'] : null;
-               $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
-               $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
-               $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
-               $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
-               $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
-               $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
-
-               if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
-
-                       if(!\OCP\Util::isValidFileName($name)) {
-                               return new \OC_OCS_Result(null, 400, 'The mountpoint name contains invalid characters.');
-                       }
-
-                       // FIXME this should be a method in the user management instead
-                       \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
-                       \OCP\Util::emitHook(
-                               '\OCA\Files_Sharing\API\Server2Server',
-                               'preLoginNameUsedAsUserName',
-                               array('uid' => &$shareWith)
-                       );
-                       \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
-
-                       if (!\OCP\User::userExists($shareWith)) {
-                               return new \OC_OCS_Result(null, 400, 'User does not exists');
-                       }
-
-                       \OC_Util::setupFS($shareWith);
-
-                       $discoveryManager = new DiscoveryManager(
-                               \OC::$server->getMemCacheFactory(),
-                               \OC::$server->getHTTPClientService()
-                       );
-                       $externalManager = new \OCA\Files_Sharing\External\Manager(
-                                       \OC::$server->getDatabaseConnection(),
-                                       \OC\Files\Filesystem::getMountManager(),
-                                       \OC\Files\Filesystem::getLoader(),
-                                       \OC::$server->getHTTPClientService(),
-                                       \OC::$server->getNotificationManager(),
-                                       $discoveryManager,
-                                       $shareWith
-                               );
-
-                       try {
-                               $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
-                               $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
-
-                               if ($ownerFederatedId === null) {
-                                       $ownerFederatedId = $owner . '@' . $this->cleanupRemote($remote);
-                               }
-                               // if the owner of the share and the initiator are the same user
-                               // we also complete the federated share ID for the initiator
-                               if ($sharedByFederatedId === null && $owner === $sharedBy) {
-                                       $sharedByFederatedId = $ownerFederatedId;
-                               }
-
-                               \OC::$server->getActivityManager()->publishActivity(
-                                       Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_RECEIVED, array($ownerFederatedId, trim($name, '/')), '', array(),
-                                       '', '', $shareWith, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_LOW);
-
-                               $urlGenerator = \OC::$server->getURLGenerator();
-
-                               $notificationManager = \OC::$server->getNotificationManager();
-                               $notification = $notificationManager->createNotification();
-                               $notification->setApp('files_sharing')
-                                       ->setUser($shareWith)
-                                       ->setDateTime(new \DateTime())
-                                       ->setObject('remote_share', $shareId)
-                                       ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
-
-                               $declineAction = $notification->createAction();
-                               $declineAction->setLabel('decline')
-                                       ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
-                               $notification->addAction($declineAction);
-
-                               $acceptAction = $notification->createAction();
-                               $acceptAction->setLabel('accept')
-                                       ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
-                               $notification->addAction($acceptAction);
-
-                               $notificationManager->notify($notification);
-
-                               return new \OC_OCS_Result();
-                       } catch (\Exception $e) {
-                               \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
-                               return new \OC_OCS_Result(null, 500, 'internal server error, was not able to add share from ' . $remote);
-                       }
-               }
-
-               return new \OC_OCS_Result(null, 400, 'server can not add remote share, missing parameter');
-       }
-
-       /**
-        * create re-share on behalf of another user
-        *
-        * @param $params
-        * @return \OC_OCS_Result
-        */
-       public function reShare($params) {
-
-               $id = isset($params['id']) ? (int)$params['id'] : null;
-               $token = $this->request->getParam('token', null);
-               $shareWith = $this->request->getParam('shareWith', null);
-               $permission = (int)$this->request->getParam('permission', null);
-               $remoteId = (int)$this->request->getParam('remoteId', null);
-
-               if ($id === null ||
-                       $token === null ||
-                       $shareWith === null ||
-                       $permission === null ||
-                       $remoteId === null
-               ) {
-                       return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-               }
-
-               try {
-                       $share = $this->federatedShareProvider->getShareById($id);
-               } catch (Share\Exceptions\ShareNotFound $e) {
-                       return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND);
-               }
-
-               // don't allow to share a file back to the owner
-               list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
-               $owner = $share->getShareOwner();
-               $currentServer = $this->addressHandler->generateRemoteURL();
-               if ($this->addressHandler->compareAddresses($user, $remote,$owner , $currentServer)) {
-                       return new \OC_OCS_Result(null, Http::STATUS_FORBIDDEN);
-               }
-
-               if ($this->verifyShare($share, $token)) {
-
-                       // check if re-sharing is allowed
-                       if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
-                               $share->setPermissions($share->getPermissions() & $permission);
-                               // the recipient of the initial share is now the initiator for the re-share
-                               $share->setSharedBy($share->getSharedWith());
-                               $share->setSharedWith($shareWith);
-                               try {
-                                       $result = $this->federatedShareProvider->create($share);
-                                       $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
-                                       return new \OC_OCS_Result(['token' => $result->getToken(), 'remoteId' => $result->getId()]);
-                               } catch (\Exception $e) {
-                                       return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-                               }
-                       } else {
-                               return new \OC_OCS_Result(null, Http::STATUS_FORBIDDEN);
-                       }
-               }
-               return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-
-       }
-
-       /**
-        * accept server-to-server share
-        *
-        * @param array $params
-        * @return \OC_OCS_Result
-        */
-       public function acceptShare($params) {
-
-               if (!$this->isS2SEnabled()) {
-                       return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing');
-               }
-
-               $id = $params['id'];
-               $token = isset($_POST['token']) ? $_POST['token'] : null;
-
-               try {
-                       $share = $this->federatedShareProvider->getShareById($id);
-               } catch (Share\Exceptions\ShareNotFound $e) {
-                       return new \OC_OCS_Result();
-               }
-
-               if ($this->verifyShare($share, $token)) {
-                       $this->executeAcceptShare($share);
-                       if ($share->getShareOwner() !== $share->getSharedBy()) {
-                               list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
-                               $remoteId = $this->federatedShareProvider->getRemoteId($share);
-                               $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
-                       }
-               }
-
-               return new \OC_OCS_Result();
-       }
-
-       protected function executeAcceptShare(Share\IShare $share) {
-               list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
-
-               $event = \OC::$server->getActivityManager()->generateEvent();
-               $event->setApp(Activity::FILES_SHARING_APP)
-                       ->setType(Activity::TYPE_REMOTE_SHARE)
-                       ->setAffectedUser($this->getCorrectUid($share))
-                       ->setSubject(Activity::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), basename($file)])
-                       ->setObject('files', $share->getNode()->getId(), $file)
-                       ->setLink($link);
-               \OC::$server->getActivityManager()->publish($event);
-       }
-
-       /**
-        * decline server-to-server share
-        *
-        * @param array $params
-        * @return \OC_OCS_Result
-        */
-       public function declineShare($params) {
-
-               if (!$this->isS2SEnabled()) {
-                       return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing');
-               }
-
-               $id = (int)$params['id'];
-               $token = isset($_POST['token']) ? $_POST['token'] : null;
-
-               try {
-                       $share = $this->federatedShareProvider->getShareById($id);
-               } catch (Share\Exceptions\ShareNotFound $e) {
-                       return new \OC_OCS_Result();
-               }
-
-               if($this->verifyShare($share, $token)) {
-                       if ($share->getShareOwner() !== $share->getSharedBy()) {
-                               list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
-                               $remoteId = $this->federatedShareProvider->getRemoteId($share);
-                               $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
-                       }
-                       $this->executeDeclineShare($share);
-               }
-
-               return new \OC_OCS_Result();
-       }
-
-       /**
-        * delete declined share and create a activity
-        *
-        * @param Share\IShare $share
-        */
-       protected function executeDeclineShare(Share\IShare $share) {
-               $this->federatedShareProvider->removeShareFromTable($share);
-               list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
-
-               $event = \OC::$server->getActivityManager()->generateEvent();
-               $event->setApp(Activity::FILES_SHARING_APP)
-                       ->setType(Activity::TYPE_REMOTE_SHARE)
-                       ->setAffectedUser($this->getCorrectUid($share))
-                       ->setSubject(Activity::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), basename($file)])
-                       ->setObject('files', $share->getNode()->getId(), $file)
-                       ->setLink($link);
-               \OC::$server->getActivityManager()->publish($event);
-
-       }
-
-       /**
-        * check if we are the initiator or the owner of a re-share and return the correct UID
-        *
-        * @param Share\IShare $share
-        * @return string
-        */
-       protected function getCorrectUid(Share\IShare $share) {
-               if($this->userManager->userExists($share->getShareOwner())) {
-                       return $share->getShareOwner();
-               }
-
-               return $share->getSharedBy();
-       }
-
-       /**
-        * remove server-to-server share if it was unshared by the owner
-        *
-        * @param array $params
-        * @return \OC_OCS_Result
-        */
-       public function unshare($params) {
-
-               if (!$this->isS2SEnabled()) {
-                       return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing');
-               }
-
-               $id = $params['id'];
-               $token = isset($_POST['token']) ? $_POST['token'] : null;
-
-               $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
-               $query->execute(array($id, $token));
-               $share = $query->fetchRow();
-
-               if ($token && $id && !empty($share)) {
-
-                       $remote = $this->cleanupRemote($share['remote']);
-
-                       $owner = $share['owner'] . '@' . $remote;
-                       $mountpoint = $share['mountpoint'];
-                       $user = $share['user'];
-
-                       $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
-                       $query->execute(array($id, $token));
-
-                       if ($share['accepted']) {
-                               $path = trim($mountpoint, '/');
-                       } else {
-                               $path = trim($share['name'], '/');
-                       }
-
-                       $notificationManager = \OC::$server->getNotificationManager();
-                       $notification = $notificationManager->createNotification();
-                       $notification->setApp('files_sharing')
-                               ->setUser($share['user'])
-                               ->setObject('remote_share', (int) $share['id']);
-                       $notificationManager->markProcessed($notification);
-
-                       \OC::$server->getActivityManager()->publishActivity(
-                               Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_UNSHARED, array($owner, $path), '', array(),
-                               '', '', $user, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_MEDIUM);
-               }
-
-               return new \OC_OCS_Result();
-       }
-
-       private function cleanupRemote($remote) {
-               $remote = substr($remote, strpos($remote, '://') + 3);
-
-               return rtrim($remote, '/');
-       }
-
-
-       /**
-        * federated share was revoked, either by the owner or the re-sharer
-        *
-        * @param $params
-        * @return \OC_OCS_Result
-        */
-       public function revoke($params) {
-               $id = (int)$params['id'];
-               $token = $this->request->getParam('token');
-               
-               $share = $this->federatedShareProvider->getShareById($id);
-               
-               if ($this->verifyShare($share, $token)) {
-                       $this->federatedShareProvider->removeShareFromTable($share);
-                       return new \OC_OCS_Result();
-               }
-
-       return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-
-       }
-       
-       /**
-        * get share
-        *
-        * @param int $id
-        * @param string $token
-        * @return array|bool
-        */
-       protected function getShare($id, $token) {
-               $query = $this->connection->getQueryBuilder();
-               $query->select('*')->from($this->shareTable)
-                       ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
-                       ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
-                       ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
-
-               $result = $query->execute()->fetchAll();
-
-               if (!empty($result) && isset($result[0])) {
-                       return $result[0];
-               }
-
-               return false;
-       }
-
-       /**
-        * get file
-        *
-        * @param string $user
-        * @param int $fileSource
-        * @return array with internal path of the file and a absolute link to it
-        */
-       private function getFile($user, $fileSource) {
-               \OC_Util::setupFS($user);
-
-               try {
-                       $file = \OC\Files\Filesystem::getPath($fileSource);
-               } catch (NotFoundException $e) {
-                       $file = null;
-               }
-               $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
-               $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
-
-               return array($file, $link);
-
-       }
-
-       /**
-        * check if server-to-server sharing is enabled
-        *
-        * @param bool $incoming
-        * @return bool
-        */
-       private function isS2SEnabled($incoming = false) {
-
-               $result = \OCP\App::isEnabled('files_sharing');
-
-               if ($incoming) {
-                       $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
-               } else {
-                       $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
-               }
-
-               return $result;
-       }
-
-       /**
-        * check if we got the right share
-        *
-        * @param Share\IShare $share
-        * @param string $token
-        * @return bool
-        */
-       protected function verifyShare(Share\IShare $share, $token) {
-               if (
-                       $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
-                       $share->getToken() === $token
-               ) {
-                       return true;
-               }
-
-               return false;
-       }
-
-       /**
-        * update share information to keep federated re-shares in sync
-        *
-        * @param array $params
-        * @return \OC_OCS_Result
-        */
-       public function updatePermissions($params) {
-               $id = (int)$params['id'];
-               $token = $this->request->getParam('token', null);
-               $permissions = $this->request->getParam('permissions', null);
-
-               try {
-                       $share = $this->federatedShareProvider->getShareById($id);
-               } catch (Share\Exceptions\ShareNotFound $e) {
-                       return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-               }
-
-               $validPermission = ctype_digit($permissions);
-               $validToken = $this->verifyShare($share, $token);
-               if ($validPermission && $validToken) {
-                       $this->updatePermissionsInDatabase($share, (int)$permissions);
-               } else {
-                       return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST);
-               }
-
-               return new \OC_OCS_Result();
-       }
-
-       /**
-        * update permissions in database
-        *
-        * @param IShare $share
-        * @param int $permissions
-        */
-       protected function updatePermissionsInDatabase(IShare $share, $permissions) {
-               $query = $this->connection->getQueryBuilder();
-               $query->update('share')
-                       ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
-                       ->set('permissions', $query->createNamedParameter($permissions))
-                       ->execute();
-       }
-
-}
diff --git a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php
new file mode 100644 (file)
index 0000000..8e1000f
--- /dev/null
@@ -0,0 +1,383 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016, ownCloud, Inc.
+ *
+ * @author Björn Schießle <bjoern@schiessle.org>
+ * @author Joas Schilling <coding@schilljs.com>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @author Morris Jobke <hey@morrisjobke.de>
+ * @author Robin Appelman <robin@icewind.nl>
+ * @author Thomas Müller <thomas.mueller@tmit.eu>
+ *
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+namespace OCA\FederatedFileSharing\Tests;
+
+use OC\Files\Filesystem;
+use OCA\FederatedFileSharing\DiscoveryManager;
+use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCA\FederatedFileSharing\Controller\RequestHandlerController;
+use OCP\IUserManager;
+use OCP\Share\IShare;
+
+/**
+ * Class RequestHandlerTest
+ *
+ * @package OCA\FederatedFileSharing\Tests
+ * @group DB
+ */
+class RequestHandlerControllerTest extends TestCase {
+
+       const TEST_FOLDER_NAME = '/folder_share_api_test';
+
+       /**
+        * @var \OCP\IDBConnection
+        */
+       private $connection;
+
+       /**
+        * @var RequestHandlerController
+        */
+       private $s2s;
+
+       /** @var  \OCA\FederatedFileSharing\FederatedShareProvider|\PHPUnit_Framework_MockObject_MockObject */
+       private $federatedShareProvider;
+
+       /** @var  \OCA\FederatedFileSharing\Notifications|\PHPUnit_Framework_MockObject_MockObject */
+       private $notifications;
+
+       /** @var  \OCA\FederatedFileSharing\AddressHandler|\PHPUnit_Framework_MockObject_MockObject */
+       private $addressHandler;
+       
+       /** @var  IUserManager|\PHPUnit_Framework_MockObject_MockObject */
+       private $userManager;
+
+       /** @var  IShare|\PHPUnit_Framework_MockObject_MockObject */
+       private $share;
+
+       protected function setUp() {
+               parent::setUp();
+
+               self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
+               \OCP\Share::registerBackend('test', 'Test\Share\Backend');
+
+               $config = $this->getMockBuilder('\OCP\IConfig')
+                               ->disableOriginalConstructor()->getMock();
+               $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService')->getMock();
+               $httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper')
+                               ->setConstructorArgs([$config, $clientService])
+                               ->getMock();
+               $httpHelperMock->expects($this->any())->method('post')->with($this->anything())->will($this->returnValue(true));
+               $this->share = $this->getMockBuilder('\OCP\Share\IShare')->getMock();
+               $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider')
+                       ->disableOriginalConstructor()->getMock();
+               $this->federatedShareProvider->expects($this->any())
+                       ->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
+               $this->federatedShareProvider->expects($this->any())
+                       ->method('isIncomingServer2serverShareEnabled')->willReturn(true);
+               $this->federatedShareProvider->expects($this->any())->method('getShareById')
+                       ->willReturn($this->share);
+
+               $this->notifications = $this->getMockBuilder('OCA\FederatedFileSharing\Notifications')
+                       ->disableOriginalConstructor()->getMock();
+               $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler')
+                       ->disableOriginalConstructor()->getMock();
+               $this->userManager = $this->getMockBuilder('OCP\IUserManager')->getMock();
+               
+               $this->registerHttpHelper($httpHelperMock);
+
+               $this->s2s = new RequestHandlerController(
+                       'federatedfilesharing',
+                       \OC::$server->getRequest(),
+                       $this->federatedShareProvider,
+                       \OC::$server->getDatabaseConnection(),
+                       \OC::$server->getShareManager(),
+                       $this->notifications,
+                       $this->addressHandler,
+                       $this->userManager
+               );
+
+               $this->connection = \OC::$server->getDatabaseConnection();
+       }
+
+       protected function tearDown() {
+               $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external`');
+               $query->execute();
+
+               $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share`');
+               $query->execute();
+
+               $this->restoreHttpHelper();
+
+               parent::tearDown();
+       }
+
+       /**
+        * Register an http helper mock for testing purposes.
+        * @param \OC\HTTPHelper $httpHelper helper mock
+        */
+       private function registerHttpHelper($httpHelper) {
+               $this->oldHttpHelper = \OC::$server->query('HTTPHelper');
+               \OC::$server->registerService('HTTPHelper', function ($c) use ($httpHelper) {
+                       return $httpHelper;
+               });
+       }
+
+       /**
+        * Restore the original http helper
+        */
+       private function restoreHttpHelper() {
+               $oldHttpHelper = $this->oldHttpHelper;
+               \OC::$server->registerService('HTTPHelper', function ($c) use ($oldHttpHelper) {
+                       return $oldHttpHelper;
+               });
+       }
+
+       /**
+        * @medium
+        */
+       function testCreateShare() {
+               // simulate a post request
+               $_POST['remote'] = 'localhost';
+               $_POST['token'] = 'token';
+               $_POST['name'] = 'name';
+               $_POST['owner'] = 'owner';
+               $_POST['shareWith'] = self::TEST_FILES_SHARING_API_USER2;
+               $_POST['remoteId'] = 1;
+
+               $this->s2s->createShare(null);
+
+               $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ?');
+               $result = $query->execute(array('1'));
+               $data = $result->fetchRow();
+
+               $this->assertSame('localhost', $data['remote']);
+               $this->assertSame('token', $data['share_token']);
+               $this->assertSame('/name', $data['name']);
+               $this->assertSame('owner', $data['owner']);
+               $this->assertSame(self::TEST_FILES_SHARING_API_USER2, $data['user']);
+               $this->assertSame(1, (int)$data['remote_id']);
+               $this->assertSame(0, (int)$data['accepted']);
+       }
+
+
+       function testDeclineShare() {
+
+               $this->s2s = $this->getMockBuilder('\OCA\FederatedFileSharing\Controller\RequestHandlerController')
+                       ->setConstructorArgs(
+                               [
+                                       'federatedfilessharing',
+                                       \OC::$server->getRequest(),
+                                       $this->federatedShareProvider,
+                                       \OC::$server->getDatabaseConnection(),
+                                       \OC::$server->getShareManager(),
+                                       $this->notifications,
+                                       $this->addressHandler,
+                                       $this->userManager
+                               ]
+                       )->setMethods(['executeDeclineShare', 'verifyShare'])->getMock();
+
+               $this->s2s->expects($this->once())->method('executeDeclineShare');
+
+               $this->s2s->expects($this->any())->method('verifyShare')->willReturn(true);
+
+               $_POST['token'] = 'token';
+
+               $this->s2s->declineShare(42);
+
+       }
+
+       function XtestDeclineShareMultiple() {
+
+               $this->share->expects($this->any())->method('verifyShare')->willReturn(true);
+
+               $dummy = \OCP\DB::prepare('
+                       INSERT INTO `*PREFIX*share`
+                       (`share_type`, `uid_owner`, `item_type`, `item_source`, `item_target`, `file_source`, `file_target`, `permissions`, `stime`, `token`, `share_with`)
+                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+                       ');
+               $dummy->execute(array(\OCP\Share::SHARE_TYPE_REMOTE, self::TEST_FILES_SHARING_API_USER1, 'test', '1', '/1', '1', '/test.txt', '1', time(), 'token1', 'foo@bar'));
+               $dummy->execute(array(\OCP\Share::SHARE_TYPE_REMOTE, self::TEST_FILES_SHARING_API_USER1, 'test', '1', '/1', '1', '/test.txt', '1', time(), 'token2', 'bar@bar'));
+
+               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
+               $result = $verify->execute();
+               $data = $result->fetchAll();
+               $this->assertCount(2, $data);
+
+               $_POST['token'] = 'token1';
+               $this->s2s->declineShare(array('id' => $data[0]['id']));
+
+               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
+               $result = $verify->execute();
+               $data = $result->fetchAll();
+               $this->assertCount(1, $data);
+               $this->assertEquals('bar@bar', $data[0]['share_with']);
+
+               $_POST['token'] = 'token2';
+               $this->s2s->declineShare(array('id' => $data[0]['id']));
+
+               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
+               $result = $verify->execute();
+               $data = $result->fetchAll();
+               $this->assertEmpty($data);
+       }
+
+       /**
+        * @dataProvider dataTestDeleteUser
+        */
+       function testDeleteUser($toDelete, $expected, $remainingUsers) {
+               $this->createDummyS2SShares();
+
+               $discoveryManager = new DiscoveryManager(
+                       \OC::$server->getMemCacheFactory(),
+                       \OC::$server->getHTTPClientService()
+               );
+               $manager = new \OCA\Files_Sharing\External\Manager(
+                       \OC::$server->getDatabaseConnection(),
+                       Filesystem::getMountManager(),
+                       Filesystem::getLoader(),
+                       \OC::$server->getHTTPClientService(),
+                       \OC::$server->getNotificationManager(),
+                       $discoveryManager,
+                       $toDelete
+               );
+
+               $manager->removeUserShares($toDelete);
+
+               $query = $this->connection->prepare('SELECT `user` FROM `*PREFIX*share_external`');
+               $query->execute();
+               $result = $query->fetchAll();
+
+               foreach ($result as $r) {
+                       $remainingShares[$r['user']] = isset($remainingShares[$r['user']]) ? $remainingShares[$r['user']] + 1 : 1;
+               }
+
+               $this->assertSame($remainingUsers, count($remainingShares));
+
+               foreach ($expected as $key => $value) {
+                       if ($key === $toDelete) {
+                               $this->assertArrayNotHasKey($key, $remainingShares);
+                       } else {
+                               $this->assertSame($value, $remainingShares[$key]);
+                       }
+               }
+
+       }
+
+       function dataTestDeleteUser() {
+               return array(
+                       array('user1', array('user1' => 0, 'user2' => 3, 'user3' => 3), 2),
+                       array('user2', array('user1' => 4, 'user2' => 0, 'user3' => 3), 2),
+                       array('user3', array('user1' => 4, 'user2' => 3, 'user3' => 0), 2),
+                       array('user4', array('user1' => 4, 'user2' => 3, 'user3' => 3), 3),
+               );
+       }
+
+       private function createDummyS2SShares() {
+               $query = $this->connection->prepare('
+                       INSERT INTO `*PREFIX*share_external`
+                       (`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `remote_id`, `accepted`)
+                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+                       ');
+
+               $users = array('user1', 'user2', 'user3');
+
+               for ($i = 0; $i < 10; $i++) {
+                       $user = $users[$i%3];
+                       $query->execute(array('remote', 'token', 'password', 'name', 'owner', $user, 'mount point', $i, $i, 0));
+               }
+
+               $query = $this->connection->prepare('SELECT `id` FROM `*PREFIX*share_external`');
+               $query->execute();
+               $dummyEntries = $query->fetchAll();
+
+               $this->assertSame(10, count($dummyEntries));
+       }
+
+       /**
+        * @dataProvider dataTestGetShare
+        *
+        * @param bool $found
+        * @param bool $correctId
+        * @param bool $correctToken
+        */
+       public function testGetShare($found, $correctId, $correctToken) {
+
+               $connection = \OC::$server->getDatabaseConnection();
+               $query = $connection->getQueryBuilder();
+               $stime = time();
+               $query->insert('share')
+                       ->values(
+                               [
+                                       'share_type' => $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE),
+                                       'uid_owner' => $query->createNamedParameter(self::TEST_FILES_SHARING_API_USER1),
+                                       'uid_initiator' => $query->createNamedParameter(self::TEST_FILES_SHARING_API_USER2),
+                                       'item_type' => $query->createNamedParameter('test'),
+                                       'item_source' => $query->createNamedParameter('1'),
+                                       'item_target' => $query->createNamedParameter('/1'),
+                                       'file_source' => $query->createNamedParameter('1'),
+                                       'file_target' => $query->createNamedParameter('/test.txt'),
+                                       'permissions' => $query->createNamedParameter('1'),
+                                       'stime' => $query->createNamedParameter($stime),
+                                       'token' => $query->createNamedParameter('token'),
+                                       'share_with' => $query->createNamedParameter('foo@bar'),
+                               ]
+                       )->execute();
+               $id = $query->getLastInsertId();
+
+               $expected = [
+                       'share_type' => (string)FederatedShareProvider::SHARE_TYPE_REMOTE,
+                       'uid_owner' => self::TEST_FILES_SHARING_API_USER1,
+                       'item_type' => 'test',
+                       'item_source' => '1',
+                       'item_target' => '/1',
+                       'file_source' => '1',
+                       'file_target' => '/test.txt',
+                       'permissions' => '1',
+                       'stime' => (string)$stime,
+                       'token' => 'token',
+                       'share_with' => 'foo@bar',
+                       'id' => (string)$id,
+                       'uid_initiator' => self::TEST_FILES_SHARING_API_USER2,
+                       'parent' => null,
+                       'accepted' => '0',
+                       'expiration' => null,
+                       'mail_send' => '0'
+               ];
+
+               $searchToken = $correctToken ? 'token' : 'wrongToken';
+               $searchId = $correctId ? $id : -1;
+
+               $result = $this->invokePrivate($this->s2s, 'getShare', [$searchId, $searchToken]);
+
+               if ($found) {
+                       $this->assertEquals($expected, $result);
+               } else {
+                       $this->assertSame(false, $result);
+               }
+       }
+
+       public function dataTestGetShare() {
+               return [
+                       [true, true, true],
+                       [false, false, true],
+                       [false, true, false],
+                       [false, false, false],
+               ];
+       }
+
+}
diff --git a/apps/federatedfilesharing/tests/RequestHandlerTest.php b/apps/federatedfilesharing/tests/RequestHandlerTest.php
deleted file mode 100644 (file)
index 8f9f138..0000000
+++ /dev/null
@@ -1,383 +0,0 @@
-<?php
-/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program.  If not, see <http://www.gnu.org/licenses/>
- *
- */
-
-namespace OCA\FederatedFileSharing\Tests;
-
-use OC\Files\Filesystem;
-use OCA\FederatedFileSharing\DiscoveryManager;
-use OCA\FederatedFileSharing\FederatedShareProvider;
-use OCA\FederatedFileSharing\RequestHandler;
-use OCP\IUserManager;
-use OCP\Share\IShare;
-
-/**
- * Class RequestHandlerTest
- *
- * @package OCA\FederatedFileSharing\Tests
- * @group DB
- */
-class RequestHandlerTest extends TestCase {
-
-       const TEST_FOLDER_NAME = '/folder_share_api_test';
-
-       /**
-        * @var \OCP\IDBConnection
-        */
-       private $connection;
-
-       /**
-        * @var RequestHandler
-        */
-       private $s2s;
-
-       /** @var  \OCA\FederatedFileSharing\FederatedShareProvider | PHPUnit_Framework_MockObject_MockObject */
-       private $federatedShareProvider;
-
-       /** @var  \OCA\FederatedFileSharing\Notifications | PHPUnit_Framework_MockObject_MockObject */
-       private $notifications;
-
-       /** @var  \OCA\FederatedFileSharing\AddressHandler | PHPUnit_Framework_MockObject_MockObject */
-       private $addressHandler;
-       
-       /** @var  IUserManager | \PHPUnit_Framework_MockObject_MockObject */
-       private $userManager;
-
-       /** @var  IShare | \PHPUnit_Framework_MockObject_MockObject */
-       private $share;
-
-       protected function setUp() {
-               parent::setUp();
-
-               self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
-               \OCP\Share::registerBackend('test', 'Test\Share\Backend');
-
-               $config = $this->getMockBuilder('\OCP\IConfig')
-                               ->disableOriginalConstructor()->getMock();
-               $clientService = $this->getMock('\OCP\Http\Client\IClientService');
-               $httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper')
-                               ->setConstructorArgs([$config, $clientService])
-                               ->getMock();
-               $httpHelperMock->expects($this->any())->method('post')->with($this->anything())->will($this->returnValue(true));
-               $this->share = $this->getMock('\OCP\Share\IShare');
-               $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider')
-                       ->disableOriginalConstructor()->getMock();
-               $this->federatedShareProvider->expects($this->any())
-                       ->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
-               $this->federatedShareProvider->expects($this->any())
-                       ->method('isIncomingServer2serverShareEnabled')->willReturn(true);
-               $this->federatedShareProvider->expects($this->any())->method('getShareById')
-                       ->willReturn($this->share);
-
-               $this->notifications = $this->getMockBuilder('OCA\FederatedFileSharing\Notifications')
-                       ->disableOriginalConstructor()->getMock();
-               $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler')
-                       ->disableOriginalConstructor()->getMock();
-               $this->userManager = $this->getMock('OCP\IUserManager');
-               
-               $this->registerHttpHelper($httpHelperMock);
-
-               $this->s2s = new RequestHandler(
-                       $this->federatedShareProvider,
-                       \OC::$server->getDatabaseConnection(),
-                       \OC::$server->getShareManager(),
-                       \OC::$server->getRequest(),
-                       $this->notifications,
-                       $this->addressHandler,
-                       $this->userManager
-               );
-
-               $this->connection = \OC::$server->getDatabaseConnection();
-       }
-
-       protected function tearDown() {
-               $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external`');
-               $query->execute();
-
-               $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share`');
-               $query->execute();
-
-               $this->restoreHttpHelper();
-
-               parent::tearDown();
-       }
-
-       /**
-        * Register an http helper mock for testing purposes.
-        * @param $httpHelper http helper mock
-        */
-       private function registerHttpHelper($httpHelper) {
-               $this->oldHttpHelper = \OC::$server->query('HTTPHelper');
-               \OC::$server->registerService('HTTPHelper', function ($c) use ($httpHelper) {
-                       return $httpHelper;
-               });
-       }
-
-       /**
-        * Restore the original http helper
-        */
-       private function restoreHttpHelper() {
-               $oldHttpHelper = $this->oldHttpHelper;
-               \OC::$server->registerService('HTTPHelper', function ($c) use ($oldHttpHelper) {
-                       return $oldHttpHelper;
-               });
-       }
-
-       /**
-        * @medium
-        */
-       function testCreateShare() {
-               // simulate a post request
-               $_POST['remote'] = 'localhost';
-               $_POST['token'] = 'token';
-               $_POST['name'] = 'name';
-               $_POST['owner'] = 'owner';
-               $_POST['shareWith'] = self::TEST_FILES_SHARING_API_USER2;
-               $_POST['remoteId'] = 1;
-
-               $result = $this->s2s->createShare(null);
-
-               $this->assertTrue($result->succeeded());
-
-               $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ?');
-               $result = $query->execute(array('1'));
-               $data = $result->fetchRow();
-
-               $this->assertSame('localhost', $data['remote']);
-               $this->assertSame('token', $data['share_token']);
-               $this->assertSame('/name', $data['name']);
-               $this->assertSame('owner', $data['owner']);
-               $this->assertSame(self::TEST_FILES_SHARING_API_USER2, $data['user']);
-               $this->assertSame(1, (int)$data['remote_id']);
-               $this->assertSame(0, (int)$data['accepted']);
-       }
-
-
-       function testDeclineShare() {
-
-               $this->s2s = $this->getMockBuilder('\OCA\FederatedFileSharing\RequestHandler')
-                       ->setConstructorArgs(
-                               [
-                                       $this->federatedShareProvider,
-                                       \OC::$server->getDatabaseConnection(),
-                                       \OC::$server->getShareManager(),
-                                       \OC::$server->getRequest(),
-                                       $this->notifications,
-                                       $this->addressHandler,
-                                       $this->userManager
-                               ]
-                       )->setMethods(['executeDeclineShare', 'verifyShare'])->getMock();
-
-               $this->s2s->expects($this->once())->method('executeDeclineShare');
-
-               $this->s2s->expects($this->any())->method('verifyShare')->willReturn(true);
-
-               $_POST['token'] = 'token';
-
-               $this->s2s->declineShare(array('id' => 42));
-
-       }
-
-       function XtestDeclineShareMultiple() {
-
-               $this->share->expects($this->any())->method('verifyShare')->willReturn(true);
-
-               $dummy = \OCP\DB::prepare('
-                       INSERT INTO `*PREFIX*share`
-                       (`share_type`, `uid_owner`, `item_type`, `item_source`, `item_target`, `file_source`, `file_target`, `permissions`, `stime`, `token`, `share_with`)
-                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
-                       ');
-               $dummy->execute(array(\OCP\Share::SHARE_TYPE_REMOTE, self::TEST_FILES_SHARING_API_USER1, 'test', '1', '/1', '1', '/test.txt', '1', time(), 'token1', 'foo@bar'));
-               $dummy->execute(array(\OCP\Share::SHARE_TYPE_REMOTE, self::TEST_FILES_SHARING_API_USER1, 'test', '1', '/1', '1', '/test.txt', '1', time(), 'token2', 'bar@bar'));
-
-               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
-               $result = $verify->execute();
-               $data = $result->fetchAll();
-               $this->assertCount(2, $data);
-
-               $_POST['token'] = 'token1';
-               $this->s2s->declineShare(array('id' => $data[0]['id']));
-
-               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
-               $result = $verify->execute();
-               $data = $result->fetchAll();
-               $this->assertCount(1, $data);
-               $this->assertEquals('bar@bar', $data[0]['share_with']);
-
-               $_POST['token'] = 'token2';
-               $this->s2s->declineShare(array('id' => $data[0]['id']));
-
-               $verify = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share`');
-               $result = $verify->execute();
-               $data = $result->fetchAll();
-               $this->assertEmpty($data);
-       }
-
-       /**
-        * @dataProvider dataTestDeleteUser
-        */
-       function testDeleteUser($toDelete, $expected, $remainingUsers) {
-               $this->createDummyS2SShares();
-
-               $discoveryManager = new DiscoveryManager(
-                       \OC::$server->getMemCacheFactory(),
-                       \OC::$server->getHTTPClientService()
-               );
-               $manager = new \OCA\Files_Sharing\External\Manager(
-                       \OC::$server->getDatabaseConnection(),
-                       Filesystem::getMountManager(),
-                       Filesystem::getLoader(),
-                       \OC::$server->getHTTPClientService(),
-                       \OC::$server->getNotificationManager(),
-                       $discoveryManager,
-                       $toDelete
-               );
-
-               $manager->removeUserShares($toDelete);
-
-               $query = $this->connection->prepare('SELECT `user` FROM `*PREFIX*share_external`');
-               $query->execute();
-               $result = $query->fetchAll();
-
-               foreach ($result as $r) {
-                       $remainingShares[$r['user']] = isset($remainingShares[$r['user']]) ? $remainingShares[$r['user']] + 1 : 1;
-               }
-
-               $this->assertSame($remainingUsers, count($remainingShares));
-
-               foreach ($expected as $key => $value) {
-                       if ($key === $toDelete) {
-                               $this->assertArrayNotHasKey($key, $remainingShares);
-                       } else {
-                               $this->assertSame($value, $remainingShares[$key]);
-                       }
-               }
-
-       }
-
-       function dataTestDeleteUser() {
-               return array(
-                       array('user1', array('user1' => 0, 'user2' => 3, 'user3' => 3), 2),
-                       array('user2', array('user1' => 4, 'user2' => 0, 'user3' => 3), 2),
-                       array('user3', array('user1' => 4, 'user2' => 3, 'user3' => 0), 2),
-                       array('user4', array('user1' => 4, 'user2' => 3, 'user3' => 3), 3),
-               );
-       }
-
-       private function createDummyS2SShares() {
-               $query = $this->connection->prepare('
-                       INSERT INTO `*PREFIX*share_external`
-                       (`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `remote_id`, `accepted`)
-                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
-                       ');
-
-               $users = array('user1', 'user2', 'user3');
-
-               for ($i = 0; $i < 10; $i++) {
-                       $user = $users[$i%3];
-                       $query->execute(array('remote', 'token', 'password', 'name', 'owner', $user, 'mount point', $i, $i, 0));
-               }
-
-               $query = $this->connection->prepare('SELECT `id` FROM `*PREFIX*share_external`');
-               $query->execute();
-               $dummyEntries = $query->fetchAll();
-
-               $this->assertSame(10, count($dummyEntries));
-       }
-
-       /**
-        * @dataProvider dataTestGetShare
-        *
-        * @param bool $found
-        * @param bool $correctId
-        * @param bool $correctToken
-        */
-       public function testGetShare($found, $correctId, $correctToken) {
-
-               $connection = \OC::$server->getDatabaseConnection();
-               $query = $connection->getQueryBuilder();
-               $stime = time();
-               $query->insert('share')
-                       ->values(
-                               [
-                                       'share_type' => $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE),
-                                       'uid_owner' => $query->createNamedParameter(self::TEST_FILES_SHARING_API_USER1),
-                                       'uid_initiator' => $query->createNamedParameter(self::TEST_FILES_SHARING_API_USER2),
-                                       'item_type' => $query->createNamedParameter('test'),
-                                       'item_source' => $query->createNamedParameter('1'),
-                                       'item_target' => $query->createNamedParameter('/1'),
-                                       'file_source' => $query->createNamedParameter('1'),
-                                       'file_target' => $query->createNamedParameter('/test.txt'),
-                                       'permissions' => $query->createNamedParameter('1'),
-                                       'stime' => $query->createNamedParameter($stime),
-                                       'token' => $query->createNamedParameter('token'),
-                                       'share_with' => $query->createNamedParameter('foo@bar'),
-                               ]
-                       )->execute();
-               $id = $query->getLastInsertId();
-
-               $expected = [
-                       'share_type' => (string)FederatedShareProvider::SHARE_TYPE_REMOTE,
-                       'uid_owner' => self::TEST_FILES_SHARING_API_USER1,
-                       'item_type' => 'test',
-                       'item_source' => '1',
-                       'item_target' => '/1',
-                       'file_source' => '1',
-                       'file_target' => '/test.txt',
-                       'permissions' => '1',
-                       'stime' => (string)$stime,
-                       'token' => 'token',
-                       'share_with' => 'foo@bar',
-                       'id' => (string)$id,
-                       'uid_initiator' => self::TEST_FILES_SHARING_API_USER2,
-                       'parent' => null,
-                       'accepted' => '0',
-                       'expiration' => null,
-                       'mail_send' => '0'
-               ];
-
-               $searchToken = $correctToken ? 'token' : 'wrongToken';
-               $searchId = $correctId ? $id : -1;
-
-               $result = $this->invokePrivate($this->s2s, 'getShare', [$searchId, $searchToken]);
-
-               if ($found) {
-                       $this->assertEquals($expected, $result);
-               } else {
-                       $this->assertSame(false, $result);
-               }
-       }
-
-       public function dataTestGetShare() {
-               return [
-                       [true, true, true],
-                       [false, false, true],
-                       [false, true, false],
-                       [false, false, false],
-               ];
-       }
-
-}
index d14f32e045c8d42c8afafaf98a5bf59b6ad092c6..3085cd9db65c3eaeae992d1749b6848819ccd485 100644 (file)
@@ -75,76 +75,3 @@ API::register(
        'core',
        API::USER_AUTH
        );
-
-// Server-to-Server Sharing
-if (\OC::$server->getAppManager()->isEnabledForUser('files_sharing')) {
-       $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
-       $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
-               \OC::$server->getURLGenerator(),
-               \OC::$server->getL10N('federatedfilesharing')
-       );
-       $notification = new \OCA\FederatedFileSharing\Notifications(
-               $addressHandler,
-               \OC::$server->getHTTPClientService(),
-               new \OCA\FederatedFileSharing\DiscoveryManager(\OC::$server->getMemCacheFactory(), \OC::$server->getHTTPClientService()),
-               \OC::$server->getJobList()
-       );
-       $s2s = new OCA\FederatedFileSharing\RequestHandler(
-               $federatedSharingApp->getFederatedShareProvider(),
-               \OC::$server->getDatabaseConnection(),
-               \OC::$server->getShareManager(),
-               \OC::$server->getRequest(),
-               $notification,
-               $addressHandler,
-               \OC::$server->getUserManager()
-       );
-       API::register('post',
-               '/cloud/shares',
-               array($s2s, 'createShare'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-       API::register('post',
-               '/cloud/shares/{id}/reshare',
-               array($s2s, 'reShare'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-       API::register('post',
-               '/cloud/shares/{id}/permissions',
-               array($s2s, 'updatePermissions'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-
-       API::register('post',
-               '/cloud/shares/{id}/accept',
-               array($s2s, 'acceptShare'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-       API::register('post',
-               '/cloud/shares/{id}/decline',
-               array($s2s, 'declineShare'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-       API::register('post',
-               '/cloud/shares/{id}/unshare',
-               array($s2s, 'unshare'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-
-       API::register('post',
-               '/cloud/shares/{id}/revoke',
-               array($s2s, 'revoke'),
-               'files_sharing',
-               API::GUEST_AUTH
-       );
-}