Completed
Pull Request — master (#59)
by Joas
02:09
created

Push   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 18
c 0
b 0
f 0
lcom 1
cbo 0
dl 0
loc 144
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
C pushToDevice() 0 60 14
B encryptAndSign() 0 25 2
A getDevicesForUser() 0 12 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\Http\Client\IClientService;
31
use OCP\IConfig;
32
use OCP\IDBConnection;
33
use OCP\ILogger;
34
use OCP\IUser;
35
use OCP\IUserManager;
36
use OCP\Notification\IManager;
37
use OCP\Notification\INotification;
38
39
class Push {
40
	/** @var IDBConnection */
41
	protected $connection;
42
	/** @var IManager */
43
	protected $manager;
44
	/** @var IConfig */
45
	protected $config;
46
	/** @var IProvider */
47
	protected $tokenProvider;
48
	/** @var Manager */
49
	private $keyManager;
50
	/** @var IUserManager */
51
	private $userManager;
52
	/** @var IClientService */
53
	protected $clientService;
54
	/** @var ILogger */
55
	protected $log;
56
57
	public function __construct(IDBConnection $connection, IManager $manager, IConfig $config, IProvider $tokenProvider, Manager $keyManager, IUserManager $userManager, IClientService $clientService, ILogger $log) {
58
		$this->connection = $connection;
59
		$this->manager = $manager;
60
		$this->config = $config;
61
		$this->tokenProvider = $tokenProvider;
62
		$this->keyManager = $keyManager;
63
		$this->userManager = $userManager;
64
		$this->clientService = $clientService;
65
		$this->log = $log;
66
	}
67
68
	/**
69
	 * @param INotification $notification
70
	 */
71
	public function pushToDevice(INotification $notification) {
72
		$devices = $this->getDevicesForUser($notification->getUser());
73
		$user = $this->userManager->get($notification->getUser());
74
75
		if (empty($devices) || !($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...
76
			return;
77
		}
78
79
		$language = $this->config->getUserValue($notification->getUser(), 'core', 'lang', 'en');
80
		try {
81
			$notification = $this->manager->prepare($notification, $language);
82
		} catch (\InvalidArgumentException $e) {
83
			return;
84
		}
85
86
		$userKey = $this->keyManager->getKey($user);
87
88
		$pushNotifications = [];
89
		foreach ($devices as $device) {
90
			try {
91
				$pushNotifications[] = json_encode($this->encryptAndSign($userKey, $device, $notification));
92
			} 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...
93
				// Token does not exist anymore, should drop the push device entry
94
				// FIXME delete push token
95
			} catch (\InvalidArgumentException $e) {
96
				// Token does not exist anymore, should drop the push device entry
97
				// FIXME delete push token
98
			}
99
		}
100
101
		$client = $this->clientService->newClient();
102
		try {
103
			$pushServer = rtrim($this->config->getAppValue('notifications', 'push_server', 'https://push-notifications.nextcloud.com'), '/');
104
			$response = $client->post($pushServer . '/notifications', [
105
				'body' => [
106
					'notifications' => $pushNotifications,
107
				],
108
			]);
109
		} catch (\Exception $e) {
110
			$this->log->logException($e, [
111
				'app' => 'notifications',
112
			]);
113
			return;
114
		}
115
116
		$status = $response->getStatusCode();
117
		if ($status !== Http::STATUS_OK && $status !== Http::STATUS_SERVICE_UNAVAILABLE) {
118
			$body = $response->getBody();
119
			$this->log->error('Could not send notification to push server: {error}',[
120
				'error' => is_string($body) ? $body : 'no reason given',
121
				'app' => 'notifications',
122
			]);
123
		} else if ($status === Http::STATUS_SERVICE_UNAVAILABLE && $this->config->getSystemValue('debug', false)) {
124
			$body = $response->getBody();
125
			$this->log->debug('Could not send notification to push server: {error}',[
126
				'error' => is_string($body) ? $body : 'no reason given',
127
				'app' => 'notifications',
128
			]);
129
		}
130
	}
131
132
	/**
133
	 * @param Key $userKey
134
	 * @param array $device
135
	 * @param INotification $notification
136
	 * @return array
137
	 * @throws InvalidTokenException
138
	 * @throws \InvalidArgumentException
139
	 */
140
	protected function encryptAndSign(Key $userKey, array $device, INotification $notification) {
141
		// Check if the token is still valid...
142
		$this->tokenProvider->getTokenById($device['token']);
143
144
		$data = [
145
			'app' => $notification->getApp(),
146
			'subject' => $notification->getParsedSubject(),
147
		];
148
149
		if (!openssl_public_encrypt(json_encode($data), $encryptedSubject, $device['devicepublickey'], OPENSSL_PKCS1_PADDING)) {
150
			$this->log->error(openssl_error_string(), ['app' => 'notifications']);
151
			throw new \InvalidArgumentException('Failed to encrypt message for device');
152
		}
153
154
		openssl_sign($encryptedSubject, $signature, $userKey->getPrivate(), OPENSSL_ALGO_SHA512);
155
		$base64EncryptedSubject = base64_encode(hash('sha512', $encryptedSubject, true));
156
		$base64Signature = base64_encode($signature);
157
158
		return [
159
			'deviceIdentifier' => $device['deviceidentifier'],
160
			'pushTokenHash' => $device['pushtokenhash'],
161
			'subject' => $base64EncryptedSubject,
162
			'signature' => $base64Signature,
163
		];
164
	}
165
166
	/**
167
	 * @param string $uid
168
	 * @return array[]
169
	 */
170
	protected function getDevicesForUser($uid) {
171
		$query = $this->connection->getQueryBuilder();
172
		$query->select('*')
173
			->from('notifications_pushtokens')
174
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)));
175
176
		$result = $query->execute();
177
		$devices = $result->fetchAll();
178
		$result->closeCursor();
179
180
		return $devices;
181
	}
182
}
183