RefreshWebcalService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020, Thomas Citharel <nextcloud@tcit.fr>
  5. * @copyright Copyright (c) 2020, leith abdulla (<online-nextcloud@eleith.com>)
  6. *
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author eleith <online+github@eleith.com>
  9. * @author Georg Ehrke <oc.list@georgehrke.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Thomas Citharel <nextcloud@tcit.fr>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OCA\DAV\CalDAV\WebcalCaching;
  30. use Exception;
  31. use GuzzleHttp\HandlerStack;
  32. use GuzzleHttp\Middleware;
  33. use OCA\DAV\CalDAV\CalDavBackend;
  34. use OCP\Http\Client\IClientService;
  35. use OCP\Http\Client\LocalServerException;
  36. use OCP\IConfig;
  37. use Psr\Http\Message\RequestInterface;
  38. use Psr\Http\Message\ResponseInterface;
  39. use Psr\Log\LoggerInterface;
  40. use Sabre\DAV\Exception\BadRequest;
  41. use Sabre\DAV\PropPatch;
  42. use Sabre\DAV\Xml\Property\Href;
  43. use Sabre\VObject\Component;
  44. use Sabre\VObject\DateTimeParser;
  45. use Sabre\VObject\InvalidDataException;
  46. use Sabre\VObject\Recur\NoInstancesException;
  47. use Sabre\VObject\ParseException;
  48. use Sabre\VObject\Reader;
  49. use Sabre\VObject\Splitter\ICalendar;
  50. use Sabre\VObject\UUIDUtil;
  51. use function count;
  52. class RefreshWebcalService {
  53. private CalDavBackend $calDavBackend;
  54. private IClientService $clientService;
  55. private IConfig $config;
  56. /** @var LoggerInterface */
  57. private LoggerInterface $logger;
  58. public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
  59. public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
  60. public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
  61. public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
  62. public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, LoggerInterface $logger) {
  63. $this->calDavBackend = $calDavBackend;
  64. $this->clientService = $clientService;
  65. $this->config = $config;
  66. $this->logger = $logger;
  67. }
  68. public function refreshSubscription(string $principalUri, string $uri) {
  69. $subscription = $this->getSubscription($principalUri, $uri);
  70. $mutations = [];
  71. if (!$subscription) {
  72. return;
  73. }
  74. $webcalData = $this->queryWebcalFeed($subscription, $mutations);
  75. if (!$webcalData) {
  76. return;
  77. }
  78. $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
  79. $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
  80. $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
  81. try {
  82. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  83. // we wait with deleting all outdated events till we parsed the new ones
  84. // in case the new calendar is broken and `new ICalendar` throws a ParseException
  85. // the user will still see the old data
  86. $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
  87. while ($vObject = $splitter->getNext()) {
  88. /** @var Component $vObject */
  89. $compName = null;
  90. foreach ($vObject->getComponents() as $component) {
  91. if ($component->name === 'VTIMEZONE') {
  92. continue;
  93. }
  94. $compName = $component->name;
  95. if ($stripAlarms) {
  96. unset($component->{'VALARM'});
  97. }
  98. if ($stripAttachments) {
  99. unset($component->{'ATTACH'});
  100. }
  101. }
  102. if ($stripTodos && $compName === 'VTODO') {
  103. continue;
  104. }
  105. $objectUri = $this->getRandomCalendarObjectUri();
  106. $calendarData = $vObject->serialize();
  107. try {
  108. $this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  109. } catch (NoInstancesException | BadRequest $ex) {
  110. $this->logger->error('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]);
  111. }
  112. }
  113. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  114. if ($newRefreshRate) {
  115. $mutations[self::REFRESH_RATE] = $newRefreshRate;
  116. }
  117. $this->updateSubscription($subscription, $mutations);
  118. } catch (ParseException $ex) {
  119. $this->logger->error("Subscription {subscriptionId} could not be refreshed due to a parsing error", ['exception' => $ex, 'subscriptionId' => $subscription['id']]);
  120. }
  121. }
  122. /**
  123. * loads subscription from backend
  124. */
  125. public function getSubscription(string $principalUri, string $uri): ?array {
  126. $subscriptions = array_values(array_filter(
  127. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  128. function ($sub) use ($uri) {
  129. return $sub['uri'] === $uri;
  130. }
  131. ));
  132. if (count($subscriptions) === 0) {
  133. return null;
  134. }
  135. return $subscriptions[0];
  136. }
  137. /**
  138. * gets webcal feed from remote server
  139. */
  140. private function queryWebcalFeed(array $subscription, array &$mutations): ?string {
  141. $client = $this->clientService->newClient();
  142. $didBreak301Chain = false;
  143. $latestLocation = null;
  144. $handlerStack = HandlerStack::create();
  145. $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
  146. return $request
  147. ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
  148. ->withHeader('User-Agent', 'Nextcloud Webcal Service');
  149. }));
  150. $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
  151. if (!$didBreak301Chain) {
  152. if ($response->getStatusCode() !== 301) {
  153. $didBreak301Chain = true;
  154. } else {
  155. $latestLocation = $response->getHeader('Location');
  156. }
  157. }
  158. return $response;
  159. }));
  160. $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
  161. $subscriptionId = $subscription['id'];
  162. $url = $this->cleanURL($subscription['source']);
  163. if ($url === null) {
  164. return null;
  165. }
  166. try {
  167. $params = [
  168. 'allow_redirects' => [
  169. 'redirects' => 10
  170. ],
  171. 'handler' => $handlerStack,
  172. 'nextcloud' => [
  173. 'allow_local_address' => $allowLocalAccess === 'yes',
  174. ]
  175. ];
  176. $user = parse_url($subscription['source'], PHP_URL_USER);
  177. $pass = parse_url($subscription['source'], PHP_URL_PASS);
  178. if ($user !== null && $pass !== null) {
  179. $params['auth'] = [$user, $pass];
  180. }
  181. $response = $client->get($url, $params);
  182. $body = $response->getBody();
  183. if ($latestLocation) {
  184. $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
  185. }
  186. $contentType = $response->getHeader('Content-Type');
  187. $contentType = explode(';', $contentType, 2)[0];
  188. switch ($contentType) {
  189. case 'application/calendar+json':
  190. try {
  191. $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
  192. } catch (Exception $ex) {
  193. // In case of a parsing error return null
  194. $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
  195. return null;
  196. }
  197. return $jCalendar->serialize();
  198. case 'application/calendar+xml':
  199. try {
  200. $xCalendar = Reader::readXML($body);
  201. } catch (Exception $ex) {
  202. // In case of a parsing error return null
  203. $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
  204. return null;
  205. }
  206. return $xCalendar->serialize();
  207. case 'text/calendar':
  208. default:
  209. try {
  210. $vCalendar = Reader::read($body);
  211. } catch (Exception $ex) {
  212. // In case of a parsing error return null
  213. $this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
  214. return null;
  215. }
  216. return $vCalendar->serialize();
  217. }
  218. } catch (LocalServerException $ex) {
  219. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [
  220. 'exception' => $ex,
  221. ]);
  222. return null;
  223. } catch (Exception $ex) {
  224. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [
  225. 'exception' => $ex,
  226. ]);
  227. return null;
  228. }
  229. }
  230. /**
  231. * check if:
  232. * - current subscription stores a refreshrate
  233. * - the webcal feed suggests a refreshrate
  234. * - return suggested refreshrate if user didn't set a custom one
  235. *
  236. */
  237. private function checkWebcalDataForRefreshRate(array $subscription, string $webcalData): ?string {
  238. // if there is no refreshrate stored in the database, check the webcal feed
  239. // whether it suggests any refresh rate and store that in the database
  240. if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
  241. return null;
  242. }
  243. /** @var Component\VCalendar $vCalendar */
  244. $vCalendar = Reader::read($webcalData);
  245. $newRefreshRate = null;
  246. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  247. $newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  248. }
  249. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  250. $newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  251. }
  252. if (!$newRefreshRate) {
  253. return null;
  254. }
  255. // check if new refresh rate is even valid
  256. try {
  257. DateTimeParser::parseDuration($newRefreshRate);
  258. } catch (InvalidDataException $ex) {
  259. return null;
  260. }
  261. return $newRefreshRate;
  262. }
  263. /**
  264. * update subscription stored in database
  265. * used to set:
  266. * - refreshrate
  267. * - source
  268. *
  269. * @param array $subscription
  270. * @param array $mutations
  271. */
  272. private function updateSubscription(array $subscription, array $mutations) {
  273. if (empty($mutations)) {
  274. return;
  275. }
  276. $propPatch = new PropPatch($mutations);
  277. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  278. $propPatch->commit();
  279. }
  280. /**
  281. * This method will strip authentication information and replace the
  282. * 'webcal' or 'webcals' protocol scheme
  283. *
  284. * @param string $url
  285. * @return string|null
  286. */
  287. private function cleanURL(string $url): ?string {
  288. $parsed = parse_url($url);
  289. if ($parsed === false) {
  290. return null;
  291. }
  292. if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  293. $scheme = 'http';
  294. } else {
  295. $scheme = 'https';
  296. }
  297. $host = $parsed['host'] ?? '';
  298. $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
  299. $path = $parsed['path'] ?? '';
  300. $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
  301. $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
  302. $cleanURL = "$scheme://$host$port$path$query$fragment";
  303. // parse_url is giving some weird results if no url and no :// is given,
  304. // so let's test the url again
  305. $parsedClean = parse_url($cleanURL);
  306. if ($parsedClean === false || !isset($parsedClean['host'])) {
  307. return null;
  308. }
  309. return $cleanURL;
  310. }
  311. /**
  312. * Returns a random uri for a calendar-object
  313. *
  314. * @return string
  315. */
  316. public function getRandomCalendarObjectUri():string {
  317. return UUIDUtil::getUUID() . '.ics';
  318. }
  319. }