aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/FilesMetadata/FilesMetadataManager.php
blob: 231fb2ec98f563d18df702c6764c8c60125cab57 (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
<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\FilesMetadata;

use JsonException;
use OC\FilesMetadata\Job\UpdateSingleMetadata;
use OC\FilesMetadata\Listener\MetadataDelete;
use OC\FilesMetadata\Listener\MetadataUpdate;
use OC\FilesMetadata\Model\FilesMetadata;
use OC\FilesMetadata\Service\IndexRequestService;
use OC\FilesMetadata\Service\MetadataRequestService;
use OCP\BackgroundJob\IJobList;
use OCP\DB\Exception;
use OCP\DB\Exception as DBException;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Cache\CacheEntryRemovedEvent;
use OCP\Files\Events\Node\NodeWrittenEvent;
use OCP\Files\InvalidPathException;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\FilesMetadata\Event\MetadataBackgroundEvent;
use OCP\FilesMetadata\Event\MetadataLiveEvent;
use OCP\FilesMetadata\Event\MetadataNamedEvent;
use OCP\FilesMetadata\Exceptions\FilesMetadataException;
use OCP\FilesMetadata\Exceptions\FilesMetadataNotFoundException;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\FilesMetadata\IMetadataQuery;
use OCP\FilesMetadata\Model\IFilesMetadata;
use OCP\FilesMetadata\Model\IMetadataValueWrapper;
use OCP\IAppConfig;
use Psr\Log\LoggerInterface;

/**
 * @inheritDoc
 * @since 28.0.0
 */
class FilesMetadataManager implements IFilesMetadataManager {
	public const CONFIG_KEY = 'files_metadata';
	public const MIGRATION_DONE = 'files_metadata_installed';
	private const JSON_MAXSIZE = 100000;

	private ?IFilesMetadata $all = null;

	public function __construct(
		private IEventDispatcher $eventDispatcher,
		private IJobList $jobList,
		private IAppConfig $appConfig,
		private LoggerInterface $logger,
		private MetadataRequestService $metadataRequestService,
		private IndexRequestService $indexRequestService,
	) {
	}

	/**
	 * @inheritDoc
	 *
	 * @param Node $node related node
	 * @param int $process type of process
	 *
	 * @return IFilesMetadata
	 * @throws FilesMetadataException if metadata are invalid
	 * @throws InvalidPathException if path to file is not valid
	 * @throws NotFoundException if file cannot be found
	 * @see self::PROCESS_BACKGROUND
	 * @see self::PROCESS_LIVE
	 * @since 28.0.0
	 */
	public function refreshMetadata(
		Node $node,
		int $process = self::PROCESS_LIVE,
		string $namedEvent = ''
	): IFilesMetadata {
		try {
			$metadata = $this->metadataRequestService->getMetadataFromFileId($node->getId());
		} catch (FilesMetadataNotFoundException) {
			$metadata = new FilesMetadata($node->getId());
		}

		// if $process is LIVE, we enforce LIVE
		// if $process is NAMED, we go NAMED
		// else BACKGROUND
		if ((self::PROCESS_LIVE & $process) !== 0) {
			$event = new MetadataLiveEvent($node, $metadata);
		} elseif ((self::PROCESS_NAMED & $process) !== 0) {
			$event = new MetadataNamedEvent($node, $metadata, $namedEvent);
		} else {
			$event = new MetadataBackgroundEvent($node, $metadata);
		}

		$this->eventDispatcher->dispatchTyped($event);
		$this->saveMetadata($event->getMetadata());

		// if requested, we add a new job for next cron to refresh metadata out of main thread
		// if $process was set to LIVE+BACKGROUND, we run background process directly
		if ($event instanceof MetadataLiveEvent && $event->isRunAsBackgroundJobRequested()) {
			if ((self::PROCESS_BACKGROUND & $process) !== 0) {
				return $this->refreshMetadata($node, self::PROCESS_BACKGROUND);
			}

			$this->jobList->add(UpdateSingleMetadata::class, [$node->getOwner()->getUID(), $node->getId()]);
		}

		return $metadata;
	}

	/**
	 * @param int $fileId file id
	 * @param boolean $generate Generate if metadata does not exists
	 *
	 * @inheritDoc
	 * @return IFilesMetadata
	 * @throws FilesMetadataNotFoundException if not found
	 * @since 28.0.0
	 */
	public function getMetadata(int $fileId, bool $generate = false): IFilesMetadata {
		try {
			return $this->metadataRequestService->getMetadataFromFileId($fileId);
		} catch (FilesMetadataNotFoundException $ex) {
			if ($generate) {
				return new FilesMetadata($fileId);
			}

			throw $ex;
		}
	}

	/**
	 * returns metadata of multiple file ids
	 *
	 * @param int[] $fileIds file ids
	 *
	 * @return array File ID is the array key, files without metadata are not returned in the array
	 * @psalm-return array<int, IFilesMetadata>
	 * @since 28.0.0
	 */
	public function getMetadataForFiles(array $fileIds): array {
		return $this->metadataRequestService->getMetadataFromFileIds($fileIds);
	}

	/**
	 * @param IFilesMetadata $filesMetadata metadata
	 *
	 * @inheritDoc
	 * @throws FilesMetadataException if metadata seems malformed
	 * @since 28.0.0
	 */
	public function saveMetadata(IFilesMetadata $filesMetadata): void {
		if ($filesMetadata->getFileId() === 0 || !$filesMetadata->updated()) {
			return;
		}

		$json = json_encode($filesMetadata->jsonSerialize());
		if (strlen($json) > self::JSON_MAXSIZE) {
			$this->logger->debug('huge metadata content detected: ' . $json);
			throw new FilesMetadataException('json cannot exceed ' . self::JSON_MAXSIZE . ' characters long; fileId: ' . $filesMetadata->getFileId() . '; size: ' . strlen($json));
		}

		try {
			if ($filesMetadata->getSyncToken() === '') {
				$this->metadataRequestService->store($filesMetadata);
			} else {
				$this->metadataRequestService->updateMetadata($filesMetadata);
			}
		} catch (DBException $e) {
			// most of the logged exception are the result of race condition
			// between 2 simultaneous process trying to create/update metadata
			$this->logger->warning('issue while saveMetadata', ['exception' => $e, 'metadata' => $filesMetadata]);

			return;
		}

		// update indexes
		foreach ($filesMetadata->getIndexes() as $index) {
			try {
				$this->indexRequestService->updateIndex($filesMetadata, $index);
			} catch (DBException $e) {
				$this->logger->warning('issue while updateIndex', ['exception' => $e]);
			}
		}

		// update metadata types list
		$current = $this->getKnownMetadata();
		$current->import($filesMetadata->jsonSerialize(true));
		$this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
	}

	/**
	 * @param int $fileId file id
	 *
	 * @inheritDoc
	 * @since 28.0.0
	 */
	public function deleteMetadata(int $fileId): void {
		try {
			$this->metadataRequestService->dropMetadata($fileId);
		} catch (Exception $e) {
			$this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
		}

		try {
			$this->indexRequestService->dropIndex($fileId);
		} catch (Exception $e) {
			$this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
		}
	}

	/**
	 * @param IQueryBuilder $qb
	 * @param string $fileTableAlias alias of the table that contains data about files
	 * @param string $fileIdField alias of the field that contains file ids
	 *
	 * @inheritDoc
	 * @return IMetadataQuery
	 * @see IMetadataQuery
	 * @since 28.0.0
	 */
	public function getMetadataQuery(
		IQueryBuilder $qb,
		string $fileTableAlias,
		string $fileIdField
	): IMetadataQuery {
		return new MetadataQuery($qb, $this, $fileTableAlias, $fileIdField);
	}

	/**
	 * @inheritDoc
	 * @return IFilesMetadata
	 * @since 28.0.0
	 */
	public function getKnownMetadata(): IFilesMetadata {
		if ($this->all !== null) {
			return $this->all;
		}
		$this->all = new FilesMetadata();

		try {
			$this->all->import($this->appConfig->getValueArray('core', self::CONFIG_KEY, lazy: true));
		} catch (JsonException) {
			$this->logger->warning('issue while reading stored list of metadata. Advised to run ./occ files:scan --all --generate-metadata');
		}

		return $this->all;
	}

	/**
	 * @param string $key metadata key
	 * @param string $type metadata type
	 * @param bool $indexed TRUE if metadata can be search
	 * @param int $editPermission remote edit permission via Webdav PROPPATCH
	 *
	 * @inheritDoc
	 * @since 28.0.0
	 * @see IMetadataValueWrapper::TYPE_INT
	 * @see IMetadataValueWrapper::TYPE_FLOAT
	 * @see IMetadataValueWrapper::TYPE_BOOL
	 * @see IMetadataValueWrapper::TYPE_ARRAY
	 * @see IMetadataValueWrapper::TYPE_STRING_LIST
	 * @see IMetadataValueWrapper::TYPE_INT_LIST
	 * @see IMetadataValueWrapper::TYPE_STRING
	 * @see IMetadataValueWrapper::EDIT_FORBIDDEN
	 * @see IMetadataValueWrapper::EDIT_REQ_OWNERSHIP
	 * @see IMetadataValueWrapper::EDIT_REQ_WRITE_PERMISSION
	 * @see IMetadataValueWrapper::EDIT_REQ_READ_PERMISSION
	 */
	public function initMetadata(
		string $key,
		string $type,
		bool $indexed = false,
		int $editPermission = IMetadataValueWrapper::EDIT_FORBIDDEN
	): void {
		$current = $this->getKnownMetadata();
		try {
			if ($current->getType($key) === $type
				&& $indexed === $current->isIndex($key)
				&& $editPermission === $current->getEditPermission($key)) {
				return; // if key exists, with same type and indexed, we do nothing.
			}
		} catch (FilesMetadataNotFoundException) {
			// if value does not exist, we keep on the writing of course
		}

		$current->import([$key => ['type' => $type, 'indexed' => $indexed, 'editPermission' => $editPermission]]);
		$this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
		$this->all = $current;
	}

	/**
	 * load listeners
	 *
	 * @param IEventDispatcher $eventDispatcher
	 */
	public static function loadListeners(IEventDispatcher $eventDispatcher): void {
		$eventDispatcher->addServiceListener(NodeWrittenEvent::class, MetadataUpdate::class);
		$eventDispatcher->addServiceListener(CacheEntryRemovedEvent::class, MetadataDelete::class);
	}
}