Completed
Pull Request — master (#30)
by Joas
02:33
created

EndpointController::notificationToArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 19
cts 19
cp 1
rs 9.0856
cc 2
eloc 18
nc 2
nop 2
crap 2
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 22
	public function __construct($appName, IRequest $request, Handler $handler, IManager $manager, IConfig $config, IUserSession $session) {
58 22
		parent::__construct($appName, $request);
59
60 22
		$this->handler = $handler;
61 22
		$this->manager = $manager;
62 22
		$this->config = $config;
63 22
		$this->session = $session;
64 22
	}
65
66
	/**
67
	 * @NoAdminRequired
68
	 * @NoCSRFRequired
69
	 *
70
	 * @return DataResponse
71
	 */
72 5
	public function listNotifications() {
73
		// When there are no apps registered that use the notifications
74
		// We stop polling for them.
75 5
		if (!$this->manager->hasNotifiers()) {
76 1
			return new DataResponse(null, Http::STATUS_NO_CONTENT);
77
		}
78
79 4
		$filter = $this->manager->createNotification();
80 4
		$filter->setUser($this->getCurrentUser());
81 4
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
82
83 4
		$notifications = $this->handler->get($filter);
84
85 4
		$data = [];
86 4
		$notificationIds = [];
87 4
		foreach ($notifications as $notificationId => $notification) {
88
			/** @var INotification $notification */
89
			try {
90 3
				$notification = $this->manager->prepare($notification, $language);
91 3
			} catch (\InvalidArgumentException $e) {
92
				// The app was disabled, skip the notification
93 1
				continue;
94
			}
95
96 3
			$notificationIds[] = $notificationId;
97 3
			$data[] = $this->notificationToArray($notificationId, $notification);
98 4
		}
99
100 4
		$etag = $this->generateEtag($notificationIds);
101
		/**
102
		 * Not documented yet, check with clients
103
		if ($this->request->getHeader('ETag') === $etag) {
104
			return new DataResponse($data, Http::STATUS_NOT_MODIFIED);
105
		}
106
		 */
107
108 4
		return new DataResponse($data, Http::STATUS_OK, ['ETag' => $etag]);
109
	}
110
111
	/**
112
	 * @NoAdminRequired
113
	 * @NoCSRFRequired
114
	 *
115
	 * @param int $id
116
	 * @return DataResponse
117
	 */
118 6
	public function getNotification($id = 0) {
119 6
		if (!$this->manager->hasNotifiers()) {
120 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
121
		}
122
123 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...
124 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
125
		}
126
127 4
		$notification = $this->handler->getById($id, $this->getCurrentUser());
128
129 4
		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...
130 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
131
		}
132
133 3
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
134
135
		try {
136 3
			$notification = $this->manager->prepare($notification, $language);
137 3
		} catch (\InvalidArgumentException $e) {
138
			// The app was disabled
139 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
140
		}
141
142 2
		return new DataResponse($this->notificationToArray($id, $notification));
143
	}
144
145
	/**
146
	 * @NoAdminRequired
147
	 *
148
	 * @param int $id
149
	 * @return DataResponse
150
	 */
151 3
	public function deleteNotification($id = 0) {
152 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...
153 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
154
		}
155 2
		$id = (int) $id;
156
157 2
		$this->handler->deleteById($id, $this->getCurrentUser());
158 2
		return new DataResponse();
159
	}
160
161
	/**
162
	 * Get an Etag for the notification ids
163
	 *
164
	 * @param array $notifications
165
	 * @return string
166
	 */
167 4
	protected function generateEtag(array $notifications) {
168 4
		return md5(json_encode($notifications));
169
	}
170
171
	/**
172
	 * @param int $notificationId
173
	 * @param INotification $notification
174
	 * @return array
175
	 */
176 2
	protected function notificationToArray($notificationId, INotification $notification) {
177
		$data = [
178 2
			'notification_id' => $notificationId,
179 2
			'app' => $notification->getApp(),
180 2
			'user' => $notification->getUser(),
181 2
			'datetime' => $notification->getDateTime()->format('c'),
182 2
			'object_type' => $notification->getObjectType(),
183 2
			'object_id' => $notification->getObjectId(),
184 2
			'subject' => $notification->getParsedSubject(),
185 2
			'subjectRich' => $notification->getRichSubject(),
186 2
			'subjectRichParameters' => $notification->getRichSubjectParameters(),
187 2
			'message' => $notification->getParsedMessage(),
188
			'icon' => $notification->getIcon(),
189 2
			'link' => $notification->getLink(),
190 2
		];
191 2
192
		$data['actions'] = [];
193 2
		foreach ($notification->getParsedActions() as $action) {
194 2
			$data['actions'][] = $this->actionToArray($action);
195 1
		}
196 2
197
		return $data;
198 2
	}
199
200
	/**
201
	 * @param IAction $action
202
	 * @return array
203
	 */
204
	protected function actionToArray(IAction $action) {
205 2
		return [
206
			'label' => $action->getParsedLabel(),
207 2
			'link' => $action->getLink(),
208 2
			'type' => $action->getRequestType(),
209 2
			'primary' => $action->isPrimary(),
210 2
		];
211 2
	}
212
213
	/**
214
	 * @return string
215
	 */
216
	protected function getCurrentUser() {
217 10
		$user = $this->session->getUser();
218 10
		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...
219 10
			$user = $user->getUID();
220 10
		}
221 10
222
		return (string) $user;
223 10
	}
224
}
225