-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathWatchService.php
More file actions
97 lines (82 loc) · 2.38 KB
/
Copy pathWatchService.php
File metadata and controls
97 lines (82 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Polls\Service;
use OCA\Polls\Db\Poll;
use OCA\Polls\Db\PollMapper;
use OCA\Polls\Db\Watch;
use OCA\Polls\Db\WatchMapper;
use OCA\Polls\Exceptions\NoUpdatesException;
use OCA\Polls\Exceptions\WatchModeChanged;
use OCA\Polls\Model\Settings\AppSettings;
use OCA\Polls\UserSession;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\DB\Exception;
class WatchService {
/** @psalm-suppress PossiblyUnusedMethod */
public function __construct(
private AppSettings $appSettings,
private PollMapper $pollMapper,
private UserSession $userSession,
private Watch $watch,
private WatchMapper $watchMapper,
) {
}
/**
* Watch poll for updates
*/
public function watchUpdates(int $pollId, string $mode, ?int $offset = null): array {
if ($pollId) {
$this->pollMapper->get($pollId)
->request(Poll::PERMISSION_POLL_ACCESS);
}
$start = time();
$timeout = 30;
$offset = $offset ?? $start;
$updateType = $this->appSettings->getUpdateType();
if ($updateType !== $mode) {
throw new WatchModeChanged('Update type mismatch: expected ' . $updateType . ', got ' . $mode);
}
if ($updateType === AppSettings::SETTING_UPDATE_TYPE_LONG_POLLING) {
while (empty($updates) && time() <= $start + $timeout) {
sleep(1);
$updates = $this->getUpdates($pollId, $offset);
}
} else {
$updates = $this->getUpdates($pollId, $offset);
}
if (empty($updates)) {
throw new NoUpdatesException;
}
return $updates;
}
/**
* @return Watch[]
*/
private function getUpdates(int $pollId, int $offset): array {
try {
return $this->watchMapper->findUpdatesForPollId($pollId, $offset);
} catch (DoesNotExistException $e) {
return [];
}
}
public function writeUpdate(int $pollId, string $table): void {
$this->watch = new Watch();
$this->watch->setPollId($pollId);
$this->watch->setTable($table);
$this->watch->setSessionId($this->userSession->getClientIdHashed());
try {
$this->watch = $this->watchMapper->insert($this->watch);
} catch (Exception $e) {
if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
throw $e;
}
$this->watch = $this->watchMapper->findForPollIdAndTable($pollId, $table);
}
$this->watch->setUpdated(time());
$this->watchMapper->update($this->watch);
}
}