ContactsMigrator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\UserMigration;
  8. use OCA\DAV\AppInfo\Application;
  9. use OCA\DAV\CardDAV\CardDavBackend;
  10. use OCA\DAV\CardDAV\Plugin as CardDAVPlugin;
  11. use OCA\DAV\Connector\Sabre\CachingTree;
  12. use OCA\DAV\Connector\Sabre\Server as SabreDavServer;
  13. use OCA\DAV\RootCollection;
  14. use OCP\IL10N;
  15. use OCP\IUser;
  16. use OCP\UserMigration\IExportDestination;
  17. use OCP\UserMigration\IImportSource;
  18. use OCP\UserMigration\IMigrator;
  19. use OCP\UserMigration\ISizeEstimationMigrator;
  20. use OCP\UserMigration\TMigratorBasicVersionHandling;
  21. use Sabre\VObject\Component\VCard;
  22. use Sabre\VObject\Parser\Parser as VObjectParser;
  23. use Sabre\VObject\Reader as VObjectReader;
  24. use Sabre\VObject\Splitter\VCard as VCardSplitter;
  25. use Sabre\VObject\UUIDUtil;
  26. use Symfony\Component\Console\Output\NullOutput;
  27. use Symfony\Component\Console\Output\OutputInterface;
  28. use Throwable;
  29. use function sort;
  30. use function substr;
  31. class ContactsMigrator implements IMigrator, ISizeEstimationMigrator {
  32. use TMigratorBasicVersionHandling;
  33. private CardDavBackend $cardDavBackend;
  34. private IL10N $l10n;
  35. private SabreDavServer $sabreDavServer;
  36. private const USERS_URI_ROOT = 'principals/users/';
  37. private const FILENAME_EXT = 'vcf';
  38. private const METADATA_EXT = 'json';
  39. private const MIGRATED_URI_PREFIX = 'migrated-';
  40. private const PATH_ROOT = Application::APP_ID . '/address_books/';
  41. public function __construct(
  42. CardDavBackend $cardDavBackend,
  43. IL10N $l10n,
  44. ) {
  45. $this->cardDavBackend = $cardDavBackend;
  46. $this->l10n = $l10n;
  47. $root = new RootCollection();
  48. $this->sabreDavServer = new SabreDavServer(new CachingTree($root));
  49. $this->sabreDavServer->addPlugin(new CardDAVPlugin());
  50. }
  51. private function getPrincipalUri(IUser $user): string {
  52. return ContactsMigrator::USERS_URI_ROOT . $user->getUID();
  53. }
  54. /**
  55. * @return array{name: string, displayName: string, description: ?string, vCards: VCard[]}
  56. *
  57. * @throws InvalidAddressBookException
  58. */
  59. private function getAddressBookExportData(IUser $user, array $addressBookInfo, OutputInterface $output): array {
  60. $userId = $user->getUID();
  61. if (!isset($addressBookInfo['uri'])) {
  62. throw new InvalidAddressBookException();
  63. }
  64. $uri = $addressBookInfo['uri'];
  65. $path = CardDAVPlugin::ADDRESSBOOK_ROOT . "/users/$userId/$uri";
  66. /**
  67. * @see \Sabre\CardDAV\VCFExportPlugin::httpGet() implementation reference
  68. */
  69. $addressBookDataProp = '{' . CardDAVPlugin::NS_CARDDAV . '}address-data';
  70. $addressBookNode = $this->sabreDavServer->tree->getNodeForPath($path);
  71. $nodes = $this->sabreDavServer->getPropertiesIteratorForPath($path, [$addressBookDataProp], 1);
  72. /**
  73. * @see \Sabre\CardDAV\VCFExportPlugin::generateVCF() implementation reference
  74. */
  75. /** @var VCard[] $vCards */
  76. $vCards = [];
  77. foreach ($nodes as $node) {
  78. if (isset($node[200][$addressBookDataProp])) {
  79. $vCard = VObjectReader::read($node[200][$addressBookDataProp]);
  80. $problems = $vCard->validate();
  81. if (!empty($problems)) {
  82. $output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
  83. continue;
  84. }
  85. $vCards[] = $vCard;
  86. }
  87. }
  88. if (count($vCards) === 0) {
  89. throw new InvalidAddressBookException();
  90. }
  91. return [
  92. 'name' => $addressBookNode->getName(),
  93. 'displayName' => $addressBookInfo['{DAV:}displayname'],
  94. 'description' => $addressBookInfo['{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description'],
  95. 'vCards' => $vCards,
  96. ];
  97. }
  98. /**
  99. * @return array<int, array{name: string, displayName: string, description: ?string, vCards: VCard[]}>
  100. */
  101. private function getAddressBookExports(IUser $user, OutputInterface $output): array {
  102. $principalUri = $this->getPrincipalUri($user);
  103. return array_values(array_filter(array_map(
  104. function (array $addressBookInfo) use ($user, $output) {
  105. try {
  106. return $this->getAddressBookExportData($user, $addressBookInfo, $output);
  107. } catch (InvalidAddressBookException $e) {
  108. // Allow this exception as invalid address books are not to be exported
  109. return null;
  110. }
  111. },
  112. $this->cardDavBackend->getAddressBooksForUser($principalUri),
  113. )));
  114. }
  115. /**
  116. * @throws InvalidAddressBookException
  117. */
  118. private function getUniqueAddressBookUri(IUser $user, string $initialAddressBookUri): string {
  119. $principalUri = $this->getPrincipalUri($user);
  120. $initialAddressBookUri = substr($initialAddressBookUri, 0, strlen(ContactsMigrator::MIGRATED_URI_PREFIX)) === ContactsMigrator::MIGRATED_URI_PREFIX
  121. ? $initialAddressBookUri
  122. : ContactsMigrator::MIGRATED_URI_PREFIX . $initialAddressBookUri;
  123. if ($initialAddressBookUri === '') {
  124. throw new InvalidAddressBookException();
  125. }
  126. $existingAddressBookUris = array_map(
  127. fn (array $addressBookInfo): string => $addressBookInfo['uri'],
  128. $this->cardDavBackend->getAddressBooksForUser($principalUri),
  129. );
  130. $addressBookUri = $initialAddressBookUri;
  131. $acc = 1;
  132. while (in_array($addressBookUri, $existingAddressBookUris, true)) {
  133. $addressBookUri = $initialAddressBookUri . "-$acc";
  134. ++$acc;
  135. }
  136. return $addressBookUri;
  137. }
  138. /**
  139. * @param VCard[] $vCards
  140. */
  141. private function serializeCards(array $vCards): string {
  142. return array_reduce(
  143. $vCards,
  144. fn (string $addressBookBlob, VCard $vCard) => $addressBookBlob . $vCard->serialize(),
  145. '',
  146. );
  147. }
  148. /**
  149. * {@inheritDoc}
  150. */
  151. public function getEstimatedExportSize(IUser $user): int|float {
  152. $addressBookExports = $this->getAddressBookExports($user, new NullOutput());
  153. $addressBookCount = count($addressBookExports);
  154. // 50B for each metadata JSON
  155. $size = ($addressBookCount * 50) / 1024;
  156. $contactsCount = array_sum(array_map(
  157. fn (array $data): int => count($data['vCards']),
  158. $addressBookExports,
  159. ));
  160. // 350B for each contact
  161. $size += ($contactsCount * 350) / 1024;
  162. return ceil($size);
  163. }
  164. /**
  165. * {@inheritDoc}
  166. */
  167. public function export(IUser $user, IExportDestination $exportDestination, OutputInterface $output): void {
  168. $output->writeln('Exporting contacts into ' . ContactsMigrator::PATH_ROOT . '…');
  169. $addressBookExports = $this->getAddressBookExports($user, $output);
  170. if (empty($addressBookExports)) {
  171. $output->writeln('No contacts to export…');
  172. }
  173. try {
  174. /**
  175. * @var string $name
  176. * @var string $displayName
  177. * @var ?string $description
  178. * @var VCard[] $vCards
  179. */
  180. foreach ($addressBookExports as ['name' => $name, 'displayName' => $displayName, 'description' => $description, 'vCards' => $vCards]) {
  181. // Set filename to sanitized address book name
  182. $basename = preg_replace('/[^a-z0-9-_]/iu', '', $name);
  183. $exportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::FILENAME_EXT;
  184. $metadataExportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::METADATA_EXT;
  185. $exportDestination->addFileContents($exportPath, $this->serializeCards($vCards));
  186. $metadata = array_filter(['displayName' => $displayName, 'description' => $description]);
  187. $exportDestination->addFileContents($metadataExportPath, json_encode($metadata, JSON_THROW_ON_ERROR));
  188. }
  189. } catch (Throwable $e) {
  190. throw new CalendarMigratorException('Could not export address book', 0, $e);
  191. }
  192. }
  193. private function importContact(int $addressBookId, VCard $vCard, string $filename, OutputInterface $output): void {
  194. // Operate on clone to prevent mutation of the original
  195. $vCard = clone $vCard;
  196. $vCard->PRODID = '-//IDN nextcloud.com//Migrated contact//EN';
  197. try {
  198. $this->cardDavBackend->createCard(
  199. $addressBookId,
  200. UUIDUtil::getUUID() . '.' . ContactsMigrator::FILENAME_EXT,
  201. $vCard->serialize(),
  202. );
  203. } catch (Throwable $e) {
  204. $output->writeln('Error creating contact "' . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…");
  205. }
  206. }
  207. /**
  208. * @param array{displayName: string, description?: string} $metadata
  209. * @param VCard[] $vCards
  210. *
  211. * @throws InvalidAddressBookException
  212. */
  213. private function importAddressBook(IUser $user, string $filename, string $initialAddressBookUri, array $metadata, array $vCards, OutputInterface $output): void {
  214. $principalUri = $this->getPrincipalUri($user);
  215. $addressBookUri = $this->getUniqueAddressBookUri($user, $initialAddressBookUri);
  216. $addressBookId = $this->cardDavBackend->createAddressBook($principalUri, $addressBookUri, array_filter([
  217. '{DAV:}displayname' => $metadata['displayName'],
  218. '{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description' => $metadata['description'] ?? null,
  219. ]));
  220. foreach ($vCards as $vCard) {
  221. $this->importContact($addressBookId, $vCard, $filename, $output);
  222. }
  223. }
  224. /**
  225. * @return array<int, array{addressBook: string, metadata: string}>
  226. */
  227. private function getAddressBookImports(array $importFiles): array {
  228. $addressBookImports = array_filter(
  229. $importFiles,
  230. fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::FILENAME_EXT,
  231. );
  232. $metadataImports = array_filter(
  233. $importFiles,
  234. fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::METADATA_EXT,
  235. );
  236. $addressBookSort = sort($addressBookImports);
  237. $metadataSort = sort($metadataImports);
  238. if ($addressBookSort === false || $metadataSort === false) {
  239. throw new ContactsMigratorException('Failed to sort address book files in ' . ContactsMigrator::PATH_ROOT);
  240. }
  241. if (count($addressBookImports) !== count($metadataImports)) {
  242. throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
  243. }
  244. for ($i = 0; $i < count($addressBookImports); ++$i) {
  245. if (pathinfo($addressBookImports[$i], PATHINFO_FILENAME) !== pathinfo($metadataImports[$i], PATHINFO_FILENAME)) {
  246. throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
  247. }
  248. }
  249. return array_map(
  250. fn (string $addressBookFilename, string $metadataFilename) => ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename],
  251. $addressBookImports,
  252. $metadataImports,
  253. );
  254. }
  255. /**
  256. * {@inheritDoc}
  257. *
  258. * @throws ContactsMigratorException
  259. */
  260. public function import(IUser $user, IImportSource $importSource, OutputInterface $output): void {
  261. if ($importSource->getMigratorVersion($this->getId()) === null) {
  262. $output->writeln('No version for ' . static::class . ', skipping import…');
  263. return;
  264. }
  265. $output->writeln('Importing contacts from ' . ContactsMigrator::PATH_ROOT . '…');
  266. $importFiles = $importSource->getFolderListing(ContactsMigrator::PATH_ROOT);
  267. if (empty($importFiles)) {
  268. $output->writeln('No contacts to import…');
  269. }
  270. foreach ($this->getAddressBookImports($importFiles) as ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename]) {
  271. $addressBookImportPath = ContactsMigrator::PATH_ROOT . $addressBookFilename;
  272. $metadataImportPath = ContactsMigrator::PATH_ROOT . $metadataFilename;
  273. $vCardSplitter = new VCardSplitter(
  274. $importSource->getFileAsStream($addressBookImportPath),
  275. VObjectParser::OPTION_FORGIVING,
  276. );
  277. /** @var VCard[] $vCards */
  278. $vCards = [];
  279. /** @var ?VCard $vCard */
  280. while ($vCard = $vCardSplitter->getNext()) {
  281. $problems = $vCard->validate();
  282. if (!empty($problems)) {
  283. $output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
  284. continue;
  285. }
  286. $vCards[] = $vCard;
  287. }
  288. $splitFilename = explode('.', $addressBookFilename, 2);
  289. if (count($splitFilename) !== 2) {
  290. $output->writeln("Invalid filename \"$addressBookFilename\", expected filename of the format \"<address_book_name>." . ContactsMigrator::FILENAME_EXT . '", skipping…');
  291. continue;
  292. }
  293. [$initialAddressBookUri, $ext] = $splitFilename;
  294. /** @var array{displayName: string, description?: string} $metadata */
  295. $metadata = json_decode($importSource->getFileContents($metadataImportPath), true, 512, JSON_THROW_ON_ERROR);
  296. try {
  297. $this->importAddressBook(
  298. $user,
  299. $addressBookFilename,
  300. $initialAddressBookUri,
  301. $metadata,
  302. $vCards,
  303. $output,
  304. );
  305. } catch (InvalidAddressBookException $e) {
  306. // Allow this exception to skip a failed import
  307. } finally {
  308. foreach ($vCards as $vCard) {
  309. $vCard->destroy();
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * {@inheritDoc}
  316. */
  317. public function getId(): string {
  318. return 'contacts';
  319. }
  320. /**
  321. * {@inheritDoc}
  322. */
  323. public function getDisplayName(): string {
  324. return $this->l10n->t('Contacts');
  325. }
  326. /**
  327. * {@inheritDoc}
  328. */
  329. public function getDescription(): string {
  330. return $this->l10n->t('Contacts and groups');
  331. }
  332. }