Notifier.php 8.4 KB

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