ReferenceManager.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. private Coordinator $coordinator;
  45. private ContainerInterface $container;
  46. private LinkReferenceProvider $linkReferenceProvider;
  47. private LoggerInterface $logger;
  48. private IConfig $config;
  49. private IUserSession $userSession;
  50. public function __construct(LinkReferenceProvider $linkReferenceProvider,
  51. ICacheFactory $cacheFactory,
  52. Coordinator $coordinator,
  53. ContainerInterface $container,
  54. LoggerInterface $logger,
  55. IConfig $config,
  56. IUserSession $userSession) {
  57. $this->linkReferenceProvider = $linkReferenceProvider;
  58. $this->cache = $cacheFactory->createDistributed('reference');
  59. $this->coordinator = $coordinator;
  60. $this->container = $container;
  61. $this->logger = $logger;
  62. $this->config = $config;
  63. $this->userSession = $userSession;
  64. }
  65. /**
  66. * Extract a list of URLs from a text
  67. *
  68. * @param string $text
  69. * @return string[]
  70. */
  71. public function extractReferences(string $text): array {
  72. preg_match_all(IURLGenerator::URL_REGEX, $text, $matches);
  73. $references = $matches[0] ?? [];
  74. return array_map(function ($reference) {
  75. return trim($reference);
  76. }, $references);
  77. }
  78. /**
  79. * Try to get a cached reference object from a reference string
  80. *
  81. * @param string $referenceId
  82. * @return IReference|null
  83. */
  84. public function getReferenceFromCache(string $referenceId): ?IReference {
  85. $matchedProvider = $this->getMatchedProvider($referenceId);
  86. if ($matchedProvider === null) {
  87. return null;
  88. }
  89. $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId);
  90. return $this->getReferenceByCacheKey($cacheKey);
  91. }
  92. /**
  93. * Try to get a cached reference object from a full cache key
  94. *
  95. * @param string $cacheKey
  96. * @return IReference|null
  97. */
  98. public function getReferenceByCacheKey(string $cacheKey): ?IReference {
  99. $cached = $this->cache->get($cacheKey);
  100. if ($cached) {
  101. return Reference::fromCache($cached);
  102. }
  103. return null;
  104. }
  105. /**
  106. * Get a reference object from a reference string with a matching provider
  107. * Use a cached reference if possible
  108. *
  109. * @param string $referenceId
  110. * @return IReference|null
  111. */
  112. public function resolveReference(string $referenceId): ?IReference {
  113. $matchedProvider = $this->getMatchedProvider($referenceId);
  114. if ($matchedProvider === null) {
  115. return null;
  116. }
  117. $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId);
  118. $cached = $this->cache->get($cacheKey);
  119. if ($cached) {
  120. return Reference::fromCache($cached);
  121. }
  122. $reference = $matchedProvider->resolveReference($referenceId);
  123. if ($reference) {
  124. $this->cache->set($cacheKey, Reference::toCache($reference), self::CACHE_TTL);
  125. return $reference;
  126. }
  127. return null;
  128. }
  129. /**
  130. * Try to match a reference string with all the registered providers
  131. * Fallback to the link reference provider (using OpenGraph)
  132. *
  133. * @param string $referenceId
  134. * @return IReferenceProvider|null the first matching provider
  135. */
  136. private function getMatchedProvider(string $referenceId): ?IReferenceProvider {
  137. $matchedProvider = null;
  138. foreach ($this->getProviders() as $provider) {
  139. $matchedProvider = $provider->matchReference($referenceId) ? $provider : null;
  140. if ($matchedProvider !== null) {
  141. break;
  142. }
  143. }
  144. if ($matchedProvider === null && $this->linkReferenceProvider->matchReference($referenceId)) {
  145. $matchedProvider = $this->linkReferenceProvider;
  146. }
  147. return $matchedProvider;
  148. }
  149. /**
  150. * Get a hashed full cache key from a key and prefix given by a provider
  151. *
  152. * @param IReferenceProvider $provider
  153. * @param string $referenceId
  154. * @return string
  155. */
  156. private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string {
  157. $cacheKey = $provider->getCacheKey($referenceId);
  158. return md5($provider->getCachePrefix($referenceId)) . (
  159. $cacheKey !== null ? ('-' . md5($cacheKey)) : ''
  160. );
  161. }
  162. /**
  163. * Remove a specific cache entry from its key+prefix
  164. *
  165. * @param string $cachePrefix
  166. * @param string|null $cacheKey
  167. * @return void
  168. */
  169. public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void {
  170. if ($cacheKey === null) {
  171. $this->cache->clear(md5($cachePrefix));
  172. return;
  173. }
  174. $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey));
  175. }
  176. /**
  177. * @return IReferenceProvider[]
  178. */
  179. public function getProviders(): array {
  180. if ($this->providers === null) {
  181. $context = $this->coordinator->getRegistrationContext();
  182. if ($context === null) {
  183. return [];
  184. }
  185. $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider {
  186. try {
  187. /** @var IReferenceProvider $provider */
  188. $provider = $this->container->get($registration->getService());
  189. } catch (Throwable $e) {
  190. $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [
  191. 'exception' => $e,
  192. ]);
  193. return null;
  194. }
  195. return $provider;
  196. }, $context->getReferenceProviders()));
  197. $this->providers[] = $this->container->get(FileReferenceProvider::class);
  198. }
  199. return $this->providers;
  200. }
  201. /**
  202. * @inheritDoc
  203. */
  204. public function getDiscoverableProviders(): array {
  205. // preserve 0 based index to avoid returning an object in data responses
  206. return array_values(
  207. array_filter($this->getProviders(), static function (IReferenceProvider $provider) {
  208. return $provider instanceof IDiscoverableReferenceProvider;
  209. })
  210. );
  211. }
  212. /**
  213. * @inheritDoc
  214. */
  215. public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool {
  216. $providers = $this->getDiscoverableProviders();
  217. $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) {
  218. return $provider->getId() === $providerId;
  219. });
  220. if (!empty($matchingProviders)) {
  221. if ($timestamp === null) {
  222. $timestamp = time();
  223. }
  224. $configKey = 'provider-last-use_' . $providerId;
  225. $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp);
  226. return true;
  227. }
  228. return false;
  229. }
  230. /**
  231. * @inheritDoc
  232. */
  233. public function getUserProviderTimestamps(): array {
  234. $user = $this->userSession->getUser();
  235. if ($user === null) {
  236. return [];
  237. }
  238. $userId = $user->getUID();
  239. $keys = $this->config->getUserKeys($userId, 'references');
  240. $prefix = 'provider-last-use_';
  241. $keys = array_filter($keys, static function (string $key) use ($prefix) {
  242. return str_starts_with($key, $prefix);
  243. });
  244. $timestamps = [];
  245. foreach ($keys as $key) {
  246. $providerId = substr($key, strlen($prefix));
  247. $timestamp = (int) $this->config->getUserValue($userId, 'references', $key);
  248. $timestamps[$providerId] = $timestamp;
  249. }
  250. return $timestamps;
  251. }
  252. }