1
0

Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Notification;
  9. use OC\AppFramework\Bootstrap\Coordinator;
  10. use OCP\ICache;
  11. use OCP\ICacheFactory;
  12. use OCP\IUserManager;
  13. use OCP\Notification\AlreadyProcessedException;
  14. use OCP\Notification\IApp;
  15. use OCP\Notification\IDeferrableApp;
  16. use OCP\Notification\IDismissableNotifier;
  17. use OCP\Notification\IManager;
  18. use OCP\Notification\IncompleteNotificationException;
  19. use OCP\Notification\IncompleteParsedNotificationException;
  20. use OCP\Notification\INotification;
  21. use OCP\Notification\INotifier;
  22. use OCP\Notification\UnknownNotificationException;
  23. use OCP\RichObjectStrings\IValidator;
  24. use OCP\Support\Subscription\IRegistry;
  25. use Psr\Container\ContainerExceptionInterface;
  26. use Psr\Log\LoggerInterface;
  27. class Manager implements IManager {
  28. /** @var ICache */
  29. protected ICache $cache;
  30. /** @var IApp[] */
  31. protected array $apps;
  32. /** @var string[] */
  33. protected array $appClasses;
  34. /** @var INotifier[] */
  35. protected array $notifiers;
  36. /** @var string[] */
  37. protected array $notifierClasses;
  38. /** @var bool */
  39. protected bool $preparingPushNotification;
  40. /** @var bool */
  41. protected bool $deferPushing;
  42. /** @var bool */
  43. private bool $parsedRegistrationContext;
  44. public function __construct(
  45. protected IValidator $validator,
  46. private IUserManager $userManager,
  47. ICacheFactory $cacheFactory,
  48. protected IRegistry $subscription,
  49. protected LoggerInterface $logger,
  50. private Coordinator $coordinator,
  51. ) {
  52. $this->cache = $cacheFactory->createDistributed('notifications');
  53. $this->apps = [];
  54. $this->notifiers = [];
  55. $this->appClasses = [];
  56. $this->notifierClasses = [];
  57. $this->preparingPushNotification = false;
  58. $this->deferPushing = false;
  59. $this->parsedRegistrationContext = false;
  60. }
  61. /**
  62. * @param string $appClass The service must implement IApp, otherwise a
  63. * \InvalidArgumentException is thrown later
  64. * @since 17.0.0
  65. */
  66. public function registerApp(string $appClass): void {
  67. $this->appClasses[] = $appClass;
  68. }
  69. /**
  70. * @param \Closure $service The service must implement INotifier, otherwise a
  71. * \InvalidArgumentException is thrown later
  72. * @param \Closure $info An array with the keys 'id' and 'name' containing
  73. * the app id and the app name
  74. * @deprecated 17.0.0 use registerNotifierService instead.
  75. * @since 8.2.0 - Parameter $info was added in 9.0.0
  76. */
  77. public function registerNotifier(\Closure $service, \Closure $info): void {
  78. $infoData = $info();
  79. $exception = new \InvalidArgumentException(
  80. 'Notifier ' . $infoData['name'] . ' (id: ' . $infoData['id'] . ') is not considered because it is using the old way to register.'
  81. );
  82. $this->logger->error($exception->getMessage(), ['exception' => $exception]);
  83. }
  84. /**
  85. * @param string $notifierService The service must implement INotifier, otherwise a
  86. * \InvalidArgumentException is thrown later
  87. * @since 17.0.0
  88. */
  89. public function registerNotifierService(string $notifierService): void {
  90. $this->notifierClasses[] = $notifierService;
  91. }
  92. /**
  93. * @return IApp[]
  94. */
  95. protected function getApps(): array {
  96. if (empty($this->appClasses)) {
  97. return $this->apps;
  98. }
  99. foreach ($this->appClasses as $appClass) {
  100. try {
  101. $app = \OC::$server->get($appClass);
  102. } catch (ContainerExceptionInterface $e) {
  103. $this->logger->error('Failed to load notification app class: ' . $appClass, [
  104. 'exception' => $e,
  105. 'app' => 'notifications',
  106. ]);
  107. continue;
  108. }
  109. if (!($app instanceof IApp)) {
  110. $this->logger->error('Notification app class ' . $appClass . ' is not implementing ' . IApp::class, [
  111. 'app' => 'notifications',
  112. ]);
  113. continue;
  114. }
  115. $this->apps[] = $app;
  116. }
  117. $this->appClasses = [];
  118. return $this->apps;
  119. }
  120. /**
  121. * @return INotifier[]
  122. */
  123. public function getNotifiers(): array {
  124. if (!$this->parsedRegistrationContext) {
  125. $notifierServices = $this->coordinator->getRegistrationContext()->getNotifierServices();
  126. foreach ($notifierServices as $notifierService) {
  127. try {
  128. $notifier = \OC::$server->get($notifierService->getService());
  129. } catch (ContainerExceptionInterface $e) {
  130. $this->logger->error('Failed to load notification notifier class: ' . $notifierService->getService(), [
  131. 'exception' => $e,
  132. 'app' => 'notifications',
  133. ]);
  134. continue;
  135. }
  136. if (!($notifier instanceof INotifier)) {
  137. $this->logger->error('Notification notifier class ' . $notifierService->getService() . ' is not implementing ' . INotifier::class, [
  138. 'app' => 'notifications',
  139. ]);
  140. continue;
  141. }
  142. $this->notifiers[] = $notifier;
  143. }
  144. $this->parsedRegistrationContext = true;
  145. }
  146. if (empty($this->notifierClasses)) {
  147. return $this->notifiers;
  148. }
  149. foreach ($this->notifierClasses as $notifierClass) {
  150. try {
  151. $notifier = \OC::$server->get($notifierClass);
  152. } catch (ContainerExceptionInterface $e) {
  153. $this->logger->error('Failed to load notification notifier class: ' . $notifierClass, [
  154. 'exception' => $e,
  155. 'app' => 'notifications',
  156. ]);
  157. continue;
  158. }
  159. if (!($notifier instanceof INotifier)) {
  160. $this->logger->error('Notification notifier class ' . $notifierClass . ' is not implementing ' . INotifier::class, [
  161. 'app' => 'notifications',
  162. ]);
  163. continue;
  164. }
  165. $this->notifiers[] = $notifier;
  166. }
  167. $this->notifierClasses = [];
  168. return $this->notifiers;
  169. }
  170. /**
  171. * @return INotification
  172. * @since 8.2.0
  173. */
  174. public function createNotification(): INotification {
  175. return new Notification($this->validator);
  176. }
  177. /**
  178. * @return bool
  179. * @since 8.2.0
  180. */
  181. public function hasNotifiers(): bool {
  182. return !empty($this->notifiers) || !empty($this->notifierClasses);
  183. }
  184. /**
  185. * @param bool $preparingPushNotification
  186. * @since 14.0.0
  187. */
  188. public function setPreparingPushNotification(bool $preparingPushNotification): void {
  189. $this->preparingPushNotification = $preparingPushNotification;
  190. }
  191. /**
  192. * @return bool
  193. * @since 14.0.0
  194. */
  195. public function isPreparingPushNotification(): bool {
  196. return $this->preparingPushNotification;
  197. }
  198. /**
  199. * The calling app should only "flush" when it got returned true on the defer call
  200. * @return bool
  201. * @since 20.0.0
  202. */
  203. public function defer(): bool {
  204. $alreadyDeferring = $this->deferPushing;
  205. $this->deferPushing = true;
  206. $apps = $this->getApps();
  207. foreach ($apps as $app) {
  208. if ($app instanceof IDeferrableApp) {
  209. $app->defer();
  210. }
  211. }
  212. return !$alreadyDeferring;
  213. }
  214. /**
  215. * @since 20.0.0
  216. */
  217. public function flush(): void {
  218. $apps = $this->getApps();
  219. foreach ($apps as $app) {
  220. if (!$app instanceof IDeferrableApp) {
  221. continue;
  222. }
  223. try {
  224. $app->flush();
  225. } catch (\InvalidArgumentException $e) {
  226. }
  227. }
  228. $this->deferPushing = false;
  229. }
  230. /**
  231. * {@inheritDoc}
  232. */
  233. public function isFairUseOfFreePushService(): bool {
  234. $pushAllowed = $this->cache->get('push_fair_use');
  235. if ($pushAllowed === null) {
  236. /**
  237. * We want to keep offering our push notification service for free, but large
  238. * users overload our infrastructure. For this reason we have to rate-limit the
  239. * use of push notifications. If you need this feature, consider using Nextcloud Enterprise.
  240. */
  241. $isFairUse = $this->subscription->delegateHasValidSubscription() || $this->userManager->countSeenUsers() < 1000;
  242. $pushAllowed = $isFairUse ? 'yes' : 'no';
  243. $this->cache->set('push_fair_use', $pushAllowed, 3600);
  244. }
  245. return $pushAllowed === 'yes';
  246. }
  247. /**
  248. * {@inheritDoc}
  249. */
  250. public function notify(INotification $notification): void {
  251. if (!$notification->isValid()) {
  252. throw new IncompleteNotificationException('The given notification is invalid');
  253. }
  254. $apps = $this->getApps();
  255. foreach ($apps as $app) {
  256. try {
  257. $app->notify($notification);
  258. } catch (IncompleteNotificationException) {
  259. } catch (\InvalidArgumentException $e) {
  260. // todo 33.0.0 Log as warning
  261. // todo 39.0.0 Log as error
  262. $this->logger->debug(get_class($app) . '::notify() threw \InvalidArgumentException which is deprecated. Throw \OCP\Notification\IncompleteNotificationException when the notification is incomplete for your app and otherwise handle all \InvalidArgumentException yourself.');
  263. }
  264. }
  265. }
  266. /**
  267. * Identifier of the notifier, only use [a-z0-9_]
  268. *
  269. * @return string
  270. * @since 17.0.0
  271. */
  272. public function getID(): string {
  273. return 'core';
  274. }
  275. /**
  276. * Human readable name describing the notifier
  277. *
  278. * @return string
  279. * @since 17.0.0
  280. */
  281. public function getName(): string {
  282. return 'core';
  283. }
  284. /**
  285. * {@inheritDoc}
  286. */
  287. public function prepare(INotification $notification, string $languageCode): INotification {
  288. $notifiers = $this->getNotifiers();
  289. foreach ($notifiers as $notifier) {
  290. try {
  291. $notification = $notifier->prepare($notification, $languageCode);
  292. } catch (AlreadyProcessedException $e) {
  293. $this->markProcessed($notification);
  294. throw $e;
  295. } catch (UnknownNotificationException) {
  296. continue;
  297. } catch (\InvalidArgumentException $e) {
  298. // todo 33.0.0 Log as warning
  299. // todo 39.0.0 Log as error
  300. $this->logger->debug(get_class($notifier) . '::prepare() threw \InvalidArgumentException which is deprecated. Throw \OCP\Notification\UnknownNotificationException when the notification is not known to your notifier and otherwise handle all \InvalidArgumentException yourself.');
  301. continue;
  302. }
  303. if (!$notification->isValidParsed()) {
  304. $this->logger->info('Notification was claimed to be parsed, but was not fully parsed by ' . get_class($notifier) . ' [app: ' . $notification->getApp() . ', subject: ' . $notification->getSubject() . ']');
  305. throw new IncompleteParsedNotificationException();
  306. }
  307. }
  308. if (!$notification->isValidParsed()) {
  309. $this->logger->info('Notification was not parsed by any notifier [app: ' . $notification->getApp() . ', subject: ' . $notification->getSubject() . ']');
  310. throw new IncompleteParsedNotificationException();
  311. }
  312. $link = $notification->getLink();
  313. if ($link !== '' && !str_starts_with($link, 'http://') && !str_starts_with($link, 'https://')) {
  314. $this->logger->warning('Link of notification is not an absolute URL and does not work in mobile and desktop clients [app: ' . $notification->getApp() . ', subject: ' . $notification->getSubject() . ']');
  315. }
  316. $icon = $notification->getIcon();
  317. if ($icon !== '' && !str_starts_with($icon, 'http://') && !str_starts_with($icon, 'https://')) {
  318. $this->logger->warning('Icon of notification is not an absolute URL and does not work in mobile and desktop clients [app: ' . $notification->getApp() . ', subject: ' . $notification->getSubject() . ']');
  319. }
  320. foreach ($notification->getParsedActions() as $action) {
  321. $link = $action->getLink();
  322. if ($link !== '' && !str_starts_with($link, 'http://') && !str_starts_with($link, 'https://')) {
  323. $this->logger->warning('Link of action is not an absolute URL and does not work in mobile and desktop clients [app: ' . $notification->getApp() . ', subject: ' . $notification->getSubject() . ']');
  324. }
  325. }
  326. return $notification;
  327. }
  328. /**
  329. * @param INotification $notification
  330. */
  331. public function markProcessed(INotification $notification): void {
  332. $apps = $this->getApps();
  333. foreach ($apps as $app) {
  334. $app->markProcessed($notification);
  335. }
  336. }
  337. /**
  338. * @param INotification $notification
  339. * @return int
  340. */
  341. public function getCount(INotification $notification): int {
  342. $apps = $this->getApps();
  343. $count = 0;
  344. foreach ($apps as $app) {
  345. $count += $app->getCount($notification);
  346. }
  347. return $count;
  348. }
  349. /**
  350. * {@inheritDoc}
  351. */
  352. public function dismissNotification(INotification $notification): void {
  353. $notifiers = $this->getNotifiers();
  354. foreach ($notifiers as $notifier) {
  355. if ($notifier instanceof IDismissableNotifier) {
  356. try {
  357. $notifier->dismissNotification($notification);
  358. } catch (UnknownNotificationException) {
  359. continue;
  360. } catch (\InvalidArgumentException $e) {
  361. // todo 33.0.0 Log as warning
  362. // todo 39.0.0 Log as error
  363. $this->logger->debug(get_class($notifier) . '::dismissNotification() threw \InvalidArgumentException which is deprecated. Throw \OCP\Notification\UnknownNotificationException when the notification is not known to your notifier and otherwise handle all \InvalidArgumentException yourself.');
  364. continue;
  365. }
  366. }
  367. }
  368. }
  369. }