Passed
Push — master ( 3eb748...99ee00 )
by Roeland
12:40 queued 12s
created
apps/user_status/lib/Service/JSDataService.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -31,55 +31,55 @@
 block discarded – undo
31 31
 
32 32
 class JSDataService implements \JsonSerializable {
33 33
 
34
-	/** @var IUserSession */
35
-	private $userSession;
34
+    /** @var IUserSession */
35
+    private $userSession;
36 36
 
37
-	/** @var StatusService */
38
-	private $statusService;
37
+    /** @var StatusService */
38
+    private $statusService;
39 39
 
40
-	/**
41
-	 * JSDataService constructor.
42
-	 *
43
-	 * @param IUserSession $userSession
44
-	 * @param StatusService $statusService
45
-	 */
46
-	public function __construct(IUserSession $userSession,
47
-								StatusService $statusService) {
48
-		$this->userSession = $userSession;
49
-		$this->statusService = $statusService;
50
-	}
40
+    /**
41
+     * JSDataService constructor.
42
+     *
43
+     * @param IUserSession $userSession
44
+     * @param StatusService $statusService
45
+     */
46
+    public function __construct(IUserSession $userSession,
47
+                                StatusService $statusService) {
48
+        $this->userSession = $userSession;
49
+        $this->statusService = $statusService;
50
+    }
51 51
 
52
-	public function jsonSerialize() {
53
-		$user = $this->userSession->getUser();
52
+    public function jsonSerialize() {
53
+        $user = $this->userSession->getUser();
54 54
 
55
-		if ($user === null) {
56
-			return [];
57
-		}
55
+        if ($user === null) {
56
+            return [];
57
+        }
58 58
 
59
-		try {
60
-			$status = $this->statusService->findByUserId($user->getUID());
61
-		} catch (DoesNotExistException $ex) {
62
-			return [
63
-				'userId' => $user->getUID(),
64
-				'message' => null,
65
-				'messageId' => null,
66
-				'messageIsPredefined' => false,
67
-				'icon' => null,
68
-				'clearAt' => null,
69
-				'status' => IUserStatus::OFFLINE,
70
-				'statusIsUserDefined' => false,
71
-			];
72
-		}
59
+        try {
60
+            $status = $this->statusService->findByUserId($user->getUID());
61
+        } catch (DoesNotExistException $ex) {
62
+            return [
63
+                'userId' => $user->getUID(),
64
+                'message' => null,
65
+                'messageId' => null,
66
+                'messageIsPredefined' => false,
67
+                'icon' => null,
68
+                'clearAt' => null,
69
+                'status' => IUserStatus::OFFLINE,
70
+                'statusIsUserDefined' => false,
71
+            ];
72
+        }
73 73
 
74
-		return [
75
-			'userId' => $status->getUserId(),
76
-			'message' => $status->getCustomMessage(),
77
-			'messageId' => $status->getMessageId(),
78
-			'messageIsPredefined' => $status->getMessageId() !== null,
79
-			'icon' => $status->getCustomIcon(),
80
-			'clearAt' => $status->getClearAt(),
81
-			'status' => $status->getStatus(),
82
-			'statusIsUserDefined' => $status->getIsUserDefined(),
83
-		];
84
-	}
74
+        return [
75
+            'userId' => $status->getUserId(),
76
+            'message' => $status->getCustomMessage(),
77
+            'messageId' => $status->getMessageId(),
78
+            'messageIsPredefined' => $status->getMessageId() !== null,
79
+            'icon' => $status->getCustomIcon(),
80
+            'clearAt' => $status->getClearAt(),
81
+            'status' => $status->getStatus(),
82
+            'statusIsUserDefined' => $status->getIsUserDefined(),
83
+        ];
84
+    }
85 85
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Service/StatusService.php 2 patches
Indentation   +342 added lines, -342 removed lines patch added patch discarded remove patch
@@ -43,346 +43,346 @@
 block discarded – undo
43 43
  */
44 44
 class StatusService {
45 45
 
46
-	/** @var UserStatusMapper */
47
-	private $mapper;
48
-
49
-	/** @var ITimeFactory */
50
-	private $timeFactory;
51
-
52
-	/** @var PredefinedStatusService */
53
-	private $predefinedStatusService;
54
-
55
-	/** @var EmojiService */
56
-	private $emojiService;
57
-
58
-	/**
59
-	 * List of priorities ordered by their priority
60
-	 */
61
-	public const PRIORITY_ORDERED_STATUSES = [
62
-		IUserStatus::ONLINE,
63
-		IUserStatus::AWAY,
64
-		IUserStatus::DND,
65
-		IUserStatus::INVISIBLE,
66
-		IUserStatus::OFFLINE
67
-	];
68
-
69
-	/**
70
-	 * List of statuses that persist the clear-up
71
-	 * or UserLiveStatusEvents
72
-	 */
73
-	public const PERSISTENT_STATUSES = [
74
-		IUserStatus::AWAY,
75
-		IUserStatus::DND,
76
-		IUserStatus::INVISIBLE,
77
-	];
78
-
79
-	/** @var int */
80
-	public const INVALIDATE_STATUS_THRESHOLD = 5 /* minutes */ * 60 /* seconds */;
81
-
82
-	/** @var int */
83
-	public const MAXIMUM_MESSAGE_LENGTH = 80;
84
-
85
-	/**
86
-	 * StatusService constructor.
87
-	 *
88
-	 * @param UserStatusMapper $mapper
89
-	 * @param ITimeFactory $timeFactory
90
-	 * @param PredefinedStatusService $defaultStatusService,
91
-	 * @param EmojiService $emojiService
92
-	 */
93
-	public function __construct(UserStatusMapper $mapper,
94
-								ITimeFactory $timeFactory,
95
-								PredefinedStatusService $defaultStatusService,
96
-								EmojiService $emojiService) {
97
-		$this->mapper = $mapper;
98
-		$this->timeFactory = $timeFactory;
99
-		$this->predefinedStatusService = $defaultStatusService;
100
-		$this->emojiService = $emojiService;
101
-	}
102
-
103
-	/**
104
-	 * @param int|null $limit
105
-	 * @param int|null $offset
106
-	 * @return UserStatus[]
107
-	 */
108
-	public function findAll(?int $limit = null, ?int $offset = null): array {
109
-		return array_map(function ($status) {
110
-			return $this->processStatus($status);
111
-		}, $this->mapper->findAll($limit, $offset));
112
-	}
113
-
114
-	/**
115
-	 * @param int|null $limit
116
-	 * @param int|null $offset
117
-	 * @return array
118
-	 */
119
-	public function findAllRecentStatusChanges(?int $limit = null, ?int $offset = null): array {
120
-		return array_map(function ($status) {
121
-			return $this->processStatus($status);
122
-		}, $this->mapper->findAllRecent($limit, $offset));
123
-	}
124
-
125
-	/**
126
-	 * @param string $userId
127
-	 * @return UserStatus
128
-	 * @throws DoesNotExistException
129
-	 */
130
-	public function findByUserId(string $userId):UserStatus {
131
-		return $this->processStatus($this->mapper->findByUserId($userId));
132
-	}
133
-
134
-	/**
135
-	 * @param array $userIds
136
-	 * @return UserStatus[]
137
-	 */
138
-	public function findByUserIds(array $userIds):array {
139
-		return array_map(function ($status) {
140
-			return $this->processStatus($status);
141
-		}, $this->mapper->findByUserIds($userIds));
142
-	}
143
-
144
-	/**
145
-	 * @param string $userId
146
-	 * @param string $status
147
-	 * @param int|null $statusTimestamp
148
-	 * @param bool $isUserDefined
149
-	 * @return UserStatus
150
-	 * @throws InvalidStatusTypeException
151
-	 */
152
-	public function setStatus(string $userId,
153
-							  string $status,
154
-							  ?int $statusTimestamp,
155
-							  bool $isUserDefined): UserStatus {
156
-		try {
157
-			$userStatus = $this->mapper->findByUserId($userId);
158
-		} catch (DoesNotExistException $ex) {
159
-			$userStatus = new UserStatus();
160
-			$userStatus->setUserId($userId);
161
-		}
162
-
163
-		// Check if status-type is valid
164
-		if (!\in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
165
-			throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
166
-		}
167
-		if ($statusTimestamp === null) {
168
-			$statusTimestamp = $this->timeFactory->getTime();
169
-		}
170
-
171
-		$userStatus->setStatus($status);
172
-		$userStatus->setStatusTimestamp($statusTimestamp);
173
-		$userStatus->setIsUserDefined($isUserDefined);
174
-
175
-		if ($userStatus->getId() === null) {
176
-			return $this->mapper->insert($userStatus);
177
-		}
178
-
179
-		return $this->mapper->update($userStatus);
180
-	}
181
-
182
-	/**
183
-	 * @param string $userId
184
-	 * @param string $messageId
185
-	 * @param int|null $clearAt
186
-	 * @return UserStatus
187
-	 * @throws InvalidMessageIdException
188
-	 * @throws InvalidClearAtException
189
-	 */
190
-	public function setPredefinedMessage(string $userId,
191
-										 string $messageId,
192
-										 ?int $clearAt): UserStatus {
193
-		try {
194
-			$userStatus = $this->mapper->findByUserId($userId);
195
-		} catch (DoesNotExistException $ex) {
196
-			$userStatus = new UserStatus();
197
-			$userStatus->setUserId($userId);
198
-			$userStatus->setStatus(IUserStatus::OFFLINE);
199
-			$userStatus->setStatusTimestamp(0);
200
-			$userStatus->setIsUserDefined(false);
201
-		}
202
-
203
-		if (!$this->predefinedStatusService->isValidId($messageId)) {
204
-			throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
205
-		}
206
-
207
-		// Check that clearAt is in the future
208
-		if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
209
-			throw new InvalidClearAtException('ClearAt is in the past');
210
-		}
211
-
212
-		$userStatus->setMessageId($messageId);
213
-		$userStatus->setCustomIcon(null);
214
-		$userStatus->setCustomMessage(null);
215
-		$userStatus->setClearAt($clearAt);
216
-
217
-		if ($userStatus->getId() === null) {
218
-			return $this->mapper->insert($userStatus);
219
-		}
220
-
221
-		return $this->mapper->update($userStatus);
222
-	}
223
-
224
-	/**
225
-	 * @param string $userId
226
-	 * @param string|null $statusIcon
227
-	 * @param string|null $message
228
-	 * @param int|null $clearAt
229
-	 * @return UserStatus
230
-	 * @throws InvalidClearAtException
231
-	 * @throws InvalidStatusIconException
232
-	 * @throws StatusMessageTooLongException
233
-	 */
234
-	public function setCustomMessage(string $userId,
235
-									 ?string $statusIcon,
236
-									 string $message,
237
-									 ?int $clearAt): UserStatus {
238
-		try {
239
-			$userStatus = $this->mapper->findByUserId($userId);
240
-		} catch (DoesNotExistException $ex) {
241
-			$userStatus = new UserStatus();
242
-			$userStatus->setUserId($userId);
243
-			$userStatus->setStatus(IUserStatus::OFFLINE);
244
-			$userStatus->setStatusTimestamp(0);
245
-			$userStatus->setIsUserDefined(false);
246
-		}
247
-
248
-		// Check if statusIcon contains only one character
249
-		if ($statusIcon !== null && !$this->emojiService->isValidEmoji($statusIcon)) {
250
-			throw new InvalidStatusIconException('Status-Icon is longer than one character');
251
-		}
252
-		// Check for maximum length of custom message
253
-		if (\mb_strlen($message) > self::MAXIMUM_MESSAGE_LENGTH) {
254
-			throw new StatusMessageTooLongException('Message is longer than supported length of ' . self::MAXIMUM_MESSAGE_LENGTH . ' characters');
255
-		}
256
-		// Check that clearAt is in the future
257
-		if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
258
-			throw new InvalidClearAtException('ClearAt is in the past');
259
-		}
260
-
261
-		$userStatus->setMessageId(null);
262
-		$userStatus->setCustomIcon($statusIcon);
263
-		$userStatus->setCustomMessage($message);
264
-		$userStatus->setClearAt($clearAt);
265
-
266
-		if ($userStatus->getId() === null) {
267
-			return $this->mapper->insert($userStatus);
268
-		}
269
-
270
-		return $this->mapper->update($userStatus);
271
-	}
272
-
273
-	/**
274
-	 * @param string $userId
275
-	 * @return bool
276
-	 */
277
-	public function clearStatus(string $userId): bool {
278
-		try {
279
-			$userStatus = $this->mapper->findByUserId($userId);
280
-		} catch (DoesNotExistException $ex) {
281
-			// if there is no status to remove, just return
282
-			return false;
283
-		}
284
-
285
-		$userStatus->setStatus(IUserStatus::OFFLINE);
286
-		$userStatus->setStatusTimestamp(0);
287
-		$userStatus->setIsUserDefined(false);
288
-
289
-		$this->mapper->update($userStatus);
290
-		return true;
291
-	}
292
-
293
-	/**
294
-	 * @param string $userId
295
-	 * @return bool
296
-	 */
297
-	public function clearMessage(string $userId): bool {
298
-		try {
299
-			$userStatus = $this->mapper->findByUserId($userId);
300
-		} catch (DoesNotExistException $ex) {
301
-			// if there is no status to remove, just return
302
-			return false;
303
-		}
304
-
305
-		$userStatus->setMessageId(null);
306
-		$userStatus->setCustomMessage(null);
307
-		$userStatus->setCustomIcon(null);
308
-		$userStatus->setClearAt(null);
309
-
310
-		$this->mapper->update($userStatus);
311
-		return true;
312
-	}
313
-
314
-	/**
315
-	 * @param string $userId
316
-	 * @return bool
317
-	 */
318
-	public function removeUserStatus(string $userId): bool {
319
-		try {
320
-			$userStatus = $this->mapper->findByUserId($userId);
321
-		} catch (DoesNotExistException $ex) {
322
-			// if there is no status to remove, just return
323
-			return false;
324
-		}
325
-
326
-		$this->mapper->delete($userStatus);
327
-		return true;
328
-	}
329
-
330
-	/**
331
-	 * Processes a status to check if custom message is still
332
-	 * up to date and provides translated default status if needed
333
-	 *
334
-	 * @param UserStatus $status
335
-	 * @returns UserStatus
336
-	 */
337
-	private function processStatus(UserStatus $status): UserStatus {
338
-		$clearAt = $status->getClearAt();
339
-
340
-		if ($status->getStatusTimestamp() < $this->timeFactory->getTime() - self::INVALIDATE_STATUS_THRESHOLD
341
-			&& (!$status->getIsUserDefined() || $status->getStatus() === IUserStatus::ONLINE)) {
342
-			$this->cleanStatus($status);
343
-		}
344
-		if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
345
-			$this->cleanStatusMessage($status);
346
-		}
347
-		if ($status->getMessageId() !== null) {
348
-			$this->addDefaultMessage($status);
349
-		}
350
-
351
-		return $status;
352
-	}
353
-
354
-	/**
355
-	 * @param UserStatus $status
356
-	 */
357
-	private function cleanStatus(UserStatus $status): void {
358
-		$status->setStatus(IUserStatus::OFFLINE);
359
-		$status->setStatusTimestamp($this->timeFactory->getTime());
360
-		$status->setIsUserDefined(false);
361
-
362
-		$this->mapper->update($status);
363
-	}
364
-
365
-	/**
366
-	 * @param UserStatus $status
367
-	 */
368
-	private function cleanStatusMessage(UserStatus $status): void {
369
-		$status->setMessageId(null);
370
-		$status->setCustomIcon(null);
371
-		$status->setCustomMessage(null);
372
-		$status->setClearAt(null);
373
-
374
-		$this->mapper->update($status);
375
-	}
376
-
377
-	/**
378
-	 * @param UserStatus $status
379
-	 */
380
-	private function addDefaultMessage(UserStatus $status): void {
381
-		// If the message is predefined, insert the translated message and icon
382
-		$predefinedMessage = $this->predefinedStatusService->getDefaultStatusById($status->getMessageId());
383
-		if ($predefinedMessage !== null) {
384
-			$status->setCustomMessage($predefinedMessage['message']);
385
-			$status->setCustomIcon($predefinedMessage['icon']);
386
-		}
387
-	}
46
+    /** @var UserStatusMapper */
47
+    private $mapper;
48
+
49
+    /** @var ITimeFactory */
50
+    private $timeFactory;
51
+
52
+    /** @var PredefinedStatusService */
53
+    private $predefinedStatusService;
54
+
55
+    /** @var EmojiService */
56
+    private $emojiService;
57
+
58
+    /**
59
+     * List of priorities ordered by their priority
60
+     */
61
+    public const PRIORITY_ORDERED_STATUSES = [
62
+        IUserStatus::ONLINE,
63
+        IUserStatus::AWAY,
64
+        IUserStatus::DND,
65
+        IUserStatus::INVISIBLE,
66
+        IUserStatus::OFFLINE
67
+    ];
68
+
69
+    /**
70
+     * List of statuses that persist the clear-up
71
+     * or UserLiveStatusEvents
72
+     */
73
+    public const PERSISTENT_STATUSES = [
74
+        IUserStatus::AWAY,
75
+        IUserStatus::DND,
76
+        IUserStatus::INVISIBLE,
77
+    ];
78
+
79
+    /** @var int */
80
+    public const INVALIDATE_STATUS_THRESHOLD = 5 /* minutes */ * 60 /* seconds */;
81
+
82
+    /** @var int */
83
+    public const MAXIMUM_MESSAGE_LENGTH = 80;
84
+
85
+    /**
86
+     * StatusService constructor.
87
+     *
88
+     * @param UserStatusMapper $mapper
89
+     * @param ITimeFactory $timeFactory
90
+     * @param PredefinedStatusService $defaultStatusService,
91
+     * @param EmojiService $emojiService
92
+     */
93
+    public function __construct(UserStatusMapper $mapper,
94
+                                ITimeFactory $timeFactory,
95
+                                PredefinedStatusService $defaultStatusService,
96
+                                EmojiService $emojiService) {
97
+        $this->mapper = $mapper;
98
+        $this->timeFactory = $timeFactory;
99
+        $this->predefinedStatusService = $defaultStatusService;
100
+        $this->emojiService = $emojiService;
101
+    }
102
+
103
+    /**
104
+     * @param int|null $limit
105
+     * @param int|null $offset
106
+     * @return UserStatus[]
107
+     */
108
+    public function findAll(?int $limit = null, ?int $offset = null): array {
109
+        return array_map(function ($status) {
110
+            return $this->processStatus($status);
111
+        }, $this->mapper->findAll($limit, $offset));
112
+    }
113
+
114
+    /**
115
+     * @param int|null $limit
116
+     * @param int|null $offset
117
+     * @return array
118
+     */
119
+    public function findAllRecentStatusChanges(?int $limit = null, ?int $offset = null): array {
120
+        return array_map(function ($status) {
121
+            return $this->processStatus($status);
122
+        }, $this->mapper->findAllRecent($limit, $offset));
123
+    }
124
+
125
+    /**
126
+     * @param string $userId
127
+     * @return UserStatus
128
+     * @throws DoesNotExistException
129
+     */
130
+    public function findByUserId(string $userId):UserStatus {
131
+        return $this->processStatus($this->mapper->findByUserId($userId));
132
+    }
133
+
134
+    /**
135
+     * @param array $userIds
136
+     * @return UserStatus[]
137
+     */
138
+    public function findByUserIds(array $userIds):array {
139
+        return array_map(function ($status) {
140
+            return $this->processStatus($status);
141
+        }, $this->mapper->findByUserIds($userIds));
142
+    }
143
+
144
+    /**
145
+     * @param string $userId
146
+     * @param string $status
147
+     * @param int|null $statusTimestamp
148
+     * @param bool $isUserDefined
149
+     * @return UserStatus
150
+     * @throws InvalidStatusTypeException
151
+     */
152
+    public function setStatus(string $userId,
153
+                                string $status,
154
+                              ?int $statusTimestamp,
155
+                                bool $isUserDefined): UserStatus {
156
+        try {
157
+            $userStatus = $this->mapper->findByUserId($userId);
158
+        } catch (DoesNotExistException $ex) {
159
+            $userStatus = new UserStatus();
160
+            $userStatus->setUserId($userId);
161
+        }
162
+
163
+        // Check if status-type is valid
164
+        if (!\in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
165
+            throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
166
+        }
167
+        if ($statusTimestamp === null) {
168
+            $statusTimestamp = $this->timeFactory->getTime();
169
+        }
170
+
171
+        $userStatus->setStatus($status);
172
+        $userStatus->setStatusTimestamp($statusTimestamp);
173
+        $userStatus->setIsUserDefined($isUserDefined);
174
+
175
+        if ($userStatus->getId() === null) {
176
+            return $this->mapper->insert($userStatus);
177
+        }
178
+
179
+        return $this->mapper->update($userStatus);
180
+    }
181
+
182
+    /**
183
+     * @param string $userId
184
+     * @param string $messageId
185
+     * @param int|null $clearAt
186
+     * @return UserStatus
187
+     * @throws InvalidMessageIdException
188
+     * @throws InvalidClearAtException
189
+     */
190
+    public function setPredefinedMessage(string $userId,
191
+                                            string $messageId,
192
+                                         ?int $clearAt): UserStatus {
193
+        try {
194
+            $userStatus = $this->mapper->findByUserId($userId);
195
+        } catch (DoesNotExistException $ex) {
196
+            $userStatus = new UserStatus();
197
+            $userStatus->setUserId($userId);
198
+            $userStatus->setStatus(IUserStatus::OFFLINE);
199
+            $userStatus->setStatusTimestamp(0);
200
+            $userStatus->setIsUserDefined(false);
201
+        }
202
+
203
+        if (!$this->predefinedStatusService->isValidId($messageId)) {
204
+            throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
205
+        }
206
+
207
+        // Check that clearAt is in the future
208
+        if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
209
+            throw new InvalidClearAtException('ClearAt is in the past');
210
+        }
211
+
212
+        $userStatus->setMessageId($messageId);
213
+        $userStatus->setCustomIcon(null);
214
+        $userStatus->setCustomMessage(null);
215
+        $userStatus->setClearAt($clearAt);
216
+
217
+        if ($userStatus->getId() === null) {
218
+            return $this->mapper->insert($userStatus);
219
+        }
220
+
221
+        return $this->mapper->update($userStatus);
222
+    }
223
+
224
+    /**
225
+     * @param string $userId
226
+     * @param string|null $statusIcon
227
+     * @param string|null $message
228
+     * @param int|null $clearAt
229
+     * @return UserStatus
230
+     * @throws InvalidClearAtException
231
+     * @throws InvalidStatusIconException
232
+     * @throws StatusMessageTooLongException
233
+     */
234
+    public function setCustomMessage(string $userId,
235
+                                     ?string $statusIcon,
236
+                                        string $message,
237
+                                     ?int $clearAt): UserStatus {
238
+        try {
239
+            $userStatus = $this->mapper->findByUserId($userId);
240
+        } catch (DoesNotExistException $ex) {
241
+            $userStatus = new UserStatus();
242
+            $userStatus->setUserId($userId);
243
+            $userStatus->setStatus(IUserStatus::OFFLINE);
244
+            $userStatus->setStatusTimestamp(0);
245
+            $userStatus->setIsUserDefined(false);
246
+        }
247
+
248
+        // Check if statusIcon contains only one character
249
+        if ($statusIcon !== null && !$this->emojiService->isValidEmoji($statusIcon)) {
250
+            throw new InvalidStatusIconException('Status-Icon is longer than one character');
251
+        }
252
+        // Check for maximum length of custom message
253
+        if (\mb_strlen($message) > self::MAXIMUM_MESSAGE_LENGTH) {
254
+            throw new StatusMessageTooLongException('Message is longer than supported length of ' . self::MAXIMUM_MESSAGE_LENGTH . ' characters');
255
+        }
256
+        // Check that clearAt is in the future
257
+        if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
258
+            throw new InvalidClearAtException('ClearAt is in the past');
259
+        }
260
+
261
+        $userStatus->setMessageId(null);
262
+        $userStatus->setCustomIcon($statusIcon);
263
+        $userStatus->setCustomMessage($message);
264
+        $userStatus->setClearAt($clearAt);
265
+
266
+        if ($userStatus->getId() === null) {
267
+            return $this->mapper->insert($userStatus);
268
+        }
269
+
270
+        return $this->mapper->update($userStatus);
271
+    }
272
+
273
+    /**
274
+     * @param string $userId
275
+     * @return bool
276
+     */
277
+    public function clearStatus(string $userId): bool {
278
+        try {
279
+            $userStatus = $this->mapper->findByUserId($userId);
280
+        } catch (DoesNotExistException $ex) {
281
+            // if there is no status to remove, just return
282
+            return false;
283
+        }
284
+
285
+        $userStatus->setStatus(IUserStatus::OFFLINE);
286
+        $userStatus->setStatusTimestamp(0);
287
+        $userStatus->setIsUserDefined(false);
288
+
289
+        $this->mapper->update($userStatus);
290
+        return true;
291
+    }
292
+
293
+    /**
294
+     * @param string $userId
295
+     * @return bool
296
+     */
297
+    public function clearMessage(string $userId): bool {
298
+        try {
299
+            $userStatus = $this->mapper->findByUserId($userId);
300
+        } catch (DoesNotExistException $ex) {
301
+            // if there is no status to remove, just return
302
+            return false;
303
+        }
304
+
305
+        $userStatus->setMessageId(null);
306
+        $userStatus->setCustomMessage(null);
307
+        $userStatus->setCustomIcon(null);
308
+        $userStatus->setClearAt(null);
309
+
310
+        $this->mapper->update($userStatus);
311
+        return true;
312
+    }
313
+
314
+    /**
315
+     * @param string $userId
316
+     * @return bool
317
+     */
318
+    public function removeUserStatus(string $userId): bool {
319
+        try {
320
+            $userStatus = $this->mapper->findByUserId($userId);
321
+        } catch (DoesNotExistException $ex) {
322
+            // if there is no status to remove, just return
323
+            return false;
324
+        }
325
+
326
+        $this->mapper->delete($userStatus);
327
+        return true;
328
+    }
329
+
330
+    /**
331
+     * Processes a status to check if custom message is still
332
+     * up to date and provides translated default status if needed
333
+     *
334
+     * @param UserStatus $status
335
+     * @returns UserStatus
336
+     */
337
+    private function processStatus(UserStatus $status): UserStatus {
338
+        $clearAt = $status->getClearAt();
339
+
340
+        if ($status->getStatusTimestamp() < $this->timeFactory->getTime() - self::INVALIDATE_STATUS_THRESHOLD
341
+            && (!$status->getIsUserDefined() || $status->getStatus() === IUserStatus::ONLINE)) {
342
+            $this->cleanStatus($status);
343
+        }
344
+        if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
345
+            $this->cleanStatusMessage($status);
346
+        }
347
+        if ($status->getMessageId() !== null) {
348
+            $this->addDefaultMessage($status);
349
+        }
350
+
351
+        return $status;
352
+    }
353
+
354
+    /**
355
+     * @param UserStatus $status
356
+     */
357
+    private function cleanStatus(UserStatus $status): void {
358
+        $status->setStatus(IUserStatus::OFFLINE);
359
+        $status->setStatusTimestamp($this->timeFactory->getTime());
360
+        $status->setIsUserDefined(false);
361
+
362
+        $this->mapper->update($status);
363
+    }
364
+
365
+    /**
366
+     * @param UserStatus $status
367
+     */
368
+    private function cleanStatusMessage(UserStatus $status): void {
369
+        $status->setMessageId(null);
370
+        $status->setCustomIcon(null);
371
+        $status->setCustomMessage(null);
372
+        $status->setClearAt(null);
373
+
374
+        $this->mapper->update($status);
375
+    }
376
+
377
+    /**
378
+     * @param UserStatus $status
379
+     */
380
+    private function addDefaultMessage(UserStatus $status): void {
381
+        // If the message is predefined, insert the translated message and icon
382
+        $predefinedMessage = $this->predefinedStatusService->getDefaultStatusById($status->getMessageId());
383
+        if ($predefinedMessage !== null) {
384
+            $status->setCustomMessage($predefinedMessage['message']);
385
+            $status->setCustomIcon($predefinedMessage['icon']);
386
+        }
387
+    }
388 388
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	 * @return UserStatus[]
107 107
 	 */
