ContactsMigrator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. /**
  133. * @throws InvalidAddressBookException
  134. */
  135. private function getUniqueAddressBookUri(IUser $user, string $initialAddressBookUri): string {
  136. $principalUri = $this->getPrincipalUri($user);
  137. $initialAddressBookUri = substr($initialAddressBookUri, 0, strlen(ContactsMigrator::MIGRATED_URI_PREFIX)) === ContactsMigrator::MIGRATED_URI_PREFIX
  138. ? $initialAddressBookUri
  139. : ContactsMigrator::MIGRATED_URI_PREFIX . $initialAddressBookUri;
  140. if ($initialAddressBookUri === '') {
  141. throw new InvalidAddressBookException();
  142. }
  143. $existingAddressBookUris = array_map(
  144. fn (array $addressBookInfo): string => $addressBookInfo['uri'],
  145. $this->cardDavBackend->getAddressBooksForUser($principalUri),
  146. );
  147. $addressBookUri = $initialAddressBookUri;
  148. $acc = 1;
  149. while (in_array($addressBookUri, $existingAddressBookUris, true)) {
  150. $addressBookUri = $initialAddressBookUri . "-$acc";
  151. ++$acc;
  152. }
  153. return $addressBookUri;
  154. }
  155. /**
  156. * @param VCard[] $vCards
  157. */
  158. private function serializeCards(array $vCards): string {
  159. return array_reduce(
  160. $vCards,
  161. fn (string $addressBookBlob, VCard $vCard) => $addressBookBlob . $vCard->serialize(),
  162. '',
  163. );
  164. }
  165. /**
  166. * {@inheritDoc}
  167. */
  168. public function getEstimatedExportSize(IUser $user): int|float {
  169. $addressBookExports = $this->getAddressBookExports($user, new NullOutput());
  170. $addressBookCount = count($addressBookExports);
  171. // 50B for each metadata JSON
  172. $size = ($addressBookCount * 50) / 1024;
  173. $contactsCount = array_sum(array_map(
  174. fn (array $data): int => count($data['vCards']),
  175. $addressBookExports,
  176. ));
  177. // 350B for each contact
  178. $size += ($contactsCount * 350) / 1024;
  179. return ceil($size);
  180. }
  181. /**
  182. * {@inheritDoc}
  183. */
  184. public function export(IUser $user, IExportDestination $exportDestination, OutputInterface $output): void {
  185. $output->writeln('Exporting contacts into ' . ContactsMigrator::PATH_ROOT . '…');
  186. $addressBookExports = $this->getAddressBookExports($user, $output);
  187. if (empty($addressBookExports)) {
  188. $output->writeln('No contacts to export…');
  189. }
  190. try {
  191. /**
  192. * @var string $name
  193. * @var string $displayName
  194. * @var ?string $description
  195. * @var VCard[] $vCards
  196. */
  197. foreach ($addressBookExports as ['name' => $name, 'displayName' => $displayName, 'description' => $description, 'vCards' => $vCards]) {
  198. // Set filename to sanitized address book name
  199. $basename = preg_replace('/[^a-z0-9-_]/iu', '', $name);
  200. $exportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::FILENAME_EXT;
  201. $metadataExportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::METADATA_EXT;
  202. $exportDestination->addFileContents($exportPath, $this->serializeCards($vCards));
  203. $metadata = array_filter(['displayName' => $displayName, 'description' => $description]);
  204. $exportDestination->addFileContents($metadataExportPath, json_encode($metadata, JSON_THROW_ON_ERROR));
  205. }
  206. } catch (Throwable $e) {
  207. throw new CalendarMigratorException('Could not export address book', 0, $e);
  208. }
  209. }
  210. private function importContact(int $addressBookId, VCard $vCard, string $filename, OutputInterface $output): void {
  211. // Operate on clone to prevent mutation of the original
  212. $vCard = clone $vCard;
  213. $vCard->PRODID = '-//IDN nextcloud.com//Migrated contact//EN';
  214. try {
  215. $this->cardDavBackend->createCard(
  216. $addressBookId,
  217. UUIDUtil::getUUID() . '.' . ContactsMigrator::FILENAME_EXT,
  218. $vCard->serialize(),
  219. );
  220. } catch (Throwable $e) {
  221. $output->writeln("Error creating contact \"" . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…");
  222. }
  223. }
  224. /**
  225. * @param array{displayName: string, description?: string} $metadata
  226. * @param VCard[] $vCards
  227. *
  228. * @throws InvalidAddressBookException
  229. */
  230. private function importAddressBook(IUser $user, string $filename, string $initialAddressBookUri, array $metadata, array $vCards, OutputInterface $output): void {
  231. $principalUri = $this->getPrincipalUri($user);
  232. $addressBookUri = $this->getUniqueAddressBookUri($user, $initialAddressBookUri);
  233. $addressBookId = $this->cardDavBackend->createAddressBook($principalUri, $addressBookUri, array_filter([
  234. '{DAV:}displayname' => $metadata['displayName'],
  235. '{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description' => $metadata['description'] ?? null,
  236. ]));
  237. foreach ($vCards as $vCard) {
  238. $this->importContact($addressBookId, $vCard, $filename, $output);
  239. }
  240. }
  241. /**
  242. * @return array<int, array{addressBook: string, metadata: string}>
  243. */
  244. private function getAddressBookImports(array $importFiles): array {
  245. $addressBookImports = array_filter(
  246. $importFiles,
  247. fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::FILENAME_EXT,
  248. );
  249. $metadataImports = array_filter(
  250. $importFiles,
  251. fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::METADATA_EXT,
  252. );
  253. $addressBookSort = sort($addressBookImports);
  254. $metadataSort = sort($metadataImports);
  255. if ($addressBookSort === false || $metadataSort === false) {
  256. throw new ContactsMigratorException('Failed to sort address book files in ' . ContactsMigrator::PATH_ROOT);
  257. }
  258. if (count($addressBookImports) !== count($metadataImports)) {
  259. throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
  260. }
  261. for ($i = 0; $i < count($addressBookImports); ++$i) {
  262. if (pathinfo($addressBookImports[$i], PATHINFO_FILENAME) !== pathinfo($metadataImports[$i], PATHINFO_FILENAME)) {
  263. throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
  264. }
  265. }
  266. return array_map(
  267. fn (string $addressBookFilename, string $metadataFilename) => ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename],
  268. $addressBookImports,
  269. $metadataImports,
  270. );
  271. }
  272. /**
  273. * {@inheritDoc}
  274. *
  275. * @throws ContactsMigratorException
  276. */
  277. public function import(IUser $user, IImportSource $importSource, OutputInterface $output): void {
  278. if ($importSource->getMigratorVersion($this->getId()) === null) {
  279. $output->writeln('No version for ' . static::class . ', skipping import…');
  280. return;
  281. }
  282. $output->writeln('Importing contacts from ' . ContactsMigrator::PATH_ROOT . '…');
  283. $importFiles = $importSource->getFolderListing(ContactsMigrator::PATH_ROOT);
  284. if (empty($importFiles)) {
  285. $output->writeln('No contacts to import…');
  286. }
  287. foreach ($this->getAddressBookImports($importFiles) as ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename]) {
  288. $addressBookImportPath = ContactsMigrator::PATH_ROOT . $addressBookFilename;
  289. $metadataImportPath = ContactsMigrator::PATH_ROOT . $metadataFilename;
  290. $vCardSplitter = new VCardSplitter(
  291. $importSource->getFileAsStream($addressBookImportPath),
  292. VObjectParser::OPTION_FORGIVING,
  293. );
  294. /** @var VCard[] $vCards */
  295. $vCards = [];
  296. /** @var ?VCard $vCard */
  297. while ($vCard = $vCardSplitter->getNext()) {
  298. $problems = $vCard->validate();
  299. if (!empty($problems)) {
  300. $output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
  301. continue;
  302. }
  303. $vCards[] = $vCard;
  304. }
  305. $splitFilename = explode('.', $addressBookFilename, 2);
  306. if (count($splitFilename) !== 2) {
  307. $output->writeln("Invalid filename \"$addressBookFilename\", expected filename of the format \"<address_book_name>." . ContactsMigrator::FILENAME_EXT . '", skipping…');
  308. continue;
  309. }
  310. [$initialAddressBookUri, $ext] = $splitFilename;
  311. /** @var array{displayName: string, description?: string} $metadata */
  312. $metadata = json_decode($importSource->getFileContents($metadataImportPath), true, 512, JSON_THROW_ON_ERROR);
  313. try {
  314. $this->importAddressBook(
  315. $user,
  316. $addressBookFilename,
  317. $initialAddressBookUri,
  318. $metadata,
  319. $vCards,
  320. $output,
  321. );
  322. } catch (InvalidAddressBookException $e) {
  323. // Allow this exception to skip a failed import
  324. } finally {
  325. foreach ($vCards as $vCard) {
  326. $vCard->destroy();
  327. }
  328. }
  329. }
  330. }
  331. /**
  332. * {@inheritDoc}
  333. */
  334. public function getId(): string {
  335. return 'contacts';
  336. }
  337. /**
  338. * {@inheritDoc}
  339. */
  340. public function getDisplayName(): string {
  341. return $this->l10n->t('Contacts');
  342. }
  343. /**
  344. * {@inheritDoc}
  345. */
  346. public function getDescription(): string {
  347. return $this->l10n->t('Contacts and groups');
  348. }
  349. }