Completed
Push — master ( df3a33...72e066 )
by Joas
06:36
created

Push::pushToDevice()   F

Complexity

Conditions 24
Paths 364

Size

Total Lines 100

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 59
CRAP Score 24

Importance

Changes 0
Metric Value
dl 0
loc 100
ccs 59
cts 59
cp 1
rs 1.0266
c 0
b 0
f 0
cc 24
nc 364
nop 1
crap 24

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
 * @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 19
	public function __construct(IDBConnection $connection, INotificationManager $notificationManager, IConfig $config, IProvider $tokenProvider, Manager $keyManager, IUserManager $userManager, IClientService $clientService, ILogger $log) {
59 19
		$this->db = $connection;
60 19
		$this->notificationManager = $notificationManager;
61 19
		$this->config = $config;
62 19
		$this->tokenProvider = $tokenProvider;
63 19
		$this->keyManager = $keyManager;
64 19
		$this->userManager = $userManager;
65 19
		$this->clientService = $clientService;
66 19
		$this->log = $log;
67 19
	}
68
69
	/**
70
	 * @param INotification $notification
71
	 */
72 15
	public function pushToDevice(INotification $notification) {
73 15
		$user = $this->userManager->get($notification->getUser());
74 15
		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 14
		$devices = $this->getDevicesForUser($notification->getUser());
79 14
		if (empty($devices)) {
80 1
			return;
81
		}
82
83 13
		$language = $this->config->getSystemValue('force_language', false);
84 13
		$language = \is_string($language) ? $language : $this->config->getUserValue($notification->getUser(), 'core', 'lang', null);
85 13
		$language = $language ?? $this->config->getSystemValue('default_language', 'en');
86
		try {
87 13
			$notification = $this->notificationManager->prepare($notification, $language);
88 1
		} catch (\InvalidArgumentException $e) {
89 1
			return;
90
		}
91
92 12
		$userKey = $this->keyManager->getKey($user);
93
94 12
		$isTalkNotification = \in_array($notification->getApp(), ['spreed', 'talk'], true)
95 12
			&& \in_array($notification->getSubject(), ['invitation', 'call', 'mention'], true);
96 12
		$talkApps = array_filter($devices, function($device) {
97 12
			return $device['apptype'] === 'talk';
98 12
		});
99 12
		$hasTalkApps = !empty($talkApps);
100
101 12
		$pushNotifications = [];
102 12
		foreach ($devices as $device) {
103 12
			if (!$isTalkNotification && $device['apptype'] === 'talk') {
104
				// The iOS app can not kill notifications,
105
				// therefor we should only send relevant notifications to the Talk
106
				// app, so it does not pollute the notifications bar with useless
107
				// notifications, especially when the Sync client app is also installed.
108 3
				continue;
109
			}
110 11
			if ($isTalkNotification && $hasTalkApps && $device['apptype'] !== 'talk') {
111
				// Similar to the previous case, we also don't send Talk notifications
112
				// to the Sync client app, when there is a Talk app installed. We only
113
				// do this, when you don't have a Talk app on your device, so you still
114
				// get the push notification.
115 2
				continue;
116
			}
117
118
			try {
119 11
				$payload = json_encode($this->encryptAndSign($userKey, $device, $notification, $isTalkNotification));
120
121 9
				$proxyServer = rtrim($device['proxyserver'], '/');
122 9
				if (!isset($pushNotifications[$proxyServer])) {
123 9
					$pushNotifications[$proxyServer] = [];
124
				}
125 9
				$pushNotifications[$proxyServer][] = $payload;
126 2
			} 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...
127
				// Token does not exist anymore, should drop the push device entry
128 1
				$this->deletePushToken($device['token']);
129 1
			} catch (\InvalidArgumentException $e) {
130
				// Failed to encrypt message for device: public key is invalid
131 11
				$this->deletePushToken($device['token']);
132
			}
133
		}
134
135 12
		if (empty($pushNotifications)) {
136 3
			return;
137
		}
138
139 9
		$client = $this->clientService->newClient();
