Fetcher.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\App\AppStore\Fetcher;
  7. use GuzzleHttp\Exception\ConnectException;
  8. use OC\Files\AppData\Factory;
  9. use OCP\AppFramework\Http;
  10. use OCP\AppFramework\Utility\ITimeFactory;
  11. use OCP\Files\IAppData;
  12. use OCP\Files\NotFoundException;
  13. use OCP\Http\Client\IClientService;
  14. use OCP\IConfig;
  15. use OCP\Support\Subscription\IRegistry;
  16. use Psr\Log\LoggerInterface;
  17. abstract class Fetcher {
  18. public const INVALIDATE_AFTER_SECONDS = 3600;
  19. public const INVALIDATE_AFTER_SECONDS_UNSTABLE = 900;
  20. public const RETRY_AFTER_FAILURE_SECONDS = 300;
  21. public const APP_STORE_URL = 'https://apps.nextcloud.com/api/v1';
  22. /** @var IAppData */
  23. protected $appData;
  24. /** @var string */
  25. protected $fileName;
  26. /** @var string */
  27. protected $endpointName;
  28. /** @var ?string */
  29. protected $version = null;
  30. /** @var ?string */
  31. protected $channel = null;
  32. public function __construct(
  33. Factory $appDataFactory,
  34. protected IClientService $clientService,
  35. protected ITimeFactory $timeFactory,
  36. protected IConfig $config,
  37. protected LoggerInterface $logger,
  38. protected IRegistry $registry,
  39. ) {
  40. $this->appData = $appDataFactory->get('appstore');
  41. }
  42. /**
  43. * Fetches the response from the server
  44. *
  45. * @param string $ETag
  46. * @param string $content
  47. *
  48. * @return array
  49. */
  50. protected function fetch($ETag, $content) {
  51. $appstoreenabled = $this->config->getSystemValueBool('appstoreenabled', true);
  52. if ((int)$this->config->getAppValue('settings', 'appstore-fetcher-lastFailure', '0') > time() - self::RETRY_AFTER_FAILURE_SECONDS) {
  53. return [];
  54. }
  55. if (!$appstoreenabled) {
  56. return [];
  57. }
  58. $options = [
  59. 'timeout' => 60,
  60. ];
  61. if ($ETag !== '') {
  62. $options['headers'] = [
  63. 'If-None-Match' => $ETag,
  64. ];
  65. }
  66. if ($this->config->getSystemValueString('appstoreurl', self::APP_STORE_URL) === self::APP_STORE_URL) {
  67. // If we have a valid subscription key, send it to the appstore
  68. $subscriptionKey = $this->config->getAppValue('support', 'subscription_key');
  69. if ($this->registry->delegateHasValidSubscription() && $subscriptionKey) {
  70. $options['headers'] ??= [];
  71. $options['headers']['X-NC-Subscription-Key'] = $subscriptionKey;
  72. }
  73. }
  74. $client = $this->clientService->newClient();
  75. try {
  76. $response = $client->get($this->getEndpoint(), $options);
  77. } catch (ConnectException $e) {
  78. $this->config->setAppValue('settings', 'appstore-fetcher-lastFailure', (string)time());
  79. $this->logger->error('Failed to connect to the app store', ['exception' => $e]);
  80. return [];
  81. }
  82. $responseJson = [];
  83. if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
  84. $responseJson['data'] = json_decode($content, true);
  85. } else {
  86. $responseJson['data'] = json_decode($response->getBody(), true);
  87. $ETag = $response->getHeader('ETag');
  88. }
  89. $this->config->deleteAppValue('settings', 'appstore-fetcher-lastFailure');
  90. $responseJson['timestamp'] = $this->timeFactory->getTime();
  91. $responseJson['ncversion'] = $this->getVersion();
  92. if ($ETag !== '') {
  93. $responseJson['ETag'] = $ETag;
  94. }
  95. return $responseJson;
  96. }
  97. /**
  98. * Returns the array with the entries on the appstore server
  99. *
  100. * @param bool [$allowUnstable] Allow unstable releases
  101. * @return array
  102. */
  103. public function get($allowUnstable = false) {
  104. $appstoreenabled = $this->config->getSystemValueBool('appstoreenabled', true);
  105. $internetavailable = $this->config->getSystemValueBool('has_internet_connection', true);
  106. $isDefaultAppStore = $this->config->getSystemValueString('appstoreurl', self::APP_STORE_URL) === self::APP_STORE_URL;
  107. if (!$appstoreenabled || (!$internetavailable && $isDefaultAppStore)) {
  108. $this->logger->info('AppStore is disabled or this instance has no Internet connection to access the default app store', ['app' => 'appstoreFetcher']);
  109. return [];
  110. }
  111. $rootFolder = $this->appData->getFolder('/');
  112. $ETag = '';
  113. $content = '';
  114. try {
  115. // File does already exists
  116. $file = $rootFolder->getFile($this->fileName);
  117. $jsonBlob = json_decode($file->getContent(), true);
  118. if (is_array($jsonBlob)) {
  119. // No caching when the version has been updated
  120. if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
  121. // If the timestamp is older than 3600 seconds request the files new
  122. $invalidateAfterSeconds = self::INVALIDATE_AFTER_SECONDS;
  123. if ($allowUnstable) {
  124. $invalidateAfterSeconds = self::INVALIDATE_AFTER_SECONDS_UNSTABLE;
  125. }
  126. if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - $invalidateAfterSeconds)) {
  127. return $jsonBlob['data'];
  128. }
  129. if (isset($jsonBlob['ETag'])) {
  130. $ETag = $jsonBlob['ETag'];
  131. $content = json_encode($jsonBlob['data']);
  132. }
  133. }
  134. }
  135. } catch (NotFoundException $e) {
  136. // File does not already exists
  137. $file = $rootFolder->newFile($this->fileName);
  138. }
  139. // Refresh the file content
  140. try {
  141. $responseJson = $this->fetch($ETag, $content, $allowUnstable);
  142. if (empty($responseJson) || empty($responseJson['data'])) {
  143. return [];
  144. }
  145. $file->putContent(json_encode($responseJson));
  146. return json_decode($file->getContent(), true)['data'];
  147. } catch (ConnectException $e) {
  148. $this->logger->warning('Could not connect to appstore: ' . $e->getMessage(), ['app' => 'appstoreFetcher']);
  149. return [];
  150. } catch (\Exception $e) {
  151. $this->logger->warning($e->getMessage(), [
  152. 'exception' => $e,
  153. 'app' => 'appstoreFetcher',
  154. ]);
  155. return [];
  156. }
  157. }
  158. /**
  159. * Get the currently Nextcloud version
  160. * @return string
  161. */
  162. protected function getVersion() {
  163. if ($this->version === null) {
  164. $this->version = $this->config->getSystemValueString('version', '0.0.0');
  165. }
  166. return $this->version;
  167. }
  168. /**
  169. * Set the current Nextcloud version
  170. * @param string $version
  171. */
  172. public function setVersion(string $version) {
  173. $this->version = $version;
  174. }
  175. /**
  176. * Get the currently Nextcloud update channel
  177. * @return string
  178. */
  179. protected function getChannel() {
  180. if ($this->channel === null) {
  181. $this->channel = \OC_Util::getChannel();
  182. }
  183. return $this->channel;
  184. }
  185. /**
  186. * Set the current Nextcloud update channel
  187. * @param string $channel
  188. */
  189. public function setChannel(string $channel) {
  190. $this->channel = $channel;
  191. }
  192. protected function getEndpoint(): string {
  193. return $this->config->getSystemValueString('appstoreurl', 'https://apps.nextcloud.com/api/v1') . '/' . $this->endpointName;
  194. }
  195. }