Completed
Push — master ( 363a27...0ca584 )
by Maxence
06:28 queued 03:00
created

FederatedService::requestLinkWithCircle()   B

Complexity

Conditions 2
Paths 9

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 29
rs 8.8571
cc 2
eloc 21
nc 9
nop 2
1
<?php
2
/**
3
 * Circles - Bring cloud-users closer together.
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Maxence Lange <[email protected]>
9
 * @copyright 2017
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 *
25
 */
26
27
namespace OCA\Circles\Service;
28
29
30
use Exception;
31
use OC\Http\Client\ClientService;
32
use OCA\Circles\Db\CirclesRequest;
33
use OCA\Circles\Db\FederatedLinksRequest;
34
use OCA\Circles\Exceptions\FederatedCircleLinkFormatException;
35
use OCA\Circles\Exceptions\FederatedCircleNotAllowedException;
36
use OCA\Circles\Exceptions\CircleTypeNotValid;
37
use OCA\Circles\Exceptions\FederatedRemoteCircleDoesNotExistException;
38
use OCA\Circles\Exceptions\FederatedRemoteDoesNotAllowException;
39
use OCA\Circles\Exceptions\LinkCreationException;
40
use OCA\Circles\Exceptions\MemberIsNotAdminException;
41
use OCA\Circles\Model\Circle;
42
use OCA\Circles\Model\FederatedLink;
43
use OCA\Circles\Model\SharingFrame;
44
use OCP\IL10N;
45
46
class FederatedService {
47
48
49
	/** @var string */
50
	private $userId;
51
52
	/** @var IL10N */
53
	private $l10n;
54
55
	/** @var CirclesRequest */
56
	private $circlesRequest;
57
58
	/** @var ConfigService */
59
	private $configService;
60
61
	/** @var CirclesService */
62
	private $circlesService;
63
64
	/** @var BroadcastService */
65
	private $broadcastService;
66
67
	/** @var FederatedLinksRequest */
68
	private $federatedLinksRequest;
69
70
	/** @var string */
71
	private $serverHost;
72
73
	/** @var ClientService */
74
	private $clientService;
75
76
	/** @var MiscService */
77
	private $miscService;
78
79
80
	/**
81
	 * CirclesService constructor.
82
	 *
83
	 * @param $userId
84
	 * @param IL10N $l10n
85
	 * @param CirclesRequest $circlesRequest
86
	 * @param ConfigService $configService
87
	 * @param CirclesService $circlesService
88
	 * @param BroadcastService $broadcastService
89
	 * @param FederatedLinksRequest $federatedLinksRequest
90
	 * @param string $serverHost
91
	 * @param ClientService $clientService
92
	 * @param MiscService $miscService
93
	 */
94
	public function __construct(
95
		$userId,
96
		IL10N $l10n,
97
		CirclesRequest $circlesRequest,
98
		ConfigService $configService,
99
		CirclesService $circlesService,
100
		BroadcastService $broadcastService,
101
		FederatedLinksRequest $federatedLinksRequest,
102
		$serverHost,
103
		ClientService $clientService,
104
		MiscService $miscService
105
	) {
106
		$this->userId = $userId;
107
		$this->l10n = $l10n;
108
		$this->circlesRequest = $circlesRequest;
109
		$this->configService = $configService;
110
		$this->circlesService = $circlesService;
111
		$this->broadcastService = $broadcastService;
112
		$this->federatedLinksRequest = $federatedLinksRequest;
113
		$this->serverHost = (string)$serverHost;
114
		$this->clientService = $clientService;
115
		$this->miscService = $miscService;
116
	}
117
118
119
	/**
120
	 * linkCircle()
121
	 *
122
	 * link to a circle.
123
	 * Function will check if settings allow Federated links between circles, and the format of
124
	 * the link ($remote). If no exception, a request to the remote circle will be initiated
125
	 * using requestLinkWithCircle()
126
	 *
127
	 * $remote format: <circle_name>@<remote_host>
128
	 *
129
	 * @param int $circleId
130
	 * @param string $remote
131
	 *
132
	 * @throws Exception
133
	 * @throws FederatedCircleLinkFormatException
134
	 * @throws CircleTypeNotValid
135
	 * @throws MemberIsNotAdminException
136
	 *
137
	 * @return FederatedLink
138
	 */
139
	public function linkCircle($circleId, $remote) {
140
141
		if (!$this->configService->isFederatedAllowed()) {
142
			throw new FederatedCircleNotAllowedException(
143
				$this->l10n->t("Federated circles are not allowed on this Nextcloud")
144
			);
145
		}
146
147
		if (strpos($remote, '@') === false) {
148
			throw new FederatedCircleLinkFormatException(
149
				$this->l10n->t("Federated link does not have a valid format")
150
			);
151
		}
152
153
		try {
154
			return $this->requestLinkWithCircle($circleId, $remote);
155
		} catch (Exception $e) {
156
			throw $e;
157
		}
158
	}
159
160
161
	/**
162
	 * requestLinkWithCircle()
163
	 *
164
	 * Using CircleId, function will get more infos from the database.
165
	 * Will check if author is not admin and initiate a FederatedLink, save it
166
	 * in the database and send a request to the remote circle using requestLink()
167
	 * If any issue, entry is removed from the database.
168
	 *
169
	 * @param integer $circleId
170
	 * @param string $remote
171
	 *
172
	 * @return FederatedLink
173
	 * @throws Exception
174
	 */
175
	private function requestLinkWithCircle($circleId, $remote) {
176
177
		$link = null;
178
		try {
179
			list($remoteCircle, $remoteAddress) = explode('@', $remote, 2);
180
181
			$circle = $this->circlesService->detailsCircle($circleId);
182
			$circle->getUser()
183
				   ->hasToBeAdmin();
184
			$circle->cantBePersonal();
185
186
			$link = new FederatedLink();
187
			$link->setCircleId($circleId)
188
				 ->setLocalAddress($this->serverHost)
189
				 ->setAddress($remoteAddress)
190
				 ->setRemoteCircleName($remoteCircle)
191
				 ->setStatus(FederatedLink::STATUS_LINK_SETUP)
192
				 ->generateToken();
193
194
			$this->federatedLinksRequest->create($link);
195
			$this->requestLink($circle, $link);
196
197
		} catch (Exception $e) {
198
			$this->federatedLinksRequest->delete($link);
0 ignored issues
show
Bug introduced by
It seems like $link defined by null on line 177 can be null; however, OCA\Circles\Db\FederatedLinksRequest::delete() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
199
			throw $e;
200
		}
201
202
		return $link;
203
	}
204
205
206
	/**
207
	 * @param string $remote
208
	 *
209
	 * @return string
210
	 */
211 View Code Duplication
	private function generateLinkRemoteURL($remote) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212
		if (strpos($remote, 'https') !== 0) {
213
			$remote = 'https://' . $remote;
214
		}
215
216
		return rtrim($remote, '/') . '/index.php/apps/circles/v1/circles/link/';
217
	}
