-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathMailNotifications.php
More file actions
344 lines (298 loc) Β· 11.6 KB
/
Copy pathMailNotifications.php
File metadata and controls
344 lines (298 loc) Β· 11.6 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Notifications;
use OCA\Notifications\Model\Settings;
use OCA\Notifications\Model\SettingsMapper;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IDateTimeFormatter;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Mail\IMailer;
use OCP\Mail\IMessage;
use OCP\Notification\AlreadyProcessedException;
use OCP\Notification\IAction;
use OCP\Notification\IManager;
use OCP\Notification\IncompleteParsedNotificationException;
use OCP\Notification\INotification;
use OCP\Util;
use Psr\Log\LoggerInterface;
class MailNotifications {
public const BATCH_SIZE_CLI = 500;
public const BATCH_SIZE_WEB = 25;
public function __construct(
protected IConfig $config,
protected IManager $manager,
protected Handler $handler,
protected IUserManager $userManager,
protected LoggerInterface $logger,
protected IMailer $mailer,
protected IURLGenerator $urlGenerator,
protected Defaults $defaults,
protected IFactory $l10nFactory,
protected IDateTimeFormatter $dateFormatter,
protected ITimeFactory $timeFactory,
protected SettingsMapper $settingsMapper,
) {
}
/**
* Send all due notification emails.
*
* @param int $batchSize
* @param int $sendTime
*/
public function sendEmails(int $batchSize, int $sendTime): void {
$userSettings = $this->settingsMapper->getUsersByNextSendTime($batchSize);
if (empty($userSettings)) {
return;
}
$userIds = array_map(static fn (Settings $settings) => $settings->getUserId(), $userSettings);
// Batch-read settings
$fallbackTimeZone = date_default_timezone_get();
/** @psalm-var array<string, string> $userTimezones */
$userTimezones = $this->config->getUserValueForUsers('core', 'timezone', $userIds);
$userEnabled = $this->config->getUserValueForUsers('core', 'enabled', $userIds);
$fallbackLang = $this->config->getSystemValue('force_language', null);
if (is_string($fallbackLang)) {
/** @psalm-var array<string, string> $userLanguages */
$userLanguages = [];
} else {
$fallbackLang = $this->config->getSystemValueString('default_language', 'en');
/** @psalm-var array<string, string> $userLanguages */
$userLanguages = $this->config->getUserValueForUsers('core', 'lang', $userIds);
}
foreach ($userSettings as $settings) {
$userId = $settings->getUserId();
if (isset($userEnabled[$userId]) && $userEnabled[$userId] === 'false') {
// User is disabled, skip sending the email for them
if ($settings->getNextSendTime() <= $sendTime) {
$settings->setNextSendTime(
$sendTime + $settings->getBatchTime()
);
$this->settingsMapper->update($settings);
}
continue;
}
// Get the settings for this particular user, then check if we have notifications to email them
$languageCode = $userLanguages[$userId] ?? $fallbackLang;
$timezone = $userTimezones[$userId] ?? $fallbackTimeZone;
/** @var array<int, INotification> $notifications */
$notifications = $this->handler->getAfterId($settings->getLastSendId(), $userId);
if (!empty($notifications)) {
$oldestNotification = end($notifications);
$shouldSendAfter = $oldestNotification->getDateTime()->getTimestamp() + $settings->getBatchTime();
if ($shouldSendAfter <= $sendTime) {
// User has notifications that should send
$this->sendEmailToUser($settings, $notifications, $languageCode, $timezone);
} else {
// User has notifications but we didn't reach the timeout yet,
// So delay sending to the time of the notification + batch setting
$settings->setNextSendTime($shouldSendAfter);
$this->settingsMapper->update($settings);
}
} else {
$settings->setNextSendTime($sendTime + $settings->getBatchTime());
$this->settingsMapper->update($settings);
}
}
}
/**
* Send an email to the user containing given list of notifications
*
* @param Settings $settings
* @param non-empty-array<int, INotification> $notifications
* @param string $language
* @param string $timezone
*/
protected function sendEmailToUser(Settings $settings, array $notifications, string $language, string $timezone): void {
$lastSendId = array_key_first($notifications);
$lastSendTime = $this->timeFactory->getTime();
$this->manager->preloadDataForParsing($notifications, $language);
$preparedNotifications = [];
foreach ($notifications as $notification) {
/** @var INotification $preparedNotification */
try {
$preparedNotification = $this->manager->prepare($notification, $language);
} catch (AlreadyProcessedException|IncompleteParsedNotificationException|\InvalidArgumentException) {
// FIXME remove \InvalidArgumentException in Nextcloud 39
// The app was disabled, skip the notification
continue;
} catch (\Exception $e) {
$this->logger->error($e->getMessage(), [
'exception' => $e,
]);
continue;
}
$preparedNotifications[] = $preparedNotification;
}
if (count($preparedNotifications) > 0) {
$message = $this->prepareEmailMessage($settings->getUserId(), $preparedNotifications, $language, $timezone);
if ($message !== null) {
try {
$this->mailer->send($message);
} catch (\Exception $e) {
$this->logger->error($e->getMessage(), [
'exception' => $e,
]);
return;
}
$settings->setLastSendId($lastSendId);
$settings->setNextSendTime($lastSendTime + $settings->getBatchTime());
$this->settingsMapper->update($settings);
}
}
}
/**
* prepare the contents of the email message containing the provided list of notifications
*
* @param string $uid
* @param INotification[] $notifications
* @param string $language
* @param string $timezone
* @return ?IMessage message contents
*/
protected function prepareEmailMessage(string $uid, array $notifications, string $language, string $timezone): ?IMessage {
$user = $this->userManager->get($uid);
if (!$user instanceof IUser) {
return null;
}
$userEmailAddress = $user->getEMailAddress();
if (empty($userEmailAddress)) {
return null;
}
// Prepare our email template
$l10n = $this->l10nFactory->get('notifications', $language);
$userDisplayName = $user->getDisplayName();
$absoluteUrl = $this->urlGenerator->getAbsoluteURL('/');
$instanceName = $this->defaults->getName();
$template = $this->mailer->createEMailTemplate('notifications.EmailNotification', [
'displayname' => $userDisplayName,
'url' => $absoluteUrl
]);
// Prepare email header
$template->addHeader();
$template->addHeading($l10n->t('Hello %s', [$userDisplayName]), $l10n->t('Hello %s,', [$userDisplayName]));
// Prepare email subject and body mentioning amount of notifications
$homeLink = '<a href="' . $absoluteUrl . '">' . htmlspecialchars($instanceName) . '</a>';
$notificationsCount = count($notifications);
$template->setSubject($l10n->n('New notification for %s', '%n new notifications for %s', $notificationsCount, [$instanceName]));
$template->addBodyText(
$l10n->n('You have a new notification for %s', 'You have %n new notifications for %s', $notificationsCount, [$homeLink]),
$l10n->n('You have a new notification for %s', 'You have %n new notifications for %s', $notificationsCount, [$absoluteUrl])
);
// Prepare email body with the content of missed notifications
// Notifications are assumed to be passed-in in descending order (latest first). Reversing to present chronologically.
$notifications = array_reverse($notifications);
foreach ($notifications as $notification) {
try {
$relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay(
$notification->getDateTime(),
'long',
'short',
new \DateTimeZone($timezone ?: 'UTC'),
$l10n
);
$template->addBodyListItem($this->getHTMLContents($notification), $relativeDateTime, $notification->getIcon(), $notification->getParsedSubject());
// Buttons probably were not intended for this, but it works ok enough for showing the idea.
$actions = $notification->getParsedActions();
foreach ($actions as $action) {
if ($action->getRequestType() === IAction::TYPE_WEB) {
$template->addBodyButton($action->getParsedLabel(), $action->getLink());
}
}
} catch (\Throwable $e) {
$this->logger->error(
'An error occurred while preparing a notification ('
. $notification->getApp() . '|' . $notification->getSubject()
. '|' . $notification->getObjectType() . '|' . $notification->getObjectId()
. ') for sending',
['exception' => $e]
);
return null;
}
}
// Prepare email footer
$linkToPersonalSettings = $this->urlGenerator->linkToRouteAbsolute('settings.PersonalSettings.index', ['section' => 'notifications']);
$template->addBodyText(
$l10n->t('You can change the frequency of these emails or disable them in the <a href="%s">settings</a>.', $linkToPersonalSettings),
$l10n->t('You can change the frequency of these emails or disable them in the settings: %s', $linkToPersonalSettings)
);
$template->addFooter();
$message = $this->mailer->createMessage();
$message->useTemplate($template);
$message->setTo([$userEmailAddress => $userDisplayName]);
$message->setFrom([Util::getDefaultEmailAddress('no-reply') => $instanceName]);
return $message;
}
/**
* return HTML to display this notification
*
* @param INotification $notification
* @return string
*/
protected function getHTMLContents(INotification $notification): string {
$HTMLSubject = $this->getHTMLSubject($notification);
$link = $notification->getLink();
if ($link !== '') {
$HTMLSubject = '<a href="' . $link . '">' . $HTMLSubject . '</a>';
}
return $HTMLSubject . '<br>' . $this->getHTMLMessage($notification);
}
/**
* return HTML to display the subject of this notification
*
* @param INotification $notification
* @return string
*/
protected function getHTMLSubject(INotification $notification): string {
$contentString = htmlspecialchars($notification->getRichSubject());
if ($contentString === '') {
return htmlspecialchars($notification->getParsedSubject());
}
return $this->replaceRichParameters($notification->getRichSubjectParameters(), $contentString);
}
/**
* return HTML to display the message body of this notification
*
* @param INotification $notification
* @return string
*/
protected function getHTMLMessage(INotification $notification): string {
$contentString = htmlspecialchars($notification->getRichMessage());
if ($contentString === '') {
return htmlspecialchars($notification->getParsedMessage());
}
return $this->replaceRichParameters($notification->getRichMessageParameters(), $contentString);
}
/**
* replace the given parameters in the input content string for display in an email
*
* @param array<string, array<string, string>> $parameters
* @param string $contentString
* @return string $contentString with parameters processed
*/
protected function replaceRichParameters(array $parameters, string $contentString): string {
$placeholders = $replacements = [];
foreach ($parameters as $placeholder => $parameter) {
$placeholders[] = '{' . $placeholder . '}';
if ($parameter['type'] === 'file') {
$replacement = $parameter['path'];
} else {
$replacement = $parameter['name'];
}
if (isset($parameter['link'])) {
$replacements[] = '<a href="' . $parameter['link'] . '">' . htmlspecialchars($replacement) . '</a>';
} else {
$replacements[] = '<strong>' . htmlspecialchars($replacement) . '</strong>';
}
}
return str_replace($placeholders, $replacements, $contentString);
}
}