108 108
 	public function findAll(?int $limit = null, ?int $offset = null): array {
109
-		return array_map(function ($status) {
109
+		return array_map(function($status) {
110 110
 			return $this->processStatus($status);
111 111
 		}, $this->mapper->findAll($limit, $offset));
112 112
 	}
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 	 * @return array
118 118
 	 */
119 119
 	public function findAllRecentStatusChanges(?int $limit = null, ?int $offset = null): array {
120
-		return array_map(function ($status) {
120
+		return array_map(function($status) {
121 121
 			return $this->processStatus($status);
122 122
 		}, $this->mapper->findAllRecent($limit, $offset));
123 123
 	}
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 	 * @return UserStatus[]
137 137
 	 */
138 138
 	public function findByUserIds(array $userIds):array {
139
-		return array_map(function ($status) {
139
+		return array_map(function($status) {
140 140
 			return $this->processStatus($status);
141 141
 		}, $this->mapper->findByUserIds($userIds));
142 142
 	}
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 
163 163
 		// Check if status-type is valid
164 164
 		if (!\in_array($status, self::PRIORITY_ORDERED_STATUSES, true)) {
165
-			throw new InvalidStatusTypeException('Status-type "' . $status . '" is not supported');
165
+			throw new InvalidStatusTypeException('Status-type "'.$status.'" is not supported');
166 166
 		}
167 167
 		if ($statusTimestamp === null) {
168 168
 			$statusTimestamp = $this->timeFactory->getTime();
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		}
202 202
 
203 203
 		if (!$this->predefinedStatusService->isValidId($messageId)) {
204
-			throw new InvalidMessageIdException('Message-Id "' . $messageId . '" is not supported');
204
+			throw new InvalidMessageIdException('Message-Id "'.$messageId.'" is not supported');
205 205
 		}
206 206
 
207 207
 		// Check that clearAt is in the future
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 		}
252 252
 		// Check for maximum length of custom message
253 253
 		if (\mb_strlen($message) > self::MAXIMUM_MESSAGE_LENGTH) {
254
-			throw new StatusMessageTooLongException('Message is longer than supported length of ' . self::MAXIMUM_MESSAGE_LENGTH . ' characters');
254
+			throw new StatusMessageTooLongException('Message is longer than supported length of '.self::MAXIMUM_MESSAGE_LENGTH.' characters');
255 255
 		}
256 256
 		// Check that clearAt is in the future
257 257
 		if ($clearAt !== null && $clearAt < $this->timeFactory->getTime()) {
Please login to merge, or discard this patch.
apps/user_status/lib/BackgroundJob/ClearOldStatusesBackgroundJob.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -37,31 +37,31 @@
 block discarded – undo
37 37
  */
38 38
 class ClearOldStatusesBackgroundJob extends TimedJob {
39 39
 
40
-	/** @var UserStatusMapper */
41
-	private $mapper;
40
+    /** @var UserStatusMapper */
41
+    private $mapper;
42 42
 
43
-	/**
44
-	 * ClearOldStatusesBackgroundJob constructor.
45
-	 *
46
-	 * @param ITimeFactory $time
47
-	 * @param UserStatusMapper $mapper
48
-	 */
49
-	public function __construct(ITimeFactory $time,
50
-								UserStatusMapper $mapper) {
51
-		parent::__construct($time);
52
-		$this->mapper = $mapper;
43
+    /**
44
+     * ClearOldStatusesBackgroundJob constructor.
45
+     *
46
+     * @param ITimeFactory $time
47
+     * @param UserStatusMapper $mapper
48
+     */
49
+    public function __construct(ITimeFactory $time,
50
+                                UserStatusMapper $mapper) {
51
+        parent::__construct($time);
52
+        $this->mapper = $mapper;
53 53
 
54
-		// Run every time the cron is run
55
-		$this->setInterval(60);
56
-	}
54
+        // Run every time the cron is run
55
+        $this->setInterval(60);
56
+    }
57 57
 
58
-	/**
59
-	 * @inheritDoc
60
-	 */
61
-	protected function run($argument) {
62
-		$now = $this->time->getTime();
58
+    /**
59
+     * @inheritDoc
60
+     */
61
+    protected function run($argument) {
62
+        $now = $this->time->getTime();
63 63
 
64
-		$this->mapper->clearMessagesOlderThan($now);
65
-		$this->mapper->clearStatusesOlderThan($now - StatusService::INVALIDATE_STATUS_THRESHOLD, $now);
66
-	}
64
+        $this->mapper->clearMessagesOlderThan($now);
65
+        $this->mapper->clearStatusesOlderThan($now - StatusService::INVALIDATE_STATUS_THRESHOLD, $now);
66
+    }
67 67
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Connector/UserStatus.php 2 patches
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -30,72 +30,72 @@
 block discarded – undo
30 30
 
31 31
 class UserStatus implements IUserStatus {
32 32
 
33
-	/** @var string */
34
-	private $userId;
35
-
36
-	/** @var string */
37
-	private $status;
38
-
39
-	/** @var string|null */
40
-	private $message;
41
-
42
-	/** @var string|null */
43
-	private $icon;
44
-
45
-	/** @var DateTimeImmutable|null */
46
-	private $clearAt;
47
-
48
-	/**
49
-	 * UserStatus constructor.
50
-	 *
51
-	 * @param Db\UserStatus $status
52
-	 */
53
-	public function __construct(Db\UserStatus $status) {
54
-		$this->userId = $status->getUserId();
55
-		$this->status = $status->getStatus();
56
-		$this->message = $status->getCustomMessage();
57
-		$this->icon = $status->getCustomIcon();
58
-
59
-		if ($status->getStatus() === IUserStatus::INVISIBLE) {
60
-			$this->status = IUserStatus::OFFLINE;
61
-		}
62
-		if ($status->getClearAt() !== null) {
63
-			$this->clearAt = DateTimeImmutable::createFromFormat('U', (string)$status->getClearAt());
64
-		}
65
-	}
66
-
67
-	/**
68
-	 * @inheritDoc
69
-	 */
70
-	public function getUserId(): string {
71
-		return $this->userId;
72
-	}
73
-
74
-	/**
75
-	 * @inheritDoc
76
-	 */
77
-	public function getStatus(): string {
78
-		return $this->status;
79
-	}
80
-
81
-	/**
82
-	 * @inheritDoc
83
-	 */
84
-	public function getMessage(): ?string {
85
-		return $this->message;
86
-	}
87
-
88
-	/**
89
-	 * @inheritDoc
90
-	 */
91
-	public function getIcon(): ?string {
92
-		return $this->icon;
93
-	}
94
-
95
-	/**
96
-	 * @inheritDoc
97
-	 */
98
-	public function getClearAt(): ?DateTimeImmutable {
99
-		return $this->clearAt;
100
-	}
33
+    /** @var string */
34
+    private $userId;
35
+
36
+    /** @var string */
37
+    private $status;
38
+
39
+    /** @var string|null */
40
+    private $message;
41
+
42
+    /** @var string|null */
43
+    private $icon;
44
+
45
+    /** @var DateTimeImmutable|null */
46
+    private $clearAt;
47
+
48
+    /**
49
+     * UserStatus constructor.
50
+     *
51
+     * @param Db\UserStatus $status
52
+     */
53
+    public function __construct(Db\UserStatus $status) {
54
+        $this->userId = $status->getUserId();
55
+        $this->status = $status->getStatus();
56
+        $this->message = $status->getCustomMessage();
57
+        $this->icon = $status->getCustomIcon();
58
+
59
+        if ($status->getStatus() === IUserStatus::INVISIBLE) {
60
+            $this->status = IUserStatus::OFFLINE;
61
+        }
62
+        if ($status->getClearAt() !== null) {
63
+            $this->clearAt = DateTimeImmutable::createFromFormat('U', (string)$status->getClearAt());
64
+        }
65
+    }
66
+
67
+    /**
68
+     * @inheritDoc
69
+     */
70
+    public function getUserId(): string {
71
+        return $this->userId;
72
+    }
73
+
74
+    /**
75
+     * @inheritDoc
76
+     */
77
+    public function getStatus(): string {
78
+        return $this->status;
79
+    }
80
+
81
+    /**
82
+     * @inheritDoc
83
+     */
84
+    public function getMessage(): ?string {
85
+        return $this->message;
86
+    }
87
+
88
+    /**
89
+     * @inheritDoc
90
+     */
91
+    public function getIcon(): ?string {
92
+        return $this->icon;
93
+    }
94
+
95
+    /**
96
+     * @inheritDoc
97
+     */
98
+    public function getClearAt(): ?DateTimeImmutable {
99
+        return $this->clearAt;
100
+    }
101 101
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 			$this->status = IUserStatus::OFFLINE;
61 61
 		}
62 62
 		if ($status->getClearAt() !== null) {
63
-			$this->clearAt = DateTimeImmutable::createFromFormat('U', (string)$status->getClearAt());
63
+			$this->clearAt = DateTimeImmutable::createFromFormat('U', (string) $status->getClearAt());
64 64
 		}
65 65
 	}
66 66
 
Please login to merge, or discard this patch.
apps/user_status/lib/Migration/Version0002Date20200902144824.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -36,22 +36,22 @@
 block discarded – undo
36 36
  */
37 37
 class Version0002Date20200902144824 extends SimpleMigrationStep {
38 38
 
39
-	/**
40
-	 * @param IOutput $output
41
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
42
-	 * @param array $options
43
-	 * @return null|ISchemaWrapper
44
-	 * @since 20.0.0
45
-	 */
46
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
47
-		/** @var ISchemaWrapper $schema */
48
-		$schema = $schemaClosure();
49
-
50
-		$statusTable = $schema->getTable('user_status');
51
-
52
-		$statusTable->addIndex(['status_timestamp'], 'user_status_tstmp_ix');
53
-		$statusTable->addIndex(['is_user_defined', 'status'], 'user_status_iud_ix');
54
-
55
-		return $schema;
56
-	}
39
+    /**
40
+     * @param IOutput $output
41
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
42
+     * @param array $options
43
+     * @return null|ISchemaWrapper
44
+     * @since 20.0.0
45
+     */
46
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
47
+        /** @var ISchemaWrapper $schema */
48
+        $schema = $schemaClosure();
49
+
50
+        $statusTable = $schema->getTable('user_status');
51
+
52
+        $statusTable->addIndex(['status_timestamp'], 'user_status_tstmp_ix');
53
+        $statusTable->addIndex(['is_user_defined', 'status'], 'user_status_iud_ix');
54
+
55
+        return $schema;
56
+    }
57 57
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Db/UserStatusMapper.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -42,124 +42,124 @@
 block discarded – undo
42 42
  */
43 43
 class UserStatusMapper extends QBMapper {
44 44
 
45
-	/**
46
-	 * @param IDBConnection $db
47
-	 */
48
-	public function __construct(IDBConnection $db) {
49
-		parent::__construct($db, 'user_status');
50
-	}
51
-
52
-	/**
53
-	 * @param int|null $limit
54
-	 * @param int|null $offset
55
-	 * @return UserStatus[]
56
-	 */
57
-	public function findAll(?int $limit = null, ?int $offset = null):array {
58
-		$qb = $this->db->getQueryBuilder();
59
-		$qb
60
-			->select('*')
61
-			->from($this->tableName);
62
-
63
-		if ($limit !== null) {
64
-			$qb->setMaxResults($limit);
65
-		}
66
-		if ($offset !== null) {
67
-			$qb->setFirstResult($offset);
68
-		}
69
-
70
-		return $this->findEntities($qb);
71
-	}
72
-
73
-	/**
74
-	 * @param int|null $limit
75
-	 * @param int|null $offset
76
-	 * @return array
77
-	 */
78
-	public function findAllRecent(?int $limit = null, ?int $offset = null): array {
79
-		$qb = $this->db->getQueryBuilder();
80
-
81
-		$qb
82
-			->select('*')
83
-			->from($this->tableName)
84
-			->orderBy('status_timestamp', 'DESC')
85
-			->where($qb->expr()->notIn('status', $qb->createNamedParameter([IUserStatus::ONLINE, IUserStatus::AWAY, IUserStatus::OFFLINE], IQueryBuilder::PARAM_STR_ARRAY)))
86
-			->orWhere($qb->expr()->isNotNull('message_id'))
87
-			->orWhere($qb->expr()->isNotNull('custom_icon'))
88
-			->orWhere($qb->expr()->isNotNull('custom_message'));
89
-
90
-		if ($limit !== null) {
91
-			$qb->setMaxResults($limit);
92
-		}
93
-		if ($offset !== null) {
94
-			$qb->setFirstResult($offset);
95
-		}
96
-
97
-		return $this->findEntities($qb);
98
-	}
99
-
100
-	/**
101
-	 * @param string $userId
102
-	 * @return UserStatus
103
-	 * @throws \OCP\AppFramework\Db\DoesNotExistException
104
-	 */
105
-	public function findByUserId(string $userId):UserStatus {
106
-		$qb = $this->db->getQueryBuilder();
107
-		$qb
108
-			->select('*')
109
-			->from($this->tableName)
110
-			->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR)));
111
-
112
-		return $this->findEntity($qb);
113
-	}
114
-
115
-	/**
116
-	 * @param array $userIds
117
-	 * @return array
118
-	 */
119
-	public function findByUserIds(array $userIds):array {
120
-		$qb = $this->db->getQueryBuilder();
121
-		$qb
122
-			->select('*')
123
-			->from($this->tableName)
124
-			->where($qb->expr()->in('user_id', $qb->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
125
-
126
-		return $this->findEntities($qb);
127
-	}
128
-
129
-	/**
130
-	 * @param int $olderThan
131
-	 * @param int $now
132
-	 */
133
-	public function clearStatusesOlderThan(int $olderThan, int $now): void {
134
-		$qb = $this->db->getQueryBuilder();
135
-		$qb->update($this->tableName)
136
-			->set('status', $qb->createNamedParameter(IUserStatus::OFFLINE))
137
-			->set('is_user_defined', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL))
138
-			->set('status_timestamp', $qb->createNamedParameter($now, IQueryBuilder::PARAM_INT))
139
-			->where($qb->expr()->lte('status_timestamp', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
140
-			->andWhere($qb->expr()->orX(
141
-				$qb->expr()->eq('is_user_defined', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL), IQueryBuilder::PARAM_BOOL),
142
-				$qb->expr()->eq('status', $qb->createNamedParameter(IUserStatus::ONLINE))
143
-			));
144
-
145
-		$qb->execute();
146
-	}
147
-
148
-	/**
149
-	 * Clear all statuses older than a given timestamp
150
-	 *
151
-	 * @param int $timestamp
152
-	 */
153
-	public function clearMessagesOlderThan(int $timestamp): void {
154
-		$qb = $this->db->getQueryBuilder();
155
-		$qb->update($this->tableName)
156
-			->set('message_id', $qb->createNamedParameter(null))
157
-			->set('custom_icon', $qb->createNamedParameter(null))
158
-			->set('custom_message', $qb->createNamedParameter(null))
159
-			->set('clear_at', $qb->createNamedParameter(null))
160
-			->where($qb->expr()->isNotNull('clear_at'))
161
-			->andWhere($qb->expr()->lte('clear_at', $qb->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT)));
162
-
163
-		$qb->execute();
164
-	}
45
+    /**
46
+     * @param IDBConnection $db
47
+     */
48
+    public function __construct(IDBConnection $db) {
49
+        parent::__construct($db, 'user_status');
50
+    }
51
+
52
+    /**
53
+     * @param int|null $limit
54
+     * @param int|null $offset
55
+     * @return UserStatus[]
56
+     */
57
+    public function findAll(?int $limit = null, ?int $offset = null):array {
58
+        $qb = $this->db->getQueryBuilder();
59
+        $qb
60
+            ->select('*')
61
+            ->from($this->tableName);
62
+
63
+        if ($limit !== null) {
64
+            $qb->setMaxResults($limit);
65
+        }
66
+        if ($offset !== null) {
67
+            $qb->setFirstResult($offset);
68
+        }
69
+
70
+        return $this->findEntities($qb);
71
+    }
72
+
73
+    /**
74
+     * @param int|null $limit
75
+     * @param int|null $offset
76
+     * @return array
77
+     */
78
+    public function findAllRecent(?int $limit = null, ?int $offset = null): array {
79
+        $qb = $this->db->getQueryBuilder();
80
+
81
+        $qb
82
+            ->select('*')
83
+            ->from($this->tableName)
84
+            ->orderBy('status_timestamp', 'DESC')
85
+            ->where($qb->expr()->notIn('status', $qb->createNamedParameter([IUserStatus::ONLINE, IUserStatus::AWAY, IUserStatus::OFFLINE], IQueryBuilder::PARAM_STR_ARRAY)))
86
+            ->orWhere($qb->expr()->isNotNull('message_id'))
87
+            ->orWhere($qb->expr()->isNotNull('custom_icon'))
88
+            ->orWhere($qb->expr()->isNotNull('custom_message'));
89
+
90
+        if ($limit !== null) {
91
+            $qb->setMaxResults($limit);
92
+        }
93
+        if ($offset !== null) {
94
+            $qb->setFirstResult($offset);
95
+        }
96
+
97
+        return $this->findEntities($qb);
98
+    }
99
+
100
+    /**
101
+     * @param string $userId
102
+     * @return UserStatus
103
+     * @throws \OCP\AppFramework\Db\DoesNotExistException
104
+     */
105
+    public function findByUserId(string $userId):UserStatus {
106
+        $qb = $this->db->getQueryBuilder();
107
+        $qb
108
+            ->select('*')
109
+            ->from($this->tableName)
110
+            ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR)));
111
+
112
+        return $this->findEntity($qb);
113
+    }
114
+
115
+    /**
116
+     * @param array $userIds
117
+     * @return array
118
+     */
119
+    public function findByUserIds(array $userIds):array {
120
+        $qb = $this->db->getQueryBuilder();
121
+        $qb
122
+            ->select('*')
123
+            ->from($this->tableName)
124
+            ->where($qb->expr()->in('user_id', $qb->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
125
+
126
+        return $this->findEntities($qb);
127
+    }
128
+
129
+    /**
130
+     * @param int $olderThan
131
+     * @param int $now
132
+     */
133
+    public function clearStatusesOlderThan(int $olderThan, int $now): void {
134
+        $qb = $this->db->getQueryBuilder();
135
+        $qb->update($this->tableName)
136
+            ->set('status', $qb->createNamedParameter(IUserStatus::OFFLINE))
137
+            ->set('is_user_defined', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL))
138
+            ->set('status_timestamp', $qb->createNamedParameter($now, IQueryBuilder::PARAM_INT))
139
+            ->where($qb->expr()->lte('status_timestamp', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
140
+            ->andWhere($qb->expr()->orX(
141
+                $qb->expr()->eq('is_user_defined', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL), IQueryBuilder::PARAM_BOOL),
142
+                $qb->expr()->eq('status', $qb->createNamedParameter(IUserStatus::ONLINE))
143
+            ));
144
+
145
+        $qb->execute();
146
+    }
147
+
148
+    /**
149
+     * Clear all statuses older than a given timestamp
150
+     *
151
+     * @param int $timestamp
152
+     */
153
+    public function clearMessagesOlderThan(int $timestamp): void {
154
+        $qb = $this->db->getQueryBuilder();
155
+        $qb->update($this->tableName)
156
+            ->set('message_id', $qb->createNamedParameter(null))
157
+            ->set('custom_icon', $qb->createNamedParameter(null))
158
+            ->set('custom_message', $qb->createNamedParameter(null))
159
+            ->set('clear_at', $qb->createNamedParameter(null))
160
+            ->where($qb->expr()->isNotNull('clear_at'))
161
+            ->andWhere($qb->expr()->lte('clear_at', $qb->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT)));
162
+
163
+        $qb->execute();
164
+    }
165 165
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Controller/StatusesController.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -36,73 +36,73 @@
 block discarded – undo
36 36
 
37 37
 class StatusesController extends OCSController {
38 38
 
39
-	/** @var StatusService */
40
-	private $service;
39
+    /** @var StatusService */
40
+    private $service;
41 41
 
42
-	/**
43
-	 * StatusesController constructor.
44
-	 *
45
-	 * @param string $appName
46
-	 * @param IRequest $request
47
-	 * @param StatusService $service
48
-	 */
49
-	public function __construct(string $appName,
50
-								IRequest $request,
51
-								StatusService $service) {
52
-		parent::__construct($appName, $request);
53
-		$this->service = $service;
54
-	}
42
+    /**
43
+     * StatusesController constructor.
44
+     *
45
+     * @param string $appName
46
+     * @param IRequest $request
47
+     * @param StatusService $service
48
+     */
49
+    public function __construct(string $appName,
50
+                                IRequest $request,
51
+                                StatusService $service) {
52
+        parent::__construct($appName, $request);
53
+        $this->service = $service;
54
+    }
55 55
 
56
-	/**
57
-	 * @NoAdminRequired
58
-	 *
59
-	 * @param int|null $limit
60
-	 * @param int|null $offset
61
-	 * @return DataResponse
62
-	 */
63
-	public function findAll(?int $limit=null, ?int $offset=null): DataResponse {
64
-		$allStatuses = $this->service->findAll($limit, $offset);
56
+    /**
57
+     * @NoAdminRequired
58
+     *
59
+     * @param int|null $limit
60
+     * @param int|null $offset
61
+     * @return DataResponse
62
+     */
63
+    public function findAll(?int $limit=null, ?int $offset=null): DataResponse {
64
+        $allStatuses = $this->service->findAll($limit, $offset);
65 65
 
66
-		return new DataResponse(array_map(function ($userStatus) {
67
-			return $this->formatStatus($userStatus);
68
-		}, $allStatuses));
69
-	}
66
+        return new DataResponse(array_map(function ($userStatus) {
67
+            return $this->formatStatus($userStatus);
68
+        }, $allStatuses));
69
+    }
70 70
 
71
-	/**
72
-	 * @NoAdminRequired
73
-	 *
74
-	 * @param string $userId
75
-	 * @return DataResponse
76
-	 * @throws OCSNotFoundException
77
-	 */
78
-	public function find(string $userId): DataResponse {
79
-		try {
80
-			$userStatus = $this->service->findByUserId($userId);
81
-		} catch (DoesNotExistException $ex) {
82
-			throw new OCSNotFoundException('No status for the requested userId');
83
-		}
71
+    /**
72
+     * @NoAdminRequired
73
+     *
74
+     * @param string $userId
75
+     * @return DataResponse
76
+     * @throws OCSNotFoundException
77
+     */
78
+    public function find(string $userId): DataResponse {
79
+        try {
80
+            $userStatus = $this->service->findByUserId($userId);
81
+        } catch (DoesNotExistException $ex) {
82
+            throw new OCSNotFoundException('No status for the requested userId');
83
+        }
84 84
 
85
-		return new DataResponse($this->formatStatus($userStatus));
86
-	}
85
+        return new DataResponse($this->formatStatus($userStatus));
86
+    }
87 87
 
88
-	/**
89
-	 * @NoAdminRequired
90
-	 *
91
-	 * @param UserStatus $status
92
-	 * @return array
93
-	 */
94
-	private function formatStatus(UserStatus $status): array {
95
-		$visibleStatus = $status->getStatus();
96
-		if ($visibleStatus === IUserStatus::INVISIBLE) {
97
-			$visibleStatus = IUserStatus::OFFLINE;
98
-		}
88
+    /**
89
+     * @NoAdminRequired
90
+     *
91
+     * @param UserStatus $status
92
+     * @return array
93
+     */
94
+    private function formatStatus(UserStatus $status): array {
95
+        $visibleStatus = $status->getStatus();
96
+        if ($visibleStatus === IUserStatus::INVISIBLE) {
97
+            $visibleStatus = IUserStatus::OFFLINE;
98
+        }
99 99
 
100
-		return [
101
-			'userId' => $status->getUserId(),
102
-			'message' => $status->getCustomMessage(),
103
-			'icon' => $status->getCustomIcon(),
104
-			'clearAt' => $status->getClearAt(),
105
-			'status' => $visibleStatus,
106
-		];
107
-	}
100
+        return [
101
+            'userId' => $status->getUserId(),
102
+            'message' => $status->getCustomMessage(),
103
+            'icon' => $status->getCustomIcon(),
104
+            'clearAt' => $status->getClearAt(),
105
+            'status' => $visibleStatus,
106
+        ];
107
+    }
108 108
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Controller/HeartbeatController.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -37,59 +37,59 @@
 block discarded – undo
37 37
 
38 38
 class HeartbeatController extends Controller {
39 39
 
40
-	/** @var IEventDispatcher */
41
-	private $eventDispatcher;
40
+    /** @var IEventDispatcher */
41
+    private $eventDispatcher;
42 42
 
43
-	/** @var IUserSession */
44
-	private $userSession;
43
+    /** @var IUserSession */
44
+    private $userSession;
45 45
 
46
-	/** @var ITimeFactory */
47
-	private $timeFactory;
46
+    /** @var ITimeFactory */
47
+    private $timeFactory;
48 48
 
49
-	/**
50
-	 * HeartbeatController constructor.
51
-	 *
52
-	 * @param string $appName
53
-	 * @param IRequest $request
54
-	 * @param IEventDispatcher $eventDispatcher
55
-	 * @param IUserSession $userSession
56
-	 * @param ITimeFactory $timeFactory
57
-	 */
58
-	public function __construct(string $appName,
59
-								IRequest $request,
60
-								IEventDispatcher $eventDispatcher,
61
-								IUserSession $userSession,
62
-								ITimeFactory $timeFactory) {
63
-		parent::__construct($appName, $request);
64
-		$this->eventDispatcher = $eventDispatcher;
65
-		$this->userSession = $userSession;
66
-		$this->timeFactory = $timeFactory;
67
-	}
49
+    /**
50
+     * HeartbeatController constructor.
51
+     *
52
+     * @param string $appName
53
+     * @param IRequest $request
54
+     * @param IEventDispatcher $eventDispatcher
55
+     * @param IUserSession $userSession
56
+     * @param ITimeFactory $timeFactory
57
+     */
58
+    public function __construct(string $appName,
59
+                                IRequest $request,
60
+                                IEventDispatcher $eventDispatcher,
61
+                                IUserSession $userSession,
62
+                                ITimeFactory $timeFactory) {
63
+        parent::__construct($appName, $request);
64
+        $this->eventDispatcher = $eventDispatcher;
65
+        $this->userSession = $userSession;
66
+        $this->timeFactory = $timeFactory;
67
+    }
68 68
 
69
-	/**
70
-	 * @NoAdminRequired
71
-	 *
72
-	 * @param string $status
73
-	 * @return JSONResponse
74
-	 */
75
-	public function heartbeat(string $status): JSONResponse {
76
-		if (!\in_array($status, [IUserStatus::ONLINE, IUserStatus::AWAY], true)) {
77
-			return new JSONResponse([], Http::STATUS_BAD_REQUEST);
78
-		}
69
+    /**
70
+     * @NoAdminRequired
71
+     *
72
+     * @param string $status
73
+     * @return JSONResponse
74
+     */
75
+    public function heartbeat(string $status): JSONResponse {
76
+        if (!\in_array($status, [IUserStatus::ONLINE, IUserStatus::AWAY], true)) {
77
+            return new JSONResponse([], Http::STATUS_BAD_REQUEST);
78
+        }
79 79
 
80
-		$user = $this->userSession->getUser();
81
-		if ($user === null) {
82
-			return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
83
-		}
80
+        $user = $this->userSession->getUser();
81
+        if ($user === null) {
82
+            return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
83
+        }
84 84
 
85
-		$this->eventDispatcher->dispatchTyped(
86
-			new UserLiveStatusEvent(
87
-				$user,
88
-				$status,
89
-				$this->timeFactory->getTime()
90
-			)
91
-		);
85
+        $this->eventDispatcher->dispatchTyped(
86
+            new UserLiveStatusEvent(
87
+                $user,
88
+                $status,
89
+                $this->timeFactory->getTime()
90
+            )
91
+        );
92 92
 
93
-		return new JSONResponse([], Http::STATUS_NO_CONTENT);
94
-	}
93
+        return new JSONResponse([], Http::STATUS_NO_CONTENT);
94
+    }
95 95
 }
Please login to merge, or discard this patch.
apps/user_status/lib/Listener/UserLiveStatusListener.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -42,75 +42,75 @@
 block discarded – undo
42 42
  */
43 43
 class UserLiveStatusListener implements IEventListener {
44 44
 
45
-	/** @var UserStatusMapper */
46
-	private $mapper;
47
-
48
-	/** @var ITimeFactory */
49
-	private $timeFactory;
50
-
51
-	/**
52
-	 * UserLiveStatusListener constructor.
53
-	 *
54
-	 * @param UserStatusMapper $mapper
55
-	 * @param ITimeFactory $timeFactory
56
-	 */
57
-	public function __construct(UserStatusMapper $mapper,
58
-								ITimeFactory $timeFactory) {
59
-		$this->mapper = $mapper;
60
-		$this->timeFactory = $timeFactory;
61
-	}
62
-
63
-	/**
64
-	 * @inheritDoc
65
-	 */
66
-	public function handle(Event $event): void {
67
-		if (!($event instanceof UserLiveStatusEvent)) {
68
-			// Unrelated
69
-			return;
70
-		}
71
-
72
-		$user = $event->getUser();
73
-		try {
74
-			$userStatus = $this->mapper->findByUserId($user->getUID());
75
-		} catch (DoesNotExistException $ex) {
76
-			$userStatus = new UserStatus();
77
-			$userStatus->setUserId($user->getUID());
78
-			$userStatus->setStatus(IUserStatus::OFFLINE);
79
-			$userStatus->setStatusTimestamp(0);
80
-			$userStatus->setIsUserDefined(false);
81
-		}
82
-
83
-		// If the status is user-defined and one of the persistent statuses, we
84
-		// will not override it.
85
-		if ($userStatus->getIsUserDefined() &&
86
-			\in_array($userStatus->getStatus(), StatusService::PERSISTENT_STATUSES, true)) {
87
-			return;
88
-		}
89
-
90
-		$needsUpdate = false;
91
-
92
-		// If the current status is older than 5 minutes,
93
-		// treat it as outdated and update
94
-		if ($userStatus->getStatusTimestamp() < ($this->timeFactory->getTime() - StatusService::INVALIDATE_STATUS_THRESHOLD)) {
95
-			$needsUpdate = true;
96
-		}
97
-
98
-		// If the emitted status is more important than the current status
99
-		// treat it as outdated and update
100
-		if (array_search($event->getStatus(), StatusService::PRIORITY_ORDERED_STATUSES) < array_search($userStatus->getStatus(), StatusService::PRIORITY_ORDERED_STATUSES)) {
101
-			$needsUpdate = true;
102
-		}
103
-
104
-		if ($needsUpdate) {
105
-			$userStatus->setStatus($event->getStatus());
106
-			$userStatus->setStatusTimestamp($event->getTimestamp());
107
-			$userStatus->setIsUserDefined(false);
108
-
109
-			if ($userStatus->getId() === null) {
110
-				$this->mapper->insert($userStatus);
111
-			} else {
112
-				$this->mapper->update($userStatus);
113
-			}
114
-		}
115
-	}
45
+    /** @var UserStatusMapper */
46
+    private $mapper;
47
+
48
+    /** @var ITimeFactory */
49
+    private $timeFactory;
50
+
51
+    /**
52
+     * UserLiveStatusListener constructor.
53
+     *
54
+     * @param UserStatusMapper $mapper
55
+     * @param ITimeFactory $timeFactory
56
+     */
57
+    public function __construct(UserStatusMapper $mapper,
58
+                                ITimeFactory $timeFactory) {
59
+        $this->mapper = $mapper;
60
+        $this->timeFactory = $timeFactory;
61
+    }
62
+
63
+    /**
64
+     * @inheritDoc
65
+     */
66
+    public function handle(Event $event): void {
67
+        if (!($event instanceof UserLiveStatusEvent)) {
68
+            // Unrelated
69
+            return;
70
+        }
71
+
72
+        $user = $event->getUser();
73
+        try {
74
+            $userStatus = $this->mapper->findByUserId($user->getUID());
75
+        } catch (DoesNotExistException $ex) {
76
+            $userStatus = new UserStatus();
77
+            $userStatus->setUserId($user->getUID());
78
+            $userStatus->setStatus(IUserStatus::OFFLINE);
79
+            $userStatus->setStatusTimestamp(0);
80
+            $userStatus->setIsUserDefined(false);
81
+        }
82
+
83
+        // If the status is user-defined and one of the persistent statuses, we
84
+        // will not override it.
85
+        if ($userStatus->getIsUserDefined() &&
86
+            \in_array($userStatus->getStatus(), StatusService::PERSISTENT_STATUSES, true)) {
87
+            return;
88
+        }
89
+
90
+        $needsUpdate = false;
91
+
92
+        // If the current status is older than 5 minutes,
93
+        // treat it as outdated and update
94
+        if ($userStatus->getStatusTimestamp() < ($this->timeFactory->getTime() - StatusService::INVALIDATE_STATUS_THRESHOLD)) {
95
+            $needsUpdate = true;
96
+        }
97
+
98
+        // If the emitted status is more important than the current status
99
+        // treat it as outdated and update
100
+        if (array_search($event->getStatus(), StatusService::PRIORITY_ORDERED_STATUSES) < array_search($userStatus->getStatus(), StatusService::PRIORITY_ORDERED_STATUSES)) {
101
+            $needsUpdate = true;
102
+        }
103
+
104
+        if ($needsUpdate) {
105
+            $userStatus->setStatus($event->getStatus());
106
+            $userStatus->setStatusTimestamp($event->getTimestamp());
107
+            $userStatus->setIsUserDefined(false);
108
+
109
+            if ($userStatus->getId() === null) {
110
+                $this->mapper->insert($userStatus);
111
+            } else {
112
+                $this->mapper->update($userStatus);
113
+            }
114
+        }
115
+    }
116 116
 }
Please login to merge, or discard this patch.