218
219
	/**
220
	 * @param string $remote
221
	 *
222
	 * @return string
223
	 */
224 View Code Duplication
	private function generatePayloadDeliveryURL($remote) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
		if (strpos($remote, 'https') !== 0) {
226
			$remote = 'https://' . $remote;
227
		}
228
229
		return rtrim($remote, '/') . '/index.php/apps/circles/v1/circles/payload/';
230
	}
231
232
233
	/**
234
	 * requestLink()
235
	 *
236
	 *
237
	 * @param Circle $circle
238
	 * @param FederatedLink $link
239
	 *
240
	 * @return boolean
241
	 * @throws Exception
242
	 */
243
	private function requestLink(Circle $circle, FederatedLink & $link) {
244
		$args = [
245
			'token'      => $link->getToken(),
246
			'uniqueId'   => $circle->getUniqueId(),
247
			'sourceName' => $circle->getName(),
248
			'linkTo'     => $link->getRemoteCircleName(),
249
			'address'    => $link->getLocalAddress()
250
		];
251
252
		$client = $this->clientService->newClient();
253
254
		try {
255
			$request = $client->post(
256
				$this->generateLinkRemoteURL($link->getAddress()), [
257
																	 'body'            => $args,
258
																	 'timeout'         => 10,
259
																	 'connect_timeout' => 10,
260
																 ]
261
			);
262
263
			$result = json_decode($request->getBody(), true);
264
265
			$link->setStatus($result['status']);
266
			if (!$link->isValid()) {
267
				$this->parsingRequestLinkResult($result);
268
			}
269
270
			$link->setUniqueId($result['uniqueId']);
271
			$this->federatedLinksRequest->update($link);
272
273
			return true;
274
		} catch (Exception $e) {
275
			throw $e;
276
		}
277
	}
