RefreshWebcalService.php 11 KB

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