Completed
Pull Request — master (#96)
by Joas
123:31 queued 121:53
created

Push   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 67.35%

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 0
dl 0
loc 174
ccs 66
cts 98
cp 0.6735
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
C pushToDevice() 0 76 17
B encryptAndSign() 0 27 2
A getDevicesForUser() 0 12 1
A deletePushToken() 0 7 1
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Joas Schilling <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OCA\Notifications;
23
24
25
use OC\Authentication\Exceptions\InvalidTokenException;
26
use OC\Authentication\Token\IProvider;
27
use OC\Security\IdentityProof\Key;
28
use OC\Security\IdentityProof\Manager;
29
use OCP\AppFramework\Http;
30
use OCP\DB\QueryBuilder\IQueryBuilder;
31
use OCP\Http\Client\IClientService;
32
use OCP\IConfig;
33
use OCP\IDBConnection;
34
use OCP\ILogger;
35
use OCP\IUser;
36
use OCP\IUserManager;
37
use OCP\Notification\IManager as INotificationManager;
38
use OCP\Notification\INotification;
39
40
class Push {
41
	/** @var IDBConnection */
42
	protected $db;
43
	/** @var INotificationManager */
44
	protected $notificationManager;
45
	/** @var IConfig */
46
	protected $config;
47
	/** @var IProvider */
48
	protected $tokenProvider;
49
	/** @var Manager */
50
	private $keyManager;
51
	/** @var IUserManager */
52
	private $userManager;
53
	/** @var IClientService */
54
	protected $clientService;
55
	/** @var ILogger */
56
	protected $log;
57
58 11
	public function __construct(IDBConnection $connection, INotificationManager $notificationManager, IConfig $config, IProvider $tokenProvider, Manager $keyManager, IUserManager $userManager, IClientService $clientService, ILogger $log) {
59 11
		$this->db = $connection;
60 11
		$this->notificationManager = $notificationManager;
61 11
		$this->config = $config;
62 11
		$this->tokenProvider = $tokenProvider;
63 11
		$this->keyManager = $keyManager;
64 11
		$this->userManager = $userManager;
65 11
		$this->clientService = $clientService;
66 11
		$this->log = $log;
67 11
	}
68
69
	/**
70
	 * @param INotification $notification
71
	 */
72 7
	public function pushToDevice(INotification $notification) {
73 7
		$user = $this->userManager->get($notification->getUser());
74 7
		if (!($user instanceof IUser)) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
75 1
			return;
76
		}
77
78 6
		$devices = $this->getDevicesForUser($notification->getUser());
79 6
		if (empty($devices)) {
80 1
			return;
81
		}
82
83 5
		$language = $this->config->getUserValue($notification->getUser(), 'core', 'lang', 'en');
84
		try {
85 5
			$notification = $this->notificationManager->prepare($notification, $language);
86 5
		} catch (\InvalidArgumentException $e) {
87 1
			return;
88
		}
89
90 4
		$userKey = $this->keyManager->getKey($user);
91
92 4
		$pushNotifications = [];
93 4
		foreach ($devices as $device) {
94
			try {
95 4
				$payload = json_encode($this->encryptAndSign($userKey, $device, $notification));
96
97 2
				$proxyServer = rtrim($device['proxyserver'], '/');
98 2
				if (!isset($pushNotifications[$proxyServer])) {
99 2
					$pushNotifications[$proxyServer] = [];
100 2
				}
101 2
				$pushNotifications[$proxyServer][] = $payload;
102 4
			} catch (InvalidTokenException $e) {
0 ignored issues
show
Bug introduced by
The class OC\Authentication\Exceptions\InvalidTokenException 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...
103
				// Token does not exist anymore, should drop the push device entry
104 1
				$this->deletePushToken($device['token']);
105 2
			} catch (\InvalidArgumentException $e) {
106
				// Failed to encrypt message for device: public key is invalid
107 1
				$this->deletePushToken($device['token']);
108
			}
109 4
		}
110
111 4
		if (empty($pushNotifications)) {
112 2
			return;
113
		}
114
115 2
		$client = $this->clientService->newClient();
116 2
		foreach ($pushNotifications as $proxyServer => $notifications) {
117
			try {
118 2
				$response = $client->post($proxyServer . '/notifications', [
119
					'body' => [
120 2
						'notifications' => $notifications,
121 2
					],
122 2
				]);
123 2
			} catch (\Exception $e) {
124 2
				$this->log->logException($e, [
125 2
					'app' => 'notifications',
126 2
				]);
127 2
				continue;
128
			}
129
130 2
			$status = $response->getStatusCode();
131 2
			if ($status !== Http::STATUS_OK && $status !== Http::STATUS_SERVICE_UNAVAILABLE) {
132 2
				$body = $response->getBody();
133 2
				$this->log->error('Could not send notification to push server [{url}]: {error}',[
134 2
					'error' => is_string($body) ? $body : 'no reason given',
135 2
					'url' => $proxyServer,
136 2
					'app' => 'notifications',
137 2
				]);
138 2
			} else if ($status === Http::STATUS_SERVICE_UNAVAILABLE && $this->config->getSystemValue('debug', false)) {
139 1
				$body = $response->getBody();
140 1
				$this->log->debug('Could not send notification to push server [{url}]: {error}',[
141 1
					'error' => is_string($body) ? $body : 'no reason given',
142 1
					'url' => $proxyServer,
143 1
					'app' => 'notifications',
144 1
				]);
145 1
			}
146 2
		}
147 2
	}
148
149
	/**
150
	 * @param Key $userKey
151
	 * @param array $device
152
	 * @param INotification $notification
153
	 * @return array
154
	 * @throws InvalidTokenException
155
	 * @throws \InvalidArgumentException
156
	 */
157
	protected function encryptAndSign(Key $userKey, array $device, INotification $notification) {
158
		// Check if the token is still valid...
159
		$this->tokenProvider->getTokenById($device['token']);
160
161
		$data = [
162
			'app' => $notification->getApp(),
163
			'subject' => $notification->getParsedSubject(),
164
		];
165
166
		if (!openssl_public_encrypt(json_encode($data), $encryptedSubject, $device['devicepublickey'], OPENSSL_PKCS1_PADDING)) {
167
			$this->log->error(openssl_error_string(), ['app' => 'notifications']);
168
			throw new \InvalidArgumentException('Failed to encrypt message for device');
169
		}
170
171
		openssl_sign($encryptedSubject, $signature, $userKey->getPrivate(), OPENSSL_ALGO_SHA512);
172
		$base64EncryptedSubject = base64_encode($encryptedSubject);
173
		$base64HashedEncryptedSubject = base64_encode(hash('sha512', $encryptedSubject, true));
174
		$base64Signature = base64_encode($signature);
175
176
		return [
177
			'deviceIdentifier' => $device['deviceidentifier'],
178
			'pushTokenHash' => $device['pushtokenhash'],
179
			'subject' => $base64EncryptedSubject,
180
			'subjectHashed' => $base64HashedEncryptedSubject,
181
			'signature' => $base64Signature,
182
		];
183
	}
184
185
	/**
186
	 * @param string $uid
187
	 * @return array[]
188
	 */
189
	protected function getDevicesForUser($uid) {
190
		$query = $this->db->getQueryBuilder();
191
		$query->select('*')
192
			->from('notifications_pushtokens')
193
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)));
194
195
		$result = $query->execute();
196
		$devices = $result->fetchAll();
197
		$result->closeCursor();
198
199
		return $devices;
200
	}
201
202
	/**
203
	 * @param int $tokenId
204
	 * @return bool
205
	 */
206
	protected function deletePushToken($tokenId) {
207
		$query = $this->db->getQueryBuilder();
208
		$query->delete('notifications_pushtokens')
209
			->where($query->expr()->eq('token', $query->createNamedParameter($tokenId, IQueryBuilder::PARAM_INT)));
210
211
		return $query->execute() !== 0;
212
	}
213
}
214