278
279
280
	private function parsingRequestLinkResult($result) {
281
282
		if ($result['reason'] === 'federated_not_allowed') {
283
			throw new FederatedRemoteDoesNotAllowException(
284
				$this->l10n->t('Federated circles are not allowed on the remote Nextcloud')
285
			);
286
		}
287
288
		if ($result['reason'] === 'duplicate_unique_id') {
289
			throw new FederatedRemoteDoesNotAllowException(
290
				$this->l10n->t('It seems that you are trying to link a circle to itself')
291
			);
292
		}
293
294
		if ($result['reason'] === 'duplicate_link') {
295
			throw new FederatedRemoteDoesNotAllowException(
296
				$this->l10n->t('This link exists already')
297
			);
298
		}
299
300
		if ($result['reason'] === 'circle_does_not_exist') {
301
			throw new FederatedRemoteCircleDoesNotExistException(
302
				$this->l10n->t('The requested remote circle does not exist')
303
			);
304
		}
305
306
		throw new Exception($result['reason']);
307
	}
308
309
310
	/**
311
	 * Create a new link into database and assign the correct status.
312
	 *
313
	 * @param Circle $circle
314
	 * @param FederatedLink $link
315
	 *
316
	 * @throws Exception
317
	 */
318
	public function initiateLink(Circle $circle, FederatedLink & $link) {
319
320
		try {
321
			$this->checkLinkRequestValidity($circle, $link);
322
			$link->setCircleId($circle->getId());
323
324
			if ($circle->getType() === Circle::CIRCLES_PUBLIC) {
325
				$link->setStatus(FederatedLink::STATUS_LINK_UP);
326
			} else {
327
				$link->setStatus(FederatedLink::STATUS_REQUEST_SENT);
328
			}
329
330
			$this->federatedLinksRequest->create($link);
331
		} catch (Exception $e) {
332
			throw $e;
333
		}
334
	}
335
336
337
	/**
338
	 * @param Circle $circle
339
	 * @param FederatedLink $link
340
	 *
341
	 * @throws LinkCreationException
342
	 */
343
	private function checkLinkRequestValidity($circle, $link) {
344
345
		if ($circle === null) {
346
			throw new LinkCreationException('circle_does_not_exist');
347
		}
348
349
		if ($circle->getUniqueId() === $link->getUniqueId()) {
350
			throw new LinkCreationException('duplicate_unique_id');
351
		}
352
353
		if ($this->getLink($circle->getId(), $link->getUniqueId()) !== null) {
354
			throw new LinkCreationException('duplicate_link');
355
		}
356
	}
357
358
359
	/**
360
	 * @param string $token
361
	 * @param string $uniqueId
362
	 * @param SharingFrame $frame
363
	 *
364
	 * @return bool
365
	 * @throws Exception
366
	 */
