Passed
Push — master ( 70483a...bb2b94 )
by Blizzz
13:06 queued 11s
created
lib/private/Federation/CloudFederationProviderManager.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -43,197 +43,197 @@
 block discarded – undo
43 43
  */
44 44
 class CloudFederationProviderManager implements ICloudFederationProviderManager {
45 45
 
46
-	/** @var array list of available cloud federation providers */
47
-	private $cloudFederationProvider;
48
-
49
-	/** @var IAppManager */
50
-	private $appManager;
51
-
52
-	/** @var IClientService */
53
-	private $httpClientService;
54
-
55
-	/** @var ICloudIdManager */
56
-	private $cloudIdManager;
57
-
58
-	/** @var ILogger */
59
-	private $logger;
60
-
61
-	/** @var array cache OCM end-points */
62
-	private $ocmEndPoints = [];
63
-
64
-	private $supportedAPIVersion = '1.0-proposal1';
65
-
66
-	/**
67
-	 * CloudFederationProviderManager constructor.
68
-	 *
69
-	 * @param IAppManager $appManager
70
-	 * @param IClientService $httpClientService
71
-	 * @param ICloudIdManager $cloudIdManager
72
-	 * @param ILogger $logger
73
-	 */
74
-	public function __construct(IAppManager $appManager,
75
-								IClientService $httpClientService,
76
-								ICloudIdManager $cloudIdManager,
77
-								ILogger $logger) {
78
-		$this->cloudFederationProvider = [];
79
-		$this->appManager = $appManager;
80
-		$this->httpClientService = $httpClientService;
81
-		$this->cloudIdManager = $cloudIdManager;
82
-		$this->logger = $logger;
83
-	}
84
-
85
-
86
-	/**
87
-	 * Registers an callback function which must return an cloud federation provider
88
-	 *
89
-	 * @param string $resourceType which resource type does the provider handles
90
-	 * @param string $displayName user facing name of the federated share provider
91
-	 * @param callable $callback
92
-	 */
93
-	public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
94
-		$this->cloudFederationProvider[$resourceType] = [
95
-			'resourceType' => $resourceType,
96
-			'displayName' => $displayName,
97
-			'callback' => $callback,
98
-		];
99
-	}
100
-
101
-	/**
102
-	 * remove cloud federation provider
103
-	 *
104
-	 * @param string $providerId
105
-	 */
106
-	public function removeCloudFederationProvider($providerId) {
107
-		unset($this->cloudFederationProvider[$providerId]);
108
-	}
109
-
110
-	/**
111
-	 * get a list of all cloudFederationProviders
112
-	 *
113
-	 * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
114
-	 */
115
-	public function getAllCloudFederationProviders() {
116
-		return $this->cloudFederationProvider;
117
-	}
118
-
119
-	/**
120
-	 * get a specific cloud federation provider
121
-	 *
122
-	 * @param string $resourceType
123
-	 * @return ICloudFederationProvider
124
-	 * @throws ProviderDoesNotExistsException
125
-	 */
126
-	public function getCloudFederationProvider($resourceType) {
127
-		if (isset($this->cloudFederationProvider[$resourceType])) {
128
-			return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
129
-		} else {
130
-			throw new ProviderDoesNotExistsException($resourceType);
131
-		}
132
-	}
133
-
134
-	public function sendShare(ICloudFederationShare $share) {
135
-		$cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
136
-		$ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
137
-		if (empty($ocmEndPoint)) {
138
-			return false;
139
-		}
140
-
141
-		$client = $this->httpClientService->newClient();
142
-		try {
143
-			$response = $client->post($ocmEndPoint . '/shares', [
144
-				'body' => json_encode($share->getShare()),
145
-				'headers' => ['content-type' => 'application/json'],
146
-				'timeout' => 10,
147
-				'connect_timeout' => 10,
148
-			]);
149
-
150
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
151
-				$result = json_decode($response->getBody(), true);
152
-				return (is_array($result)) ? $result : [];
153
-			}
154
-		} catch (\Exception $e) {
155
-			// if flat re-sharing is not supported by the remote server
156
-			// we re-throw the exception and fall back to the old behaviour.
157
-			// (flat re-shares has been introduced in Nextcloud 9.1)
158
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
159
-				$this->logger->debug($e->getMessage());
160
-				throw $e;
161
-			}
162
-		}
163
-
164
-		return false;
165
-	}
166
-
167
-	/**
168
-	 * @param string $url
169
-	 * @param ICloudFederationNotification $notification
170
-	 * @return array|false
171
-	 */
172
-	public function sendNotification($url, ICloudFederationNotification $notification) {
173
-		$ocmEndPoint = $this->getOCMEndPoint($url);
174
-
175
-		if (empty($ocmEndPoint)) {
176
-			return false;
177
-		}
178
-
179
-		$client = $this->httpClientService->newClient();
180
-		try {
181
-			$response = $client->post($ocmEndPoint . '/notifications', [
182
-				'body' => json_encode($notification->getMessage()),
183
-				'headers' => ['content-type' => 'application/json'],
184
-				'timeout' => 10,
185
-				'connect_timeout' => 10,
186
-			]);
187
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
188
-				$result = json_decode($response->getBody(), true);
189
-				return (is_array($result)) ? $result : [];
190
-			}
191
-		} catch (\Exception $e) {
192
-			// log the error and return false
193
-			$this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
194
-		}
195
-
196
-		return false;
197
-	}
198
-
199
-	/**
200
-	 * check if the new cloud federation API is ready to be used
201
-	 *
202
-	 * @return bool
203
-	 */
204
-	public function isReady() {
205
-		return $this->appManager->isEnabledForUser('cloud_federation_api');
206
-	}
207
-	/**
208
-	 * check if server supports the new OCM api and ask for the correct end-point
209
-	 *
210
-	 * @param string $url full base URL of the cloud server
211
-	 * @return string
212
-	 */
213
-	protected function getOCMEndPoint($url) {
214
-		if (isset($this->ocmEndPoints[$url])) {
215
-			return $this->ocmEndPoints[$url];
216
-		}
217
-
218
-		$client = $this->httpClientService->newClient();
219
-		try {
220
-			$response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
221
-		} catch (\Exception $e) {
222
-			$this->ocmEndPoints[$url] = '';
223
-			return '';
224
-		}
225
-
226
-		$result = $response->getBody();
227
-		$result = json_decode($result, true);
228
-
229
-		$supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
230
-
231
-		if (isset($result['endPoint']) && $supportedVersion) {
232
-			$this->ocmEndPoints[$url] = $result['endPoint'];
233
-			return $result['endPoint'];
234
-		}
235
-
236
-		$this->ocmEndPoints[$url] = '';
237
-		return '';
238
-	}
46
+    /** @var array list of available cloud federation providers */
47
+    private $cloudFederationProvider;
48
+
49
+    /** @var IAppManager */
50
+    private $appManager;
51
+
52
+    /** @var IClientService */
53
+    private $httpClientService;
54
+
55
+    /** @var ICloudIdManager */
56
+    private $cloudIdManager;
57
+
58
+    /** @var ILogger */
59
+    private $logger;
60
+
61
+    /** @var array cache OCM end-points */
62
+    private $ocmEndPoints = [];
63
+
64
+    private $supportedAPIVersion = '1.0-proposal1';
65
+
66
+    /**
67
+     * CloudFederationProviderManager constructor.
68
+     *
69
+     * @param IAppManager $appManager
70
+     * @param IClientService $httpClientService
71
+     * @param ICloudIdManager $cloudIdManager
72
+     * @param ILogger $logger
73
+     */
74
+    public function __construct(IAppManager $appManager,
75
+                                IClientService $httpClientService,
76
+                                ICloudIdManager $cloudIdManager,
77
+                                ILogger $logger) {
78
+        $this->cloudFederationProvider = [];
79
+        $this->appManager = $appManager;
80
+        $this->httpClientService = $httpClientService;
81
+        $this->cloudIdManager = $cloudIdManager;
82
+        $this->logger = $logger;
83
+    }
84
+
85
+
86
+    /**
87
+     * Registers an callback function which must return an cloud federation provider
88
+     *
89
+     * @param string $resourceType which resource type does the provider handles
90
+     * @param string $displayName user facing name of the federated share provider
91
+     * @param callable $callback
92
+     */
93
+    public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
94
+        $this->cloudFederationProvider[$resourceType] = [
95
+            'resourceType' => $resourceType,
96
+            'displayName' => $displayName,
97
+            'callback' => $callback,
98
+        ];
99
+    }
100
+
101
+    /**
102
+     * remove cloud federation provider
103
+     *
104
+     * @param string $providerId
105
+     */
106
+    public function removeCloudFederationProvider($providerId) {
107
+        unset($this->cloudFederationProvider[$providerId]);
108
+    }
109
+
110
+    /**
111
+     * get a list of all cloudFederationProviders
112
+     *
113
+     * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
114
+     */
115
+    public function getAllCloudFederationProviders() {
116
+        return $this->cloudFederationProvider;
117
+    }
118
+
119
+    /**
120
+     * get a specific cloud federation provider
121
+     *
122
+     * @param string $resourceType
123
+     * @return ICloudFederationProvider
124
+     * @throws ProviderDoesNotExistsException
125
+     */
126
+    public function getCloudFederationProvider($resourceType) {
127
+        if (isset($this->cloudFederationProvider[$resourceType])) {
128
+            return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
129
+        } else {
130
+            throw new ProviderDoesNotExistsException($resourceType);
131
+        }
132
+    }
133
+
134
+    public function sendShare(ICloudFederationShare $share) {
135
+        $cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
136
+        $ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
137
+        if (empty($ocmEndPoint)) {
138
+            return false;
139
+        }
140
+
141
+        $client = $this->httpClientService->newClient();
142
+        try {
143
+            $response = $client->post($ocmEndPoint . '/shares', [
144
+                'body' => json_encode($share->getShare()),
145
+                'headers' => ['content-type' => 'application/json'],
146
+                'timeout' => 10,
147
+                'connect_timeout' => 10,
148
+            ]);
149
+
150
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
151
+                $result = json_decode($response->getBody(), true);
152
+                return (is_array($result)) ? $result : [];
153
+            }
154
+        } catch (\Exception $e) {
155
+            // if flat re-sharing is not supported by the remote server
156
+            // we re-throw the exception and fall back to the old behaviour.
157
+            // (flat re-shares has been introduced in Nextcloud 9.1)
158
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
159
+                $this->logger->debug($e->getMessage());
160
+                throw $e;
161
+            }
162
+        }
163
+
164
+        return false;
165
+    }
166
+
167
+    /**
168
+     * @param string $url
169
+     * @param ICloudFederationNotification $notification
170
+     * @return array|false
171
+     */
172
+    public function sendNotification($url, ICloudFederationNotification $notification) {
173
+        $ocmEndPoint = $this->getOCMEndPoint($url);
174
+
175
+        if (empty($ocmEndPoint)) {
176
+            return false;
177
+        }
178
+
179
+        $client = $this->httpClientService->newClient();
180
+        try {
181
+            $response = $client->post($ocmEndPoint . '/notifications', [
182
+                'body' => json_encode($notification->getMessage()),
183
+                'headers' => ['content-type' => 'application/json'],
184
+                'timeout' => 10,
185
+                'connect_timeout' => 10,
186
+            ]);
187
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
188
+                $result = json_decode($response->getBody(), true);
189
+                return (is_array($result)) ? $result : [];
190
+            }
191
+        } catch (\Exception $e) {
192
+            // log the error and return false
193
+            $this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
194
+        }
195
+
196
+        return false;
197
+    }
198
+
199
+    /**
200
+     * check if the new cloud federation API is ready to be used
201
+     *
202
+     * @return bool
203
+     */
204
+    public function isReady() {
205
+        return $this->appManager->isEnabledForUser('cloud_federation_api');
206
+    }
207
+    /**
208
+     * check if server supports the new OCM api and ask for the correct end-point
209
+     *
210
+     * @param string $url full base URL of the cloud server
211
+     * @return string
212
+     */
213
+    protected function getOCMEndPoint($url) {
214
+        if (isset($this->ocmEndPoints[$url])) {
215
+            return $this->ocmEndPoints[$url];
216
+        }
217
+
218
+        $client = $this->httpClientService->newClient();
219
+        try {
220
+            $response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
221
+        } catch (\Exception $e) {
222
+            $this->ocmEndPoints[$url] = '';
223
+            return '';
224
+        }
225
+
226
+        $result = $response->getBody();
227
+        $result = json_decode($result, true);
228
+
229
+        $supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
230
+
231
+        if (isset($result['endPoint']) && $supportedVersion) {
232
+            $this->ocmEndPoints[$url] = $result['endPoint'];
233
+            return $result['endPoint'];
234
+        }
235
+
236
+        $this->ocmEndPoints[$url] = '';
237
+        return '';
238
+    }
239 239
 }
