Notifier.php 8.3 KB

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