Completed
Push — master ( 1801e4...143145 )
by Morris
19:04 queued 02:13
created

ChangesCheck::getChangesForVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2018 Arthur Schiwon <[email protected]>
5
 *
6
 * @author Arthur Schiwon <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
25
namespace OC\Updater;
26
27
use OCP\AppFramework\Db\DoesNotExistException;
28
use OCP\Http\Client\IClientService;
29
use OCP\Http\Client\IResponse;
30
use OCP\ILogger;
31
32
class ChangesCheck {
33
	/** @var IClientService */
34
	protected $clientService;
35
	/** @var ChangesMapper */
36
	private $mapper;
37
	/** @var ILogger */
38
	private $logger;
39
40
	const RESPONSE_NO_CONTENT = 0;
41
	const RESPONSE_USE_CACHE = 1;
42
	const RESPONSE_HAS_CONTENT = 2;
43
44
	public function __construct(IClientService $clientService, ChangesMapper $mapper, ILogger $logger) {
45
		$this->clientService = $clientService;
46
		$this->mapper = $mapper;
47
		$this->logger = $logger;
48
	}
49
50
	/**
51
	 * @throws DoesNotExistException
52
	 */
53
	public function getChangesForVersion(string $version): array {
54
		$version = $this->normalizeVersion($version);
55
		$changesInfo = $this->mapper->getChanges($version);
56
		return json_decode($changesInfo->getData(), true);
57
	}
58
59
	/**
60
	 * @throws \Exception
61
	 */
62
	public function check(string $uri, string $version): array {
63
		try {
64
			$version = $this->normalizeVersion($version);
65
			$changesInfo = $this->mapper->getChanges($version);
66
			if($changesInfo->getLastCheck() + 1800 > time()) {
67
				return json_decode($changesInfo->getData(), true);
68
			}
69
		} catch (DoesNotExistException $e) {
70
			$changesInfo = new ChangesResult();
71
		}
72
73
		$response = $this->queryChangesServer($uri, $changesInfo);
74
75
		switch($this->evaluateResponse($response)) {
76
			case self::RESPONSE_NO_CONTENT:
77
				return [];
78
			case self::RESPONSE_USE_CACHE:
79
				return json_decode($changesInfo->getData(), true);
80
			case self::RESPONSE_HAS_CONTENT:
81
			default:
82
				$data = $this->extractData($response->getBody());
83
				$changesInfo->setData(json_encode($data));
84
				$changesInfo->setEtag($response->getHeader('Etag'));
85
				$this->cacheResult($changesInfo, $version);
86
87
				return $data;
88
		}
89
	}
90
91
	protected function evaluateResponse(IResponse $response): int {
92
		if($response->getStatusCode() === 304) {
93
			return self::RESPONSE_USE_CACHE;
94
		} else if($response->getStatusCode() === 404) {
95
			return self::RESPONSE_NO_CONTENT;
96
		} else if($response->getStatusCode() === 200) {
97
			return self::RESPONSE_HAS_CONTENT;
98
		}
99
		$this->logger->debug('Unexpected return code {code} from changelog server', [
100
			'app' => 'core',
101
			'code' => $response->getStatusCode(),
102
		]);
103
		return self::RESPONSE_NO_CONTENT;
104
	}
105
106
	protected function cacheResult(ChangesResult $entry, string $version) {
107
		if($entry->getVersion() === $version) {
108
			$this->mapper->update($entry);
109
		} else {
110
			$entry->setVersion($version);
111
			$this->mapper->insert($entry);
112
		}
113
	}
114
115
	/**
116
	 * @throws \Exception
117
	 */
118
	protected function queryChangesServer(string $uri, ChangesResult $entry): IResponse {
119
		$headers = [];
120
		if($entry->getEtag() !== '') {
121
			$headers['If-None-Match'] = [$entry->getEtag()];
122
		}
123
124
		$entry->setLastCheck(time());
125
		$client = $this->clientService->newClient();
126
		return $client->get($uri, [
127
			'headers' => $headers,
128
		]);
129
	}
130
131
	protected function extractData($body):array {
132
		$data = [];
133
		if ($body) {
134
			$loadEntities = libxml_disable_entity_loader(true);
135
			$xml = @simplexml_load_string($body);
136
			libxml_disable_entity_loader($loadEntities);
137
			if ($xml !== false) {
138
				$data['changelogURL'] = (string)$xml->changelog['href'];
139
				$data['whatsNew'] = [];
140
				foreach($xml->whatsNew as $infoSet) {
141
					$data['whatsNew'][(string)$infoSet['lang']] = [
142
						'regular' => (array)$infoSet->regular->item,
143
						'admin' => (array)$infoSet->admin->item,
144
					];
145
				}
146
			} else {
147
				libxml_clear_errors();
148
			}
149
		}
150
		return $data;
151
	}
152
153
	/**
154
	 * returns a x.y.z form of the provided version. Extra numbers will be
155
	 * omitted, missing ones added as zeros.
156
	 */
157
	public function normalizeVersion(string $version): string {
158
		$versionNumbers = array_slice(explode('.', $version), 0, 3);
159
		$versionNumbers[0] = $versionNumbers[0] ?: '0'; // deal with empty input
160
		while(count($versionNumbers) < 3) {
161
			// changelog server expects x.y.z, pad 0 if it is too short
162
			$versionNumbers[] = 0;
163
		}
164
		return implode('.', $versionNumbers);
165
	}
166
}
167