Notifier.php 9.2 KB

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