367
	public function receiveFrame($token, $uniqueId, SharingFrame & $frame) {
368
369
		$link = $this->circlesRequest->getLinkFromToken((string)$token, (string)$uniqueId);
370
		if ($link === null) {
371
			return false;
372
			// TODO: throw Exception
373
		}
374
375
		if ($this->circlesRequest->getFrame($link->getCircleId(), $frame->getUniqueId())) {
376
			$this->miscService->log("FRAME ALREADY EXIST !!!");
377
378
			return false;
379
			// TODO: throw Exception
380
		}
381
382
383
		$circle = $this->circlesRequest->getDetails($link->getCircleId());
384
		if ($circle === null) {
385
			throw new Exception('unknown_circle');
386
		}
387
		$frame->setCircleId($link->getCircleId());
388
		$frame->setCircleName($circle->getName());
389
390
		$this->circlesRequest->saveFrame($frame);
391
		$this->broadcastService->broadcastFrame($frame->getHeader('broadcast'), $frame);
392
393
		return true;
394
	}
395
396
	/**
397
	 * @param integer $circleId
398
	 * @param string $uniqueId
399
	 *
400
	 * @return FederatedLink
0 ignored issues
show
Documentation introduced by
Should the return type not be FederatedLink|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
401
	 */
402
	public function getLink($circleId, $uniqueId) {
403
		return $this->federatedLinksRequest->getFromUniqueId($circleId, $uniqueId);
404
	}
405
406
407
	/**
408
	 * @param integer $circleId
409
	 *
410
	 * @return FederatedLink[]
411
	 */
412
	public function getLinks($circleId) {
413
		return $this->federatedLinksRequest->getLinked($circleId);
414
	}
415
416
417
	/**
418
	 * @param int $circleId
419
	 * @param string $uniqueId
420
	 *
421
	 * @return bool
422
	 * @throws Exception
423
	 */
424
	public function initiateRemoteShare($circleId, $uniqueId) {
425
		$args = [
426
			'circleId' => (int)$circleId,
427
			'uniqueId' => (string)$uniqueId
428
		];
429
430
		$client = $this->clientService->newClient();
431
		try {
432
			$request = $client->post(
433
				$this->generatePayloadDeliveryURL($this->serverHost), [
434
																		'body'            => $args,
435
																		'timeout'         => 10,
436
																		'connect_timeout' => 10,
437
																	]
438
			);
439
440
			$result = json_decode($request->getBody(), true);
441
			$this->miscService->log(
442
				"initiateRemoteShare result: " . $uniqueId . '  ----  ' . var_export($result, true)
443
			);
444
445
			return true;
446
		} catch (Exception $e) {
447
			throw $e;
448
		}
449
	}
450
451
452
	/**
453
	 * @param SharingFrame $frame
454
	 *
455
	 * @throws Exception
456
	 */
457
	public function sendRemoteShare(SharingFrame $frame) {
458
459
		$circle = $this->circlesRequest->getDetails($frame->getCircleId());
460
		if ($circle === null) {
461
			throw new Exception('unknown_circle');
462
		}
463
464
		$links = $this->getLinks($frame->getCircleId());
465
		foreach ($links AS $link) {
466
467
			$args = [
468
				'token'    => $link->getToken(),
469
				'uniqueId' => $circle->getUniqueId(),
470
				'item'     => json_encode($frame)
471
			];
472
473
			$client = $this->clientService->newClient();
474
			try {
475
				$client->put(
476
					$this->generatePayloadDeliveryURL($link->getAddress()), [
477
																			  'body'            => $args,
478
																			  'timeout'         => 10,
479
																			  'connect_timeout' => 10,
480
																		  ]
481
				);
482
			} catch (Exception $e) {
483
				throw $e;
484
			}
485
		}
486
	}
487
488
489
	/**
490
	 * generateHeaders()
491
	 *
492
	 * Generate new headers for the current Payload, and save them in the SharingFrame.
493
	 *
494
	 * @param SharingFrame $frame
495
	 */
496
	public function updateFrameWithCloudId(SharingFrame $frame) {
497
		$frame->setCloudId($this->serverHost);
498
		$this->circlesRequest->updateFrame($frame);
499
	}
500
501
}