Please login to merge, or discard this patch.
lib/public/Federation/ICloudFederationProviderManager.php 1 patch
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -33,74 +33,74 @@
 block discarded – undo
33 33
  */
34 34
 interface ICloudFederationProviderManager {
35 35
 
36
-	/**
37
-	 * Registers an callback function which must return an cloud federation provider
38
-	 *
39
-	 * @param string $resourceType which resource type does the provider handles
40
-	 * @param string $displayName user facing name of the federated share provider
41
-	 * @param callable $callback
42
-	 * @throws Exceptions\ProviderAlreadyExistsException
43
-	 *
44
-	 * @since 14.0.0
45
-	 */
46
-	public function addCloudFederationProvider($resourceType, $displayName, callable $callback);
36
+    /**
37
+     * Registers an callback function which must return an cloud federation provider
38
+     *
39
+     * @param string $resourceType which resource type does the provider handles
40
+     * @param string $displayName user facing name of the federated share provider
41
+     * @param callable $callback
42
+     * @throws Exceptions\ProviderAlreadyExistsException
43
+     *
44
+     * @since 14.0.0
45
+     */
46
+    public function addCloudFederationProvider($resourceType, $displayName, callable $callback);
47 47
 
48
-	/**
49
-	 * remove cloud federation provider
50
-	 *
51
-	 * @param string $resourceType
52
-	 *
53
-	 * @since 14.0.0
54
-	 */
55
-	public function removeCloudFederationProvider($resourceType);
48
+    /**
49
+     * remove cloud federation provider
50
+     *
51
+     * @param string $resourceType
52
+     *
53
+     * @since 14.0.0
54
+     */
55
+    public function removeCloudFederationProvider($resourceType);
56 56
 
57
-	/**
58
-	 * get a list of all cloudFederationProviders
59
-	 *
60
-	 * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
61
-	 *
62
-	 * @since 14.0.0
63
-	 */
64
-	public function getAllCloudFederationProviders();
57
+    /**
58
+     * get a list of all cloudFederationProviders
59
+     *
60
+     * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
61
+     *
62
+     * @since 14.0.0
63
+     */
64
+    public function getAllCloudFederationProviders();
65 65
 
66
-	/**
67
-	 * get a specific cloud federation provider
68
-	 *
69
-	 * @param string $resourceType
70
-	 * @return ICloudFederationProvider
71
-	 * @throws Exceptions\ProviderDoesNotExistsException
72
-	 *
73
-	 * @since 14.0.0
74
-	 */
75
-	public function getCloudFederationProvider($resourceType);
66
+    /**
67
+     * get a specific cloud federation provider
68
+     *
69
+     * @param string $resourceType
70
+     * @return ICloudFederationProvider
71
+     * @throws Exceptions\ProviderDoesNotExistsException
72
+     *
73
+     * @since 14.0.0
74
+     */
75
+    public function getCloudFederationProvider($resourceType);
76 76
 
77
-	/**
78
-	 * send federated share
79
-	 *
80
-	 * @param ICloudFederationShare $share
81
-	 * @return mixed
82
-	 *
83
-	 * @since 14.0.0
84
-	 */
85
-	public function sendShare(ICloudFederationShare $share);
77
+    /**
78
+     * send federated share
79
+     *
80
+     * @param ICloudFederationShare $share
81
+     * @return mixed
82
+     *
83
+     * @since 14.0.0
84
+     */
85
+    public function sendShare(ICloudFederationShare $share);
86 86
 
87
-	/**
88
-	 * send notification about existing share
89
-	 *
90
-	 * @param string $url
91
-	 * @param ICloudFederationNotification $notification
92
-	 * @return array|false
93
-	 *
94
-	 * @since 14.0.0
95
-	 */
96
-	public function sendNotification($url, ICloudFederationNotification $notification);
87
+    /**
88
+     * send notification about existing share
89
+     *
90
+     * @param string $url
91
+     * @param ICloudFederationNotification $notification
92
+     * @return array|false
93
+     *
94
+     * @since 14.0.0
95
+     */
96
+    public function sendNotification($url, ICloudFederationNotification $notification);
97 97
 
98
-	/**
99
-	 * check if the new cloud federation API is ready to be used
100
-	 *
101
-	 * @return bool
102
-	 *
103
-	 * @since 14.0.0
104
-	 */
105
-	public function isReady();
98
+    /**
99
+     * check if the new cloud federation API is ready to be used
100
+     *
101
+     * @return bool
102
+     *
103
+     * @since 14.0.0
104
+     */
105
+    public function isReady();
106 106
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 1 patch
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -38,433 +38,433 @@
 block discarded – undo
38 38
 use OCP\ILogger;
39 39
 
40 40
 class Notifications {
41
-	public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
42
-
43
-	/** @var AddressHandler */
44
-	private $addressHandler;
45
-
46
-	/** @var IClientService */
47
-	private $httpClientService;
48
-
49
-	/** @var IDiscoveryService */
50
-	private $discoveryService;
51
-
52
-	/** @var IJobList  */
53
-	private $jobList;
54
-
55
-	/** @var ICloudFederationProviderManager */
56
-	private $federationProviderManager;
57
-
58
-	/** @var ICloudFederationFactory */
59
-	private $cloudFederationFactory;
60
-
61
-	/** @var IEventDispatcher */
62
-	private $eventDispatcher;
63
-
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	public function __construct(
68
-		AddressHandler $addressHandler,
69
-		IClientService $httpClientService,
70
-		IDiscoveryService $discoveryService,
71
-		ILogger $logger,
72
-		IJobList $jobList,
73
-		ICloudFederationProviderManager $federationProviderManager,
74
-		ICloudFederationFactory $cloudFederationFactory,
75
-		IEventDispatcher $eventDispatcher
76
-	) {
77
-		$this->addressHandler = $addressHandler;
78
-		$this->httpClientService = $httpClientService;
79
-		$this->discoveryService = $discoveryService;
80
-		$this->jobList = $jobList;
81
-		$this->logger = $logger;
82
-		$this->federationProviderManager = $federationProviderManager;
83
-		$this->cloudFederationFactory = $cloudFederationFactory;
84
-		$this->eventDispatcher = $eventDispatcher;
85
-	}
86
-
87
-	/**
88
-	 * send server-to-server share to remote server
89
-	 *
90
-	 * @param string $token
91
-	 * @param string $shareWith
92
-	 * @param string $name
93
-	 * @param string $remoteId
94
-	 * @param string $owner
95
-	 * @param string $ownerFederatedId
96
-	 * @param string $sharedBy
97
-	 * @param string $sharedByFederatedId
98
-	 * @param int $shareType (can be a remote user or group share)
99
-	 * @return bool
100
-	 * @throws \OC\HintException
101
-	 * @throws \OC\ServerNotAvailableException
102
-	 */
103
-	public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
104
-		[$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
105
-
106
-		if ($user && $remote) {
107
-			$local = $this->addressHandler->generateRemoteURL();
108
-
109
-			$fields = [
110
-				'shareWith' => $user,
111
-				'token' => $token,
112
-				'name' => $name,
113
-				'remoteId' => $remoteId,
114
-				'owner' => $owner,
115
-				'ownerFederatedId' => $ownerFederatedId,
116
-				'sharedBy' => $sharedBy,
117
-				'sharedByFederatedId' => $sharedByFederatedId,
118
-				'remote' => $local,
119
-				'shareType' => $shareType
120
-			];
121
-
122
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
123
-			$status = json_decode($result['result'], true);
124
-
125
-			$ocsStatus = isset($status['ocs']);
126
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
127
-
128
-			if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
129
-				$event = new FederatedShareAddedEvent($remote);
130
-				$this->eventDispatcher->dispatchTyped($event);
131
-				return true;
132
-			} else {
133
-				$this->logger->info(
134
-					"failed sharing $name with $shareWith",
135
-					['app' => 'federatedfilesharing']
136
-				);
137
-			}
138
-		} else {
139
-			$this->logger->info(
140
-				"could not share $name, invalid contact $shareWith",
141
-				['app' => 'federatedfilesharing']
142
-			);
143
-		}
144
-
145
-		return false;
146
-	}
147
-
148
-	/**
149
-	 * ask owner to re-share the file with the given user
150
-	 *
151
-	 * @param string $token
152
-	 * @param string $id remote Id
153
-	 * @param string $shareId internal share Id
154
-	 * @param string $remote remote address of the owner
155
-	 * @param string $shareWith
156
-	 * @param int $permission
157
-	 * @param string $filename
158
-	 * @return array|false
159
-	 * @throws \OC\HintException
160
-	 * @throws \OC\ServerNotAvailableException
161
-	 */
162
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
163
-		$fields = [
164
-			'shareWith' => $shareWith,
165
-			'token' => $token,
166
-			'permission' => $permission,
167
-			'remoteId' => $shareId,
168
-		];
169
-
170
-		$ocmFields = $fields;
171
-		$ocmFields['remoteId'] = (string)$id;
172
-		$ocmFields['localId'] = $shareId;
173
-		$ocmFields['name'] = $filename;
174
-
175
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
176
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
177
-			return [$ocmResult['token'], $ocmResult['providerId']];
178
-		}
179
-
180
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
181
-		$status = json_decode($result['result'], true);
182
-
183
-		$httpRequestSuccessful = $result['success'];
184
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
185
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
186
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
187
-
188
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
189
-			return [
190
-				$status['ocs']['data']['token'],
191
-				$status['ocs']['data']['remoteId']
192
-			];
193
-		} elseif (!$validToken) {
194
-			$this->logger->info(
195
-				"invalid or missing token requesting re-share for $filename to $remote",
196
-				['app' => 'federatedfilesharing']
197
-			);
198
-		} elseif (!$validRemoteId) {
199
-			$this->logger->info(
200
-				"missing remote id requesting re-share for $filename to $remote",
201
-				['app' => 'federatedfilesharing']
202
-			);
203
-		} else {
204
-			$this->logger->info(
205
-				"failed requesting re-share for $filename to $remote",
206
-				['app' => 'federatedfilesharing']
207
-			);
208
-		}
209
-
210
-		return false;
211
-	}
212
-
213
-	/**
214
-	 * send server-to-server unshare to remote server
215
-	 *
216
-	 * @param string $remote url
217
-	 * @param string $id share id
218
-	 * @param string $token
219
-	 * @return bool
220
-	 */
221
-	public function sendRemoteUnShare($remote, $id, $token) {
222
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
223
-	}
224
-
225
-	/**
226
-	 * send server-to-server unshare to remote server
227
-	 *
228
-	 * @param string $remote url
229
-	 * @param string $id share id
230
-	 * @param string $token
231
-	 * @return bool
232
-	 */
233
-	public function sendRevokeShare($remote, $id, $token) {
234
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
235
-	}
236
-
237
-	/**
238
-	 * send notification to remote server if the permissions was changed
239
-	 *
240
-	 * @param string $remote
241
-	 * @param string $remoteId
242
-	 * @param string $token
243
-	 * @param int $permissions
244
-	 * @return bool
245
-	 */
246
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
247
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
248
-	}
249
-
250
-	/**
251
-	 * forward accept reShare to remote server
252
-	 *
253
-	 * @param string $remote
254
-	 * @param string $remoteId
255
-	 * @param string $token
256
-	 */
257
-	public function sendAcceptShare($remote, $remoteId, $token) {
258
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
259
-	}
260
-
261
-	/**
262
-	 * forward decline reShare to remote server
263
-	 *
264
-	 * @param string $remote
265
-	 * @param string $remoteId
266
-	 * @param string $token
267
-	 */
268
-	public function sendDeclineShare($remote, $remoteId, $token) {
269
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
270
-	}
271
-
272
-	/**
273
-	 * inform remote server whether server-to-server share was accepted/declined
274
-	 *
275
-	 * @param string $remote
276
-	 * @param string $token
277
-	 * @param string $remoteId Share id on the remote host
278
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
279
-	 * @param array $data
280
-	 * @param int $try
281
-	 * @return boolean
282
-	 */
283
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
284
-		$fields = [
285
-			'token' => $token,
286
-			'remoteId' => $remoteId
287
-		];
288
-		foreach ($data as $key => $value) {
289
-			$fields[$key] = $value;
290
-		}
291
-
292
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
293
-		$status = json_decode($result['result'], true);
294
-
295
-		if ($result['success'] &&
296
-			($status['ocs']['meta']['statuscode'] === 100 ||
297
-				$status['ocs']['meta']['statuscode'] === 200
298
-			)
299
-		) {
300
-			return true;
301
-		} elseif ($try === 0) {
302
-			// only add new job on first try
303
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
304
-				[
305
-					'remote' => $remote,
306
-					'remoteId' => $remoteId,
307
-					'token' => $token,
308
-					'action' => $action,
309
-					'data' => json_encode($data),
310
-					'try' => $try,
311
-					'lastRun' => $this->getTimestamp()
312
-				]
313
-			);
314
-		}
315
-
316
-		return false;
317
-	}
318
-
319
-
320
-	/**
321
-	 * return current timestamp
322
-	 *
323
-	 * @return int
324
-	 */
325
-	protected function getTimestamp() {
326
-		return time();
327
-	}
328
-
329
-	/**
330
-	 * try http post with the given protocol, if no protocol is given we pick
331
-	 * the secure one (https)
332
-	 *
333
-	 * @param string $remoteDomain
334
-	 * @param string $urlSuffix
335
-	 * @param array $fields post parameters
336
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
337
-	 * @return array
338
-	 * @throws \Exception
339
-	 */
340
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
341
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
342
-			$remoteDomain = 'https://' . $remoteDomain;
343
-		}
344
-
345
-		$result = [
346
-			'success' => false,
347
-			'result' => '',
348
-		];
349
-
350
-		// if possible we use the new OCM API
351
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
352
-		if (is_array($ocmResult)) {
353
-			$result['success'] = true;
354
-			$result['result'] = json_encode([
355
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
356
-			return $result;
357
-		}
358
-
359
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
360
-	}
361
-
362
-	/**
363
-	 * try old federated sharing API if the OCM api doesn't work
364
-	 *
365
-	 * @param $remoteDomain
366
-	 * @param $urlSuffix
367
-	 * @param array $fields
368
-	 * @return mixed
369
-	 * @throws \Exception
370
-	 */
371
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
372
-		$result = [
373
-			'success' => false,
374
-			'result' => '',
375
-		];
376
-
377
-		// Fall back to old API
378
-		$client = $this->httpClientService->newClient();
379
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
380
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
381
-		try {
382
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
383
-				'body' => $fields,
384
-				'timeout' => 10,
385
-				'connect_timeout' => 10,
386
-			]);
387
-			$result['result'] = $response->getBody();
388
-			$result['success'] = true;
389
-		} catch (\Exception $e) {
390
-			// if flat re-sharing is not supported by the remote server
391
-			// we re-throw the exception and fall back to the old behaviour.
392
-			// (flat re-shares has been introduced in Nextcloud 9.1)
393
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
394
-				throw $e;
395
-			}
396
-		}
397
-
398
-		return $result;
399
-	}
400
-
401
-	/**
402
-	 * send action regarding federated sharing to the remote server using the OCM API
403
-	 *
404
-	 * @param $remoteDomain
405
-	 * @param $fields
406
-	 * @param $action
407
-	 *
408
-	 * @return array|false
409
-	 */
410
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
411
-		switch ($action) {
412
-			case 'share':
413
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
414
-					$fields['shareWith'] . '@' . $remoteDomain,
415
-					$fields['name'],
416
-					'',
417
-					$fields['remoteId'],
418
-					$fields['ownerFederatedId'],
419
-					$fields['owner'],
420
-					$fields['sharedByFederatedId'],
421
-					$fields['sharedBy'],
422
-					$fields['token'],
423
-					$fields['shareType'],
424
-					'file'
425
-				);
426
-				return $this->federationProviderManager->sendShare($share);
427
-			case 'reshare':
428
-				// ask owner to reshare a file
429
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
430
-				$notification->setMessage('REQUEST_RESHARE',
431
-					'file',
432
-					$fields['remoteId'],
433
-					[
434
-						'sharedSecret' => $fields['token'],
435
-						'shareWith' => $fields['shareWith'],
436
-						'senderId' => $fields['localId'],
437
-						'shareType' => $fields['shareType'],
438
-						'message' => 'Ask owner to reshare the file'
439
-					]
440
-				);
441
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
442
-			case 'unshare':
443
-				//owner unshares the file from the recipient again
444
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
445
-				$notification->setMessage('SHARE_UNSHARED',
446
-					'file',
447
-					$fields['remoteId'],
448
-					[
449
-						'sharedSecret' => $fields['token'],
450
-						'messgage' => 'file is no longer shared with you'
451
-					]
452
-				);
453
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
454
-			case 'reshare_undo':
455
-				// if a reshare was unshared we send the information to the initiator/owner
456
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
457
-				$notification->setMessage('RESHARE_UNDO',
458
-					'file',
459
-					$fields['remoteId'],
460
-					[
461
-						'sharedSecret' => $fields['token'],
462
-						'message' => 'reshare was revoked'
463
-					]
464
-				);
465
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
466
-		}
467
-
468
-		return false;
469
-	}
41
+    public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
42
+
43
+    /** @var AddressHandler */
44
+    private $addressHandler;
45
+
46
+    /** @var IClientService */
47
+    private $httpClientService;
48
+
49
+    /** @var IDiscoveryService */
50
+    private $discoveryService;
51
+
52
+    /** @var IJobList  */
53
+    private $jobList;
54
+
55
+    /** @var ICloudFederationProviderManager */
56
+    private $federationProviderManager;
57
+
58
+    /** @var ICloudFederationFactory */
59
+    private $cloudFederationFactory;
60
+
61
+    /** @var IEventDispatcher */
62
+    private $eventDispatcher;
63
+
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    public function __construct(
68
+        AddressHandler $addressHandler,
69
+        IClientService $httpClientService,
70
+        IDiscoveryService $discoveryService,
71
+        ILogger $logger,
72
+        IJobList $jobList,
73
+        ICloudFederationProviderManager $federationProviderManager,
74
+        ICloudFederationFactory $cloudFederationFactory,
75
+        IEventDispatcher $eventDispatcher
76
+    ) {
77
+        $this->addressHandler = $addressHandler;
78
+        $this->httpClientService = $httpClientService;
79
+        $this->discoveryService = $discoveryService;
80
+        $this->jobList = $jobList;
81
+        $this->logger = $logger;
82
+        $this->federationProviderManager = $federationProviderManager;
83
+        $this->cloudFederationFactory = $cloudFederationFactory;
84
+        $this->eventDispatcher = $eventDispatcher;
85
+    }
86
+
87
+    /**
88
+     * send server-to-server share to remote server
89
+     *
90
+     * @param string $token
91
+     * @param string $shareWith
92
+     * @param string $name
93
+     * @param string $remoteId
94
+     * @param string $owner
95
+     * @param string $ownerFederatedId
96
+     * @param string $sharedBy
97
+     * @param string $sharedByFederatedId
98
+     * @param int $shareType (can be a remote user or group share)
99
+     * @return bool
100
+     * @throws \OC\HintException
101
+     * @throws \OC\ServerNotAvailableException
102
+     */
103
+    public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
104
+        [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
105
+
106
+        if ($user && $remote) {
107
+            $local = $this->addressHandler->generateRemoteURL();
108
+
109
+            $fields = [
110
+                'shareWith' => $user,
111
+                'token' => $token,
112
+                'name' => $name,
113
+                'remoteId' => $remoteId,
114
+                'owner' => $owner,
115
+                'ownerFederatedId' => $ownerFederatedId,
116
+                'sharedBy' => $sharedBy,
117
+                'sharedByFederatedId' => $sharedByFederatedId,
118
+                'remote' => $local,
119
+                'shareType' => $shareType
120
+            ];
121
+
122
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
123
+            $status = json_decode($result['result'], true);
124
+
125
+            $ocsStatus = isset($status['ocs']);
126
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
127
+
128
+            if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
129
+                $event = new FederatedShareAddedEvent($remote);
130
+                $this->eventDispatcher->dispatchTyped($event);
131
+                return true;
132
+            } else {
133
+                $this->logger->info(
134
+                    "failed sharing $name with $shareWith",
135
+                    ['app' => 'federatedfilesharing']
136
+                );
137
+            }
138
+        } else {
139
+            $this->logger->info(
140
+                "could not share $name, invalid contact $shareWith",
141
+                ['app' => 'federatedfilesharing']
142
+            );
143
+        }
144
+
145
+        return false;
146
+    }
147
+
148
+    /**
149
+     * ask owner to re-share the file with the given user
150
+     *
151
+     * @param string $token
152
+     * @param string $id remote Id
153
+     * @param string $shareId internal share Id
154
+     * @param string $remote remote address of the owner
155
+     * @param string $shareWith
156
+     * @param int $permission
157
+     * @param string $filename
158
+     * @return array|false
159
+     * @throws \OC\HintException
160
+     * @throws \OC\ServerNotAvailableException
161
+     */
162
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
163
+        $fields = [
164
+            'shareWith' => $shareWith,
165
+            'token' => $token,
166
+            'permission' => $permission,
167
+            'remoteId' => $shareId,
168
+        ];
169
+
170
+        $ocmFields = $fields;
171
+        $ocmFields['remoteId'] = (string)$id;
172
+        $ocmFields['localId'] = $shareId;
173
+        $ocmFields['name'] = $filename;
174
+
175
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
176
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
177
+            return [$ocmResult['token'], $ocmResult['providerId']];
178
+        }
179
+
180
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
181
+        $status = json_decode($result['result'], true);
182
+
183
+        $httpRequestSuccessful = $result['success'];
184
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
185
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
186
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
187
+
188
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
189
+            return [
190
+                $status['ocs']['data']['token'],
191
+                $status['ocs']['data']['remoteId']
192
+            ];
193
+        } elseif (!$validToken) {
194
+            $this->logger->info(
195
+                "invalid or missing token requesting re-share for $filename to $remote",
196
+                ['app' => 'federatedfilesharing']
197
+            );
198
+        } elseif (!$validRemoteId) {
199
+            $this->logger->info(
200
+                "missing remote id requesting re-share for $filename to $remote",
201
+                ['app' => 'federatedfilesharing']
202
+            );
203
+        } else {
204
+            $this->logger->info(
205
+                "failed requesting re-share for $filename to $remote",
206
+                ['app' => 'federatedfilesharing']
207
+            );
208
+        }
209
+
210
+        return false;
211
+    }
212
+
213
+    /**
214
+     * send server-to-server unshare to remote server
215
+     *
216
+     * @param string $remote url
217
+     * @param string $id share id
218
+     * @param string $token
219
+     * @return bool
220
+     */
221
+    public function sendRemoteUnShare($remote, $id, $token) {
222
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
223
+    }
224
+
225
+    /**
226
+     * send server-to-server unshare to remote server
227
+     *
228
+     * @param string $remote url
229
+     * @param string $id share id
230
+     * @param string $token
231
+     * @return bool
232
+     */
233
+    public function sendRevokeShare($remote, $id, $token) {
234
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
235
+    }
236
+
237
+    /**
238
+     * send notification to remote server if the permissions was changed
239
+     *
240
+     * @param string $remote
241
+     * @param string $remoteId
242
+     * @param string $token
243
+     * @param int $permissions
244
+     * @return bool
245
+     */
246
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
247
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
248
+    }
249
+
250
+    /**
251
+     * forward accept reShare to remote server
252
+     *
253
+     * @param string $remote
254
+     * @param string $remoteId
255
+     * @param string $token
256
+     */
257
+    public function sendAcceptShare($remote, $remoteId, $token) {
258
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
259
+    }
260
+
261
+    /**
262
+     * forward decline reShare to remote server
263
+     *
264
+     * @param string $remote
265
+     * @param string $remoteId
266
+     * @param string $token
267
+     */
268
+    public function sendDeclineShare($remote, $remoteId, $token) {
269
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
270
+    }
271
+
272
+    /**
273
+     * inform remote server whether server-to-server share was accepted/declined
274
+     *
275
+     * @param string $remote
276
+     * @param string $token
277
+     * @param string $remoteId Share id on the remote host
278
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
279
+     * @param array $data
280
+     * @param int $try
281
+     * @return boolean
282
+     */
283
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
284
+        $fields = [
285
+            'token' => $token,
286
+            'remoteId' => $remoteId
287
+        ];
288
+        foreach ($data as $key => $value) {
289
+            $fields[$key] = $value;
290
+        }
291
+
292
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
293
+        $status = json_decode($result['result'], true);
294
+
295
+        if ($result['success'] &&
296
+            ($status['ocs']['meta']['statuscode'] === 100 ||
297
+                $status['ocs']['meta']['statuscode'] === 200
298
+            )
299
+        ) {
300
+            return true;
301
+        } elseif ($try === 0) {
302
+            // only add new job on first try
303
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
304
+                [
305
+                    'remote' => $remote,
306
+                    'remoteId' => $remoteId,
307
+                    'token' => $token,
308
+                    'action' => $action,
309
+                    'data' => json_encode($data),
310
+                    'try' => $try,
311
+                    'lastRun' => $this->getTimestamp()
312
+                ]
313
+            );
314
+        }
315
+
316
+        return false;
317
+    }
318
+
319
+
320
+    /**
321
+     * return current timestamp
322
+     *
323
+     * @return int
324
+     */
325
+    protected function getTimestamp() {
326
+        return time();
327
+    }
328
+
329
+    /**
330
+     * try http post with the given protocol, if no protocol is given we pick
331
+     * the secure one (https)
332
+     *
333
+     * @param string $remoteDomain
334
+     * @param string $urlSuffix
335
+     * @param array $fields post parameters
336
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
337
+     * @return array
338
+     * @throws \Exception
339
+     */
340
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
341
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
342
+            $remoteDomain = 'https://' . $remoteDomain;
343
+        }
344
+
345
+        $result = [
346
+            'success' => false,
347
+            'result' => '',
348
+        ];
349
+
350
+        // if possible we use the new OCM API
351
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
352
+        if (is_array($ocmResult)) {
353
+            $result['success'] = true;
354
+            $result['result'] = json_encode([
355
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
356
+            return $result;
357
+        }
358
+
359
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
360
+    }
361
+
362
+    /**
363
+     * try old federated sharing API if the OCM api doesn't work
364
+     *
365
+     * @param $remoteDomain
366
+     * @param $urlSuffix
367
+     * @param array $fields
368
+     * @return mixed
369
+     * @throws \Exception
370
+     */
371
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
372
+        $result = [
373
+            'success' => false,
374
+            'result' => '',
375
+        ];
376
+
377
+        // Fall back to old API
378
+        $client = $this->httpClientService->newClient();
379
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
380
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
381
+        try {
382
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
383
+                'body' => $fields,
384
+                'timeout' => 10,
385
+                'connect_timeout' => 10,
386
+            ]);
387
+            $result['result'] = $response->getBody();
388
+            $result['success'] = true;
389
+        } catch (\Exception $e) {
390
+            // if flat re-sharing is not supported by the remote server
391
+            // we re-throw the exception and fall back to the old behaviour.
392
+            // (flat re-shares has been introduced in Nextcloud 9.1)
393
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
394
+                throw $e;
395
+            }
396
+        }
397
+
398
+        return $result;
399
+    }
400
+
401
+    /**
402
+     * send action regarding federated sharing to the remote server using the OCM API
403
+     *
404
+     * @param $remoteDomain
405
+     * @param $fields
406
+     * @param $action
407
+     *
408
+     * @return array|false
409
+     */
410
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
411
+        switch ($action) {
412
+            case 'share':
413
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
414
+                    $fields['shareWith'] . '@' . $remoteDomain,
415
+                    $fields['name'],
416
+                    '',
417
+                    $fields['remoteId'],
418
+                    $fields['ownerFederatedId'],
419
+                    $fields['owner'],
420
+                    $fields['sharedByFederatedId'],
421
+                    $fields['sharedBy'],
422
+                    $fields['token'],
423
+                    $fields['shareType'],
424
+                    'file'
425
+                );
426
+                return $this->federationProviderManager->sendShare($share);
427
+            case 'reshare':
428
+                // ask owner to reshare a file
429
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
430
+                $notification->setMessage('REQUEST_RESHARE',
431
+                    'file',
432
+                    $fields['remoteId'],
433
+                    [
434
+                        'sharedSecret' => $fields['token'],
435
+                        'shareWith' => $fields['shareWith'],
436
+                        'senderId' => $fields['localId'],
437
+                        'shareType' => $fields['shareType'],
438
+                        'message' => 'Ask owner to reshare the file'
439
+                    ]
440
+                );
441
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
442
+            case 'unshare':
443
+                //owner unshares the file from the recipient again
444
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
445
+                $notification->setMessage('SHARE_UNSHARED',
446
+                    'file',
447
+                    $fields['remoteId'],
448
+                    [
449
+                        'sharedSecret' => $fields['token'],
450
+                        'messgage' => 'file is no longer shared with you'
451
+                    ]
452
+                );
453
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
454
+            case 'reshare_undo':
455
+                // if a reshare was unshared we send the information to the initiator/owner
456
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
457
+                $notification->setMessage('RESHARE_UNDO',
458
+                    'file',
459
+                    $fields['remoteId'],
460
+                    [
461
+                        'sharedSecret' => $fields['token'],
462
+                        'message' => 'reshare was revoked'
463
+                    ]
464
+                );
465
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
466
+        }
467
+
468
+        return false;
469
+    }
470 470
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +559 added lines, -559 removed lines patch added patch discarded remove patch
@@ -51,602 +51,602 @@
 block discarded – undo
