Fetcher.php 6.1 KB

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