1
0

ContactsMigrator.php 12 KB

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