51 51
 use OCP\Share\IShare;
52 52
 
53 53
 class Manager {
54
-	public const STORAGE = '\OCA\Files_Sharing\External\Storage';
55
-
56
-	/** @var string|null */
57
-	private $uid;
58
-
59
-	/** @var IDBConnection */
60
-	private $connection;
61
-
62
-	/** @var \OC\Files\Mount\Manager */
63
-	private $mountManager;
64
-
65
-	/** @var IStorageFactory */
66
-	private $storageLoader;
67
-
68
-	/** @var IClientService */
69
-	private $clientService;
70
-
71
-	/** @var IManager */
72
-	private $notificationManager;
73
-
74
-	/** @var IDiscoveryService */
75
-	private $discoveryService;
76
-
77
-	/** @var ICloudFederationProviderManager */
78
-	private $cloudFederationProviderManager;
79
-
80
-	/** @var ICloudFederationFactory */
81
-	private $cloudFederationFactory;
82
-
83
-	/** @var IGroupManager  */
84
-	private $groupManager;
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var IEventDispatcher */
90
-	private $eventDispatcher;
91
-
92
-	public function __construct(IDBConnection $connection,
93
-								\OC\Files\Mount\Manager $mountManager,
94
-								IStorageFactory $storageLoader,
95
-								IClientService $clientService,
96
-								IManager $notificationManager,
97
-								IDiscoveryService $discoveryService,
98
-								ICloudFederationProviderManager $cloudFederationProviderManager,
99
-								ICloudFederationFactory $cloudFederationFactory,
100
-								IGroupManager $groupManager,
101
-								IUserManager $userManager,
102
-								?string $uid,
103
-								IEventDispatcher $eventDispatcher) {
104
-		$this->connection = $connection;
105
-		$this->mountManager = $mountManager;
106
-		$this->storageLoader = $storageLoader;
107
-		$this->clientService = $clientService;
108
-		$this->uid = $uid;
109
-		$this->notificationManager = $notificationManager;
110
-		$this->discoveryService = $discoveryService;
111
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
112
-		$this->cloudFederationFactory = $cloudFederationFactory;
113
-		$this->groupManager = $groupManager;
114
-		$this->userManager = $userManager;
115
-		$this->eventDispatcher = $eventDispatcher;
116
-	}
117
-
118
-	/**
119
-	 * add new server-to-server share
120
-	 *
121
-	 * @param string $remote
122
-	 * @param string $token
123
-	 * @param string $password
124
-	 * @param string $name
125
-	 * @param string $owner
126
-	 * @param int $shareType
127
-	 * @param boolean $accepted
128
-	 * @param string $user
129
-	 * @param string $remoteId
130
-	 * @param int $parent
131
-	 * @return Mount|null
132
-	 * @throws \Doctrine\DBAL\Exception
133
-	 */
134
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
135
-		$user = $user ? $user : $this->uid;
136
-		$accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
137
-		$name = Filesystem::normalizePath('/' . $name);
138
-
139
-		if ($accepted !== IShare::STATUS_ACCEPTED) {
140
-			// To avoid conflicts with the mount point generation later,
141
-			// we only use a temporary mount point name here. The real
142
-			// mount point name will be generated when accepting the share,
143
-			// using the original share item name.
144
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
145
-			$mountPoint = $tmpMountPointName;
146
-			$hash = md5($tmpMountPointName);
147
-			$data = [
148
-				'remote' => $remote,
149
-				'share_token' => $token,
150
-				'password' => $password,
151
-				'name' => $name,
152
-				'owner' => $owner,
153
-				'user' => $user,
154
-				'mountpoint' => $mountPoint,
155
-				'mountpoint_hash' => $hash,
156
-				'accepted' => $accepted,
157
-				'remote_id' => $remoteId,
158
-				'share_type' => $shareType,
159
-			];
160
-
161
-			$i = 1;
162
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
-				// The external share already exists for the user
164
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
166
-				$i++;
167
-			}
168
-			return null;
169
-		}
170
-
171
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
172
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
-		$hash = md5($mountPoint);
174
-
175
-		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
176
-
177
-		$options = [
178
-			'remote' => $remote,
179
-			'token' => $token,
180
-			'password' => $password,
181
-			'mountpoint' => $mountPoint,
182
-			'owner' => $owner
183
-		];
184
-		return $this->mountShare($options);
185
-	}
186
-
187
-	/**
188
-	 * write remote share to the database
189
-	 *
190
-	 * @param $remote
191
-	 * @param $token
192
-	 * @param $password
193
-	 * @param $name
194
-	 * @param $owner
195
-	 * @param $user
196
-	 * @param $mountPoint
197
-	 * @param $hash
198
-	 * @param $accepted
199
-	 * @param $remoteId
200
-	 * @param $parent
201
-	 * @param $shareType
202
-	 *
203
-	 * @return void
204
-	 * @throws \Doctrine\DBAL\Driver\Exception
205
-	 */
206
-	private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {
207
-		$query = $this->connection->prepare('
54
+    public const STORAGE = '\OCA\Files_Sharing\External\Storage';
55
+
56
+    /** @var string|null */
57
+    private $uid;
58
+
59
+    /** @var IDBConnection */
60
+    private $connection;
61
+
62
+    /** @var \OC\Files\Mount\Manager */
63
+    private $mountManager;
64
+
65
+    /** @var IStorageFactory */
66
+    private $storageLoader;
67
+
68
+    /** @var IClientService */
69
+    private $clientService;
70
+
71
+    /** @var IManager */
72
+    private $notificationManager;
73
+
74
+    /** @var IDiscoveryService */
75
+    private $discoveryService;
76
+
77
+    /** @var ICloudFederationProviderManager */
78
+    private $cloudFederationProviderManager;
79
+
80
+    /** @var ICloudFederationFactory */
81
+    private $cloudFederationFactory;
82
+
83
+    /** @var IGroupManager  */
84
+    private $groupManager;
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var IEventDispatcher */
90
+    private $eventDispatcher;
91
+
92
+    public function __construct(IDBConnection $connection,
93
+                                \OC\Files\Mount\Manager $mountManager,
94
+                                IStorageFactory $storageLoader,
95
+                                IClientService $clientService,
96
+                                IManager $notificationManager,
97
+                                IDiscoveryService $discoveryService,
98
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
99
+                                ICloudFederationFactory $cloudFederationFactory,
100
+                                IGroupManager $groupManager,
101
+                                IUserManager $userManager,
102
+                                ?string $uid,
103
+                                IEventDispatcher $eventDispatcher) {
104
+        $this->connection = $connection;
105
+        $this->mountManager = $mountManager;
106
+        $this->storageLoader = $storageLoader;
107
+        $this->clientService = $clientService;
108
+        $this->uid = $uid;
109
+        $this->notificationManager = $notificationManager;
110
+        $this->discoveryService = $discoveryService;
111
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
112
+        $this->cloudFederationFactory = $cloudFederationFactory;
113
+        $this->groupManager = $groupManager;
114
+        $this->userManager = $userManager;
115
+        $this->eventDispatcher = $eventDispatcher;
116
+    }
117
+
118
+    /**
119
+     * add new server-to-server share
120
+     *
121
+     * @param string $remote
122
+     * @param string $token
123
+     * @param string $password
124
+     * @param string $name
125
+     * @param string $owner
126
+     * @param int $shareType
127
+     * @param boolean $accepted
128
+     * @param string $user
129
+     * @param string $remoteId
130
+     * @param int $parent
131
+     * @return Mount|null
132
+     * @throws \Doctrine\DBAL\Exception
133
+     */
134
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
135
+        $user = $user ? $user : $this->uid;
136
+        $accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
137
+        $name = Filesystem::normalizePath('/' . $name);
138
+
139
+        if ($accepted !== IShare::STATUS_ACCEPTED) {
140
+            // To avoid conflicts with the mount point generation later,
141
+            // we only use a temporary mount point name here. The real
142
+            // mount point name will be generated when accepting the share,
143
+            // using the original share item name.
144
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
145
+            $mountPoint = $tmpMountPointName;
146
+            $hash = md5($tmpMountPointName);
147
+            $data = [
148
+                'remote' => $remote,
149
+                'share_token' => $token,
150
+                'password' => $password,
151
+                'name' => $name,
152
+                'owner' => $owner,
153
+                'user' => $user,
154
+                'mountpoint' => $mountPoint,
155
+                'mountpoint_hash' => $hash,
156
+                'accepted' => $accepted,
157
+                'remote_id' => $remoteId,
158
+                'share_type' => $shareType,
159
+            ];
160
+
161
+            $i = 1;
162
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
+                // The external share already exists for the user
164
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
166
+                $i++;
167
+            }
168
+            return null;
169
+        }
170
+
171
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
172
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
+        $hash = md5($mountPoint);
174
+
175
+        $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
176
+
177
+        $options = [
178
+            'remote' => $remote,
179
+            'token' => $token,
180
+            'password' => $password,
181
+            'mountpoint' => $mountPoint,
182
+            'owner' => $owner
183
+        ];
184
+        return $this->mountShare($options);
185
+    }
186
+
187
+    /**
188
+     * write remote share to the database
189
+     *
190
+     * @param $remote
191
+     * @param $token
192
+     * @param $password
193
+     * @param $name
194
+     * @param $owner
195
+     * @param $user
196
+     * @param $mountPoint
197
+     * @param $hash
198
+     * @param $accepted
199
+     * @param $remoteId
200
+     * @param $parent
201
+     * @param $shareType
202
+     *
203
+     * @return void
204
+     * @throws \Doctrine\DBAL\Driver\Exception
205
+     */
206
+    private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {
207
+        $query = $this->connection->prepare('
208 208
 				INSERT INTO `*PREFIX*share_external`
209 209
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
210 210
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
211 211
 			');
212
-		$query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
213
-	}
214
-
215
-	/**
216
-	 * get share
217
-	 *
218
-	 * @param int $id share id
219
-	 * @return mixed share of false
220
-	 */
221
-	public function getShare($id) {
222
-		$getShare = $this->connection->prepare('
212
+        $query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
213
+    }
214
+
215
+    /**
216
+     * get share
217
+     *
218
+     * @param int $id share id
219
+     * @return mixed share of false
220
+     */
221
+    public function getShare($id) {
222
+        $getShare = $this->connection->prepare('
223 223
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
224 224
 			FROM  `*PREFIX*share_external`
225 225
 			WHERE `id` = ?');
226
-		$result = $getShare->execute([$id]);
227
-		$share = $result->fetch();
228
-		$result->closeCursor();
229
-		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
230
-
231
-		// check if the user is allowed to access it
232
-		if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
233
-			return $share;
234
-		} elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
235
-			$user = $this->userManager->get($this->uid);
236
-			if ($this->groupManager->get($share['user'])->inGroup($user)) {
237
-				return $share;
238
-			}
239
-		}
240
-
241
-		return false;
242
-	}
243
-
244
-	/**
245
-	 * accept server-to-server share
246
-	 *
247
-	 * @param int $id
248
-	 * @return bool True if the share could be accepted, false otherwise
249
-	 */
250
-	public function acceptShare($id) {
251
-		$share = $this->getShare($id);
252
-		$result = false;
253
-
254
-		if ($share) {
255
-			\OC_Util::setupFS($this->uid);
256
-			$shareFolder = Helper::getShareFolder();
257
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
258
-			$mountPoint = Filesystem::normalizePath($mountPoint);
259
-			$hash = md5($mountPoint);
260
-			$userShareAccepted = false;
261
-
262
-			if ((int)$share['share_type'] === IShare::TYPE_USER) {
263
-				$acceptShare = $this->connection->prepare('
226
+        $result = $getShare->execute([$id]);
227
+        $share = $result->fetch();
228
+        $result->closeCursor();
229
+        $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
230
+
231
+        // check if the user is allowed to access it
232
+        if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
233
+            return $share;
234
+        } elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
235
+            $user = $this->userManager->get($this->uid);
236
+            if ($this->groupManager->get($share['user'])->inGroup($user)) {
237
+                return $share;
238
+            }
239
+        }
240
+
241
+        return false;
242
+    }
243
+
244
+    /**
245
+     * accept server-to-server share
246
+     *
247
+     * @param int $id
248
+     * @return bool True if the share could be accepted, false otherwise
249
+     */
250
+    public function acceptShare($id) {
251
+        $share = $this->getShare($id);
252
+        $result = false;
253
+
254
+        if ($share) {
255
+            \OC_Util::setupFS($this->uid);
256
+            $shareFolder = Helper::getShareFolder();
257
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
258
+            $mountPoint = Filesystem::normalizePath($mountPoint);
259
+            $hash = md5($mountPoint);
260
+            $userShareAccepted = false;
261
+
262
+            if ((int)$share['share_type'] === IShare::TYPE_USER) {
263
+                $acceptShare = $this->connection->prepare('
264 264
 				UPDATE `*PREFIX*share_external`
265 265
 				SET `accepted` = ?,
266 266
 					`mountpoint` = ?,
267 267
 					`mountpoint_hash` = ?
268 268
 				WHERE `id` = ? AND `user` = ?');
269
-				$userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
270
-			} else {
271
-				try {
272
-					$this->writeShareToDb(
273
-						$share['remote'],
274
-						$share['share_token'],
275
-						$share['password'],
276
-						$share['name'],
277
-						$share['owner'],
278
-						$this->uid,
279
-						$mountPoint, $hash, 1,
280
-						$share['remote_id'],
281
-						$id,
282
-						$share['share_type']);
283
-					$result = true;
284
-				} catch (Exception $e) {
285
-					$result = false;
286
-				}
287
-			}
288
-			if ($userShareAccepted !== false) {
289
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
290
-				$event = new FederatedShareAddedEvent($share['remote']);
291
-				$this->eventDispatcher->dispatchTyped($event);
292
-				$result = true;
293
-			}
294
-		}
295
-
296
-		// Make sure the user has no notification for something that does not exist anymore.
297
-		$this->processNotification($id);
298
-
299
-		return $result;
300
-	}
301
-
302
-	/**
303
-	 * decline server-to-server share
304
-	 *
305
-	 * @param int $id
306
-	 * @return bool True if the share could be declined, false otherwise
307
-	 */
308
-	public function declineShare($id) {
309
-		$share = $this->getShare($id);
310
-		$result = false;
311
-
312
-		if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
313
-			$removeShare = $this->connection->prepare('
269
+                $userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
270
+            } else {
271
+                try {
272
+                    $this->writeShareToDb(
273
+                        $share['remote'],
274
+                        $share['share_token'],
275
+                        $share['password'],
276
+                        $share['name'],
277
+                        $share['owner'],
278
+                        $this->uid,
279
+                        $mountPoint, $hash, 1,
280
+                        $share['remote_id'],
281
+                        $id,
282
+                        $share['share_type']);
283
+                    $result = true;
284
+                } catch (Exception $e) {
285
+                    $result = false;
286
+                }
287
+            }
288
+            if ($userShareAccepted !== false) {
289
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
290
+                $event = new FederatedShareAddedEvent($share['remote']);
291
+                $this->eventDispatcher->dispatchTyped($event);
292
+                $result = true;
293
+            }
294
+        }
295
+
296
+        // Make sure the user has no notification for something that does not exist anymore.
297
+        $this->processNotification($id);
298
+
299
+        return $result;
300
+    }
301
+
302
+    /**
303
+     * decline server-to-server share
304
+     *
305
+     * @param int $id
306
+     * @return bool True if the share could be declined, false otherwise
307
+     */
308
+    public function declineShare($id) {
309
+        $share = $this->getShare($id);
310
+        $result = false;
311
+
312
+        if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
313
+            $removeShare = $this->connection->prepare('
314 314
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
315
-			$removeShare->execute([$id, $this->uid]);
316
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
317
-
318
-			$this->processNotification($id);
319
-			$result = true;
320
-		} elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
321
-			try {
322
-				$this->writeShareToDb(
323
-					$share['remote'],
324
-					$share['share_token'],
325
-					$share['password'],
326
-					$share['name'],
327
-					$share['owner'],
328
-					$this->uid,
329
-					$share['mountpoint'],
330
-					$share['mountpoint_hash'],
331
-					0,
332
-					$share['remote_id'],
333
-					$id,
334
-					$share['share_type']);
335
-				$result = true;
336
-			} catch (Exception $e) {
337
-				$result = false;
338
-			}
339
-			$this->processNotification($id);
340
-		}
341
-
342
-		return $result;
343
-	}
344
-
345
-	/**
346
-	 * @param int $remoteShare
347
-	 */
348
-	public function processNotification($remoteShare) {
349
-		$filter = $this->notificationManager->createNotification();
350
-		$filter->setApp('files_sharing')
351
-			->setUser($this->uid)
352
-			->setObject('remote_share', (int) $remoteShare);
353
-		$this->notificationManager->markProcessed($filter);
354
-	}
355
-
356
-	/**
357
-	 * inform remote server whether server-to-server share was accepted/declined
358
-	 *
359
-	 * @param string $remote
360
-	 * @param string $token
361
-	 * @param string $remoteId Share id on the remote host
362
-	 * @param string $feedback
363
-	 * @return boolean
364
-	 */
365
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
366
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
367
-
368
-		if (is_array($result)) {
369
-			return true;
370
-		}
371
-
372
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
373
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
374
-
375
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
376
-		$fields = ['token' => $token];
377
-
378
-		$client = $this->clientService->newClient();
379
-
380
-		try {
381
-			$response = $client->post(
382
-				$url,
383
-				[
384
-					'body' => $fields,
385
-					'connect_timeout' => 10,
386
-				]
387
-			);
388
-		} catch (\Exception $e) {
389
-			return false;
390
-		}
391
-
392
-		$status = json_decode($response->getBody(), true);
393
-
394
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
395
-	}
396
-
397
-	/**
398
-	 * try send accept message to ocm end-point
399
-	 *
400
-	 * @param string $remoteDomain
401
-	 * @param string $token
402
-	 * @param string $remoteId id of the share
403
-	 * @param string $feedback
404
-	 * @return array|false
405
-	 */
406
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
407
-		switch ($feedback) {
408
-			case 'accept':
409
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
410
-				$notification->setMessage(
411
-					'SHARE_ACCEPTED',
412
-					'file',
413
-					$remoteId,
414
-					[
415
-						'sharedSecret' => $token,
416
-						'message' => 'Recipient accept the share'
417
-					]
418
-
419
-				);
420
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
421
-			case 'decline':
422
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
423
-				$notification->setMessage(
424
-					'SHARE_DECLINED',
425
-					'file',
426
-					$remoteId,
427
-					[
428
-						'sharedSecret' => $token,
429
-						'message' => 'Recipient declined the share'
430
-					]
431
-
432
-				);
433
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
434
-		}
435
-
436
-		return false;
437
-	}
438
-
439
-
440
-	/**
441
-	 * remove '/user/files' from the path and trailing slashes
442
-	 *
443
-	 * @param string $path
444
-	 * @return string
445
-	 */
446
-	protected function stripPath($path) {
447
-		$prefix = '/' . $this->uid . '/files';
448
-		return rtrim(substr($path, strlen($prefix)), '/');
449
-	}
450
-
451
-	public function getMount($data) {
452
-		$data['manager'] = $this;
453
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
454
-		$data['mountpoint'] = $mountPoint;
455
-		$data['certificateManager'] = \OC::$server->getCertificateManager();
456
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
457
-	}
458
-
459
-	/**
460
-	 * @param array $data
461
-	 * @return Mount
462
-	 */
463
-	protected function mountShare($data) {
464
-		$mount = $this->getMount($data);
465
-		$this->mountManager->addMount($mount);
466
-		return $mount;
467
-	}
468
-
469
-	/**
470
-	 * @return \OC\Files\Mount\Manager
471
-	 */
472
-	public function getMountManager() {
473
-		return $this->mountManager;
474
-	}
475
-
476
-	/**
477
-	 * @param string $source
478
-	 * @param string $target
479
-	 * @return bool
480
-	 */
481
-	public function setMountPoint($source, $target) {
482
-		$source = $this->stripPath($source);
483
-		$target = $this->stripPath($target);
484
-		$sourceHash = md5($source);
485
-		$targetHash = md5($target);
486
-
487
-		$query = $this->connection->prepare('
315
+            $removeShare->execute([$id, $this->uid]);
316
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
317
+
318
+            $this->processNotification($id);
319
+            $result = true;
320
+        } elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
321
+            try {
322
+                $this->writeShareToDb(
323
+                    $share['remote'],
324
+                    $share['share_token'],
325
+                    $share['password'],
326
+                    $share['name'],
327
+                    $share['owner'],
328
+                    $this->uid,
329
+                    $share['mountpoint'],
330
+                    $share['mountpoint_hash'],
331
+                    0,
332
+                    $share['remote_id'],
333
+                    $id,
334
+                    $share['share_type']);
335
+                $result = true;
336
+            } catch (Exception $e) {
337
+                $result = false;
338
+            }
339
+            $this->processNotification($id);
340
+        }
341
+
342
+        return $result;
343
+    }
344
+
345
+    /**
346
+     * @param int $remoteShare
347
+     */
348
+    public function processNotification($remoteShare) {
349
+        $filter = $this->notificationManager->createNotification();
350
+        $filter->setApp('files_sharing')
351
+            ->setUser($this->uid)
352
+            ->setObject('remote_share', (int) $remoteShare);
353
+        $this->notificationManager->markProcessed($filter);
354
+    }
355
+
356
+    /**
357
+     * inform remote server whether server-to-server share was accepted/declined
358
+     *
359
+     * @param string $remote
360
+     * @param string $token
361
+     * @param string $remoteId Share id on the remote host
362
+     * @param string $feedback
363
+     * @return boolean
364
+     */
365
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
366
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
367
+
368
+        if (is_array($result)) {
369
+            return true;
370
+        }
371
+
372
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
373
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
374
+
375
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
376
+        $fields = ['token' => $token];
377
+
378
+        $client = $this->clientService->newClient();
379
+
380
+        try {
381
+            $response = $client->post(
382
+                $url,
383
+                [
384
+                    'body' => $fields,
385
+                    'connect_timeout' => 10,
386
+                ]
387
+            );
388
+        } catch (\Exception $e) {
389
+            return false;
390
+        }
391
+
392
+        $status = json_decode($response->getBody(), true);
393
+
394
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
395
+    }
396
+
397
+    /**
398
+     * try send accept message to ocm end-point
399
+     *
400
+     * @param string $remoteDomain
401
+     * @param string $token
402
+     * @param string $remoteId id of the share
403
+     * @param string $feedback
404
+     * @return array|false
405
+     */
406
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
407
+        switch ($feedback) {
408
+            case 'accept':
409
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
410
+                $notification->setMessage(
411
+                    'SHARE_ACCEPTED',
412
+                    'file',
413
+                    $remoteId,
414
+                    [
415
+                        'sharedSecret' => $token,
416
+                        'message' => 'Recipient accept the share'
417
+                    ]
418
+
419
+                );
420
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
421
+            case 'decline':
422
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
423
+                $notification->setMessage(
424
+                    'SHARE_DECLINED',
425
+                    'file',
426
+                    $remoteId,
427
+                    [
428
+                        'sharedSecret' => $token,
429
+                        'message' => 'Recipient declined the share'
430
+                    ]
431
+
432
+                );
433
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
434
+        }
435
+
436
+        return false;
437
+    }
438
+
439
+
440
+    /**
441
+     * remove '/user/files' from the path and trailing slashes
442
+     *
443
+     * @param string $path
444
+     * @return string
445
+     */
446
+    protected function stripPath($path) {
447
+        $prefix = '/' . $this->uid . '/files';
448
+        return rtrim(substr($path, strlen($prefix)), '/');
449
+    }
450
+
451
+    public function getMount($data) {
452
+        $data['manager'] = $this;
453
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
454
+        $data['mountpoint'] = $mountPoint;
455
+        $data['certificateManager'] = \OC::$server->getCertificateManager();
456
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
457
+    }
458
+
459
+    /**
460
+     * @param array $data
461
+     * @return Mount
462
+     */
463
+    protected function mountShare($data) {
464
+        $mount = $this->getMount($data);
465
+        $this->mountManager->addMount($mount);
466
+        return $mount;
467
+    }
468
+
469
+    /**
470
+     * @return \OC\Files\Mount\Manager
471
+     */
472
+    public function getMountManager() {
473
+        return $this->mountManager;
474
+    }
475
+
476
+    /**
477
+     * @param string $source
478
+     * @param string $target
479
+     * @return bool
480
+     */
481
+    public function setMountPoint($source, $target) {
482
+        $source = $this->stripPath($source);
483
+        $target = $this->stripPath($target);
484
+        $sourceHash = md5($source);
485
+        $targetHash = md5($target);
486
+
487
+        $query = $this->connection->prepare('
488 488
 			UPDATE `*PREFIX*share_external`
489 489
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
490 490
 			WHERE `mountpoint_hash` = ?
491 491
 			AND `user` = ?
492 492
 		');
493
-		$result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
493
+        $result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
494 494
 
495
-		return $result;
496
-	}
495
+        return $result;
496
+    }
497 497
 
