/** * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2015 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-or-later */ OCA = OCA || {}; (function() { /** * @classdesc This class represents the view belonging to the expert tab * in the LDAP wizard. */ var WizardTabExpert = OCA.LDAP.Wizard.WizardTabGeneric.subClass({ /** * initializes the instance. Always call it after initialization. * * @param {any} tabIndex - * @param {any} tabID - */ init: function (tabIndex, tabID) { this._super(tabIndex, tabID); var items = { ldap_expert_username_attr: { $element: $('#ldap_expert_username_attr'), setMethod: 'setUsernameAttribute' }, ldap_expert_uuid_user_attr: { $element: $('#ldap_expert_uuid_user_attr'), setMethod: 'setUserUUIDAttribute' }, ldap_expert_uuid_group_attr: { $element: $('#ldap_expert_uuid_group_attr'), setMethod: 'setGroupUUIDAttribute' }, //Buttons ldap_action_clear_user_mappings: { $element: $('#ldap_action_clear_user_mappings') }, ldap_action_clear_group_mappings: { $element: $('#ldap_action_clear_group_mappings') } }; this.setManagedItems(items); _.bindAll(this, 'onClearUserMappingsClick', 'onClearGroupMappingsClick'); this.managedItems.ldap_action_clear_user_mappings.$element.click(this.onClearUserMappingsClick); this.managedItems.ldap_action_clear_group_mappings.$element.click(this.onClearGroupMappingsClick); }, /** * Sets the config model for this view and subscribes to some events. * Also binds the config chooser to the model * * @param {OCA.LDAP.Wizard.ConfigModel} configModel */ setModel: function(configModel) { this._super(configModel); this.configModel.on('configLoaded', this.onConfigLoaded, this); this.configModel.on('receivedLdapFeature', this.onResultReceived, this); }, /** * sets the attribute to be used to create an Nextcloud ID (username) * * @param {string} attribute */ setUsernameAttribute: function(attribute) { this.setElementValue(this.managedItems.ldap_expert_username_attr.$element, attribute); }, /** * sets the attribute that provides an unique identifier per LDAP user * entry * * @param {string} attribute */ setUserUUIDAttribute: function(attribute) { this.setElementValue(this.managedItems.ldap_expert_uuid_user_attr.$element, attribute); }, /** * sets the attribute that provides an unique identifier per LDAP group * entry * * @param {string} attribute */ setGroupUUIDAttribute: function(attribute) { this.setElementValue(this.managedItems.ldap_expert_uuid_group_attr.$element, attribute); }, /** * requests clearing of all user mappings */ onClearUserMappingsClick: function() { this.configModel.requestWizard('ldap_action_clear_user_mappings', {ldap_clear_mapping: 'user'}); }, /** * requests clearing of all group mappings */ onClearGroupMappingsClick: function() { this.configModel.requestWizard('ldap_action_clear_group_mappings', {ldap_clear_mapping: 'group'}); }, /** * deals with the result of the Test Connection test * * @param {WizardTabAdvanced} view * @param {FeaturePayload} payload */ onResultReceived: function(view, payload) { if(payload.feature === 'ClearMappings') { var message; if(payload.data.status === 'success') { message = t('user_ldap', 'Mappings cleared successfully!'); } else { message = t('user_ldap', 'Error while clearing the mappings.'); } OC.Notification.showTemporary(message); } } }); OCA.LDAP.Wizard.WizardTabExpert = WizardTabExpert; })(); derCustLink'>allowUnderCustLink Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_reminders/lib/Service/ReminderService.php
blob: 6ee395620765c06579d5e3be71533603dd88052e (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\FilesReminders\Service;

use DateTime;
use DateTimeZone;
use OCA\FilesReminders\AppInfo\Application;
use OCA\FilesReminders\Db\Reminder;
use OCA\FilesReminders\Db\ReminderMapper;
use OCA\FilesReminders\Exception\NodeNotFoundException;
use OCA\FilesReminders\Exception\ReminderNotFoundException;
use OCA\FilesReminders\Exception\UserNotFoundException;
use OCA\FilesReminders\Model\RichReminder;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
use Psr\Log\LoggerInterface;
use Throwable;

class ReminderService {

	private ICache $cache;

	public function __construct(
		protected IUserManager $userManager,
		protected IURLGenerator $urlGenerator,
		protected INotificationManager $notificationManager,
		protected ReminderMapper $reminderMapper,
		protected IRootFolder $root,
		protected LoggerInterface $logger,
		protected ICacheFactory $cacheFactory,
	) {
		$this->cache = $this->cacheFactory->createInMemory();
	}

	public function cacheFolder(IUser $user, Folder $folder): void {
		$reminders = $this->reminderMapper->findAllInFolder($user, $folder);
		$reminderMap = [];
		foreach ($reminders as $reminder) {
			$reminderMap[$reminder->getFileId()] = $reminder;
		}

		$nodes = $folder->getDirectoryListing();
		foreach ($nodes as $node) {
			$reminder = $reminderMap[$node->getId()] ?? false;
			$this->cache->set("{$user->getUID()}-{$node->getId()}", $reminder);
		}
	}

	/**
	 * @throws NodeNotFoundException
	 */
	public function getDueForUser(IUser $user, int $fileId, bool $checkNode = true): ?RichReminder {
		if ($checkNode) {
			$this->checkNode($user, $fileId);
		}
		/** @var null|false|Reminder $cachedReminder */
		$cachedReminder = $this->cache->get("{$user->getUID()}-$fileId");
		if ($cachedReminder === false) {
			return null;
		}
		if ($cachedReminder instanceof Reminder) {
			return new RichReminder($cachedReminder, $this->root);
		}

		try {
			$reminder = $this->reminderMapper->findDueForUser($user, $fileId);
			$this->cache->set("{$user->getUID()}-$fileId", $reminder);
			return new RichReminder($reminder, $this->root);
		} catch (DoesNotExistException $e) {
			$this->cache->set("{$user->getUID()}-$fileId", false);
			return null;
		}
	}

	/**
	 * @return RichReminder[]
	 */
	public function getAll(?IUser $user = null) {
		$reminders = ($user !== null)
			? $this->reminderMapper->findAllForUser($user)
			: $this->reminderMapper->findAll();
		return array_map(
			fn (Reminder $reminder) => new RichReminder($reminder, $this->root),
			$reminders,
		);
	}

	/**
	 * @return bool true if created, false if updated
	 *
	 * @throws NodeNotFoundException
	 */
	public function createOrUpdate(IUser $user, int $fileId, DateTime $dueDate): bool {
		$now = new DateTime('now', new DateTimeZone('UTC'));
		$this->checkNode($user, $fileId);
		$reminder = $this->getDueForUser($user, $fileId);
		if ($reminder === null) {
			$reminder = new Reminder();
			$reminder->setUserId($user->getUID());
			$reminder->setFileId($fileId);
			$reminder->setDueDate($dueDate);
			$reminder->setUpdatedAt($now);
			$reminder->setCreatedAt($now);
			$this->reminderMapper->insert($reminder);
			$this->cache->set("{$user->getUID()}-$fileId", $reminder);
			return true;
		}
		$reminder->setDueDate($dueDate);
		$reminder->setUpdatedAt($now);
		$this->reminderMapper->update($reminder);
		$this->cache->set("{$user->getUID()}-$fileId", $reminder);
		return false;
	}

	/**
	 * @throws NodeNotFoundException
	 * @throws ReminderNotFoundException
	 */
	public function remove(IUser $user, int $fileId): void {
		$this->checkNode($user, $fileId);
		$reminder = $this->getDueForUser($user, $fileId);
		if ($reminder === null) {
			throw new ReminderNotFoundException();
		}
		$this->deleteReminder($reminder);
	}

	public function removeAllForNode(Node $node): void {
		$reminders = $this->reminderMapper->findAllForNode($node);
		foreach ($reminders as $reminder) {
			$this->deleteReminder($reminder);
		}
	}

	public function removeAllForUser(IUser $user): void {
		$reminders = $this->reminderMapper->findAllForUser($user);
		foreach ($reminders as $reminder) {
			$this->deleteReminder($reminder);
		}
	}

	/**
	 * @throws DoesNotExistException
	 * @throws UserNotFoundException
	 */
	public function send(Reminder $reminder): void {
		if ($reminder->getNotified()) {
			return;
		}

		$user = $this->userManager->get($reminder->getUserId());
		if ($user === null) {
			throw new UserNotFoundException();
		}

		$notification = $this->notificationManager->createNotification();
		$notification
			->setApp(Application::APP_ID)
			->setIcon($this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('files', 'folder.svg')))
			->setUser($user->getUID())
			->setObject('reminder', (string)$reminder->getId())
			->setSubject('reminder-due', [
				'fileId' => $reminder->getFileId(),
			])
			->setDateTime($reminder->getDueDate());

		try {
			$this->notificationManager->notify($notification);
			$this->reminderMapper->markNotified($reminder);
			$this->cache->set("{$user->getUID()}-{$reminder->getFileId()}", $reminder);
		} catch (Throwable $th) {
			$this->logger->error($th->getMessage(), $th->getTrace());
		}
	}

	public function cleanUp(?int $limit = null): void {
		$buffer = (new DateTime())
			->setTimezone(new DateTimeZone('UTC'))
			->modify('-1 day');
		$reminders = $this->reminderMapper->findNotified($buffer, $limit);
		foreach ($reminders as $reminder) {
			$this->deleteReminder($reminder);
		}
	}

	private function deleteReminder(Reminder $reminder): void {
		$this->reminderMapper->delete($reminder);
		$this->cache->set("{$reminder->getUserId()}-{$reminder->getFileId()}", false);
	}


	/**
	 * @throws NodeNotFoundException
	 */
	private function checkNode(IUser $user, int $fileId): void {
		$userFolder = $this->root->getUserFolder($user->getUID());
		$node = $userFolder->getFirstNodeById($fileId);
		if ($node === null) {
			throw new NodeNotFoundException();
		}
	}
}