FilesMetadataManager.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. try {
  74. $metadata = $this->metadataRequestService->getMetadataFromFileId($node->getId());
  75. } catch (FilesMetadataNotFoundException) {
  76. $metadata = new FilesMetadata($node->getId());
  77. }
  78. // if $process is LIVE, we enforce LIVE
  79. // if $process is NAMED, we go NAMED
  80. // else BACKGROUND
  81. if ((self::PROCESS_LIVE & $process) !== 0) {
  82. $event = new MetadataLiveEvent($node, $metadata);
  83. } elseif ((self::PROCESS_NAMED & $process) !== 0) {
  84. $event = new MetadataNamedEvent($node, $metadata, $namedEvent);
  85. } else {
  86. $event = new MetadataBackgroundEvent($node, $metadata);
  87. }
  88. $this->eventDispatcher->dispatchTyped($event);
  89. $this->saveMetadata($event->getMetadata());
  90. // if requested, we add a new job for next cron to refresh metadata out of main thread
  91. // if $process was set to LIVE+BACKGROUND, we run background process directly
  92. if ($event instanceof MetadataLiveEvent && $event->isRunAsBackgroundJobRequested()) {
  93. if ((self::PROCESS_BACKGROUND & $process) !== 0) {
  94. return $this->refreshMetadata($node, self::PROCESS_BACKGROUND);
  95. }
  96. $this->jobList->add(UpdateSingleMetadata::class, [$node->getOwner()?->getUID(), $node->getId()]);
  97. }
  98. return $metadata;
  99. }
  100. /**
  101. * @param int $fileId file id
  102. * @param boolean $generate Generate if metadata does not exists
  103. *
  104. * @inheritDoc
  105. * @return IFilesMetadata
  106. * @throws FilesMetadataNotFoundException if not found
  107. * @since 28.0.0
  108. */
  109. public function getMetadata(int $fileId, bool $generate = false): IFilesMetadata {
  110. try {
  111. return $this->metadataRequestService->getMetadataFromFileId($fileId);
  112. } catch (FilesMetadataNotFoundException $ex) {
  113. if ($generate) {
  114. return new FilesMetadata($fileId);
  115. }
  116. throw $ex;
  117. }
  118. }
  119. /**
  120. * returns metadata of multiple file ids
  121. *
  122. * @param int[] $fileIds file ids
  123. *
  124. * @return array File ID is the array key, files without metadata are not returned in the array
  125. * @psalm-return array<int, IFilesMetadata>
  126. * @since 28.0.0
  127. */
  128. public function getMetadataForFiles(array $fileIds): array {
  129. return $this->metadataRequestService->getMetadataFromFileIds($fileIds);
  130. }
  131. /**
  132. * @param IFilesMetadata $filesMetadata metadata
  133. *
  134. * @inheritDoc
  135. * @throws FilesMetadataException if metadata seems malformed
  136. * @since 28.0.0
  137. */
  138. public function saveMetadata(IFilesMetadata $filesMetadata): void {
  139. if ($filesMetadata->getFileId() === 0 || !$filesMetadata->updated()) {
  140. return;
  141. }
  142. $json = json_encode($filesMetadata->jsonSerialize());
  143. if (strlen($json) > self::JSON_MAXSIZE) {
  144. $this->logger->debug('huge metadata content detected: ' . $json);
  145. throw new FilesMetadataException('json cannot exceed ' . self::JSON_MAXSIZE . ' characters long; fileId: ' . $filesMetadata->getFileId() . '; size: ' . strlen($json));
  146. }
  147. try {
  148. if ($filesMetadata->getSyncToken() === '') {
  149. $this->metadataRequestService->store($filesMetadata);
  150. } else {
  151. $this->metadataRequestService->updateMetadata($filesMetadata);
  152. }
  153. } catch (DBException $e) {
  154. // most of the logged exception are the result of race condition
  155. // between 2 simultaneous process trying to create/update metadata
  156. $this->logger->warning('issue while saveMetadata', ['exception' => $e, 'metadata' => $filesMetadata]);
  157. return;
  158. }
  159. // update indexes
  160. foreach ($filesMetadata->getIndexes() as $index) {
  161. try {
  162. $this->indexRequestService->updateIndex($filesMetadata, $index);
  163. } catch (DBException $e) {
  164. $this->logger->warning('issue while updateIndex', ['exception' => $e]);
  165. }
  166. }
  167. // update metadata types list
  168. $current = $this->getKnownMetadata();
  169. $current->import($filesMetadata->jsonSerialize(true));
  170. $this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
  171. }
  172. /**
  173. * @param int $fileId file id
  174. *
  175. * @inheritDoc
  176. * @since 28.0.0
  177. */
  178. public function deleteMetadata(int $fileId): void {
  179. try {
  180. $this->metadataRequestService->dropMetadata($fileId);
  181. } catch (Exception $e) {
  182. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  183. }
  184. try {
  185. $this->indexRequestService->dropIndex($fileId);
  186. } catch (Exception $e) {
  187. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  188. }
  189. }
  190. /**
  191. * @param IQueryBuilder $qb
  192. * @param string $fileTableAlias alias of the table that contains data about files
  193. * @param string $fileIdField alias of the field that contains file ids
  194. *
  195. * @inheritDoc
  196. * @return IMetadataQuery
  197. * @see IMetadataQuery
  198. * @since 28.0.0
  199. */
  200. public function getMetadataQuery(
  201. IQueryBuilder $qb,
  202. string $fileTableAlias,
  203. string $fileIdField
  204. ): IMetadataQuery {
  205. return new MetadataQuery($qb, $this, $fileTableAlias, $fileIdField);
  206. }
  207. /**
  208. * @inheritDoc
  209. * @return IFilesMetadata
  210. * @since 28.0.0
  211. */
  212. public function getKnownMetadata(): IFilesMetadata {
  213. if ($this->all !== null) {
  214. return $this->all;
  215. }
  216. $this->all = new FilesMetadata();
  217. try {
  218. $this->all->import($this->appConfig->getValueArray('core', self::CONFIG_KEY, lazy: true));
  219. } catch (JsonException) {
  220. $this->logger->warning('issue while reading stored list of metadata. Advised to run ./occ files:scan --all --generate-metadata');
  221. }
  222. return $this->all;
  223. }
  224. /**
  225. * @param string $key metadata key
  226. * @param string $type metadata type
  227. * @param bool $indexed TRUE if metadata can be search
  228. * @param int $editPermission remote edit permission via Webdav PROPPATCH
  229. *
  230. * @inheritDoc
  231. * @since 28.0.0
  232. * @see IMetadataValueWrapper::TYPE_INT
  233. * @see IMetadataValueWrapper::TYPE_FLOAT
  234. * @see IMetadataValueWrapper::TYPE_BOOL
  235. * @see IMetadataValueWrapper::TYPE_ARRAY
  236. * @see IMetadataValueWrapper::TYPE_STRING_LIST
  237. * @see IMetadataValueWrapper::TYPE_INT_LIST
  238. * @see IMetadataValueWrapper::TYPE_STRING
  239. * @see IMetadataValueWrapper::EDIT_FORBIDDEN
  240. * @see IMetadataValueWrapper::EDIT_REQ_OWNERSHIP
  241. * @see IMetadataValueWrapper::EDIT_REQ_WRITE_PERMISSION
  242. * @see IMetadataValueWrapper::EDIT_REQ_READ_PERMISSION
  243. */
  244. public function initMetadata(
  245. string $key,
  246. string $type,
  247. bool $indexed = false,
  248. int $editPermission = IMetadataValueWrapper::EDIT_FORBIDDEN
  249. ): void {
  250. $current = $this->getKnownMetadata();
  251. try {
  252. if ($current->getType($key) === $type
  253. && $indexed === $current->isIndex($key)
  254. && $editPermission === $current->getEditPermission($key)) {
  255. return; // if key exists, with same type and indexed, we do nothing.
  256. }
  257. } catch (FilesMetadataNotFoundException) {
  258. // if value does not exist, we keep on the writing of course
  259. }
  260. $current->import([$key => ['type' => $type, 'indexed' => $indexed, 'editPermission' => $editPermission]]);
  261. $this->appConfig->setValueArray('core', self::CONFIG_KEY, $current->jsonSerialize(), lazy: true);
  262. $this->all = $current;
  263. }
  264. /**
  265. * load listeners
  266. *
  267. * @param IEventDispatcher $eventDispatcher
  268. */
  269. public static function loadListeners(IEventDispatcher $eventDispatcher): void {
  270. $eventDispatcher->addServiceListener(NodeWrittenEvent::class, MetadataUpdate::class);
  271. $eventDispatcher->addServiceListener(CacheEntryRemovedEvent::class, MetadataDelete::class);
  272. }
  273. }