diff options
author | Anna Larch <anna@nextcloud.com> | 2024-07-24 16:11:47 +0200 |
---|---|---|
committer | Anna Larch <anna@nextcloud.com> | 2024-08-13 13:05:58 +0200 |
commit | fb94db1cd927569b3de7e9fa3565094aab2deb76 (patch) | |
tree | f1fbd38f462c1399015f2713bc21f7afc687686e /apps/dav/lib | |
parent | cee227ae993f02cf0c72ebcb103db4223b1b07a8 (diff) | |
download | nextcloud-server-fb94db1cd927569b3de7e9fa3565094aab2deb76.tar.gz nextcloud-server-fb94db1cd927569b3de7e9fa3565094aab2deb76.zip |
feat(webcal): only update modified and deleted events from webcal calendars
Signed-off-by: Anna Larch <anna@nextcloud.com>
Diffstat (limited to 'apps/dav/lib')
-rw-r--r-- | apps/dav/lib/CalDAV/CalDavBackend.php | 76 | ||||
-rw-r--r-- | apps/dav/lib/CalDAV/WebcalCaching/Connection.php | 170 | ||||
-rw-r--r-- | apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php | 249 |
3 files changed, 323 insertions, 172 deletions
diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 8fff6902f9a..0d12b8efead 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -946,6 +946,43 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription } /** + * Returns all calendar objects with limited metadata for a calendar + * + * Every item contains an array with the following keys: + * * id - the table row id + * * etag - An arbitrary string + * * uri - a unique key which will be used to construct the uri. This can + * be any arbitrary string. + * * calendardata - The iCalendar-compatible calendar data + * + * @param mixed $calendarId + * @param int $calendarType + * @return array + */ + public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array { + $query = $this->db->getQueryBuilder(); + $query->select(['id','uid', 'etag', 'uri', 'calendardata']) + ->from('calendarobjects') + ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId))) + ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType))) + ->andWhere($query->expr()->isNull('deleted_at')); + $stmt = $query->executeQuery(); + + $result = []; + while (($row = $stmt->fetch()) !== false) { + $result[$row['uid']] = [ + 'id' => $row['id'], + 'etag' => $row['etag'], + 'uri' => $row['uri'], + 'calendardata' => $row['calendardata'], + ]; + } + $stmt->closeCursor(); + + return $result; + } + + /** * Delete all of an user's shares * * @param string $principaluri @@ -3265,6 +3302,45 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription } /** + * @param int $subscriptionId + * @param array<int> $calendarObjectIds + * @param array<string> $calendarObjectUris + */ + public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void { + if(empty($calendarObjectUris)) { + return; + } + + $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris) { + foreach (array_chunk($calendarObjectIds, 1000) as $chunk) { + $query = $this->db->getQueryBuilder(); + $query->delete($this->dbObjectPropertiesTable) + ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId))) + ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION))) + ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY)) + ->executeStatement(); + + $query = $this->db->getQueryBuilder(); + $query->delete('calendarobjects') + ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId))) + ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION))) + ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY)) + ->executeStatement(); + } + + foreach (array_chunk($calendarObjectUris, 1000) as $chunk) { + $query = $this->db->getQueryBuilder(); + $query->delete('calendarchanges') + ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId))) + ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION))) + ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY)) + ->executeStatement(); + } + $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION); + }, $this->db); + } + + /** * Move a calendar from one user to another * * @param string $uriName diff --git a/apps/dav/lib/CalDAV/WebcalCaching/Connection.php b/apps/dav/lib/CalDAV/WebcalCaching/Connection.php new file mode 100644 index 00000000000..9d626f2db6d --- /dev/null +++ b/apps/dav/lib/CalDAV/WebcalCaching/Connection.php @@ -0,0 +1,170 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\DAV\CalDAV\WebcalCaching; + +use Exception; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Middleware; +use OCP\Http\Client\IClientService; +use OCP\Http\Client\LocalServerException; +use OCP\IAppConfig; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use Psr\Log\LoggerInterface; +use Sabre\DAV\Xml\Property\Href; +use Sabre\VObject\Reader; + +class Connection { + public function __construct(private IClientService $clientService, + private IAppConfig $config, + private LoggerInterface $logger) { + } + + /** + * gets webcal feed from remote server + */ + public function queryWebcalFeed(array $subscription, array &$mutations): ?string { + $client = $this->clientService->newClient(); + + $didBreak301Chain = false; + $latestLocation = null; + + $handlerStack = HandlerStack::create(); + $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) { + return $request + ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml') + ->withHeader('User-Agent', 'Nextcloud Webcal Service'); + })); + $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) { + if (!$didBreak301Chain) { + if ($response->getStatusCode() !== 301) { + $didBreak301Chain = true; + } else { + $latestLocation = $response->getHeader('Location'); + } + } + return $response; + })); + + $allowLocalAccess = $this->config->getValueString('dav', 'webcalAllowLocalAccess', 'no'); + $subscriptionId = $subscription['id']; + $url = $this->cleanURL($subscription['source']); + if ($url === null) { + return null; + } + + try { + $params = [ + 'allow_redirects' => [ + 'redirects' => 10 + ], + 'handler' => $handlerStack, + 'nextcloud' => [ + 'allow_local_address' => $allowLocalAccess === 'yes', + ] + ]; + + $user = parse_url($subscription['source'], PHP_URL_USER); + $pass = parse_url($subscription['source'], PHP_URL_PASS); + if ($user !== null && $pass !== null) { + $params['auth'] = [$user, $pass]; + } + + $response = $client->get($url, $params); + $body = $response->getBody(); + + if ($latestLocation !== null) { + $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation); + } + + $contentType = $response->getHeader('Content-Type'); + $contentType = explode(';', $contentType, 2)[0]; + switch ($contentType) { + case 'application/calendar+json': + try { + $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING); + } catch (Exception $ex) { + // In case of a parsing error return null + $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); + return null; + } + return $jCalendar->serialize(); + + case 'application/calendar+xml': + try { + $xCalendar = Reader::readXML($body); + } catch (Exception $ex) { + // In case of a parsing error return null + $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); + return null; + } + return $xCalendar->serialize(); + + case 'text/calendar': + default: + try { + $vCalendar = Reader::read($body); + } catch (Exception $ex) { + // In case of a parsing error return null + $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); + return null; + } + return $vCalendar->serialize(); + } + } catch (LocalServerException $ex) { + $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [ + 'exception' => $ex, + ]); + + return null; + } catch (Exception $ex) { + $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [ + 'exception' => $ex, + ]); + + return null; + } + } + + /** + * This method will strip authentication information and replace the + * 'webcal' or 'webcals' protocol scheme + * + * @param string $url + * @return string|null + */ + private function cleanURL(string $url): ?string { + $parsed = parse_url($url); + if ($parsed === false) { + return null; + } + + if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + $scheme = 'http'; + } else { + $scheme = 'https'; + } + + $host = $parsed['host'] ?? ''; + $port = isset($parsed['port']) ? ':' . $parsed['port'] : ''; + $path = $parsed['path'] ?? ''; + $query = isset($parsed['query']) ? '?' . $parsed['query'] : ''; + $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : ''; + + $cleanURL = "$scheme://$host$port$path$query$fragment"; + // parse_url is giving some weird results if no url and no :// is given, + // so let's test the url again + $parsedClean = parse_url($cleanURL); + if ($parsedClean === false || !isset($parsedClean['host'])) { + return null; + } + + return $cleanURL; + } +} diff --git a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php index 209365ea5e4..102571c8ef9 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php @@ -8,19 +8,11 @@ declare(strict_types=1); */ namespace OCA\DAV\CalDAV\WebcalCaching; -use Exception; -use GuzzleHttp\HandlerStack; -use GuzzleHttp\Middleware; use OCA\DAV\CalDAV\CalDavBackend; -use OCP\Http\Client\IClientService; -use OCP\Http\Client\LocalServerException; -use OCP\IConfig; -use Psr\Http\Message\RequestInterface; -use Psr\Http\Message\ResponseInterface; +use OCP\AppFramework\Utility\ITimeFactory; use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\PropPatch; -use Sabre\DAV\Xml\Property\Href; use Sabre\VObject\Component; use Sabre\VObject\DateTimeParser; use Sabre\VObject\InvalidDataException; @@ -33,25 +25,15 @@ use function count; class RefreshWebcalService { - private CalDavBackend $calDavBackend; - - private IClientService $clientService; - - private IConfig $config; - - /** @var LoggerInterface */ - private LoggerInterface $logger; - public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate'; public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms'; public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments'; public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos'; - public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, LoggerInterface $logger) { - $this->calDavBackend = $calDavBackend; - $this->clientService = $clientService; - $this->config = $config; - $this->logger = $logger; + public function __construct(private CalDavBackend $calDavBackend, + private LoggerInterface $logger, + private Connection $connection, + private ITimeFactory $time) { } public function refreshSubscription(string $principalUri, string $uri) { @@ -61,11 +43,25 @@ class RefreshWebcalService { return; } - $webcalData = $this->queryWebcalFeed($subscription, $mutations); + // Check the refresh rate if there is any + if(!empty($subscription['{http://apple.com/ns/ical/}refreshrate'])) { + // add the refresh interval to the lastmodified timestamp + $refreshInterval = new \DateInterval($subscription['{http://apple.com/ns/ical/}refreshrate']); + $updateTime = $this->time->getDateTime(); + $updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval); + if($updateTime->getTimestamp() > $this->time->getTime()) { + return; + } + } + + + $webcalData = $this->connection->queryWebcalFeed($subscription, $mutations); if (!$webcalData) { return; } + $localData = $this->calDavBackend->getLimitedCalendarObjects((int) $subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); + $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1; $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1; $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1; @@ -73,14 +69,10 @@ class RefreshWebcalService { try { $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING); - // we wait with deleting all outdated events till we parsed the new ones - // in case the new calendar is broken and `new ICalendar` throws a ParseException - // the user will still see the old data - $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']); - while ($vObject = $splitter->getNext()) { /** @var Component $vObject */ $compName = null; + $uid = null; foreach ($vObject->getComponents() as $component) { if ($component->name === 'VTIMEZONE') { @@ -95,21 +87,62 @@ class RefreshWebcalService { if ($stripAttachments) { unset($component->{'ATTACH'}); } + + $uid = $component->{ 'UID' }->getValue(); } if ($stripTodos && $compName === 'VTODO') { continue; } - $objectUri = $this->getRandomCalendarObjectUri(); - $calendarData = $vObject->serialize(); + if (!isset($uid)) { + continue; + } + + $denormalized = $this->calDavBackend->getDenormalizedData($vObject->serialize()); + // Find all identical sets and remove them from the update + if (isset($localData[$uid]) && $denormalized['etag'] === $localData[$uid]['etag']) { + unset($localData[$uid]); + continue; + } + + $vObjectCopy = clone $vObject; + $identical = isset($localData[$uid]) && $this->compareWithoutDtstamp($vObjectCopy, $localData[$uid]); + if ($identical) { + unset($localData[$uid]); + continue; + } + + // Find all modified sets and update them + if (isset($localData[$uid]) && $denormalized['etag'] !== $localData[$uid]['etag']) { + $this->calDavBackend->updateCalendarObject($subscription['id'], $localData[$uid]['uri'], $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); + unset($localData[$uid]); + continue; + } + + // Only entirely new events get created here try { - $this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); + $objectUri = $this->getRandomCalendarObjectUri(); + $this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); } catch (NoInstancesException | BadRequest $ex) { $this->logger->error('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]); } } + $ids = array_map(static function ($dataSet): int { + return (int) $dataSet['id']; + }, $localData); + $uris = array_map(static function ($dataSet): string { + return $dataSet['uri']; + }, $localData); + + if(!empty($ids) && !empty($uris)) { + // Clean up on aisle 5 + // The only events left over in the $localData array should be those that don't exist upstream + // All deleted VObjects from upstream are removed + $this->calDavBackend->purgeCachedEventsForSubscription($subscription['id'], $ids, $uris); + } + $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData); if ($newRefreshRate) { $mutations[self::REFRESH_RATE] = $newRefreshRate; @@ -139,111 +172,6 @@ class RefreshWebcalService { return $subscriptions[0]; } - /** - * gets webcal feed from remote server - */ - private function queryWebcalFeed(array $subscription, array &$mutations): ?string { - $client = $this->clientService->newClient(); - - $didBreak301Chain = false; - $latestLocation = null; - - $handlerStack = HandlerStack::create(); - $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) { - return $request - ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml') - ->withHeader('User-Agent', 'Nextcloud Webcal Service'); - })); - $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) { - if (!$didBreak301Chain) { - if ($response->getStatusCode() !== 301) { - $didBreak301Chain = true; - } else { - $latestLocation = $response->getHeader('Location'); - } - } - return $response; - })); - - $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no'); - $subscriptionId = $subscription['id']; - $url = $this->cleanURL($subscription['source']); - if ($url === null) { - return null; - } - - try { - $params = [ - 'allow_redirects' => [ - 'redirects' => 10 - ], - 'handler' => $handlerStack, - 'nextcloud' => [ - 'allow_local_address' => $allowLocalAccess === 'yes', - ] - ]; - - $user = parse_url($subscription['source'], PHP_URL_USER); - $pass = parse_url($subscription['source'], PHP_URL_PASS); - if ($user !== null && $pass !== null) { - $params['auth'] = [$user, $pass]; - } - - $response = $client->get($url, $params); - $body = $response->getBody(); - - if ($latestLocation) { - $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation); - } - - $contentType = $response->getHeader('Content-Type'); - $contentType = explode(';', $contentType, 2)[0]; - switch ($contentType) { - case 'application/calendar+json': - try { - $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING); - } catch (Exception $ex) { - // In case of a parsing error return null - $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); - return null; - } - return $jCalendar->serialize(); - - case 'application/calendar+xml': - try { - $xCalendar = Reader::readXML($body); - } catch (Exception $ex) { - // In case of a parsing error return null - $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); - return null; - } - return $xCalendar->serialize(); - - case 'text/calendar': - default: - try { - $vCalendar = Reader::read($body); - } catch (Exception $ex) { - // In case of a parsing error return null - $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]); - return null; - } - return $vCalendar->serialize(); - } - } catch (LocalServerException $ex) { - $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [ - 'exception' => $ex, - ]); - - return null; - } catch (Exception $ex) { - $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [ - 'exception' => $ex, - ]); - - return null; - } - } /** * check if: @@ -304,47 +232,24 @@ class RefreshWebcalService { } /** - * This method will strip authentication information and replace the - * 'webcal' or 'webcals' protocol scheme + * Returns a random uri for a calendar-object * - * @param string $url - * @return string|null + * @return string */ - private function cleanURL(string $url): ?string { - $parsed = parse_url($url); - if ($parsed === false) { - return null; - } + public function getRandomCalendarObjectUri():string { + return UUIDUtil::getUUID() . '.ics'; + } - if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') { - $scheme = 'http'; - } else { - $scheme = 'https'; + private function compareWithoutDtstamp(Component $vObject, array $calendarObject): bool { + foreach ($vObject->getComponents() as $component) { + unset($component->{'DTSTAMP'}); } - $host = $parsed['host'] ?? ''; - $port = isset($parsed['port']) ? ':' . $parsed['port'] : ''; - $path = $parsed['path'] ?? ''; - $query = isset($parsed['query']) ? '?' . $parsed['query'] : ''; - $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : ''; - - $cleanURL = "$scheme://$host$port$path$query$fragment"; - // parse_url is giving some weird results if no url and no :// is given, - // so let's test the url again - $parsedClean = parse_url($cleanURL); - if ($parsedClean === false || !isset($parsedClean['host'])) { - return null; + $localVobject = Reader::read($calendarObject['calendardata']); + foreach ($localVobject->getComponents() as $component) { + unset($component->{'DTSTAMP'}); } - return $cleanURL; - } - - /** - * Returns a random uri for a calendar-object - * - * @return string - */ - public function getRandomCalendarObjectUri():string { - return UUIDUtil::getUUID() . '.ics'; + return strcasecmp($localVobject->serialize(), $vObject->serialize()) === 0; } } |