FilesMetadataManager.php 10 KB

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