ReferenceManager.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. $this->cache->set($cacheKey, Reference::toCache($reference), self::CACHE_TTL);
  105. return $reference;
  106. }
  107. return null;
  108. }
  109. /**
  110. * Try to match a reference string with all the registered providers
  111. * Fallback to the link reference provider (using OpenGraph)
  112. *
  113. * @return IReferenceProvider|null the first matching provider
  114. */
  115. private function getMatchedProvider(string $referenceId): ?IReferenceProvider {
  116. $matchedProvider = null;
  117. foreach ($this->getProviders() as $provider) {
  118. $matchedProvider = $provider->matchReference($referenceId) ? $provider : null;
  119. if ($matchedProvider !== null) {
  120. break;
  121. }
  122. }
  123. if ($matchedProvider === null && $this->linkReferenceProvider->matchReference($referenceId)) {
  124. $matchedProvider = $this->linkReferenceProvider;
  125. }
  126. return $matchedProvider;
  127. }
  128. /**
  129. * Get a hashed full cache key from a key and prefix given by a provider
  130. */
  131. private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string {
  132. $cacheKey = $provider->getCacheKey($referenceId);
  133. return md5($provider->getCachePrefix($referenceId)) . (
  134. $cacheKey !== null ? ('-' . md5($cacheKey)) : ''
  135. );
  136. }
  137. /**
  138. * Remove a specific cache entry from its key+prefix
  139. */
  140. public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void {
  141. if ($cacheKey === null) {
  142. $this->cache->clear(md5($cachePrefix));
  143. return;
  144. }
  145. $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey));
  146. }
  147. /**
  148. * @return IReferenceProvider[]
  149. */
  150. public function getProviders(): array {
  151. if ($this->providers === null) {
  152. $context = $this->coordinator->getRegistrationContext();
  153. if ($context === null) {
  154. return [];
  155. }
  156. $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider {
  157. try {
  158. /** @var IReferenceProvider $provider */
  159. $provider = $this->container->get($registration->getService());
  160. } catch (Throwable $e) {
  161. $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [
  162. 'exception' => $e,
  163. ]);
  164. return null;
  165. }
  166. return $provider;
  167. }, $context->getReferenceProviders()));
  168. $this->providers[] = $this->container->get(FileReferenceProvider::class);
  169. }
  170. return $this->providers;
  171. }
  172. /**
  173. * @inheritDoc
  174. */
  175. public function getDiscoverableProviders(): array {
  176. // preserve 0 based index to avoid returning an object in data responses
  177. return array_values(
  178. array_filter($this->getProviders(), static function (IReferenceProvider $provider) {
  179. return $provider instanceof IDiscoverableReferenceProvider;
  180. })
  181. );
  182. }
  183. /**
  184. * @inheritDoc
  185. */
  186. public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool {
  187. $providers = $this->getDiscoverableProviders();
  188. $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) {
  189. return $provider->getId() === $providerId;
  190. });
  191. if (!empty($matchingProviders)) {
  192. if ($timestamp === null) {
  193. $timestamp = time();
  194. }
  195. $configKey = 'provider-last-use_' . $providerId;
  196. $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp);
  197. return true;
  198. }
  199. return false;
  200. }
  201. /**
  202. * @inheritDoc
  203. */
  204. public function getUserProviderTimestamps(): array {
  205. $user = $this->userSession->getUser();
  206. if ($user === null) {
  207. return [];
  208. }
  209. $userId = $user->getUID();
  210. $keys = $this->config->getUserKeys($userId, 'references');
  211. $prefix = 'provider-last-use_';
  212. $keys = array_filter($keys, static function (string $key) use ($prefix) {
  213. return str_starts_with($key, $prefix);
  214. });
  215. $timestamps = [];
  216. foreach ($keys as $key) {
  217. $providerId = substr($key, strlen($prefix));
  218. $timestamp = (int) $this->config->getUserValue($userId, 'references', $key);
  219. $timestamps[$providerId] = $timestamp;
  220. }
  221. return $timestamps;
  222. }
  223. }