Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FederatedService.php « Service « lib - github.com/nextcloud/circles.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 98b6a8773d83be318a9835152d308c4539f6bca3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
<?php
/**
 * Circles - Bring cloud-users closer together.
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Maxence Lange <maxence@pontapreta.net>
 * @copyright 2017
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\Circles\Service;


use Exception;
use OC\Http\Client\ClientService;
use OCA\Circles\Api\v1\Circles;
use OCA\Circles\Db\CirclesRequest;
use OCA\Circles\Db\FederatedLinksRequest;
use OCA\Circles\Exceptions\CircleDoesNotExistException;
use OCA\Circles\Exceptions\FederatedCircleLinkFormatException;
use OCA\Circles\Exceptions\FederatedCircleNotAllowedException;
use OCA\Circles\Exceptions\CircleTypeNotValidException;
use OCA\Circles\Exceptions\FederatedCircleStatusUpdateException;
use OCA\Circles\Exceptions\FederatedLinkUpdateException;
use OCA\Circles\Exceptions\FederatedRemoteCircleDoesNotExistException;
use OCA\Circles\Exceptions\FederatedRemoteDoesNotAllowException;
use OCA\Circles\Exceptions\FederatedRemoteIsDownException;
use OCA\Circles\Exceptions\PayloadDeliveryException;
use OCA\Circles\Exceptions\SharingFrameAlreadyExistException;
use OCA\Circles\Exceptions\FederatedLinkCreationException;
use OCA\Circles\Exceptions\MemberIsNotAdminException;
use OCA\Circles\Exceptions\SharingFrameDoesNotExistException;
use OCA\Circles\Model\Circle;
use OCA\Circles\Model\FederatedLink;
use OCA\Circles\Model\SharingFrame;
use OCP\IL10N;

class FederatedService {

	const REMOTE_URL_LINK = '/index.php/apps/circles/v1/link';
	const REMOTE_URL_PAYLOAD = '/index.php/apps/circles/v1/payload';

	/** @var string */
	private $userId;

	/** @var IL10N */
	private $l10n;

	/** @var CirclesRequest */
	private $circlesRequest;

	/** @var ConfigService */
	private $configService;

	/** @var CirclesService */
	private $circlesService;

	/** @var BroadcastService */
	private $broadcastService;

	/** @var FederatedLinksRequest */
	private $federatedLinksRequest;

	/** @var EventsService */
	private $eventsService;

	/** @var string */
	private $serverHost;

	/** @var ClientService */
	private $clientService;

	/** @var MiscService */
	private $miscService;


	/**
	 * CirclesService constructor.
	 *
	 * @param $userId
	 * @param IL10N $l10n
	 * @param CirclesRequest $circlesRequest
	 * @param ConfigService $configService
	 * @param CirclesService $circlesService
	 * @param BroadcastService $broadcastService
	 * @param FederatedLinksRequest $federatedLinksRequest
	 * @param EventsService $eventsService
	 * @param ClientService $clientService
	 * @param MiscService $miscService
	 */
	public function __construct(
		$userId,
		IL10N $l10n,
		CirclesRequest $circlesRequest,
		ConfigService $configService,
		CirclesService $circlesService,
		BroadcastService $broadcastService,
		FederatedLinksRequest $federatedLinksRequest,
		EventsService $eventsService,
		ClientService $clientService,
		MiscService $miscService
	) {
		$this->userId = $userId;
		$this->l10n = $l10n;
		$this->circlesRequest = $circlesRequest;
		$this->configService = $configService;
		$this->circlesService = $circlesService;
		$this->broadcastService = $broadcastService;
		$this->federatedLinksRequest = $federatedLinksRequest;
		$this->eventsService = $eventsService;
		$this->serverHost = $this->configService->getLocalAddress();


		$this->clientService = $clientService;
		$this->miscService = $miscService;
	}


	/**
	 * linkCircle();
	 *
	 * link to a circle.
	 * Function will check if settings allow Federated links between circles, and the format of
	 * the link ($remote). If no exception, a request to the remote circle will be initiated
	 * using requestLinkWithCircle()
	 *
	 * $remote format: <circle_name>@<remote_host>
	 *
	 * @param string $circleUniqueId
	 * @param string $remote
	 *
	 * @throws Exception
	 * @throws FederatedCircleLinkFormatException
	 * @throws CircleTypeNotValidException
	 *
	 * @return FederatedLink
	 */
	public function linkCircle($circleUniqueId, $remote) {

		if (!$this->configService->isFederatedCirclesAllowed()) {
			throw new FederatedCircleNotAllowedException(
				$this->l10n->t("Federated circles are not allowed on this Nextcloud")
			);
		}

		if (strpos($remote, '@') === false) {
			throw new FederatedCircleLinkFormatException(
				$this->l10n->t("Federated link does not have a valid format")
			);
		}

		try {
			return $this->requestLinkWithCircle($circleUniqueId, $remote);
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * linkStatus()
	 *
	 * Update the status of a link.
	 * Function will check if user can edit the status, will update it and send the update to
	 * remote
	 *
	 * @param int $linkId
	 * @param int $status
	 *
	 * @throws Exception
	 * @throws FederatedCircleLinkFormatException
	 * @throws CircleTypeNotValidException
	 * @throws MemberIsNotAdminException
	 *
	 * @return FederatedLink[]
	 */
	public function linkStatus($linkId, $status) {

		$status = (int)$status;
		$link = null;
		try {

			$link = $this->circlesRequest->getLinkFromId($linkId);
			$circle = $this->circlesRequest->getCircle($link->getCircleId(), $this->userId);
			$circle->hasToBeFederated();
			$circle->getHigherViewer()
				   ->hasToBeAdmin();
			$link->hasToBeValidStatusUpdate($status);

			if (!$this->eventOnLinkStatus($circle, $link, $status)) {
				return $this->circlesRequest->getLinksFromCircle($circle->getUniqueId());
			}

		} catch (Exception $e) {
			throw $e;
		}

		$link->setStatus($status);
		$link->setCircleId($circle->getUniqueId(true));

		try {
			$this->updateLinkRemote($link);
		} catch (Exception $e) {
			if ($status !== FederatedLink::STATUS_LINK_REMOVE) {
				throw $e;
			}
		}

		$this->federatedLinksRequest->update($link);

		return $this->circlesRequest->getLinksFromCircle($circle->getUniqueId());
	}


	/**
	 * eventOnLinkStatus();
	 *
	 * Called by linkStatus() to manage events when status is changing.
	 * If status does not need update, returns false;
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 * @param $status
	 *
	 * @return bool
	 */
	private function eventOnLinkStatus(Circle $circle, FederatedLink $link, $status) {
		if ($link->getStatus() === $status) {
			return false;
		}

		if ($status === FederatedLink::STATUS_LINK_REMOVE) {
			$this->eventsService->onLinkRemove($circle, $link);
		}

		if ($status === FederatedLink::STATUS_LINK_UP) {
			$this->eventsService->onLinkRequestAccepting($circle, $link);
			$this->eventsService->onLinkUp($circle, $link);
		}

		return true;
	}


	/**
	 * requestLinkWithCircle()
	 *
	 * Using CircleId, function will get more infos from the database.
	 * Will check if author is at least admin and initiate a FederatedLink, save it
	 * in the database and send a request to the remote circle using requestLink()
	 * If any issue, entry is removed from the database.
	 *
	 * @param string $circleUniqueId
	 * @param string $remote
	 *
	 * @return FederatedLink
	 * @throws Exception
	 */
	private function requestLinkWithCircle($circleUniqueId, $remote) {

		$link = null;
		try {
			list($remoteCircle, $remoteAddress) = explode('@', $remote, 2);

			$circle = $this->circlesService->detailsCircle($circleUniqueId);
			$circle->getHigherViewer()
				   ->hasToBeAdmin();
			$circle->hasToBeFederated();
			$circle->cantBePersonal();

			$link = new FederatedLink();
			$link->setCircleId($circleUniqueId)
				 ->setLocalAddress($this->serverHost)
				 ->setAddress($remoteAddress)
				 ->setRemoteCircleName($remoteCircle)
				 ->setStatus(FederatedLink::STATUS_LINK_SETUP)
				 ->generateToken();

			$this->federatedLinksRequest->create($link);
			$this->requestLink($circle, $link);

		} catch (Exception $e) {
			if ($link !== null) {
				$this->federatedLinksRequest->delete($link);
			}
			throw $e;
		}

		return $link;
	}


	/**
	 * @param string $remote
	 *
	 * @return string
	 */
	private function generateLinkRemoteURL($remote) {
		return $this->generateRemoteHost($remote) . self::REMOTE_URL_LINK;
	}


	/**
	 * @param string $remote
	 *
	 * @return string
	 */
	private function generatePayloadDeliveryURL($remote) {
		return $this->generateRemoteHost($remote) . self::REMOTE_URL_PAYLOAD;
	}


	/**
	 * @param string $remote
	 *
	 * @return string
	 */
	private function generateRemoteHost($remote) {
		if ((!$this->configService->isNonSSLLinksAllowed() || strpos($remote, 'http://') !== 0)
			&& strpos($remote, 'https://') !== 0
		) {
			$remote = 'https://' . $remote;
		}

		return rtrim($remote, '/');
	}


	/**
	 * requestLink()
	 *
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 *
	 * @return boolean
	 * @throws Exception
	 */
	private function requestLink(Circle $circle, FederatedLink &$link) {
		$args = [
			'apiVersion' => Circles::version(),
			'token'      => $link->getToken(true),
			'uniqueId'   => $circle->getUniqueId(true),
			'sourceName' => $circle->getName(),
			'linkTo'     => $link->getRemoteCircleName(),
			'address'    => $link->getLocalAddress()
		];

		$client = $this->clientService->newClient();

		try {
			$request = $client->put(
				$this->generateLinkRemoteURL($link->getAddress()), [
																	 'body'            => $args,
																	 'timeout'         => 10,
																	 'connect_timeout' => 10,
																 ]
			);

			$result = json_decode($request->getBody(), true);
			if ($result === null) {
				throw new FederatedRemoteIsDownException(
					$this->l10n->t(
						'The remote host is down or the Circles app is not installed on it'
					)
				);
			}

			$this->eventOnRequestLink(
				$circle, $link, $result['status'],
				((key_exists('reason', $result)) ? $result['reason'] : '')
			);

			$link->setUniqueId($result['uniqueId']);
			$this->federatedLinksRequest->update($link);

			return true;
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * eventOnRequestLink();
	 *
	 * Called by requestLink() will update status and event
	 * Will also manage errors returned by the remote link
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 * @param $status
	 * @param $reason
	 *
	 * @throws Exception
	 */
	private function eventOnRequestLink(Circle $circle, FederatedLink $link, $status, $reason) {

		try {
			if ($status === FederatedLink::STATUS_LINK_UP) {
				$link->setStatus(FederatedLink::STATUS_LINK_UP);
				$this->eventsService->onLinkUp($circle, $link);
			} else if ($status === FederatedLink::STATUS_LINK_REQUESTED) {
				$link->setStatus(FederatedLink::STATUS_REQUEST_SENT);
				$this->eventsService->onLinkRequestSent($circle, $link);
			} else {
				$this->parseRequestLinkError($reason);
			}
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * parseRequestLinkError();
	 *
	 * Will parse the error reason returned by requestLink() and throw an Exception
	 *
	 * @param $reason
	 *
	 * @throws Exception
	 * @throws FederatedRemoteCircleDoesNotExistException
	 * @throws FederatedRemoteDoesNotAllowException
	 */
	private function parseRequestLinkError($reason) {

		if ($reason === 'federated_not_allowed') {
			throw new FederatedRemoteDoesNotAllowException(
				$this->l10n->t('Federated circles are not allowed on the remote Nextcloud')
			);
		}

		if ($reason === 'circle_links_disable') {
			throw new FederatedRemoteDoesNotAllowException(
				$this->l10n->t('The remote circle does not accept federated links')
			);
		}

		if ($reason === 'duplicate_unique_id') {
			throw new FederatedRemoteDoesNotAllowException(
				$this->l10n->t('It seems that you are trying to link a circle to itself')
			);
		}

		if ($reason === 'duplicate_link') {
			throw new FederatedRemoteDoesNotAllowException(
				$this->l10n->t('This link exists already')
			);
		}

		if ($reason === 'circle_does_not_exist') {
			throw new FederatedRemoteCircleDoesNotExistException(
				$this->l10n->t('The requested remote circle does not exist')
			);
		}

		throw new Exception($reason);
	}


	/**
	 * @param string $token
	 * @param string $uniqueId
	 * @param int $status
	 *
	 * @return FederatedLink
	 * @throws Exception
	 */
	public function updateLinkFromRemote($token, $uniqueId, $status) {
		try {
			$link = $this->circlesRequest->getLinkFromToken($token, $uniqueId);
			$circle = $this->circlesRequest->forceGetCircle($link->getCircleId());
			$circle->hasToBeFederated();

			$this->checkUpdateLinkFromRemote($status);
			$this->checkUpdateLinkFromRemoteLinkUp($circle, $link, $status);
			$this->checkUpdateLinkFromRemoteLinkRemove($circle, $link, $status);

			if ($link->getStatus() !== $status) {
				$this->federatedLinksRequest->update($link);
			}

			return $link;
		} catch (Exception $e) {
			throw $e;
		}
	}

	/**
	 * checkUpdateLinkFromRemote();
	 *
	 * will throw exception is the status sent by remote is not correct
	 *
	 * @param int $status
	 *
	 * @throws FederatedCircleStatusUpdateException
	 */
	private function checkUpdateLinkFromRemote($status) {
		$status = (int)$status;
		if ($status !== FederatedLink::STATUS_LINK_UP
			&& $status !== FederatedLink::STATUS_LINK_REMOVE
		) {
			throw new FederatedCircleStatusUpdateException(
				$this->l10n->t('Cannot proceed with this status update')
			);
		}
	}


	/**
	 * checkUpdateLinkFromRemoteLinkUp()
	 *
	 * in case of a request of status update from remote for a link up, we check the current
	 * status of the link locally.
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 * @param int $status
	 *
	 * @throws FederatedCircleStatusUpdateException
	 */
	private function checkUpdateLinkFromRemoteLinkUp(Circle $circle, FederatedLink $link, $status) {
		if ((int)$status !== FederatedLink::STATUS_LINK_UP) {
			return;
		}

		if ($link->getStatus() !== FederatedLink::STATUS_REQUEST_SENT) {
			throw new FederatedCircleStatusUpdateException(
				$this->l10n->t('Cannot proceed with this status update')
			);
		}

		$this->eventsService->onLinkRequestAccepted($circle, $link);
		$this->eventsService->onLinkUp($circle, $link);
		$link->setStatus($status);
	}


	/**
	 * checkUpdateLinkFromRemoteLinkRemove();
	 *
	 * in case of a request of status update from remote for a link down, we check the current
	 * status of the link locally
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 * @param int $status
	 *
	 * @throws FederatedCircleStatusUpdateException
	 */
	private function checkUpdateLinkFromRemoteLinkRemove(
		Circle $circle, FederatedLink $link, $status
	) {
		if ((int)$status !== FederatedLink::STATUS_LINK_REMOVE) {
			return;
		}

		if ($link->getStatus() === FederatedLink::STATUS_REQUEST_SENT) {
			$link->setStatus(FederatedLink::STATUS_REQUEST_DECLINED);
			$this->eventsService->onLinkRequestRejected($circle, $link);

			return;
		}

		if ($link->getStatus() === FederatedLink::STATUS_LINK_REQUESTED) {
			$link->setStatus(FederatedLink::STATUS_LINK_REMOVE);
			$this->eventsService->onLinkRequestCanceled($circle, $link);

			return;
		}

		if ($link->getStatus() > FederatedLink::STATUS_LINK_DOWN) {
			$link->setStatus(FederatedLink::STATUS_LINK_DOWN);
			$this->eventsService->onLinkDown($circle, $link);

			return;
		}

		throw new FederatedCircleStatusUpdateException(
			$this->l10n->t('Cannot proceed with this status update')
		);
	}


	/**
	 * updateLinkRemote()
	 *
	 * Send a request to the remote of the link to update its status.
	 *
	 * @param FederatedLink $link
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function updateLinkRemote(FederatedLink &$link) {
		$args = [
			'apiVersion' => Circles::version(),
			'token'      => $link->getToken(true),
			'uniqueId'   => $link->getCircleId(true),
			'status'     => $link->getStatus()
		];

		$client = $this->clientService->newClient();
		try {
			$request = $client->post(
				$this->generateLinkRemoteURL($link->getAddress()), [
																	 'body'            => $args,
																	 'timeout'         => 10,
																	 'connect_timeout' => 10,
																 ]
			);

			$result = json_decode($request->getBody(), true);
			if ($result['status'] === -1) {
				throw new FederatedLinkUpdateException($result['reason']);
			}

			return true;
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * Create a new link into database and assign the correct status.
	 *
	 * @param Circle $circle
	 * @param FederatedLink $link
	 *
	 * @throws Exception
	 */
	public function initiateLink(Circle $circle, FederatedLink &$link) {

		try {
			$this->checkLinkRequestValidity($circle, $link);
			$link->setCircleId($circle->getUniqueId());

			if ($circle->getSetting('allow_links_auto') === 'true') {
				$link->setStatus(FederatedLink::STATUS_LINK_UP);
				$this->eventsService->onLinkUp($circle, $link);
			} else {
				$link->setStatus(FederatedLink::STATUS_LINK_REQUESTED);
				$this->eventsService->onLinkRequestReceived($circle, $link);
			}

			$this->federatedLinksRequest->create($link);
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * @param Circle $circle
	 * @param FederatedLink $link
	 *
	 * @throws FederatedLinkCreationException
	 */
	private function checkLinkRequestValidity($circle, $link) {
		if ($circle->getUniqueId(true) === $link->getUniqueId(true)) {
			throw new FederatedLinkCreationException('duplicate_unique_id');
		}

		if ($this->getLink($circle->getUniqueId(), $link->getUniqueId(true)) !== null) {
			throw new FederatedLinkCreationException('duplicate_link');
		}

		if ($circle->getSetting('allow_links') !== 'true') {
			throw new FederatedLinkCreationException('circle_links_disable');
		}
	}


	/**
	 * @param string $token
	 * @param string $uniqueId
	 * @param SharingFrame $frame
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function receiveFrame($token, $uniqueId, SharingFrame &$frame) {
		try {
			$link = $this->circlesRequest->getLinkFromToken((string)$token, (string)$uniqueId);
		} catch (Exception $e) {
			throw $e;
		}

		try {
			$this->circlesRequest->getFrame($link->getCircleId(), $frame->getUniqueId());
			throw new SharingFrameAlreadyExistException('shares_is_already_known');
		} catch (SharingFrameDoesNotExistException $e) {
		}

		try {
			$circle = $this->circlesRequest->forceGetCircle($link->getCircleId());
		} catch (CircleDoesNotExistException $e) {
			throw new CircleDoesNotExistException('unknown_circle');
		}

		$frame->setCircleId($link->getCircleId());
		$frame->setCircleName($circle->getName());
		$frame->setCircleType($circle->getType());

		$this->circlesRequest->saveFrame($frame);
		$this->broadcastService->broadcastFrame($frame->getHeader('broadcast'), $frame);

		return true;
	}

	/**
	 * @param string $circleUniqueId
	 * @param string $uniqueId
	 *
	 * @return FederatedLink
	 */
	public function getLink($circleUniqueId, $uniqueId) {
		return $this->federatedLinksRequest->getFromUniqueId($circleUniqueId, $uniqueId);
	}


	/**
	 * @param string $circleUniqueId
	 *
	 * @return FederatedLink[]
	 */
	public function getLinksFromCircle($circleUniqueId) {
		return $this->federatedLinksRequest->getLinked($circleUniqueId);
	}


	/**
	 * @param string $circleUniqueId
	 * @param string $frameUniqueId
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function initiateRemoteShare($circleUniqueId, $frameUniqueId) {
		$args = [
			'apiVersion' => Circles::version(),
			'circleId'   => $circleUniqueId,
			'frameId'    => $frameUniqueId
		];

		$client = $this->clientService->newClient();
		try {
			$client->post(
				$this->generatePayloadDeliveryURL($this->serverHost), [
																		'body'            => $args,
																		'timeout'         => 10,
																		'connect_timeout' => 10,
																	]
			);

//			$result = json_decode($request->getBody(), true);
//			$this->miscService->log(
//				"initiateRemoteShare result: " . $uniqueId . '  ----  ' . var_export($result, true)
//			);

			return true;
		} catch (Exception $e) {
			throw $e;
		}
	}


	/**
	 * @param SharingFrame $frame
	 *
	 * @throws Exception
	 */
	public function sendRemoteShare(SharingFrame $frame) {

		$circle = $this->circlesRequest->forceGetCircle($frame->getCircleId());
		if ($circle === null) {
			throw new Exception('unknown_circle');
		}

		$links = $this->getLinksFromCircle($frame->getCircleId());
		foreach ($links AS $link) {

			$args = [
				'apiVersion' => Circles::version(),
				'token'      => $link->getToken(true),
				'uniqueId'   => $circle->getUniqueId(true),
				'item'       => json_encode($frame)
			];

			$client = $this->clientService->newClient();
			try {
				$request = $client->put(
					$this->generatePayloadDeliveryURL($link->getAddress()), [
																			  'body'            => $args,
																			  'timeout'         => 10,
																			  'connect_timeout' => 10,
																		  ]
				);

				$result = json_decode($request->getBody(), true);
				if ($result['status'] === -1) {
					throw new PayloadDeliveryException($result['reason']);
				}

			} catch (Exception $e) {
				$this->miscService->log(
					'Issue while sending sharing frame to ' . $link->getAddress() . ' - '
					. $e->getMessage()
				);
			}
		}
	}


	/**
	 * generateHeaders()
	 *
	 * Generate new headers for the current Payload, and save them in the SharingFrame.
	 *
	 * @param SharingFrame $frame
	 */
	public function updateFrameWithCloudId(SharingFrame $frame) {
		$frame->setCloudId($this->serverHost);
		$this->circlesRequest->updateFrame($frame);
	}

}