Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ContactsMigrator.php « UserMigration « lib « dav « apps - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 99eea2700a5bc803b345fb52608a6927199bcaf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php

declare(strict_types=1);

/**
 * @copyright 2022 Christopher Ng <chrng8@gmail.com>
 *
 * @author Christopher Ng <chrng8@gmail.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\DAV\UserMigration;

use function Safe\sort;
use function Safe\substr;
use OCA\DAV\AppInfo\Application;
use OCA\DAV\CardDAV\CardDavBackend;
use OCA\DAV\CardDAV\Plugin as CardDAVPlugin;
use OCA\DAV\Connector\Sabre\CachingTree;
use OCA\DAV\Connector\Sabre\Server as SabreDavServer;
use OCA\DAV\RootCollection;
use OCP\IL10N;
use OCP\IUser;
use OCP\UserMigration\IExportDestination;
use OCP\UserMigration\IImportSource;
use OCP\UserMigration\IMigrator;
use OCP\UserMigration\TMigratorBasicVersionHandling;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\Parser\Parser as VObjectParser;
use Sabre\VObject\Reader as VObjectReader;
use Sabre\VObject\Splitter\VCard as VCardSplitter;
use Sabre\VObject\UUIDUtil;
use Safe\Exceptions\ArrayException;
use Safe\Exceptions\StringsException;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;

class ContactsMigrator implements IMigrator {

	use TMigratorBasicVersionHandling;

	private CardDavBackend $cardDavBackend;

	private IL10N $l10n;

	private SabreDavServer $sabreDavServer;

	private const USERS_URI_ROOT = 'principals/users/';

	private const FILENAME_EXT = 'vcf';

	private const METADATA_EXT = 'json';

	private const MIGRATED_URI_PREFIX = 'migrated-';

	private const PATH_ROOT = Application::APP_ID . '/address_books/';

	public function __construct(
		CardDavBackend $cardDavBackend,
		IL10N $l10n
	) {
		$this->cardDavBackend = $cardDavBackend;
		$this->l10n = $l10n;

		$root = new RootCollection();
		$this->sabreDavServer = new SabreDavServer(new CachingTree($root));
		$this->sabreDavServer->addPlugin(new CardDAVPlugin());
	}

	private function getPrincipalUri(IUser $user): string {
		return ContactsMigrator::USERS_URI_ROOT . $user->getUID();
	}

	/**
	 * @return array{name: string, displayName: string, description: ?string, vCards: VCard[]}
	 *
	 * @throws InvalidAddressBookException
	 */
	private function getAddressBookExportData(IUser $user, array $addressBookInfo, OutputInterface $output): array {
		$userId = $user->getUID();

		if (!isset($addressBookInfo['uri'])) {
			throw new InvalidAddressBookException();
		}

		$uri = $addressBookInfo['uri'];

		$path = CardDAVPlugin::ADDRESSBOOK_ROOT . "/users/$userId/$uri";

		/**
		 * @see \Sabre\CardDAV\VCFExportPlugin::httpGet() implementation reference
		 */

		$addressBookDataProp = '{' . CardDAVPlugin::NS_CARDDAV . '}address-data';
		$addressBookNode = $this->sabreDavServer->tree->getNodeForPath($path);
		$nodes = $this->sabreDavServer->getPropertiesIteratorForPath($path, [$addressBookDataProp], 1);

		/**
		 * @see \Sabre\CardDAV\VCFExportPlugin::generateVCF() implementation reference
		 */

		/** @var VCard[] $vCards */
		$vCards = [];
		foreach ($nodes as $node) {
			if (isset($node[200][$addressBookDataProp])) {
				$vCard = VObjectReader::read($node[200][$addressBookDataProp]);

				$problems = $vCard->validate();
				if (!empty($problems)) {
					$output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
					continue;
				}
				$vCards[] = $vCard;
			}
		}

		return [
			'name' => $addressBookNode->getName(),
			'displayName' => $addressBookInfo['{DAV:}displayname'],
			'description' => $addressBookInfo['{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description'],
			'vCards' => $vCards,
		];
	}

	/**
	 * @return array<int, array{name: string, displayName: string, description: ?string, vCards: VCard[]}>
	 */
	private function getAddressBookExports(IUser $user, OutputInterface $output): array {
		$principalUri = $this->getPrincipalUri($user);

		return array_values(array_filter(array_map(
			function (array $addressBookInfo) use ($user, $output) {
				try {
					return $this->getAddressBookExportData($user, $addressBookInfo, $output);
				} catch (InvalidAddressBookException $e) {
					// Allow this exception as invalid address books are not to be exported
					return null;
				}
			},
			$this->cardDavBackend->getAddressBooksForUser($principalUri),
		)));
	}

	private function getUniqueAddressBookUri(IUser $user, string $initialAddressBookUri): string {
		$principalUri = $this->getPrincipalUri($user);

		try {
			$initialAddressBookUri = substr($initialAddressBookUri, 0, strlen(ContactsMigrator::MIGRATED_URI_PREFIX)) === ContactsMigrator::MIGRATED_URI_PREFIX
				? $initialAddressBookUri
				: ContactsMigrator::MIGRATED_URI_PREFIX . $initialAddressBookUri;
		} catch (StringsException $e) {
			throw new ContactsMigratorException('Failed to get unique address book URI', 0, $e);
		}

		$existingAddressBookUris = array_map(
			fn (array $addressBookInfo) => $addressBookInfo['uri'],
			$this->cardDavBackend->getAddressBooksForUser($principalUri),
		);

		$addressBookUri = $initialAddressBookUri;
		$acc = 1;
		while (in_array($addressBookUri, $existingAddressBookUris, true)) {
			$addressBookUri = $initialAddressBookUri . "-$acc";
			++$acc;
		}

		return $addressBookUri;
	}

	/**
	 * @param VCard[] $vCards
	 */
	private function serializeCards(array $vCards): string {
		return array_reduce(
			$vCards,
			fn (string $addressBookBlob, VCard $vCard) => $addressBookBlob . $vCard->serialize(),
			'',
		);
	}

	/**
	 * {@inheritDoc}
	 */
	public function export(IUser $user, IExportDestination $exportDestination, OutputInterface $output): void {
		$output->writeln('Exporting contacts into ' . ContactsMigrator::PATH_ROOT . '…');

		$addressBookExports = $this->getAddressBookExports($user, $output);

		if (empty($addressBookExports)) {
			$output->writeln('No contacts to export…');
		}

		/**
		 * @var string $name
		 * @var string $displayName
		 * @var ?string $description
		 * @var VCard[] $vCards
		 */
		foreach ($addressBookExports as ['name' => $name, 'displayName' => $displayName, 'description' => $description, 'vCards' => $vCards]) {
			// Set filename to sanitized address book name appended with the date
			$basename = preg_replace('/[^a-zA-Z0-9-_ ]/um', '', $name) . '_' . date('Y-m-d');
			$exportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::FILENAME_EXT;
			$metadataExportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::METADATA_EXT;

			if ($exportDestination->addFileContents($exportPath, $this->serializeCards($vCards)) === false) {
				throw new ContactsMigratorException('Could not export address book');
			}

			$metadata = array_filter(['displayName' => $displayName, 'description' => $description]);
			if ($exportDestination->addFileContents($metadataExportPath, json_encode($metadata)) === false) {
				throw new ContactsMigratorException('Could not export address book metadata');
			}
		}
	}

	private function importContact(int $addressBookId, VCard $vCard, string $filename, OutputInterface $output): void {
		// Operate on clone to prevent mutation of the original
		$vCard = clone $vCard;
		$vCard->PRODID = '-//IDN nextcloud.com//Migrated contact//EN';

		try {
			$this->cardDavBackend->createCard(
				$addressBookId,
				UUIDUtil::getUUID() . '.' . ContactsMigrator::FILENAME_EXT,
				$vCard->serialize(),
			);
		} catch (Throwable $e) {
			$output->writeln("Error creating contact \"" . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…");
		}
	}

	/**
	 * @param array{displayName: string, description?: string} $metadata
	 * @param VCard[] $vCards
	 */
	private function importAddressBook(IUser $user, string $filename, string $initialAddressBookUri, array $metadata, array $vCards, OutputInterface $output): void {
		$principalUri = $this->getPrincipalUri($user);
		$addressBookUri = $this->getUniqueAddressBookUri($user, $initialAddressBookUri);

		$addressBookId = $this->cardDavBackend->createAddressBook($principalUri, $addressBookUri, array_filter([
			'{DAV:}displayname' => $metadata['displayName'],
			'{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description' => $metadata['description'] ?? null,
		]));

		foreach ($vCards as $vCard) {
			$this->importContact($addressBookId, $vCard, $filename, $output);
		}
	}

	/**
	 * @return array<int, array{addressBook: string, metadata: string}>
	 */
	private function getAddressBookImports(array $importFiles): array {
		$addressBookImports = array_filter(
			$importFiles,
			fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::FILENAME_EXT,
		);

		$metadataImports = array_filter(
			$importFiles,
			fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::METADATA_EXT,
		);

		try {
			sort($addressBookImports);
			sort($metadataImports);
		} catch (ArrayException $e) {
			throw new ContactsMigratorException('Failed to sort address book files in ' . ContactsMigrator::PATH_ROOT, 0, $e);
		}

		if (count($addressBookImports) !== count($metadataImports)) {
			throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
		}

		for ($i = 0; $i < count($addressBookImports); ++$i) {
			if (pathinfo($addressBookImports[$i], PATHINFO_FILENAME) !== pathinfo($metadataImports[$i], PATHINFO_FILENAME)) {
				throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
			}
		}

		return array_map(
			fn (string $addressBookFilename, string $metadataFilename) => ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename],
			$addressBookImports,
			$metadataImports,
		);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @throws ContactsMigratorException
	 */
	public function import(IUser $user, IImportSource $importSource, OutputInterface $output): void {
		if ($importSource->getMigratorVersion($this->getId()) === null) {
			$output->writeln('No version for ' . static::class . ', skipping import…');
			return;
		}

		$output->writeln('Importing contacts from ' . ContactsMigrator::PATH_ROOT . '…');

		$importFiles = $importSource->getFolderListing(ContactsMigrator::PATH_ROOT);

		if (empty($importFiles)) {
			$output->writeln('No contacts to import…');
		}

		foreach ($this->getAddressBookImports($importFiles) as ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename]) {
			$addressBookImportPath = ContactsMigrator::PATH_ROOT . $addressBookFilename;
			$metadataImportPath = ContactsMigrator::PATH_ROOT . $metadataFilename;

			$vCardSplitter = new VCardSplitter(
				$importSource->getFileAsStream($addressBookImportPath),
				VObjectParser::OPTION_FORGIVING,
			);

			/** @var VCard[] $vCards */
			$vCards = [];
			/** @var ?VCard $vCard */
			while ($vCard = $vCardSplitter->getNext()) {
				$problems = $vCard->validate();
				if (!empty($problems)) {
					$output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
					continue;
				}
				$vCards[] = $vCard;
			}

			$splitFilename = explode('_', $addressBookFilename, 2);
			if (count($splitFilename) !== 2) {
				throw new ContactsMigratorException("Invalid filename \"$addressBookFilename\", expected filename of the format \"<address_book_name>_YYYY-MM-DD." . ContactsMigrator::FILENAME_EXT . '"');
			}
			[$initialAddressBookUri, $suffix] = $splitFilename;

			/** @var array{displayName: string, description?: string} $metadata */
			$metadata = json_decode($importSource->getFileContents($metadataImportPath), true, 512, JSON_THROW_ON_ERROR);

			$this->importAddressBook(
				$user,
				$addressBookFilename,
				$initialAddressBookUri,
				$metadata,
				$vCards,
				$output,
			);

			foreach ($vCards as $vCard) {
				$vCard->destroy();
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public function getId(): string {
		return 'contacts';
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDisplayName(): string {
		return $this->l10n->t('Contacts');
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDescription(): string {
		return $this->l10n->t('Contacts and groups');
	}
}