Notifier.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\Reminder;
  8. use DateTime;
  9. use OCA\DAV\AppInfo\Application;
  10. use OCP\AppFramework\Utility\ITimeFactory;
  11. use OCP\IL10N;
  12. use OCP\IURLGenerator;
  13. use OCP\L10N\IFactory;
  14. use OCP\Notification\AlreadyProcessedException;
  15. use OCP\Notification\INotification;
  16. use OCP\Notification\INotifier;
  17. use OCP\Notification\UnknownNotificationException;
  18. /**
  19. * Class Notifier
  20. *
  21. * @package OCA\DAV\CalDAV\Reminder
  22. */
  23. class Notifier implements INotifier {
  24. /** @var IL10N */
  25. private $l10n;
  26. /**
  27. * Notifier constructor.
  28. *
  29. * @param IFactory $l10nFactory
  30. * @param IURLGenerator $urlGenerator
  31. * @param ITimeFactory $timeFactory
  32. */
  33. public function __construct(
  34. private IFactory $l10nFactory,
  35. private IURLGenerator $urlGenerator,
  36. private ITimeFactory $timeFactory,
  37. ) {
  38. }
  39. /**
  40. * Identifier of the notifier, only use [a-z0-9_]
  41. *
  42. * @return string
  43. * @since 17.0.0
  44. */
  45. public function getID():string {
  46. return Application::APP_ID;
  47. }
  48. /**
  49. * Human readable name describing the notifier
  50. *
  51. * @return string
  52. * @since 17.0.0
  53. */
  54. public function getName():string {
  55. return $this->l10nFactory->get('dav')->t('Calendar');
  56. }
  57. /**
  58. * Prepare sending the notification
  59. *
  60. * @param INotification $notification
  61. * @param string $languageCode The code of the language that should be used to prepare the notification
  62. * @return INotification
  63. * @throws UnknownNotificationException
  64. */
  65. public function prepare(INotification $notification,
  66. string $languageCode):INotification {
  67. if ($notification->getApp() !== Application::APP_ID) {
  68. throw new UnknownNotificationException('Notification not from this app');
  69. }
  70. // Read the language from the notification
  71. $this->l10n = $this->l10nFactory->get('dav', $languageCode);
  72. // Handle notifier subjects
  73. switch ($notification->getSubject()) {
  74. case 'calendar_reminder':
  75. return $this->prepareReminderNotification($notification);
  76. default:
  77. throw new UnknownNotificationException('Unknown subject');
  78. }
  79. }
  80. /**
  81. * @param INotification $notification
  82. * @return INotification
  83. */
  84. private function prepareReminderNotification(INotification $notification):INotification {
  85. $imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg');
  86. $iconUrl = $this->urlGenerator->getAbsoluteURL($imagePath);
  87. $notification->setIcon($iconUrl);
  88. $this->prepareNotificationSubject($notification);
  89. $this->prepareNotificationMessage($notification);
  90. return $notification;
  91. }
  92. /**
  93. * Sets the notification subject based on the parameters set in PushProvider
  94. *
  95. * @param INotification $notification
  96. */
  97. private function prepareNotificationSubject(INotification $notification): void {
  98. $parameters = $notification->getSubjectParameters();
  99. $startTime = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
  100. $now = $this->timeFactory->getDateTime();
  101. $title = $this->getTitleFromParameters($parameters);
  102. $diff = $startTime->diff($now);
  103. if ($diff === false) {
  104. return;
  105. }
  106. $components = [];
  107. if ($diff->y) {
  108. $components[] = $this->l10n->n('%n year', '%n years', $diff->y);
  109. }
  110. if ($diff->m) {
  111. $components[] = $this->l10n->n('%n month', '%n months', $diff->m);
  112. }
  113. if ($diff->d) {
  114. $components[] = $this->l10n->n('%n day', '%n days', $diff->d);
  115. }
  116. if ($diff->h) {
  117. $components[] = $this->l10n->n('%n hour', '%n hours', $diff->h);
  118. }
  119. if ($diff->i) {
  120. $components[] = $this->l10n->n('%n minute', '%n minutes', $diff->i);
  121. }
  122. if (count($components) > 0 && !$this->hasPhpDatetimeDiffBug()) {
  123. // Limiting to the first three components to prevent
  124. // the string from getting too long
  125. $firstThreeComponents = array_slice($components, 0, 2);
  126. $diffLabel = implode(', ', $firstThreeComponents);
  127. if ($diff->invert) {
  128. $title = $this->l10n->t('%s (in %s)', [$title, $diffLabel]);
  129. } else {
  130. $title = $this->l10n->t('%s (%s ago)', [$title, $diffLabel]);
  131. }
  132. }
  133. $notification->setParsedSubject($title);
  134. }
  135. /**
  136. * @see https://github.com/nextcloud/server/issues/41615
  137. * @see https://github.com/php/php-src/issues/9699
  138. */
  139. private function hasPhpDatetimeDiffBug(): bool {
  140. $d1 = DateTime::createFromFormat(\DateTimeInterface::ATOM, '2023-11-22T11:52:00+01:00');
  141. $d2 = new DateTime('2023-11-22T10:52:03', new \DateTimeZone('UTC'));
  142. // The difference is 3 seconds, not -1year+11months+…
  143. return $d1->diff($d2)->y < 0;
  144. }
  145. /**
  146. * Sets the notification message based on the parameters set in PushProvider
  147. *
  148. * @param INotification $notification
  149. */
  150. private function prepareNotificationMessage(INotification $notification): void {
  151. $parameters = $notification->getMessageParameters();
  152. $description = [
  153. $this->l10n->t('Calendar: %s', $parameters['calendar_displayname']),
  154. $this->l10n->t('Date: %s', $this->generateDateString($parameters)),
  155. ];
  156. if ($parameters['description']) {
  157. $description[] = $this->l10n->t('Description: %s', $parameters['description']);
  158. }
  159. if ($parameters['location']) {
  160. $description[] = $this->l10n->t('Where: %s', $parameters['location']);
  161. }
  162. $message = implode("\r\n", $description);
  163. $notification->setParsedMessage($message);
  164. }
  165. /**
  166. * @param array $parameters
  167. * @return string
  168. */
  169. private function getTitleFromParameters(array $parameters):string {
  170. return $parameters['title'] ?? $this->l10n->t('Untitled event');
  171. }
  172. /**
  173. * @param array $parameters
  174. * @return string
  175. * @throws \Exception
  176. */
  177. private function generateDateString(array $parameters):string {
  178. $startDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
  179. $endDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['end_atom']);
  180. // If the event has already ended, dismiss the notification
  181. if ($endDateTime < $this->timeFactory->getDateTime()) {
  182. throw new AlreadyProcessedException();
  183. }
  184. $isAllDay = $parameters['all_day'];
  185. $diff = $startDateTime->diff($endDateTime);
  186. if ($isAllDay) {
  187. // One day event
  188. if ($diff->days === 1) {
  189. return $this->getDateString($startDateTime);
  190. }
  191. return implode(' - ', [
  192. $this->getDateString($startDateTime),
  193. $this->getDateString($endDateTime),
  194. ]);
  195. }
  196. $startTimezone = $endTimezone = null;
  197. if (!$parameters['start_is_floating']) {
  198. $startTimezone = $parameters['start_timezone'];
  199. $endTimezone = $parameters['end_timezone'];
  200. }
  201. $localeStart = implode(', ', [
  202. $this->getWeekDayName($startDateTime),
  203. $this->getDateTimeString($startDateTime)
  204. ]);
  205. // always show full date with timezone if timezones are different
  206. if ($startTimezone !== $endTimezone) {
  207. $localeEnd = implode(', ', [
  208. $this->getWeekDayName($endDateTime),
  209. $this->getDateTimeString($endDateTime)
  210. ]);
  211. return $localeStart
  212. . ' (' . $startTimezone . ') '
  213. . ' - '
  214. . $localeEnd
  215. . ' (' . $endTimezone . ')';
  216. }
  217. // Show only the time if the day is the same
  218. $localeEnd = $this->isDayEqual($startDateTime, $endDateTime)
  219. ? $this->getTimeString($endDateTime)
  220. : implode(', ', [
  221. $this->getWeekDayName($endDateTime),
  222. $this->getDateTimeString($endDateTime)
  223. ]);
  224. return $localeStart
  225. . ' - '
  226. . $localeEnd
  227. . ' (' . $startTimezone . ')';
  228. }
  229. /**
  230. * @param DateTime $dtStart
  231. * @param DateTime $dtEnd
  232. * @return bool
  233. */
  234. private function isDayEqual(DateTime $dtStart,
  235. DateTime $dtEnd):bool {
  236. return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
  237. }
  238. /**
  239. * @param DateTime $dt
  240. * @return string
  241. */
  242. private function getWeekDayName(DateTime $dt):string {
  243. return (string)$this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
  244. }
  245. /**
  246. * @param DateTime $dt
  247. * @return string
  248. */
  249. private function getDateString(DateTime $dt):string {
  250. return (string)$this->l10n->l('date', $dt, ['width' => 'medium']);
  251. }
  252. /**
  253. * @param DateTime $dt
  254. * @return string
  255. */
  256. private function getDateTimeString(DateTime $dt):string {
  257. return (string)$this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
  258. }
  259. /**
  260. * @param DateTime $dt
  261. * @return string
  262. */
  263. private function getTimeString(DateTime $dt):string {
  264. return (string)$this->l10n->l('time', $dt, ['width' => 'short']);
  265. }
  266. }