FilesMetadataManager.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\FilesMetadata;
  8. use JsonException;
  9. use OC\FilesMetadata\Job\UpdateSingleMetadata;
  10. use OC\FilesMetadata\Listener\MetadataDelete;
  11. use OC\FilesMetadata\Listener\MetadataUpdate;
  12. use OC\FilesMetadata\Model\FilesMetadata;
  13. use OC\FilesMetadata\Service\IndexRequestService;
  14. use OC\FilesMetadata\Service\MetadataRequestService;
  15. use OCP\BackgroundJob\IJobList;
  16. use OCP\DB\Exception;
  17. use OCP\DB\Exception as DBException;
  18. use OCP\DB\QueryBuilder\IQueryBuilder;
  19. use OCP\EventDispatcher\IEventDispatcher;
  20. use OCP\Files\Cache\CacheEntryRemovedEvent;
  21. use OCP\Files\Events\Node\NodeWrittenEvent;
  22. use OCP\Files\InvalidPathException;
  23. use OCP\Files\Node;
  24. use OCP\Files\NotFoundException;
  25. use OCP\FilesMetadata\Event\MetadataBackgroundEvent;
  26. use OCP\FilesMetadata\Event\MetadataLiveEvent;
  27. use OCP\FilesMetadata\Event\MetadataNamedEvent;
  28. use OCP\FilesMetadata\Exceptions\FilesMetadataException;
  29. use OCP\FilesMetadata\Exceptions\FilesMetadataNotFoundException;
  30. use OCP\FilesMetadata\IFilesMetadataManager;
  31. use OCP\FilesMetadata\IMetadataQuery;
  32. use OCP\FilesMetadata\Model\IFilesMetadata;
  33. use OCP\FilesMetadata\Model\IMetadataValueWrapper;
  34. use OCP\IAppConfig;
  35. use Psr\Log\LoggerInterface;
  36. /**
  37. * @inheritDoc
  38. * @since 28.0.0
  39. */
  40. class FilesMetadataManager implements IFilesMetadataManager {
  41. public const CONFIG_KEY = 'files_metadata';
  42. public const MIGRATION_DONE = 'files_metadata_installed';
  43. private const JSON_MAXSIZE = 100000;
  44. private ?IFilesMetadata $all = null;
  45. public function __construct(
  46. private IEventDispatcher $eventDispatcher,
  47. private IJobList $jobList,
  48. private IAppConfig $appConfig,
  49. private LoggerInterface $logger,
  50. private MetadataRequestService $metadataRequestService,
  51. private IndexRequestService $indexRequestService,
  52. ) {
  53. }
  54. /**
  55. * @inheritDoc
  56. *
  57. * @param Node $node related node
  58. * @param int $process type of process
  59. *
  60. * @return IFilesMetadata
  61. * @throws FilesMetadataException if metadata are invalid
  62. * @throws InvalidPathException if path to file is not valid
  63. * @throws NotFoundException if file cannot be found
  64. * @see self::PROCESS_BACKGROUND
  65. * @see self::PROCESS_LIVE
  66. * @since 28.0.0
  67. */
  68. public function refreshMetadata(
  69. Node $node,
  70. int $process = self::PROCESS_LIVE,
  71. string $namedEvent = '',
  72. ): IFilesMetadata {
  73. $storageId = $node->getStorage()->getCache()->getNumericStorageId();
  74. try {
  75. /** @var FilesMetadata $metadata */
  76. $metadata = $this->metadataRequestService->getMetadataFromFileId($node->getId());
  77. } catch (FilesMetadataNotFoundException) {
  78. $metadata = new FilesMetadata($node->getId());
  79. }
  80. $metadata->setStorageId($storageId);
  81. // if $process is LIVE, we enforce LIVE
  82. // if $process is NAMED, we go NAMED
  83. // else BACKGROUND
  84. if ((self::PROCESS_LIVE & $process) !== 0) {
  85. $event = new MetadataLiveEvent($node, $metadata);
  86. } elseif ((self::PROCESS_NAMED & $process) !== 0) {
  87. $event = new MetadataNamedEvent($node, $metadata, $namedEvent);
  88. } else {
  89. $event = new MetadataBackgroundEvent($node, $metadata);
  90. }
  91. $this->eventDispatcher->dispatchTyped($event);
  92. $this->saveMetadata($event->getMetadata());
  93. // if requested, we add a new job for next cron to refresh metadata out of main thread
  94. // if $process was set to LIVE+BACKGROUND, we run background process directly
  95. if ($event instanceof MetadataLiveEvent && $event->isRunAsBackgroundJobRequested()) {
  96. if ((self::PROCESS_BACKGROUND & $process) !== 0) {
  97. return $this->refreshMetadata($node, self::PROCESS_BACKGROUND);
  98. }
  99. $this->jobList->add(UpdateSingleMetadata::class, [$node->getOwner()?->getUID(), $node->getId()]);
  100. }
  101. return $metadata;
  102. }
  103. /**
  104. * @param int $fileId file id
  105. * @param boolean $generate Generate if metadata does not exists
  106. *
  107. * @inheritDoc
  108. * @return IFilesMetadata
  109. * @throws FilesMetadataNotFoundException if not found
  110. * @since 28.0.0
  111. */
  112. public function getMetadata(int $fileId, bool $generate = false): IFilesMetadata {
  113. try {
  114. return $this->metadataRequestService->getMetadataFromFileId($fileId);
  115. } catch (FilesMetadataNotFoundException $ex) {
  116. if ($generate) {
  117. return new FilesMetadata($fileId);
  118. }
  119. throw $ex;
  120. }
  121. }
  122. /**
  123. * returns metadata of multiple file ids
  124. *
  125. * @param int[] $fileIds file ids
  126. *
  127. * @return array File ID is the array key, files without metadata are not returned in the array
  128. * @psalm-return array<int, IFilesMetadata>
  129. * @since 28.0.0
  130. */
  131. public function getMetadataForFiles(array $fileIds): array {
  132. return $this->metadataRequestService->getMetadataFromFileIds($fileIds);
  133. }
  134. /**
  135. * @param IFilesMetadata $filesMetadata metadata
  136. *
  137. * @inheritDoc
  138. * @throws FilesMetadataException if metadata seems malformed
  139. * @since 28.0.0
  140. */
  141. public function saveMetadata(IFilesMetadata $filesMetadata): void {
  142. if ($filesMetadata->getFileId() === 0 || !$filesMetadata->updated()) {
  143. return;
  144. }
  145. $json = json_encode($filesMetadata->jsonSerialize());
  146. if (strlen($json) > self::JSON_MAXSIZE) {
  147. $this->logger->debug('huge metadata content detected: ' . $json);
  148. throw new FilesMetadataException('json cannot exceed ' . self::JSON_MAXSIZE . ' characters long; fileId: ' . $filesMetadata->getFileId() . '; size: ' . strlen($json));
  149. }
  150. try {
  151. if ($filesMetadata->getSyncToken() === '') {
  152. $this->metadataRequestService->store($filesMetadata);
  153. } else {
  154. $this->metadataRequestService->updateMetadata($filesMetadata);
  155. }
  156. } catch (DBException $e) {
  157. // most of the logged exception are the result of race condition
  158. // between 2 simultaneous process trying to create/update metadata
  159. $this->logger->warning('issue while saveMetadata', ['exception' => $e, 'metadata' => $filesMetadata]);
  160. return;
  161. }
  162. // update indexes
  163. foreach ($filesMetadata->getIndexes() as $index) {
  164. try {
  165. $this->indexRequestService->updateIndex($filesMetadata, $index);
  166. } catch (DBException $e) {
  167. $this->logger->warning('issue while updateIndex', ['exception' => $e]);
  168. }
  169. }
  170. // update metadata types list
  171. $current = $this->getKnownMetadata();
  172. $current->import($filesMetadata->jsonSerialize(true));
  173. $this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
  174. }
  175. /**
  176. * @param int $fileId file id
  177. *
  178. * @inheritDoc
  179. * @since 28.0.0
  180. */
  181. public function deleteMetadata(int $fileId): void {
  182. try {
  183. $this->metadataRequestService->dropMetadata($fileId);
  184. } catch (Exception $e) {
  185. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  186. }
  187. try {
  188. $this->indexRequestService->dropIndex($fileId);
  189. } catch (Exception $e) {
  190. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  191. }
  192. }
  193. /**
  194. * @param IQueryBuilder $qb
  195. * @param string $fileTableAlias alias of the table that contains data about files
  196. * @param string $fileIdField alias of the field that contains file ids
  197. *
  198. * @inheritDoc
  199. * @return IMetadataQuery
  200. * @see IMetadataQuery
  201. * @since 28.0.0
  202. */
  203. public function getMetadataQuery(
  204. IQueryBuilder $qb,
  205. string $fileTableAlias,
  206. string $fileIdField,
  207. ): IMetadataQuery {
  208. return new MetadataQuery($qb, $this, $fileTableAlias, $fileIdField);
  209. }
  210. /**
  211. * @inheritDoc
  212. * @return IFilesMetadata
  213. * @since 28.0.0
  214. */
  215. public function getKnownMetadata(): IFilesMetadata {
  216. if ($this->all !== null) {
  217. return $this->all;
  218. }
  219. $this->all = new FilesMetadata();
  220. try {
  221. $this->all->import($this->appConfig->getValueArray('core', self::CONFIG_KEY, lazy: true));
  222. } catch (JsonException) {
  223. $this->logger->warning('issue while reading stored list of metadata. Advised to run ./occ files:scan --all --generate-metadata');
  224. }
  225. return $this->all;
  226. }
  227. /**
  228. * @param string $key metadata key
  229. * @param string $type metadata type
  230. * @param bool $indexed TRUE if metadata can be search
  231. * @param int $editPermission remote edit permission via Webdav PROPPATCH
  232. *
  233. * @inheritDoc
  234. * @since 28.0.0
  235. * @see IMetadataValueWrapper::TYPE_INT
  236. * @see IMetadataValueWrapper::TYPE_FLOAT
  237. * @see IMetadataValueWrapper::TYPE_BOOL
  238. * @see IMetadataValueWrapper::TYPE_ARRAY
  239. * @see IMetadataValueWrapper::TYPE_STRING_LIST
  240. * @see IMetadataValueWrapper::TYPE_INT_LIST
  241. * @see IMetadataValueWrapper::TYPE_STRING
  242. * @see IMetadataValueWrapper::EDIT_FORBIDDEN
  243. * @see IMetadataValueWrapper::EDIT_REQ_OWNERSHIP
  244. * @see IMetadataValueWrapper::EDIT_REQ_WRITE_PERMISSION
  245. * @see IMetadataValueWrapper::EDIT_REQ_READ_PERMISSION
  246. */
  247. public function initMetadata(
  248. string $key,
  249. string $type,
  250. bool $indexed = false,
  251. int $editPermission = IMetadataValueWrapper::EDIT_FORBIDDEN,
  252. ): void {
  253. $current = $this->getKnownMetadata();
  254. try {
  255. if ($current->getType($key) === $type
  256. && $indexed === $current->isIndex($key)
  257. && $editPermission === $current->getEditPermission($key)) {
  258. return; // if key exists, with same type and indexed, we do nothing.
  259. }
  260. } catch (FilesMetadataNotFoundException) {
  261. // if value does not exist, we keep on the writing of course
  262. }
  263. $current->import([$key => ['type' => $type, 'indexed' => $indexed, 'editPermission' => $editPermission]]);
  264. $this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
  265. $this->all = $current;
  266. }
  267. /**
  268. * load listeners
  269. *
  270. * @param IEventDispatcher $eventDispatcher
  271. */
  272. public static function loadListeners(IEventDispatcher $eventDispatcher): void {
  273. $eventDispatcher->addServiceListener(NodeWrittenEvent::class, MetadataUpdate::class);
  274. $eventDispatcher->addServiceListener(CacheEntryRemovedEvent::class, MetadataDelete::class);
  275. }
  276. }