ContactsMigrator.php 13 KB

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