Completed
Push — master ( 7481a4...1f1f17 )
by Georg
23s queued 11s
created

ProxyController::proxy()   F

Complexity

Conditions 21
Paths 498

Size

Total Lines 121

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 49
CRAP Score 21.5726

Importance

Changes 0
Metric Value
dl 0
loc 121
rs 0.5577
c 0
b 0
f 0
ccs 49
cts 55
cp 0.8909
cc 21
nc 498
nop 1
crap 21.5726

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * ownCloud - Calendar App
4
 *
5
 * @author Georg Ehrke
6
 * @copyright 2016 Georg Ehrke <[email protected]>
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
10
 * License as published by the Free Software Foundation; either
11
 * version 3 of the License, or any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public
19
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
namespace OCA\Calendar\Controller;
23
24
use GuzzleHttp\Exception\RequestException;
25
use GuzzleHttp\Exception\ClientException;
26
use GuzzleHttp\Exception\ConnectException;
27
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\JSONResponse;
30
use OCP\AppFramework\Http\DataDisplayResponse;
31
use OCP\AppFramework\Controller;
32
use OCP\Http\Client\IClientService;
33
use OCP\IConfig;
34
use OCP\IL10N;
35
use OCP\ILogger;
36
use OCP\IRequest;
37
use Sabre\VObject\Reader;
38
39
class ProxyController extends Controller {
40
41
	/**
42
	 * @var IClientService
43
	 */
44
	protected $client;
45
46
	/**
47
	 * @var IL10N
48
	 */
49
	protected $l10n;
50
51
	/**
52
	 * @var ILogger
53
	 */
54
	protected $logger;
55
56
	/**
57
	 * @var IConfig
58
	 */
59
	protected $config;
60
61
	/**
62 10
	 * @param string $appName
63
	 * @param IRequest $request an instance of the request
64
	 * @param IClientService $client
65 10
	 * @param IL10N $l10n
66 10
	 * @param ILogger $logger
67 10
	 * @param IConfig $config
68 10
	 */
69 10
	public function __construct($appName, IRequest $request,
70
								IClientService $client,
71
								IL10N $l10n, ILogger $logger,
72
								IConfig $config) {
73
		parent::__construct($appName, $request);
74
		$this->client = $client;
75
		$this->l10n = $l10n;
76
		$this->logger = $logger;
77 10
		$this->config = $config;
78 10
	}
79
80 10
	/**
81 10
	 * @NoAdminRequired
82 10
	 *
83 10
	 * @param $url
84 10
	 * @return DataDisplayResponse|JSONResponse
85
	 */
86
	public function proxy($url) {
87
		$client = $this->client->newClient();
88 10
		try {
89 10
			$queryUrl = $url;
90
			$allow_redirects = false; // try to handle redirects manually at first
91
			$redirect_count = 0;
92 6
			$max_redirects = 5;
93 6
			$done = false;
94 4
95 4
			$allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
96 5
			if ($allowLocalAccess !== 'yes') {
97 2
				$host = parse_url($url, PHP_URL_HOST);
98
				// remove brackets from IPv6 addresses
99
				if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
100 1
					$host = substr($host, 1, -1);
101
				}
102
103
				if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost' ||
104
					preg_match('/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/', $host)) {
105
					$this->logger->warning("Subscription $url was not refreshed because it violates local access rules");
106 1
107
					$response = new JSONResponse([
108
						'message' => $this->l10n->t('URL violates local access rules'),
109
						'proxy_code' => 403
110 4
					], Http::STATUS_UNPROCESSABLE_ENTITY);
111
112 6
					return $response;
113
				}
114 6
			}
115 3
116 3
			// try to find a chain of 301s
117 3
			do {
118 3
				$clientResponse = $client->get($queryUrl, [
119 3
					'allow_redirects' => $allow_redirects,
120 2
				]);
121
122
				$statusCode = $clientResponse->getStatusCode();
123 2
				if ($statusCode === 301) { // 400+ goes straight to catch
124
					$redirect_count++;
125
					$queryUrl = $clientResponse->getHeader('Location');
126
				} elseif ($statusCode >= 300) {
127
					if ($redirect_count > 0) {
128
						// $redirect_count > 0 => There have been 301s before,
129
						// break and return Location from last 301
130
						break;
131
					} else {
132
						// this is the very first request
133 2
						// it's being redirected, but the redirection is not
134 2
						// permanently, just let Guzzle take care
135 2
						$allow_redirects = [
136
							'max' => $max_redirects
137
						];
138 1
					}
139 1
				} else {
140
					$done = true;
141 6
				}
142
			} while(!$done && $redirect_count <= $max_redirects);
143 4
144 1
			if ($redirect_count > 0 && $redirect_count <= $max_redirects) {
145 1
				$response = new JSONResponse([
146
					'proxy_code' => -4,
147 1
					'new_url' => $queryUrl,
148 1
				], Http::STATUS_BAD_REQUEST);
149 1
			} elseif ($done) {
150 1
				$icsData = $clientResponse->getBody();
151
152 1
				try {
153 1
					Reader::read($icsData, Reader::OPTION_FORGIVING);
154 3
				} catch(\Exception $ex) {
155 1
					$response = new JSONResponse([
156 1
						'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP 404 error)'),
157 1
						'proxy_code' => 404
158
					], Http::STATUS_UNPROCESSABLE_ENTITY);
159 1
160 2
					return $response;
161 2
				}
162
163 2
				$response = new DataDisplayResponse($icsData, 200);
164 1
				$response->setHeaders([
165
					'Content-Type' => 'text/calendar',
166 1
				]);
167
			} else {
168
				$response = new JSONResponse([
169 2
					'message' => $this->l10n->t('Too many redirects. Aborting ...'),
170 2
					'proxy_code' => -3
171
				], Http::STATUS_UNPROCESSABLE_ENTITY);
172 2
			}
173
		} catch (ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException 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...
174
			$error_code = $e->getResponse()->getStatusCode();
175 10
			$message = $e->getMessage();
176
177
			$this->logger->debug($message);
178
			$response = new JSONResponse([
179
				'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP {%s} error)', [
180
					(string) $error_code
181
				]),
182
				'proxy_code' => $error_code
183
			], Http::STATUS_UNPROCESSABLE_ENTITY);
184
		} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException 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...
185
			$this->logger->debug($e->getMessage());
186
			$response = new JSONResponse([
187
				'message' => $this->l10n->t('Error connecting to remote server'),
188
				'proxy_code' => -1
189
			], Http::STATUS_UNPROCESSABLE_ENTITY);
190
		} catch (RequestException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\RequestException 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...
191
			$this->logger->debug($e->getMessage());
192
193
			if (substr($url, 0, 8) === 'https://') {
194
				$message = $this->l10n->t('Error requesting resource on remote server. This could possible be related to a certificate mismatch');
195
			} else {
196
				$message = $this->l10n->t('Error requesting resource on remote server');
197
			}
198
199
			$response = new JSONResponse([
200
				'message' => $message,
201
				'proxy_code' => -2,
202
			], Http::STATUS_UNPROCESSABLE_ENTITY);
203
		}
204
205
		return $response;
206
	}
207
}
208