Completed
Pull Request — master (#551)
by Maxence
02:17
created

CirclesRemote   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 425
Duplicated Lines 19.53 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 39
lcom 1
cbo 14
dl 83
loc 425
rs 9.28
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A configure() 0 10 1
A execute() 0 14 2
F requestInstance() 42 157 17
A saveRemote() 19 19 2
A updateRemote() 22 22 2
A outgoingTest() 0 14 1
A checkKnownInstance() 0 4 1
A verifyGSInstances() 0 13 2
A syncGSInstance() 0 13 4
A checkRemoteInstances() 0 31 4
A getRemoteType() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare(strict_types=1);
4
5
6
/**
7
 * Circles - Bring cloud-users closer together.
8
 *
9
 * This file is licensed under the Affero General Public License version 3 or
10
 * later. See the COPYING file.
11
 *
12
 * @author Maxence Lange <[email protected]>
13
 * @copyright 2021
14
 * @license GNU AGPL version 3 or any later version
15
 *
16
 * This program is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License as
18
 * published by the Free Software Foundation, either version 3 of the
19
 * License, or (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28
 *
29
 */
30
31
32
namespace OCA\Circles\Command;
33
34
use daita\MySmallPhpTools\Exceptions\RequestNetworkException;
35
use daita\MySmallPhpTools\Exceptions\SignatoryException;
36
use daita\MySmallPhpTools\Exceptions\SignatureException;
37
use daita\MySmallPhpTools\Model\Nextcloud\nc21\NC21Request;
38
use daita\MySmallPhpTools\Model\Nextcloud\nc21\NC21SignedRequest;
39
use daita\MySmallPhpTools\Traits\Nextcloud\nc21\TNC21WellKnown;
40
use daita\MySmallPhpTools\Traits\TStringTools;
41
use Exception;
42
use OC\Core\Command\Base;
43
use OCA\Circles\AppInfo\Application;
44
use OCA\Circles\Db\RemoteRequest;
45
use OCA\Circles\Exceptions\GSStatusException;
46
use OCA\Circles\Exceptions\RemoteNotFoundException;
47
use OCA\Circles\Exceptions\RemoteUidException;
48
use OCA\Circles\Model\Federated\RemoteInstance;
49
use OCA\Circles\Service\ConfigService;
50
use OCA\Circles\Service\GlobalScaleService;
51
use OCA\Circles\Service\RemoteStreamService;
52
use Symfony\Component\Console\Helper\Table;
53
use Symfony\Component\Console\Input\InputArgument;
54
use Symfony\Component\Console\Input\InputInterface;
55
use Symfony\Component\Console\Input\InputOption;
56
use Symfony\Component\Console\Output\ConsoleOutput;
57
use Symfony\Component\Console\Output\OutputInterface;
58
use Symfony\Component\Console\Question\ConfirmationQuestion;
59
60
61
/**
62
 * Class CirclesRemote
63
 *
64
 * @package OCA\Circles\Command
65
 */
66
class CirclesRemote extends Base {
67
68
69
	use TNC21WellKnown;
70
	use TStringTools;
71
72
73
	/** @var RemoteRequest */
74
	private $remoteRequest;
75
76
	/** @var GlobalScaleService */
77
	private $globalScaleService;
78
79
	/** @var RemoteStreamService */
80
	private $remoteStreamService;
81
82
	/** @var ConfigService */
83
	private $configService;
84
85
86
	/** @var InputInterface */
87
	private $input;
88
89
	/** @var OutputInterface */
90
	private $output;
91
92
93
	/**
94
	 * CirclesRemote constructor.
95
	 *
96
	 * @param RemoteRequest $remoteRequest
97
	 * @param GlobalScaleService $globalScaleService
98
	 * @param RemoteStreamService $remoteStreamService
99
	 * @param ConfigService $configService
100
	 */
101
	public function __construct(
102
		RemoteRequest $remoteRequest, GlobalScaleService $globalScaleService,
103
		RemoteStreamService $remoteStreamService,
104
		ConfigService $configService
105
	) {
106
		parent::__construct();
107
108
		$this->remoteRequest = $remoteRequest;
109
		$this->globalScaleService = $globalScaleService;
110
		$this->remoteStreamService = $remoteStreamService;
111
		$this->configService = $configService;
112
113
		$this->setup('app', 'circles');
114
	}
115
116
117
	/**
118
	 *
119
	 */
120
	protected function configure() {
121
		parent::configure();
122
		$this->setName('circles:remote')
123
			 ->setDescription('remote features')
124
			 ->addArgument('host', InputArgument::OPTIONAL, 'host of the remote instance of Nextcloud')
125
			 ->addOption(
126
				 'type', '', InputOption::VALUE_REQUIRED, 'set type of remote', RemoteInstance::TYPE_UNKNOWN
127
			 )
128
			 ->addOption('all', '', InputOption::VALUE_NONE, 'display all information');
129
	}
130
131
132
	/**
133
	 * @param InputInterface $input
134
	 * @param OutputInterface $output
135
	 *
136
	 * @return int
137
	 * @throws Exception
138
	 */
139
	protected function execute(InputInterface $input, OutputInterface $output): int {
140
		$host = $input->getArgument('host');
141
142
		$this->input = $input;
143
		$this->output = $output;
144
145
		if ($host) {
146
			$this->requestInstance($host);
147
		} else {
148
			$this->checkKnownInstance();
149
		}
150
151
		return 0;
152
	}
153
154
155
	/**
156
	 * @param string $host
157
	 *
158
	 * @throws Exception
159
	 */
160
	private function requestInstance(string $host): void {
161
		$remoteType = $this->getRemoteType();
162
163
		$webfinger = $this->getWebfinger($host, Application::APP_SUBJECT);
164 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
165
			$this->output->writeln('- Webfinger on <info>' . $host . '</info>');
166
			$this->output->writeln(json_encode($webfinger, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
167
			$this->output->writeln('');
168
		}
169
170 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
171
			$circleLink = $this->extractLink(Application::APP_REL, $webfinger);
172
			$this->output->writeln('- Information about Circles app on <info>' . $host . '</info>');
173
			$this->output->writeln(json_encode($circleLink, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
174
			$this->output->writeln('');
175
		}
176
177
		$this->output->writeln('- Available services on <info>' . $host . '</info>');
178
		foreach ($webfinger->getLinks() as $link) {
179
			$app = $link->getProperty('name');
180
			$ver = $link->getProperty('version');
181
			if ($app !== '') {
182
				$app .= ' ';
183
			}
184
			if ($ver !== '') {
185
				$ver = 'v' . $ver;
186
			}
187
188
			$this->output->writeln(' * ' . $link->getRel() . ' ' . $app . $ver);
189
		}
190
		$this->output->writeln('');
191
192
		$this->output->writeln('- Resources related to Circles on <info>' . $host . '</info>');
193
		$resource = $this->getResourceData($host, Application::APP_SUBJECT, Application::APP_REL);
194
		$this->output->writeln(json_encode($resource, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
195
		$this->output->writeln('');
196
197
198
		$tempUid = $resource->g('uid');
199
		$this->output->writeln(
200
			'- Confirming UID=' . $tempUid . ' from parsed Signatory at <info>' . $host . '</info>'
201
		);
202
203
		try {
204
			$remoteSignatory = $this->remoteStreamService->retrieveSignatory($resource->g('id'), true);
205
			$this->output->writeln(' * No SignatureException: <info>Identity authed</info>');
206
		} catch (SignatureException $e) {
207
			$this->output->writeln(
208
				'<error>' . $host . ' cannot auth its identity: ' . $e->getMessage() . '</error>'
209
			);
210
211
			return;
212
		}
213
214
		$this->output->writeln(' * Found <info>' . $remoteSignatory->getUid() . '</info>');
215
		if ($remoteSignatory->getUid(true) !== $tempUid) {
216
			$this->output->writeln('<error>looks like ' . $host . ' is faking its identity');
217
218
			return;
219
		}
220
221
		$this->output->writeln('');
222
223
		$testUrl = $resource->g('test');
224
		$this->output->writeln('- Testing signed payload on <info>' . $testUrl . '</info>');
225
226
		try {
227
			$localSignatory = $this->remoteStreamService->getAppSignatory();
228
		} catch (SignatoryException $e) {
229
			$this->output->writeln(
230
				'<error>Federated Circles not enabled locally. Please run ./occ circles:remote:init</error>'
231
			);
232
233
			return;
234
		}
235
236
		$payload = [
237
			'test'  => 42,
238
			'token' => $this->uuid()
239
		];
240
		$signedRequest = $this->outgoingTest($testUrl, $payload);
241
		$this->output->writeln(' * Payload: ');
242
		$this->output->writeln(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
243
		$this->output->writeln('');
244
245
		$this->output->writeln(' * Clear Signature: ');
246
		$this->output->writeln('<comment>' . $signedRequest->getClearSignature() . '</comment>');
247
		$this->output->writeln('');
248
249
		$this->output->writeln(' * Signed Signature (base64 encoded): ');
250
		$this->output->writeln(
251
			'<comment>' . base64_encode($signedRequest->getSignedSignature()) . '</comment>'
252
		);
253
		$this->output->writeln('');
254
255
		$result = $signedRequest->getOutgoingRequest()->getResult();
256
		$code = $result->getStatusCode();
257
		$this->output->writeln(' * Result: ' . (($code === 200) ? '<info>' . $code . '</info>' : $code));
258
		$this->output->writeln(
259
			json_encode(json_decode($result->getContent(), true), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
260
		);
261
		$this->output->writeln('');
262
263 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
264
			$this->output->writeln('');
265
			$this->output->writeln('<info>### Complete report ###</info>');
266
			$this->output->writeln(json_encode($signedRequest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
267
			$this->output->writeln('');
268
		}
269
270
		if ($remoteSignatory->getUid() !== $localSignatory->getUid()) {
271
			$remoteSignatory->setInstance($host);
272
			$remoteSignatory->setType($remoteType);
273
274
			try {
275
				$stored = new RemoteInstance();
276
				$this->remoteStreamService->confirmValidRemote($remoteSignatory, $stored);
277
				$this->output->writeln(
278
					'<info>The remote instance ' . $host
279
					. ' is already known with this current identity</info>'
280
				);
281
282 View Code Duplication
				if ($remoteSignatory->getType() !== $stored->getType()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
283
					$this->output->writeln(
284
						'- updating type from ' . $stored->getType() . ' to '
285
						. $remoteSignatory->getType()
286
					);
287
					$this->remoteStreamService->update(
288
						$remoteSignatory, RemoteStreamService::UPDATE_TYPE
289
					);
290
				}
291
292 View Code Duplication
				if ($remoteSignatory->getInstance() !== $stored->getInstance()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
293
					$this->output->writeln(
294
						'- updating host from ' . $stored->getInstance() . ' to '
295
						. $remoteSignatory->getInstance()
296
					);
297
					$this->remoteStreamService->update(
298
						$remoteSignatory, RemoteStreamService::UPDATE_INSTANCE
299
					);
300
				}
301 View Code Duplication
				if ($remoteSignatory->getId() !== $stored->getId()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
302
					$this->output->writeln(
303
						'- updating href/Id from ' . $stored->getId() . ' to '
304
						. $remoteSignatory->getId()
305
					);
306
					$this->remoteStreamService->update($remoteSignatory, RemoteStreamService::UPDATE_HREF);
307
				}
308
309
			} catch (RemoteUidException $e) {
310
				$this->updateRemote($remoteSignatory);
311
			} catch (RemoteNotFoundException $e) {
312
				$this->saveRemote($remoteSignatory);
313
			}
314
		}
315
316
	}
317
318
319
	/**
320
	 * @param RemoteInstance $remoteSignatory
321
	 *
322
	 * @throws RemoteUidException
323
	 */
324 View Code Duplication
	private function saveRemote(RemoteInstance $remoteSignatory) {
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...
325
		$this->output->writeln('');
326
		$helper = $this->getHelper('question');
327
328
		$this->output->writeln(
329
			'The remote instance <info>' . $remoteSignatory->getInstance() . '</info> looks good.'
330
		);
331
		$question = new ConfirmationQuestion(
332
			'Would you like to identify this remote instance as \'' . $remoteSignatory->getType()
333
			. '\' ? (y/N) ',
334
			false,
335
			'/^(y|Y)/i'
336
		);
337
338
		if ($helper->ask($this->input, $this->output, $question)) {
339
			$this->remoteRequest->save($remoteSignatory);
340
			$this->output->writeln('<info>remote instance saved</info>');
341
		}
342
	}
343
344
345
	/**
346
	 * @param RemoteInstance $remoteSignatory
347
	 *
348
	 * @throws RemoteUidException
349
	 */
350 View Code Duplication
	private function updateRemote(RemoteInstance $remoteSignatory): void {
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...
351
		$this->output->writeln('');
352
		$helper = $this->getHelper('question');
353
354
		$this->output->writeln(
355
			'The remote instance <info>' . $remoteSignatory->getInstance()
356
			. '</info> is known but <error>its identity has changed.</error>'
357
		);
358
		$this->output->writeln(
359
			'<comment>If you are not sure on why identity changed, please say No to the next question and contact the admin of the remote instance</comment>'
360
		);
361
		$question = new ConfirmationQuestion(
362
			'Do you consider this new identity as valid and update the entry in the database? (y/N) ',
363
			false,
364
			'/^(y|Y)/i'
365
		);
366
367
		if ($helper->ask($this->input, $this->output, $question)) {
368
			$this->remoteStreamService->update($remoteSignatory);
369
			$this->output->writeln('remote instance updated');
370
		}
371
	}
372
373
374
	/**
375
	 * @param string $remote
376
	 * @param array $payload
377
	 *
378
	 * @return NC21SignedRequest
379
	 * @throws RequestNetworkException
380
	 * @throws SignatoryException
381
	 */
382
	private function outgoingTest(string $remote, array $payload): NC21SignedRequest {
383
		$request = new NC21Request();
384
		$request->basedOnUrl($remote);
385
		$request->setFollowLocation(true);
386
		$request->setLocalAddressAllowed(true);
387
		$request->setTimeout(5);
388
		$request->setData($payload);
389
390
		$app = $this->remoteStreamService->getAppSignatory();
391
		$signedRequest = $this->remoteStreamService->signOutgoingRequest($request, $app);
392
		$this->doRequest($signedRequest->getOutgoingRequest());
393
394
		return $signedRequest;
395
	}
396
397
398
	/**
399
	 *
400
	 */
401
	private function checkKnownInstance(): void {
402
		$this->verifyGSInstances();
403
		$this->checkRemoteInstances();
404
	}
405
406
407
	/**
408
	 *
409
	 * @throws GSStatusException
410
	 */
411
	private function verifyGSInstances(): void {
412
		$instances = $this->globalScaleService->getGlobalScaleInstances();
413
		$known = array_map(
414
			function(RemoteInstance $instance): string {
415
				return $instance->getInstance();
416
			}, $this->remoteRequest->getFromType(RemoteInstance::TYPE_GLOBAL_SCALE)
417
		);
418
419
		$missing = array_diff($instances, $known);
420
		foreach ($missing as $instance) {
421
			$this->syncGSInstance($instance);
422
		}
423
	}
424
425
426
	/**
427
	 * @param string $instance
428
	 */
429
	private function syncGSInstance(string $instance): void {
430
		if ($this->configService->isLocalInstance($instance)) {
431
			return;
432
		}
433
		$this->output->write('Adding <comment>' . $instance . '</comment>: ');
434
		try {
435
			$this->remoteStreamService->addRemoteInstance($instance, RemoteInstance::TYPE_GLOBAL_SCALE, true);
436
			$this->output->writeln('<info>ok</info>');
437
		} catch (Exception $e) {
438
			$msg = ($e->getMessage() === '') ? '' : ' (' . $e->getMessage() . ')';
439
			$this->output->writeln('<error>' . get_class($e) . $msg . '</error>');
440
		}
441
	}
442
443
444
	private function checkRemoteInstances(): void {
445
		$instances = $this->remoteRequest->getAllInstances();
446
447
		$output = new ConsoleOutput();
448
		$output = $output->section();
449
		$table = new Table($output);
450
		$table->setHeaders(['instance', 'type', 'UID', 'Authed']);
451
		$table->render();
452
453
		foreach ($instances as $instance) {
454
			try {
455
				$current = $this->remoteStreamService->retrieveRemoteInstance($instance->getInstance());
456
				if ($current->getUid(true) === $instance->getUid(true)) {
457
					$currentUid = '<info>' . $current->getUid(true) . '</info>';
458
				} else {
459
					$currentUid = '<error>' . $current->getUid(true) . '</error>';
460
				}
461
			} catch (Exception $e) {
462
				$currentUid = '<error>' . $e->getMessage() . '</error>';
463
			}
464
465
			$table->appendRow(
466
				[
467
					$instance->getInstance(),
468
					$instance->getType(),
469
					$instance->getUid(),
470
					$currentUid
471
				]
472
			);
473
		}
474
	}
475
476
477
	/**
478
	 * @throws Exception
479
	 */
480
	private function getRemoteType(): string {
481
		$type = ucfirst(strtolower($this->input->getOption('type')));
482
483
		if (!in_array($type, RemoteInstance::$LIST_TYPE)) {
484
			throw new Exception('Unknown type: ' . implode(', ', RemoteInstance::$LIST_TYPE));
485
		}
486
487
		return $type;
488
	}
489
490
}
491
492