RefreshWebcalService.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\WebcalCaching;
  8. use OCA\DAV\CalDAV\CalDavBackend;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use Psr\Log\LoggerInterface;
  11. use Sabre\DAV\Exception\BadRequest;
  12. use Sabre\DAV\Exception\Forbidden;
  13. use Sabre\DAV\PropPatch;
  14. use Sabre\VObject\Component;
  15. use Sabre\VObject\DateTimeParser;
  16. use Sabre\VObject\InvalidDataException;
  17. use Sabre\VObject\ParseException;
  18. use Sabre\VObject\Reader;
  19. use Sabre\VObject\Recur\NoInstancesException;
  20. use Sabre\VObject\Splitter\ICalendar;
  21. use Sabre\VObject\UUIDUtil;
  22. use function count;
  23. class RefreshWebcalService {
  24. public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
  25. public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
  26. public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
  27. public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
  28. public function __construct(private CalDavBackend $calDavBackend,
  29. private LoggerInterface $logger,
  30. private Connection $connection,
  31. private ITimeFactory $time) {
  32. }
  33. public function refreshSubscription(string $principalUri, string $uri) {
  34. $subscription = $this->getSubscription($principalUri, $uri);
  35. $mutations = [];
  36. if (!$subscription) {
  37. return;
  38. }
  39. // Check the refresh rate if there is any
  40. if(!empty($subscription['{http://apple.com/ns/ical/}refreshrate'])) {
  41. // add the refresh interval to the lastmodified timestamp
  42. $refreshInterval = new \DateInterval($subscription['{http://apple.com/ns/ical/}refreshrate']);
  43. $updateTime = $this->time->getDateTime();
  44. $updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval);
  45. if($updateTime->getTimestamp() > $this->time->getTime()) {
  46. return;
  47. }
  48. }
  49. $webcalData = $this->connection->queryWebcalFeed($subscription);
  50. if (!$webcalData) {
  51. return;
  52. }
  53. $localData = $this->calDavBackend->getLimitedCalendarObjects((int) $subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  54. $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
  55. $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
  56. $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
  57. try {
  58. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  59. while ($vObject = $splitter->getNext()) {
  60. /** @var Component $vObject */
  61. $compName = null;
  62. $uid = null;
  63. foreach ($vObject->getComponents() as $component) {
  64. if ($component->name === 'VTIMEZONE') {
  65. continue;
  66. }
  67. $compName = $component->name;
  68. if ($stripAlarms) {
  69. unset($component->{'VALARM'});
  70. }
  71. if ($stripAttachments) {
  72. unset($component->{'ATTACH'});
  73. }
  74. $uid = $component->{ 'UID' }->getValue();
  75. }
  76. if ($stripTodos && $compName === 'VTODO') {
  77. continue;
  78. }
  79. if (!isset($uid)) {
  80. continue;
  81. }
  82. try {
  83. $denormalized = $this->calDavBackend->getDenormalizedData($vObject->serialize());
  84. } catch (InvalidDataException|Forbidden $ex) {
  85. $this->logger->warning('Unable to denormalize calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]);
  86. continue;
  87. }
  88. // Find all identical sets and remove them from the update
  89. if (isset($localData[$uid]) && $denormalized['etag'] === $localData[$uid]['etag']) {
  90. unset($localData[$uid]);
  91. continue;
  92. }
  93. $vObjectCopy = clone $vObject;
  94. $identical = isset($localData[$uid]) && $this->compareWithoutDtstamp($vObjectCopy, $localData[$uid]);
  95. if ($identical) {
  96. unset($localData[$uid]);
  97. continue;
  98. }
  99. // Find all modified sets and update them
  100. if (isset($localData[$uid]) && $denormalized['etag'] !== $localData[$uid]['etag']) {
  101. $this->calDavBackend->updateCalendarObject($subscription['id'], $localData[$uid]['uri'], $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  102. unset($localData[$uid]);
  103. continue;
  104. }
  105. // Only entirely new events get created here
  106. try {
  107. $objectUri = $this->getRandomCalendarObjectUri();
  108. $this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  109. } catch (NoInstancesException | BadRequest $ex) {
  110. $this->logger->warning('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]);
  111. }
  112. }
  113. $ids = array_map(static function ($dataSet): int {
  114. return (int) $dataSet['id'];
  115. }, $localData);
  116. $uris = array_map(static function ($dataSet): string {
  117. return $dataSet['uri'];
  118. }, $localData);
  119. if(!empty($ids) && !empty($uris)) {
  120. // Clean up on aisle 5
  121. // The only events left over in the $localData array should be those that don't exist upstream
  122. // All deleted VObjects from upstream are removed
  123. $this->calDavBackend->purgeCachedEventsForSubscription($subscription['id'], $ids, $uris);
  124. }
  125. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  126. if ($newRefreshRate) {
  127. $mutations[self::REFRESH_RATE] = $newRefreshRate;
  128. }
  129. $this->updateSubscription($subscription, $mutations);
  130. } catch (ParseException $ex) {
  131. $this->logger->error("Subscription {subscriptionId} could not be refreshed due to a parsing error", ['exception' => $ex, 'subscriptionId' => $subscription['id']]);
  132. }
  133. }
  134. /**
  135. * loads subscription from backend
  136. */
  137. public function getSubscription(string $principalUri, string $uri): ?array {
  138. $subscriptions = array_values(array_filter(
  139. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  140. function ($sub) use ($uri) {
  141. return $sub['uri'] === $uri;
  142. }
  143. ));
  144. if (count($subscriptions) === 0) {
  145. return null;
  146. }
  147. return $subscriptions[0];
  148. }
  149. /**
  150. * check if:
  151. * - current subscription stores a refreshrate
  152. * - the webcal feed suggests a refreshrate
  153. * - return suggested refreshrate if user didn't set a custom one
  154. *
  155. */
  156. private function checkWebcalDataForRefreshRate(array $subscription, string $webcalData): ?string {
  157. // if there is no refreshrate stored in the database, check the webcal feed
  158. // whether it suggests any refresh rate and store that in the database
  159. if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
  160. return null;
  161. }
  162. /** @var Component\VCalendar $vCalendar */
  163. $vCalendar = Reader::read($webcalData);
  164. $newRefreshRate = null;
  165. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  166. $newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  167. }
  168. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  169. $newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  170. }
  171. if (!$newRefreshRate) {
  172. return null;
  173. }
  174. // check if new refresh rate is even valid
  175. try {
  176. DateTimeParser::parseDuration($newRefreshRate);
  177. } catch (InvalidDataException $ex) {
  178. return null;
  179. }
  180. return $newRefreshRate;
  181. }
  182. /**
  183. * update subscription stored in database
  184. * used to set:
  185. * - refreshrate
  186. * - source
  187. *
  188. * @param array $subscription
  189. * @param array $mutations
  190. */
  191. private function updateSubscription(array $subscription, array $mutations) {
  192. if (empty($mutations)) {
  193. return;
  194. }
  195. $propPatch = new PropPatch($mutations);
  196. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  197. $propPatch->commit();
  198. }
  199. /**
  200. * Returns a random uri for a calendar-object
  201. *
  202. * @return string
  203. */
  204. public function getRandomCalendarObjectUri():string {
  205. return UUIDUtil::getUUID() . '.ics';
  206. }
  207. private function compareWithoutDtstamp(Component $vObject, array $calendarObject): bool {
  208. foreach ($vObject->getComponents() as $component) {
  209. unset($component->{'DTSTAMP'});
  210. }
  211. $localVobject = Reader::read($calendarObject['calendardata']);
  212. foreach ($localVobject->getComponents() as $component) {
  213. unset($component->{'DTSTAMP'});
  214. }
  215. return strcasecmp($localVobject->serialize(), $vObject->serialize()) === 0;
  216. }
  217. }