140 9
		foreach ($pushNotifications as $proxyServer => $notifications) {
141
			try {
142 9
				$response = $client->post($proxyServer . '/notifications', [
143
					'body' => [
144 9
						'notifications' => $notifications,
145
					],
146
				]);
147 2
			} catch (\Exception $e) {
148 2
				$this->log->logException($e, [
149 2
					'app' => 'notifications',
150
				]);
151 2
				continue;
152
			}
153
154 9
			$status = $response->getStatusCode();
155 9
			if ($status !== Http::STATUS_OK && $status !== Http::STATUS_SERVICE_UNAVAILABLE) {
156 9
				$body = $response->getBody();
157 9
				$this->log->error('Could not send notification to push server [{url}]: {error}',[
158 9
					'error' => \is_string($body) ? $body : 'no reason given',
159 9
					'url' => $proxyServer,
160 9
					'app' => 'notifications',
161
				]);
162 2
			} else if ($status === Http::STATUS_SERVICE_UNAVAILABLE && $this->config->getSystemValue('debug', false)) {
163 1
				$body = $response->getBody();
164 1
				$this->log->debug('Could not send notification to push server [{url}]: {error}',[
165 1
					'error' => \is_string($body) ? $body : 'no reason given',
166 1
					'url' => $proxyServer,
167 9
					'app' => 'notifications',
168
				]);
169
			}
170
		}
171 9
	}
172
173
	/**
174
	 * @param Key $userKey
175
	 * @param array $device
176
	 * @param INotification $notification
177
	 * @param bool $isTalkNotification
178
	 * @return array
179
	 * @throws InvalidTokenException
180
	 * @throws \InvalidArgumentException
181
	 */
182
	protected function encryptAndSign(Key $userKey, array $device, INotification $notification, bool $isTalkNotification): array {
183
		// Check if the token is still valid...
184
		$this->tokenProvider->getTokenById($device['token']);
185
186
		$data = [
187
			'app' => $notification->getApp(),
188
			'subject' => $notification->getParsedSubject(),
189
			'type' => $notification->getObjectType(),
190
			'id' => $notification->getObjectId(),
191
		];
192
193
		if ($isTalkNotification) {
194
			$priority = 'high';
195
		} else {
196
			$priority = 'normal';
197
		}
198
199
		if (!openssl_public_encrypt(json_encode($data), $encryptedSubject, $device['devicepublickey'], OPENSSL_PKCS1_PADDING)) {
200
			$this->log->error(openssl_error_string(), ['app' => 'notifications']);
201
			throw new \InvalidArgumentException('Failed to encrypt message for device');
202
		}
203
204
		openssl_sign($encryptedSubject, $signature, $userKey->getPrivate(), OPENSSL_ALGO_SHA512);
205
		$base64EncryptedSubject = base64_encode($encryptedSubject);
206
		$base64Signature = base64_encode($signature);
207
208
		return [
209
			'deviceIdentifier' => $device['deviceidentifier'],
210
			'pushTokenHash' => $device['pushtokenhash'],
211
			'subject' => $base64EncryptedSubject,
212
			'signature' => $base64Signature,
213
			'priority' => $priority,
214
		];
215
	}
216
217
	/**
218
	 * @param string $uid
219
	 * @return array[]
220
	 */
221
	protected function getDevicesForUser(string $uid): array {
222
		$query = $this->db->getQueryBuilder();
223
		$query->select('*')
224
			->from('notifications_pushtokens')
225
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)));
226
227
		$result = $query->execute();
228
		$devices = $result->fetchAll();
229
		$result->closeCursor();
230
231
		return $devices;
232
	}
233
234
	/**
235
	 * @param int $tokenId
236
	 * @return bool
237
	 */
238
	protected function deletePushToken(int $tokenId): bool {
239
		$query = $this->db->getQueryBuilder();
240
		$query->delete('notifications_pushtokens')
241
			->where($query->expr()->eq('token', $query->createNamedParameter($tokenId, IQueryBuilder::PARAM_INT)));
242
243
		return $query->execute() !== 0;
244
	}
245
}
246