Completed
Push — master ( af4954...38e997 )
by Georg
27s
created

ProxyController::proxy()   D

Complexity

Conditions 14
Paths 140

Size

Total Lines 100

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 14.1777

Importance

Changes 0
Metric Value
dl 0
loc 100
ccs 56
cts 62
cp 0.9032
rs 4.7466
c 0
b 0
f 0
cc 14
nc 140
nop 1
crap 14.1777

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\IL10N;
34
use OCP\ILogger;
35
use OCP\IRequest;
36
use Sabre\VObject\Reader;
37
38
class ProxyController extends Controller {
39
40
	/**
41
	 * @var IClientService
42
	 */
43
	protected $client;
44
45
	/**
46
	 * @var IL10N
47
	 */
48
	protected $l10n;
49
50
	/**
51
	 * @var ILogger
52
	 */
53
	protected $logger;
54
55
	/**
56
	 * @param string $appName
57
	 * @param IRequest $request an instance of the request
58
	 * @param IClientService $client
59
	 * @param IL10N $l10n
60
	 * @param ILogger $logger
61
	 */
62 10
	public function __construct($appName, IRequest $request,
63
								IClientService $client,
64
								IL10N $l10n, ILogger $logger) {
65 10
		parent::__construct($appName, $request);
66 10
		$this->client = $client;
67 10
		$this->l10n = $l10n;
68 10
		$this->logger = $logger;
69 10
	}
70
71
	/**
72
	 * @NoAdminRequired
73
	 *
74
	 * @param $url
75
	 * @return DataDisplayResponse|JSONResponse
76
	 */
77 10
	public function proxy($url) {
78 10
		$client = $this->client->newClient();
79
		try {
80 10
			$queryUrl = $url;
81 10
			$allow_redirects = false; // try to handle redirects manually at first
82 10
			$redirect_count = 0;
83 10
			$max_redirects = 5;
84 10
			$done = false;
85
86
			// try to find a chain of 301s
87
			do {
88 10
				$clientResponse = $client->get($queryUrl, [
89 10
					'allow_redirects' => $allow_redirects,
90
				]);
91
92 6
				$statusCode = $clientResponse->getStatusCode();
93 6
				if ($statusCode === 301) { // 400+ goes straight to catch
94 4
					$redirect_count++;
95 4
					$queryUrl = $clientResponse->getHeader('Location');
96 5
				} elseif ($statusCode >= 300) {
97 2
					if ($redirect_count > 0) {
98
						// $redirect_count > 0 => There have been 301s before,
99
						// break and return Location from last 301
100 1
						break;
101
					} else {
102
						// this is the very first request
103
						// it's being redirected, but the redirection is not
104
						// permanently, just let Guzzle take care
105
						$allow_redirects = [
106 1
							'max' => $max_redirects
107
						];
108
					}
109
				} else {
110 4
					$done = true;
111
				}
112 6
			} while(!$done && $redirect_count <= $max_redirects);
113
114 6
			if ($redirect_count > 0 && $redirect_count <= $max_redirects) {
115 3
				$response = new JSONResponse([
116 3
					'proxy_code' => -4,
117 3
					'new_url' => $queryUrl,
118 3
				], Http::STATUS_BAD_REQUEST);
119 3
			} elseif ($done) {
120 2
				$icsData = $clientResponse->getBody();
121
122
				try {
123 2
					Reader::read($icsData, Reader::OPTION_FORGIVING);
124
				} catch(\Exception $ex) {
125
					$response = new JSONResponse([
126
						'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP 404 error)'),
127
						'proxy_code' => 404
128
					], Http::STATUS_UNPROCESSABLE_ENTITY);
129
130
					return $response;
131
				}
132
133 2
				$response = new DataDisplayResponse($icsData, 200);
134 2
				$response->setHeaders([
135 2
					'Content-Type' => 'text/calendar',
136
				]);
137
			} else {
138 1
				$response = new JSONResponse([
139 1
					'message' => $this->l10n->t('Too many redirects. Aborting ...'),
140
					'proxy_code' => -3
141 6
				], Http::STATUS_UNPROCESSABLE_ENTITY);
142
			}
143 4
		} 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...
144 1
			$error_code = $e->getResponse()->getStatusCode();
145 1
			$message = $e->getMessage();
146
147 1
			$this->logger->debug($message);
148 1
			$response = new JSONResponse([
149 1
				'message' => $this->l10n->t('The remote server did not give us access to the calendar (HTTP {%s} error)', [
150 1
					(string) $error_code
151
				]),
152 1
				'proxy_code' => $error_code
153 1
			], Http::STATUS_UNPROCESSABLE_ENTITY);
154 3
		} 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...
155 1
			$this->logger->debug($e->getMessage());
156 1
			$response = new JSONResponse([
157 1
				'message' => $this->l10n->t('Error connecting to remote server'),
158
				'proxy_code' => -1
159 1
			], Http::STATUS_UNPROCESSABLE_ENTITY);
160 2
		} 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...
161 2
			$this->logger->debug($e->getMessage());
162
163 2
			if (substr($url, 0, 8) === 'https://') {
164 1
				$message = $this->l10n->t('Error requesting resource on remote server. This could possible be related to a certificate mismatch');
165
			} else {
166 1
				$message = $this->l10n->t('Error requesting resource on remote server');
167
			}
168
169 2
			$response = new JSONResponse([
170 2
				'message' => $message,
171
				'proxy_code' => -2,
172 2
			], Http::STATUS_UNPROCESSABLE_ENTITY);
173
		}
174
175 10
		return $response;
176
	}
177
}
178