Completed
Pull Request — master (#60)
by John
01:57
created

EndpointController::listNotifications()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 38
ccs 17
cts 17
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 4
nop 1
crap 4
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
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, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\Notifications\Controller;
23
24
use OCA\Notifications\Handler;
25
use OCP\AppFramework\Http;
26
use OCP\AppFramework\Http\DataResponse;
27
use OCP\AppFramework\OCSController;
28
use OCP\IConfig;
29
use OCP\IRequest;
30
use OCP\IUser;
31
use OCP\IUserSession;
32
use OCP\Notification\IAction;
33
use OCP\Notification\IManager;
34
use OCP\Notification\INotification;
35
36
class EndpointController extends OCSController {
37
	/** @var Handler */
38
	private $handler;
39
40
	/** @var IManager */
41
	private $manager;
42
43
	/** @var IUserSession */
44
	private $session;
45
46
	/** @var IConfig */
47
	private $config;
48
49
	/**
50
	 * @param string $appName
51
	 * @param IRequest $request
52
	 * @param Handler $handler
53
	 * @param IManager $manager
54
	 * @param IConfig $config
55
	 * @param IUserSession $session
56
	 */
57 25
	public function __construct($appName, IRequest $request, Handler $handler, IManager $manager, IConfig $config, IUserSession $session) {
58 25
		parent::__construct($appName, $request);
59
60 25
		$this->handler = $handler;
61 25
		$this->manager = $manager;
62 25
		$this->config = $config;
63 25
		$this->session = $session;
64 25
	}
65
66
	/**
67
	 * @NoAdminRequired
68
	 * @NoCSRFRequired
69
	 *
70
	 * @param string $apiVersion
71
	 * @return DataResponse
72
	 */
73 6
	public function listNotifications($apiVersion) {
74
		// When there are no apps registered that use the notifications
75
		// We stop polling for them.
76 6
		if (!$this->manager->hasNotifiers()) {
77 2
			return new DataResponse(null, Http::STATUS_NO_CONTENT);
78
		}
79
80 4
		$filter = $this->manager->createNotification();
81 4
		$filter->setUser($this->getCurrentUser());
82 4
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
83
84 4
		$notifications = $this->handler->get($filter);
85
86 4
		$data = [];
87 4
		$notificationIds = [];
88 4
		foreach ($notifications as $notificationId => $notification) {
89
			/** @var INotification $notification */
90
			try {
91 3
				$notification = $this->manager->prepare($notification, $language);
92 1
			} catch (\InvalidArgumentException $e) {
93
				// The app was disabled, skip the notification
94 1
				continue;
95
			}
96
97 3
			$notificationIds[] = $notificationId;
98 3
			$data[] = $this->notificationToArray($notificationId, $notification, $apiVersion);
99
		}
100
101 4
		$etag = $this->generateEtag($notificationIds);
102
		/**
103
		 * Not documented yet, check with clients
104
		if ($this->request->getHeader('ETag') === $etag) {
105
			return new DataResponse($data, Http::STATUS_NOT_MODIFIED);
106
		}
107
		 */
108
109 4
		return new DataResponse($data, Http::STATUS_OK, ['ETag' => $etag]);
110
	}
111
112
	/**
113
	 * @NoAdminRequired
114
	 * @NoCSRFRequired
115
	 *
116
	 * @param string $apiVersion
117
	 * @param int $id
118
	 * @return DataResponse
119
	 */
120 6
	public function getNotification($apiVersion, $id) {
121 6
		if (!$this->manager->hasNotifiers()) {
122 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
123
		}
124
125 5 View Code Duplication
		if (!is_int($id) || $id === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
127
		}
128
129 5
		$notification = $this->handler->getById($id, $this->getCurrentUser());
130
131 5
		if (!($notification instanceof INotification)) {
0 ignored issues
show
Bug introduced by
The class OCP\Notification\INotification 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...
132 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
133
		}
134
135 4
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
136
137
		try {
138 4
			$notification = $this->manager->prepare($notification, $language);
139 2
		} catch (\InvalidArgumentException $e) {
140
			// The app was disabled
141 2
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
142
		}
143
144 2
		return new DataResponse($this->notificationToArray($id, $notification, $apiVersion));
145
	}
146
147
	/**
148
	 * @NoAdminRequired
149
	 *
150
	 * @param int $id
151
	 * @return DataResponse
152
	 */
153 3
	public function deleteNotification($id = 0) {
154 3 View Code Duplication
		if (!is_int($id) || $id === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
156
		}
157 2
		$id = (int) $id;
158
159 2
		$this->handler->deleteById($id, $this->getCurrentUser());
160 2
		return new DataResponse();
161
	}
162
163
	/**
164
	 * Get an Etag for the notification ids
165
	 *
166
	 * @param array $notifications
167
	 * @return string
168
	 */
169 4
	protected function generateEtag(array $notifications) {
170 4
		return md5(json_encode($notifications));
171
	}
172
173
	/**
174
	 * @param int $notificationId
175
	 * @param INotification $notification
176
	 * @param string $apiVersion
177
	 * @return array
178
	 */
179 4
	protected function notificationToArray($notificationId, INotification $notification, $apiVersion) {
180
		$data = [
181 4
			'notification_id' => $notificationId,
182 4
			'app' => $notification->getApp(),
183 4
			'user' => $notification->getUser(),
184 4
			'datetime' => $notification->getDateTime()->format('c'),
185 4
			'object_type' => $notification->getObjectType(),
186 4
			'object_id' => $notification->getObjectId(),
187 4
			'subject' => $notification->getParsedSubject(),
188 4
			'message' => $notification->getParsedMessage(),
189 4
			'link' => $notification->getLink(),
190
		];
191
192 4
		if ($apiVersion !== 'v1') {
193 2
			$data = array_merge($data, [
194 2
				'subjectRich' => $notification->getRichSubject(),
195 2
				'subjectRichParameters' => $notification->getRichSubjectParameters(),
196 2
				'messageRich' => $notification->getRichMessage(),
197 2
				'messageRichParameters' => $notification->getRichMessageParameters(),
198 2
				'icon' => $notification->getIcon(),
199
			]);
200
		}
201
202 4
		$data['actions'] = [];
203 4
		foreach ($notification->getParsedActions() as $action) {
204 2
			$data['actions'][] = $this->actionToArray($action);
205
		}
206
207 4
		return $data;
208
	}
209
210
	/**
211
	 * @param IAction $action
212
	 * @return array
213
	 */
214 2
	protected function actionToArray(IAction $action) {
215
		return [
216 2
			'label' => $action->getParsedLabel(),
217 2
			'link' => $action->getLink(),
218 2
			'type' => $action->getRequestType(),
219 2
			'primary' => $action->isPrimary(),
220
		];
221
	}
222
223
	/**
224
	 * @return string
225
	 */
226 11
	protected function getCurrentUser() {
227 11
		$user = $this->session->getUser();
228 11
		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...
229 11
			$user = $user->getUID();
230
		}
231
232 11
		return (string) $user;
233
	}
234
}
235