1
0

ReferenceManager.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2022 Julius Härtl <jus@bitgrid.net>
  5. *
  6. * @author Julius Härtl <jus@bitgrid.net>
  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. namespace OC\Collaboration\Reference;
  24. use OC\AppFramework\Bootstrap\Coordinator;
  25. use OC\Collaboration\Reference\File\FileReferenceProvider;
  26. use OCP\Collaboration\Reference\IDiscoverableReferenceProvider;
  27. use OCP\Collaboration\Reference\IReference;
  28. use OCP\Collaboration\Reference\IReferenceManager;
  29. use OCP\Collaboration\Reference\IReferenceProvider;
  30. use OCP\Collaboration\Reference\Reference;
  31. use OCP\ICache;
  32. use OCP\ICacheFactory;
  33. use OCP\IConfig;
  34. use OCP\IURLGenerator;
  35. use OCP\IUserSession;
  36. use Psr\Container\ContainerInterface;
  37. use Psr\Log\LoggerInterface;
  38. use Throwable;
  39. class ReferenceManager implements IReferenceManager {
  40. public const CACHE_TTL = 3600;
  41. /** @var IReferenceProvider[]|null */
  42. private ?array $providers = null;
  43. private ICache $cache;
  44. public function __construct(
  45. private LinkReferenceProvider $linkReferenceProvider,
  46. ICacheFactory $cacheFactory,
  47. private Coordinator $coordinator,
  48. private ContainerInterface $container,
  49. private LoggerInterface $logger,
  50. private IConfig $config,
  51. private IUserSession $userSession,
  52. ) {
  53. $this->cache = $cacheFactory->createDistributed('reference');
  54. }
  55. /**
  56. * Extract a list of URLs from a text
  57. *
  58. * @return string[]
  59. */
  60. public function extractReferences(string $text): array {
  61. preg_match_all(IURLGenerator::URL_REGEX, $text, $matches);
  62. $references = $matches[0] ?? [];
  63. return array_map(function ($reference) {
  64. return trim($reference);
  65. }, $references);
  66. }
  67. /**
  68. * Try to get a cached reference object from a reference string
  69. */
  70. public function getReferenceFromCache(string $referenceId): ?IReference {
  71. $matchedProvider = $this->getMatchedProvider($referenceId);
  72. if ($matchedProvider === null) {
  73. return null;
  74. }
  75. $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId);
  76. return $this->getReferenceByCacheKey($cacheKey);
  77. }
  78. /**
  79. * Try to get a cached reference object from a full cache key
  80. */
  81. public function getReferenceByCacheKey(string $cacheKey): ?IReference {
  82. $cached = $this->cache->get($cacheKey);
  83. if ($cached) {
  84. return Reference::fromCache($cached);
  85. }
  86. return null;
  87. }
  88. /**
  89. * Get a reference object from a reference string with a matching provider
  90. * Use a cached reference if possible
  91. */
  92. public function resolveReference(string $referenceId): ?IReference {
  93. $matchedProvider = $this->getMatchedProvider($referenceId);
  94. if ($matchedProvider === null) {
  95. return null;
  96. }
  97. $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId);
  98. $cached = $this->cache->get($cacheKey);
  99. if ($cached) {
  100. return Reference::fromCache($cached);
  101. }
  102. $reference = $matchedProvider->resolveReference($referenceId);
  103. if ($reference) {
  104. $cachePrefix = $matchedProvider->getCachePrefix($referenceId);
  105. if ($cachePrefix !== '') {
  106. // If a prefix is used we set an additional key to know when we need to delete by prefix during invalidateCache()
  107. $this->cache->set('hasPrefix-' . md5($cachePrefix), true, self::CACHE_TTL);
  108. }
  109. $this->cache->set($cacheKey, Reference::toCache($reference), self::CACHE_TTL);
  110. return $reference;
  111. }
  112. return null;
  113. }
  114. /**
  115. * Try to match a reference string with all the registered providers
  116. * Fallback to the link reference provider (using OpenGraph)
  117. *
  118. * @return IReferenceProvider|null the first matching provider
  119. */
  120. private function getMatchedProvider(string $referenceId): ?IReferenceProvider {
  121. $matchedProvider = null;
  122. foreach ($this->getProviders() as $provider) {
  123. $matchedProvider = $provider->matchReference($referenceId) ? $provider : null;
  124. if ($matchedProvider !== null) {
  125. break;
  126. }
  127. }
  128. if ($matchedProvider === null && $this->linkReferenceProvider->matchReference($referenceId)) {
  129. $matchedProvider = $this->linkReferenceProvider;
  130. }
  131. return $matchedProvider;
  132. }
  133. /**
  134. * Get a hashed full cache key from a key and prefix given by a provider
  135. */
  136. private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string {
  137. $cacheKey = $provider->getCacheKey($referenceId);
  138. return md5($provider->getCachePrefix($referenceId)) . (
  139. $cacheKey !== null ? ('-' . md5($cacheKey)) : ''
  140. );
  141. }
  142. /**
  143. * Remove a specific cache entry from its key+prefix
  144. */
  145. public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void {
  146. if ($cacheKey === null) {
  147. // clear might be a heavy operation, so we only do it if there have actually been keys set
  148. if ($this->cache->remove('hasPrefix-' . md5($cachePrefix))) {
  149. $this->cache->clear(md5($cachePrefix));
  150. }
  151. return;
  152. }
  153. $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey));
  154. }
  155. /**
  156. * @return IReferenceProvider[]
  157. */
  158. public function getProviders(): array {
  159. if ($this->providers === null) {
  160. $context = $this->coordinator->getRegistrationContext();
  161. if ($context === null) {
  162. return [];
  163. }
  164. $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider {
  165. try {
  166. /** @var IReferenceProvider $provider */
  167. $provider = $this->container->get($registration->getService());
  168. } catch (Throwable $e) {
  169. $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [
  170. 'exception' => $e,
  171. ]);
  172. return null;
  173. }
  174. return $provider;
  175. }, $context->getReferenceProviders()));
  176. $this->providers[] = $this->container->get(FileReferenceProvider::class);
  177. }
  178. return $this->providers;
  179. }
  180. /**
  181. * @inheritDoc
  182. */
  183. public function getDiscoverableProviders(): array {
  184. // preserve 0 based index to avoid returning an object in data responses
  185. return array_values(
  186. array_filter($this->getProviders(), static function (IReferenceProvider $provider) {
  187. return $provider instanceof IDiscoverableReferenceProvider;
  188. })
  189. );
  190. }
  191. /**
  192. * @inheritDoc
  193. */
  194. public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool {
  195. $providers = $this->getDiscoverableProviders();
  196. $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) {
  197. return $provider->getId() === $providerId;
  198. });
  199. if (!empty($matchingProviders)) {
  200. if ($timestamp === null) {
  201. $timestamp = time();
  202. }
  203. $configKey = 'provider-last-use_' . $providerId;
  204. $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp);
  205. return true;
  206. }
  207. return false;
  208. }
  209. /**
  210. * @inheritDoc
  211. */
  212. public function getUserProviderTimestamps(): array {
  213. $user = $this->userSession->getUser();
  214. if ($user === null) {
  215. return [];
  216. }
  217. $userId = $user->getUID();
  218. $keys = $this->config->getUserKeys($userId, 'references');
  219. $prefix = 'provider-last-use_';
  220. $keys = array_filter($keys, static function (string $key) use ($prefix) {
  221. return str_starts_with($key, $prefix);
  222. });
  223. $timestamps = [];
  224. foreach ($keys as $key) {
  225. $providerId = substr($key, strlen($prefix));
  226. $timestamp = (int) $this->config->getUserValue($userId, 'references', $key);
  227. $timestamps[$providerId] = $timestamp;
  228. }
  229. return $timestamps;
  230. }
  231. }