498
-	public function removeShare($mountPoint): bool {
499
-		$mountPointObj = $this->mountManager->find($mountPoint);
500
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
498
+    public function removeShare($mountPoint): bool {
499
+        $mountPointObj = $this->mountManager->find($mountPoint);
500
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
501 501
 
502
-		$mountPoint = $this->stripPath($mountPoint);
503
-		$hash = md5($mountPoint);
502
+        $mountPoint = $this->stripPath($mountPoint);
503
+        $hash = md5($mountPoint);
504 504
 
505
-		try {
506
-			$getShare = $this->connection->prepare('
505
+        try {
506
+            $getShare = $this->connection->prepare('
507 507
 				SELECT `remote`, `share_token`, `remote_id`, `share_type`, `id`
508 508
 				FROM  `*PREFIX*share_external`
509 509
 				WHERE `mountpoint_hash` = ? AND `user` = ?');
510
-			$result = $getShare->execute([$hash, $this->uid]);
511
-			$share = $result->fetch();
512
-			$result->closeCursor();
513
-			if ($share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
514
-				try {
515
-					$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
516
-				} catch (\Throwable $e) {
517
-					// if we fail to notify the remote (probably cause the remote is down)
518
-					// we still want the share to be gone to prevent undeletable remotes
519
-				}
520
-
521
-				$query = $this->connection->prepare('
510
+            $result = $getShare->execute([$hash, $this->uid]);
511
+            $share = $result->fetch();
512
+            $result->closeCursor();
513
+            if ($share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
514
+                try {
515
+                    $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
516
+                } catch (\Throwable $e) {
517
+                    // if we fail to notify the remote (probably cause the remote is down)
518
+                    // we still want the share to be gone to prevent undeletable remotes
519
+                }
520
+
521
+                $query = $this->connection->prepare('
522 522
 				DELETE FROM `*PREFIX*share_external`
523 523
 				WHERE `id` = ?
524 524
 				');
525
-				$deleteResult = $query->execute([(int)$share['id']]);
526
-				$deleteResult->closeCursor();
527
-			} elseif ($share !== false && (int)$share['share_type'] === IShare::TYPE_GROUP) {
528
-				$query = $this->connection->prepare('
525
+                $deleteResult = $query->execute([(int)$share['id']]);
526
+                $deleteResult->closeCursor();
527
+            } elseif ($share !== false && (int)$share['share_type'] === IShare::TYPE_GROUP) {
528
+                $query = $this->connection->prepare('
529 529
 					UPDATE `*PREFIX*share_external`
530 530
 					SET `accepted` = ?
531 531
 					WHERE `id` = ?');
532
-				$updateResult = $query->execute([0, (int)$share['id']]);
533
-				$updateResult->closeCursor();
534
-			}
535
-
536
-			$this->removeReShares($id);
537
-		} catch (\Doctrine\DBAL\Exception $ex) {
538
-			return false;
539
-		}
540
-
541
-		return true;
542
-	}
543
-
544
-	/**
545
-	 * remove re-shares from share table and mapping in the federated_reshares table
546
-	 *
547
-	 * @param $mountPointId
548
-	 */
549
-	protected function removeReShares($mountPointId) {
550
-		$selectQuery = $this->connection->getQueryBuilder();
551
-		$query = $this->connection->getQueryBuilder();
552
-		$selectQuery->select('id')->from('share')
553
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
554
-		$select = $selectQuery->getSQL();
555
-
556
-
557
-		$query->delete('federated_reshares')
558
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
559
-		$query->execute();
560
-
561
-		$deleteReShares = $this->connection->getQueryBuilder();
562
-		$deleteReShares->delete('share')
563
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
564
-		$deleteReShares->execute();
565
-	}
566
-
567
-	/**
568
-	 * remove all shares for user $uid if the user was deleted
569
-	 *
570
-	 * @param string $uid
571
-	 */
572
-	public function removeUserShares($uid): bool {
573
-		try {
574
-			$getShare = $this->connection->prepare('
532
+                $updateResult = $query->execute([0, (int)$share['id']]);
533
+                $updateResult->closeCursor();
534
+            }
535
+
536
+            $this->removeReShares($id);
537
+        } catch (\Doctrine\DBAL\Exception $ex) {
538
+            return false;
539
+        }
540
+
541
+        return true;
542
+    }
543
+
544
+    /**
545
+     * remove re-shares from share table and mapping in the federated_reshares table
546
+     *
547
+     * @param $mountPointId
548
+     */
549
+    protected function removeReShares($mountPointId) {
550
+        $selectQuery = $this->connection->getQueryBuilder();
551
+        $query = $this->connection->getQueryBuilder();
552
+        $selectQuery->select('id')->from('share')
553
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
554
+        $select = $selectQuery->getSQL();
555
+
556
+
557
+        $query->delete('federated_reshares')
558
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
559
+        $query->execute();
560
+
561
+        $deleteReShares = $this->connection->getQueryBuilder();
562
+        $deleteReShares->delete('share')
563
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
564
+        $deleteReShares->execute();
565
+    }
566
+
567
+    /**
568
+     * remove all shares for user $uid if the user was deleted
569
+     *
570
+     * @param string $uid
571
+     */
572
+    public function removeUserShares($uid): bool {
573
+        try {
574
+            $getShare = $this->connection->prepare('
575 575
 				SELECT `remote`, `share_token`, `remote_id`
576 576
 				FROM  `*PREFIX*share_external`
577 577
 				WHERE `user` = ?');
578
-			$result = $getShare->execute([$uid]);
579
-			$shares = $result->fetchAll();
580
-			$result->closeCursor();
581
-			foreach ($shares as $share) {
582
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
583
-			}
584
-
585
-			$query = $this->connection->prepare('
578
+            $result = $getShare->execute([$uid]);
579
+            $shares = $result->fetchAll();
580
+            $result->closeCursor();
581
+            foreach ($shares as $share) {
582
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
583
+            }
584
+
585
+            $query = $this->connection->prepare('
586 586
 				DELETE FROM `*PREFIX*share_external`
587 587
 				WHERE `user` = ?
588 588
 			');
589
-			$deleteResult = $query->execute([$uid]);
590
-			$deleteResult->closeCursor();
591
-		} catch (\Doctrine\DBAL\Exception $ex) {
592
-			return false;
593
-		}
594
-
595
-		return true;
596
-	}
597
-
598
-	/**
599
-	 * return a list of shares which are not yet accepted by the user
600
-	 *
601
-	 * @return array list of open server-to-server shares
602
-	 */
603
-	public function getOpenShares() {
604
-		return $this->getShares(false);
605
-	}
606
-
607
-	/**
608
-	 * return a list of shares which are accepted by the user
609
-	 *
610
-	 * @return array list of accepted server-to-server shares
611
-	 */
612
-	public function getAcceptedShares() {
613
-		return $this->getShares(true);
614
-	}
615
-
616
-	/**
617
-	 * return a list of shares for the user
618
-	 *
619
-	 * @param bool|null $accepted True for accepted only,
620
-	 *                            false for not accepted,
621
-	 *                            null for all shares of the user
622
-	 * @return array list of open server-to-server shares
623
-	 */
624
-	private function getShares($accepted) {
625
-		$user = $this->userManager->get($this->uid);
626
-		$groups = $this->groupManager->getUserGroups($user);
627
-		$userGroups = [];
628
-		foreach ($groups as $group) {
629
-			$userGroups[] = $group->getGID();
630
-		}
631
-
632
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
589
+            $deleteResult = $query->execute([$uid]);
590
+            $deleteResult->closeCursor();
591
+        } catch (\Doctrine\DBAL\Exception $ex) {
592
+            return false;
593
+        }
594
+
595
+        return true;
596
+    }
597
+
598
+    /**
599
+     * return a list of shares which are not yet accepted by the user
600
+     *
601
+     * @return array list of open server-to-server shares
602
+     */
603
+    public function getOpenShares() {
604
+        return $this->getShares(false);
605
+    }
606
+
607
+    /**
608
+     * return a list of shares which are accepted by the user
609
+     *
610
+     * @return array list of accepted server-to-server shares
611
+     */
612
+    public function getAcceptedShares() {
613
+        return $this->getShares(true);
614
+    }
615
+
616
+    /**
617
+     * return a list of shares for the user
618
+     *
619
+     * @param bool|null $accepted True for accepted only,
620
+     *                            false for not accepted,
621
+     *                            null for all shares of the user
622
+     * @return array list of open server-to-server shares
623
+     */
624
+    private function getShares($accepted) {
625
+        $user = $this->userManager->get($this->uid);
626
+        $groups = $this->groupManager->getUserGroups($user);
627
+        $userGroups = [];
628
+        foreach ($groups as $group) {
629
+            $userGroups[] = $group->getGID();
630
+        }
631
+
632
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
633 633
 		          FROM `*PREFIX*share_external`
634 634
 				  WHERE (`user` = ? OR `user` IN (?))';
635
-		$parameters = [$this->uid, implode(',',$userGroups)];
636
-		if (!is_null($accepted)) {
637
-			$query .= ' AND `accepted` = ?';
638
-			$parameters[] = (int) $accepted;
639
-		}
640
-		$query .= ' ORDER BY `id` ASC';
641
-
642
-		$sharesQuery = $this->connection->prepare($query);
643
-		try {
644
-			$result = $sharesQuery->execute($parameters);
645
-			$shares = $result->fetchAll();
646
-			$result->closeCursor();
647
-			return $shares;
648
-		} catch (\Doctrine\DBAL\Exception $e) {
649
-			return [];
650
-		}
651
-	}
635
+        $parameters = [$this->uid, implode(',',$userGroups)];
636
+        if (!is_null($accepted)) {
637
+            $query .= ' AND `accepted` = ?';
638
+            $parameters[] = (int) $accepted;
639
+        }
640
+        $query .= ' ORDER BY `id` ASC';
641
+
642
+        $sharesQuery = $this->connection->prepare($query);
643
+        try {
644
+            $result = $sharesQuery->execute($parameters);
645
+            $shares = $result->fetchAll();
646
+            $result->closeCursor();
647
+            return $shares;
648
+        } catch (\Doctrine\DBAL\Exception $e) {
649
+            return [];
650
+        }
651
+    }
652 652
 }
Please login to merge, or discard this patch.