Completed
Push — master ( 125f9f...2c140b )
by Julius
02:26 queued 10s
created

FederationService::getRemoteRedirectURL()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 22
cp 0
rs 9.2568
c 0
b 0
f 0
cc 5
nc 6
nop 2
crap 30
1
<?php
2
/**
3
 * @copyright Copyright (c) 2019 Julius Härtl <[email protected]>
4
 *
5
 * @author Julius Härtl <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Richdocuments\Service;
25
26
27
use OCA\Federation\TrustedServers;
28
use OCA\Files_Sharing\External\Storage as SharingExternalStorage;
29
use OCA\Richdocuments\TokenManager;
30
use OCP\AppFramework\Http\RedirectResponse;
31
use OCP\AppFramework\QueryException;
32
use OCP\Files\File;
33
use OCP\Files\InvalidPathException;
34
use OCP\Files\NotFoundException;
35
use OCP\Http\Client\IClientService;
36
use OCP\ICache;
37
use OCP\ICacheFactory;
38
use OCP\ILogger;
39
40
class FederationService {
41
42
	/** @var ICache */
43
	private $cache;
44
	/** @var IClientService */
45
	private $clientService;
46
	/** @var ILogger  */
47
	private $logger;
48
	/** @var TrustedServers */
49
	private $trustedServers;
50
	/** @var TokenManager */
51
	private $tokenManager;
52
53
	public function __construct(ICacheFactory $cacheFactory, IClientService $clientService, ILogger $logger, TokenManager $tokenManager) {
54
		$this->cache = $cacheFactory->createLocal('richdocuments_remote/');
55
		$this->clientService = $clientService;
56
		$this->logger = $logger;
57
		$this->tokenManager = $tokenManager;
58
		try {
59
			$this->trustedServers = \OC::$server->query( \OCA\Federation\TrustedServers::class);
60
		} catch (QueryException $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
61
	}
62
63
	public function getRemoteCollaboraURL($remote) {
64 View Code Duplication
		if ($this->trustedServers === null || !$this->trustedServers->isTrustedServer($remote)) {
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...
65
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote . ' - Remote is not a trusted server');
66
			return '';
67
		}
68
		if ($remoteCollabora = $this->cache->get('richdocuments_remote/' . $remote)) {
69
			return $remoteCollabora;
70
		}
71
		try {
72
			$client = $this->clientService->newClient();
73
			$response = $client->get($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation?format=json', ['timeout' => 5]);
74
			$data = \json_decode($response->getBody(), true);
75
			$remoteCollabora = $data['ocs']['data']['wopi_url'];
76
			$this->cache->get('richdocuments_remote/' . $remote, $remoteCollabora, 3600);
0 ignored issues
show
Unused Code introduced by
The call to ICache::get() has too many arguments starting with $remoteCollabora.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
77
			return $remoteCollabora;
78
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
79
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
80
			$this->cache->get('richdocuments_remote/' . $remote, '', 300);
0 ignored issues
show
Unused Code introduced by
The call to ICache::get() has too many arguments starting with ''.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
81
		}
82
		return '';
83
	}
84
85
	public function getRemoteDirectUrl($remote, $shareToken, $filePath) {
86
		if ($this->getRemoteCollaboraURL() === '') {
0 ignored issues
show
Bug introduced by
The call to getRemoteCollaboraURL() misses a required argument $remote.

This check looks for function calls that miss required arguments.

Loading history...
87
			return '';
88
		}
89
		try {
90
			$client = $this->clientService->newClient();
91
			$response = $client->post($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation/direct?format=json', [
92
				'timeout' => 5,
93
				'body' => [
94
					'shareToken' => $shareToken,
95
					'filePath' => $filePath
96
				]
97
			]);
98
			$data = \json_decode($response->getBody(), true);
99
			return $data['ocs']['data'];
100
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
101
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
102
		}
103
		return null;
104
	}
105
106
	public function getRemoteFileDetails($remote, $remoteToken) {
107 View Code Duplication
		if ($this->trustedServers === null || !$this->trustedServers->isTrustedServer($remote)) {
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...
108
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote . ' - Remote is not a trusted server');
109
			return null;
110
		}
111
		try {
112
			$client = $this->clientService->newClient();
113
			$response = $client->post($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation?format=json', [
114
				'timeout' => 5,
115
				'body' => [
116
					'token' => $remoteToken
117
				]
118
			]);
119
			$data = \json_decode($response->getBody(), true);
120
			return $data['ocs']['data'];
121
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
122
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
123
		}
124
		return null;
125
	}
126
127
	/**
128
	 * @param File $item
129
	 * @return string|null
130
	 * @throws NotFoundException
131
	 * @throws InvalidPathException
132
	 */
133
	public function getRemoteRedirectURL(File $item, $direct = null) {
134
		if ($item->getStorage()->instanceOfStorage(SharingExternalStorage::class)) {
135
			$remote = $item->getStorage()->getRemote();
0 ignored issues
show
Bug introduced by
The method getRemote() does not seem to exist on object<OCP\Files\Storage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
136
			$remoteCollabora = $this->getRemoteCollaboraURL($remote);
137
			if ($remoteCollabora !== '') {
138
				if ($direct === null) {
139
					$wopi = $this->tokenManager->getRemoteToken($item);
140
				} else {
141
					$wopi = $this->tokenManager->getRemoteTokenFromDirect($item, $direct->getUid());
142
				}
143
				$url = $remote . 'index.php/apps/richdocuments/remote?shareToken=' . $item->getStorage()->getToken() .
0 ignored issues
show
Bug introduced by
The method getToken() does not seem to exist on object<OCP\Files\Storage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
144
					'&remoteServer=' . $wopi->getServerHost() .
145
					'&remoteServerToken=' . $wopi->getToken();
146
				if ($item->getInternalPath() !== '') {
147
					$url .= '&filePath=' . $item->getInternalPath();
148
				}
149
				return $url;
150
			}
151
			throw new NotFoundException('Failed to connect to remote collabora instance for ' . $item->getId());
152
		}
153
		return null;
154
	}
155
}
156