SyncService.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\CardDAV;
  8. use OCP\AppFramework\Db\TTransactional;
  9. use OCP\AppFramework\Http;
  10. use OCP\Http\Client\IClientService;
  11. use OCP\IDBConnection;
  12. use OCP\IUser;
  13. use OCP\IUserManager;
  14. use Psr\Http\Client\ClientExceptionInterface;
  15. use Psr\Log\LoggerInterface;
  16. use Sabre\DAV\Xml\Response\MultiStatus;
  17. use Sabre\DAV\Xml\Service;
  18. use Sabre\VObject\Reader;
  19. use function is_null;
  20. class SyncService {
  21. use TTransactional;
  22. private CardDavBackend $backend;
  23. private IUserManager $userManager;
  24. private IDBConnection $dbConnection;
  25. private LoggerInterface $logger;
  26. private ?array $localSystemAddressBook = null;
  27. private Converter $converter;
  28. protected string $certPath;
  29. private IClientService $clientService;
  30. public function __construct(CardDavBackend $backend,
  31. IUserManager $userManager,
  32. IDBConnection $dbConnection,
  33. LoggerInterface $logger,
  34. Converter $converter,
  35. IClientService $clientService) {
  36. $this->backend = $backend;
  37. $this->userManager = $userManager;
  38. $this->logger = $logger;
  39. $this->converter = $converter;
  40. $this->certPath = '';
  41. $this->dbConnection = $dbConnection;
  42. $this->clientService = $clientService;
  43. }
  44. /**
  45. * @throws \Exception
  46. */
  47. public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {
  48. // 1. create addressbook
  49. $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);
  50. $addressBookId = $book['id'];
  51. // 2. query changes
  52. try {
  53. $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
  54. } catch (ClientExceptionInterface $ex) {
  55. if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
  56. // remote server revoked access to the address book, remove it
  57. $this->backend->deleteAddressBook($addressBookId);
  58. $this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
  59. throw $ex;
  60. }
  61. $this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
  62. throw $ex;
  63. }
  64. // 3. apply changes
  65. // TODO: use multi-get for download
  66. foreach ($response['response'] as $resource => $status) {
  67. $cardUri = basename($resource);
  68. if (isset($status[200])) {
  69. $vCard = $this->download($url, $userName, $sharedSecret, $resource);
  70. $this->atomic(function () use ($addressBookId, $cardUri, $vCard): void {
  71. $existingCard = $this->backend->getCard($addressBookId, $cardUri);
  72. if ($existingCard === false) {
  73. $this->backend->createCard($addressBookId, $cardUri, $vCard);
  74. } else {
  75. $this->backend->updateCard($addressBookId, $cardUri, $vCard);
  76. }
  77. }, $this->dbConnection);
  78. } else {
  79. $this->backend->deleteCard($addressBookId, $cardUri);
  80. }
  81. }
  82. return $response['token'];
  83. }
  84. /**
  85. * @throws \Sabre\DAV\Exception\BadRequest
  86. */
  87. public function ensureSystemAddressBookExists(string $principal, string $uri, array $properties): ?array {
  88. return $this->atomic(function () use ($principal, $uri, $properties) {
  89. $book = $this->backend->getAddressBooksByUri($principal, $uri);
  90. if (!is_null($book)) {
  91. return $book;
  92. }
  93. $this->backend->createAddressBook($principal, $uri, $properties);
  94. return $this->backend->getAddressBooksByUri($principal, $uri);
  95. }, $this->dbConnection);
  96. }
  97. /**
  98. * @throws ClientExceptionInterface
  99. */
  100. protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken): array {
  101. $client = $this->clientService->newClient();
  102. // the trailing slash is important for merging base_uri and uri
  103. $url = rtrim($url, '/') . '/';
  104. $options = [
  105. 'auth' => [$userName, $sharedSecret],
  106. 'base_uri' => $url,
  107. 'body' => $this->buildSyncCollectionRequestBody($syncToken),
  108. 'headers' => ['Content-Type' => 'application/xml']
  109. ];
  110. $response = $client->request(
  111. 'REPORT',
  112. $addressBookUrl,
  113. $options
  114. );
  115. $body = $response->getBody();
  116. assert(is_string($body));
  117. return $this->parseMultiStatus($body);
  118. }
  119. protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): string {
  120. $client = $this->clientService->newClient();
  121. // the trailing slash is important for merging base_uri and uri
  122. $url = rtrim($url, '/') . '/';
  123. $options = [
  124. 'auth' => [$userName, $sharedSecret],
  125. 'base_uri' => $url,
  126. ];
  127. $response = $client->get(
  128. $resourcePath,
  129. $options
  130. );
  131. return (string)$response->getBody();
  132. }
  133. private function buildSyncCollectionRequestBody(?string $syncToken): string {
  134. $dom = new \DOMDocument('1.0', 'UTF-8');
  135. $dom->formatOutput = true;
  136. $root = $dom->createElementNS('DAV:', 'd:sync-collection');
  137. $sync = $dom->createElement('d:sync-token', $syncToken ?? '');
  138. $prop = $dom->createElement('d:prop');
  139. $cont = $dom->createElement('d:getcontenttype');
  140. $etag = $dom->createElement('d:getetag');
  141. $prop->appendChild($cont);
  142. $prop->appendChild($etag);
  143. $root->appendChild($sync);
  144. $root->appendChild($prop);
  145. $dom->appendChild($root);
  146. return $dom->saveXML();
  147. }
  148. /**
  149. * @param string $body
  150. * @return array
  151. * @throws \Sabre\Xml\ParseException
  152. */
  153. private function parseMultiStatus($body) {
  154. $xml = new Service();
  155. /** @var MultiStatus $multiStatus */
  156. $multiStatus = $xml->expect('{DAV:}multistatus', $body);
  157. $result = [];
  158. foreach ($multiStatus->getResponses() as $response) {
  159. $result[$response->getHref()] = $response->getResponseProperties();
  160. }
  161. return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
  162. }
  163. /**
  164. * @param IUser $user
  165. */
  166. public function updateUser(IUser $user): void {
  167. $systemAddressBook = $this->getLocalSystemAddressBook();
  168. $addressBookId = $systemAddressBook['id'];
  169. $cardId = self::getCardUri($user);
  170. if ($user->isEnabled()) {
  171. $this->atomic(function () use ($addressBookId, $cardId, $user): void {
  172. $card = $this->backend->getCard($addressBookId, $cardId);
  173. if ($card === false) {
  174. $vCard = $this->converter->createCardFromUser($user);
  175. if ($vCard !== null) {
  176. $this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
  177. }
  178. } else {
  179. $vCard = $this->converter->createCardFromUser($user);
  180. if (is_null($vCard)) {
  181. $this->backend->deleteCard($addressBookId, $cardId);
  182. } else {
  183. $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
  184. }
  185. }
  186. }, $this->dbConnection);
  187. } else {
  188. $this->backend->deleteCard($addressBookId, $cardId);
  189. }
  190. }
  191. /**
  192. * @param IUser|string $userOrCardId
  193. */
  194. public function deleteUser($userOrCardId) {
  195. $systemAddressBook = $this->getLocalSystemAddressBook();
  196. if ($userOrCardId instanceof IUser) {
  197. $userOrCardId = self::getCardUri($userOrCardId);
  198. }
  199. $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
  200. }
  201. /**
  202. * @return array|null
  203. */
  204. public function getLocalSystemAddressBook() {
  205. if (is_null($this->localSystemAddressBook)) {
  206. $systemPrincipal = 'principals/system/system';
  207. $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
  208. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
  209. ]);
  210. }
  211. return $this->localSystemAddressBook;
  212. }
  213. /**
  214. * @return void
  215. */
  216. public function syncInstance(?\Closure $progressCallback = null) {
  217. $systemAddressBook = $this->getLocalSystemAddressBook();
  218. $this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback): void {
  219. $this->updateUser($user);
  220. if (!is_null($progressCallback)) {
  221. $progressCallback();
  222. }
  223. });
  224. // remove no longer existing
  225. $allCards = $this->backend->getCards($systemAddressBook['id']);
  226. foreach ($allCards as $card) {
  227. $vCard = Reader::read($card['carddata']);
  228. $uid = $vCard->UID->getValue();
  229. // load backend and see if user exists
  230. if (!$this->userManager->userExists($uid)) {
  231. $this->deleteUser($card['uri']);
  232. }
  233. }
  234. }
  235. /**
  236. * @param IUser $user
  237. * @return string
  238. */
  239. public static function getCardUri(IUser $user): string {
  240. return $user->getBackendClassName() . ':' . $user->getUID() . '.vcf';
  241. }
  242. }