You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

281 lines
8.8 KiB

  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\Model\MetadataQuery;
  31. use OC\FilesMetadata\Service\IndexRequestService;
  32. use OC\FilesMetadata\Service\MetadataRequestService;
  33. use OCP\BackgroundJob\IJobList;
  34. use OCP\DB\Exception;
  35. use OCP\DB\Exception as DBException;
  36. use OCP\DB\QueryBuilder\IQueryBuilder;
  37. use OCP\EventDispatcher\IEventDispatcher;
  38. use OCP\Files\Events\Node\NodeCreatedEvent;
  39. use OCP\Files\Events\Node\NodeDeletedEvent;
  40. use OCP\Files\Events\Node\NodeWrittenEvent;
  41. use OCP\Files\InvalidPathException;
  42. use OCP\Files\Node;
  43. use OCP\Files\NotFoundException;
  44. use OCP\FilesMetadata\Event\MetadataBackgroundEvent;
  45. use OCP\FilesMetadata\Event\MetadataLiveEvent;
  46. use OCP\FilesMetadata\Exceptions\FilesMetadataException;
  47. use OCP\FilesMetadata\Exceptions\FilesMetadataNotFoundException;
  48. use OCP\FilesMetadata\IFilesMetadataManager;
  49. use OCP\FilesMetadata\Model\IFilesMetadata;
  50. use OCP\FilesMetadata\Model\IMetadataQuery;
  51. use OCP\FilesMetadata\Model\IMetadataValueWrapper;
  52. use OCP\IConfig;
  53. use Psr\Log\LoggerInterface;
  54. /**
  55. * @inheritDoc
  56. * @since 28.0.0
  57. */
  58. class FilesMetadataManager implements IFilesMetadataManager {
  59. public const CONFIG_KEY = 'files_metadata';
  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 IConfig $config,
  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. ): IFilesMetadata {
  89. try {
  90. $metadata = $this->metadataRequestService->getMetadataFromFileId($node->getId());
  91. } catch (FilesMetadataNotFoundException) {
  92. $metadata = new FilesMetadata($node->getId());
  93. }
  94. // if $process is LIVE, we enforce LIVE
  95. if ((self::PROCESS_LIVE & $process) !== 0) {
  96. $event = new MetadataLiveEvent($node, $metadata);
  97. } else {
  98. $event = new MetadataBackgroundEvent($node, $metadata);
  99. }
  100. $this->eventDispatcher->dispatchTyped($event);
  101. $this->saveMetadata($event->getMetadata());
  102. // if requested, we add a new job for next cron to refresh metadata out of main thread
  103. // if $process was set to LIVE+BACKGROUND, we run background process directly
  104. if ($event instanceof MetadataLiveEvent && $event->isRunAsBackgroundJobRequested()) {
  105. if ((self::PROCESS_BACKGROUND & $process) !== 0) {
  106. return $this->refreshMetadata($node, self::PROCESS_BACKGROUND);
  107. }
  108. $this->jobList->add(UpdateSingleMetadata::class, [$node->getOwner()->getUID(), $node->getId()]);
  109. }
  110. return $metadata;
  111. }
  112. /**
  113. * @param int $fileId file id
  114. *
  115. * @inheritDoc
  116. * @return IFilesMetadata
  117. * @throws FilesMetadataNotFoundException if not found
  118. * @since 28.0.0
  119. */
  120. public function getMetadata(int $fileId): IFilesMetadata {
  121. return $this->metadataRequestService->getMetadataFromFileId($fileId);
  122. }
  123. /**
  124. * @param IFilesMetadata $filesMetadata metadata
  125. *
  126. * @inheritDoc
  127. * @throws FilesMetadataException if metadata seems malformed
  128. * @since 28.0.0
  129. */
  130. public function saveMetadata(IFilesMetadata $filesMetadata): void {
  131. if ($filesMetadata->getFileId() === 0 || !$filesMetadata->updated()) {
  132. return;
  133. }
  134. $json = json_encode($filesMetadata->jsonSerialize());
  135. if (strlen($json) > self::JSON_MAXSIZE) {
  136. throw new FilesMetadataException('json cannot exceed ' . self::JSON_MAXSIZE . ' characters long');
  137. }
  138. try {
  139. if ($filesMetadata->getSyncToken() === '') {
  140. $this->metadataRequestService->store($filesMetadata);
  141. } else {
  142. $this->metadataRequestService->updateMetadata($filesMetadata);
  143. }
  144. } catch (DBException $e) {
  145. // most of the logged exception are the result of race condition
  146. // between 2 simultaneous process trying to create/update metadata
  147. $this->logger->warning('issue while saveMetadata', ['exception' => $e, 'metadata' => $filesMetadata]);
  148. return;
  149. }
  150. // update indexes
  151. foreach ($filesMetadata->getIndexes() as $index) {
  152. try {
  153. $this->indexRequestService->updateIndex($filesMetadata, $index);
  154. } catch (DBException $e) {
  155. $this->logger->warning('issue while updateIndex', ['exception' => $e]);
  156. }
  157. }
  158. // update metadata types list
  159. $current = $this->getKnownMetadata();
  160. $current->import($filesMetadata->jsonSerialize(true));
  161. $this->config->setAppValue('core', self::CONFIG_KEY, json_encode($current));
  162. }
  163. /**
  164. * @param int $fileId file id
  165. *
  166. * @inheritDoc
  167. * @since 28.0.0
  168. */
  169. public function deleteMetadata(int $fileId): void {
  170. try {
  171. $this->metadataRequestService->dropMetadata($fileId);
  172. } catch (Exception $e) {
  173. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  174. }
  175. try {
  176. $this->indexRequestService->dropIndex($fileId);
  177. } catch (Exception $e) {
  178. $this->logger->warning('issue while deleteMetadata', ['exception' => $e, 'fileId' => $fileId]);
  179. }
  180. }
  181. /**
  182. * @param IQueryBuilder $qb
  183. * @param string $fileTableAlias alias of the table that contains data about files
  184. * @param string $fileIdField alias of the field that contains file ids
  185. *
  186. * @inheritDoc
  187. * @return IMetadataQuery
  188. * @see IMetadataQuery
  189. * @since 28.0.0
  190. */
  191. public function getMetadataQuery(
  192. IQueryBuilder $qb,
  193. string $fileTableAlias,
  194. string $fileIdField
  195. ): IMetadataQuery {
  196. return new MetadataQuery($qb, $this->getKnownMetadata(), $fileTableAlias, $fileIdField);
  197. }
  198. /**
  199. * @inheritDoc
  200. * @return IFilesMetadata
  201. * @since 28.0.0
  202. */
  203. public function getKnownMetadata(): IFilesMetadata {
  204. if (null !== $this->all) {
  205. return $this->all;
  206. }
  207. $this->all = new FilesMetadata();
  208. try {
  209. $data = json_decode($this->config->getAppValue('core', self::CONFIG_KEY, '[]'), true, 127, JSON_THROW_ON_ERROR);
  210. $this->all->import($data);
  211. } catch (JsonException) {
  212. $this->logger->warning('issue while reading stored list of metadata. Advised to run ./occ files:scan --all --generate-metadata');
  213. }
  214. return $this->all;
  215. }
  216. /**
  217. * @param string $key metadata key
  218. * @param string $type metadata type
  219. * @param bool $indexed TRUE if metadata can be search
  220. *
  221. * @inheritDoc
  222. * @since 28.0.0
  223. * @see IMetadataValueWrapper::TYPE_INT
  224. * @see IMetadataValueWrapper::TYPE_FLOAT
  225. * @see IMetadataValueWrapper::TYPE_BOOL
  226. * @see IMetadataValueWrapper::TYPE_ARRAY
  227. * @see IMetadataValueWrapper::TYPE_STRING_LIST
  228. * @see IMetadataValueWrapper::TYPE_INT_LIST
  229. * @see IMetadataValueWrapper::TYPE_STRING
  230. */
  231. public function initMetadata(string $key, string $type, bool $indexed): void {
  232. $current = $this->getKnownMetadata();
  233. try {
  234. if ($current->getType($key) === $type && $indexed === $current->isIndex($key)) {
  235. return; // if key exists, with same type and indexed, we do nothing.
  236. }
  237. } catch (FilesMetadataNotFoundException) {
  238. // if value does not exist, we keep on the writing of course
  239. }
  240. $current->import([$key => ['type' => $type, 'indexed' => $indexed]]);
  241. $this->config->setAppValue('core', self::CONFIG_KEY, json_encode($current));
  242. }
  243. /**
  244. * load listeners
  245. *
  246. * @param IEventDispatcher $eventDispatcher
  247. */
  248. public static function loadListeners(IEventDispatcher $eventDispatcher): void {
  249. $eventDispatcher->addServiceListener(NodeCreatedEvent::class, MetadataUpdate::class);
  250. $eventDispatcher->addServiceListener(NodeWrittenEvent::class, MetadataUpdate::class);
  251. $eventDispatcher->addServiceListener(NodeDeletedEvent::class, MetadataDelete::class);
  252. }
  253. }