Fetcher.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
  4. *
  5. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author John Molakvoæ <skjnldsv@protonmail.com>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Steffen Lindner <mail@steffen-lindner.de>
  14. *
  15. * @license GNU AGPL version 3 or any later version
  16. *
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License as
  19. * published by the Free Software Foundation, either version 3 of the
  20. * License, or (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. */
  31. namespace OC\App\AppStore\Fetcher;
  32. use GuzzleHttp\Exception\ConnectException;
  33. use OC\Files\AppData\Factory;
  34. use OCP\AppFramework\Http;
  35. use OCP\AppFramework\Utility\ITimeFactory;
  36. use OCP\Files\IAppData;
  37. use OCP\Files\NotFoundException;
  38. use OCP\Http\Client\IClientService;
  39. use OCP\IConfig;
  40. use OCP\Support\Subscription\IRegistry;
  41. use Psr\Log\LoggerInterface;
  42. abstract class Fetcher {
  43. public const INVALIDATE_AFTER_SECONDS = 3600;
  44. public const RETRY_AFTER_FAILURE_SECONDS = 300;
  45. public const APP_STORE_URL = 'https://apps.nextcloud.com/api/v1';
  46. /** @var IAppData */
  47. protected $appData;
  48. /** @var string */
  49. protected $fileName;
  50. /** @var string */
  51. protected $endpointName;
  52. /** @var ?string */
  53. protected $version = null;
  54. /** @var ?string */
  55. protected $channel = null;
  56. public function __construct(
  57. Factory $appDataFactory,
  58. protected IClientService $clientService,
  59. protected ITimeFactory $timeFactory,
  60. protected IConfig $config,
  61. protected LoggerInterface $logger,
  62. protected IRegistry $registry,
  63. ) {
  64. $this->appData = $appDataFactory->get('appstore');
  65. }
  66. /**
  67. * Fetches the response from the server
  68. *
  69. * @param string $ETag
  70. * @param string $content
  71. *
  72. * @return array
  73. */
  74. protected function fetch($ETag, $content) {
  75. $appstoreenabled = $this->config->getSystemValueBool('appstoreenabled', true);
  76. if ((int)$this->config->getAppValue('settings', 'appstore-fetcher-lastFailure', '0') > time() - self::RETRY_AFTER_FAILURE_SECONDS) {
  77. return [];
  78. }
  79. if (!$appstoreenabled) {
  80. return [];
  81. }
  82. $options = [
  83. 'timeout' => 60,
  84. ];
  85. if ($ETag !== '') {
  86. $options['headers'] = [
  87. 'If-None-Match' => $ETag,
  88. ];
  89. }
  90. if ($this->config->getSystemValueString('appstoreurl', self::APP_STORE_URL) === self::APP_STORE_URL) {
  91. // If we have a valid subscription key, send it to the appstore
  92. $subscriptionKey = $this->config->getAppValue('support', 'subscription_key');
  93. if ($this->registry->delegateHasValidSubscription() && $subscriptionKey) {
  94. $options['headers'] ??= [];
  95. $options['headers']['X-NC-Subscription-Key'] = $subscriptionKey;
  96. }
  97. }
  98. $client = $this->clientService->newClient();
  99. try {
  100. $response = $client->get($this->getEndpoint(), $options);
  101. } catch (ConnectException $e) {
  102. $this->config->setAppValue('settings', 'appstore-fetcher-lastFailure', (string)time());
  103. throw $e;
  104. }
  105. $responseJson = [];
  106. if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
  107. $responseJson['data'] = json_decode($content, true);
  108. } else {
  109. $responseJson['data'] = json_decode($response->getBody(), true);
  110. $ETag = $response->getHeader('ETag');
  111. }
  112. $this->config->deleteAppValue('settings', 'appstore-fetcher-lastFailure');
  113. $responseJson['timestamp'] = $this->timeFactory->getTime();
  114. $responseJson['ncversion'] = $this->getVersion();
  115. if ($ETag !== '') {
  116. $responseJson['ETag'] = $ETag;
  117. }
  118. return $responseJson;
  119. }
  120. /**
  121. * Returns the array with the entries on the appstore server
  122. *
  123. * @param bool [$allowUnstable] Allow unstable releases
  124. * @return array
  125. */
  126. public function get($allowUnstable = false) {
  127. $appstoreenabled = $this->config->getSystemValueBool('appstoreenabled', true);
  128. $internetavailable = $this->config->getSystemValueBool('has_internet_connection', true);
  129. $isDefaultAppStore = $this->config->getSystemValueString('appstoreurl', self::APP_STORE_URL) === self::APP_STORE_URL;
  130. if (!$appstoreenabled || (!$internetavailable && $isDefaultAppStore)) {
  131. return [];
  132. }
  133. $rootFolder = $this->appData->getFolder('/');
  134. $ETag = '';
  135. $content = '';
  136. try {
  137. // File does already exists
  138. $file = $rootFolder->getFile($this->fileName);
  139. $jsonBlob = json_decode($file->getContent(), true);
  140. // Always get latests apps info if $allowUnstable
  141. if (!$allowUnstable && is_array($jsonBlob)) {
  142. // No caching when the version has been updated
  143. if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
  144. // If the timestamp is older than 3600 seconds request the files new
  145. if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
  146. return $jsonBlob['data'];
  147. }
  148. if (isset($jsonBlob['ETag'])) {
  149. $ETag = $jsonBlob['ETag'];
  150. $content = json_encode($jsonBlob['data']);
  151. }
  152. }
  153. }
  154. } catch (NotFoundException $e) {
  155. // File does not already exists
  156. $file = $rootFolder->newFile($this->fileName);
  157. }
  158. // Refresh the file content
  159. try {
  160. $responseJson = $this->fetch($ETag, $content, $allowUnstable);
  161. if (empty($responseJson) || empty($responseJson['data'])) {
  162. return [];
  163. }
  164. // Don't store the apps request file
  165. if ($allowUnstable) {
  166. return $responseJson['data'];
  167. }
  168. $file->putContent(json_encode($responseJson));
  169. return json_decode($file->getContent(), true)['data'];
  170. } catch (ConnectException $e) {
  171. $this->logger->warning('Could not connect to appstore: ' . $e->getMessage(), ['app' => 'appstoreFetcher']);
  172. return [];
  173. } catch (\Exception $e) {
  174. $this->logger->warning($e->getMessage(), [
  175. 'exception' => $e,
  176. 'app' => 'appstoreFetcher',
  177. ]);
  178. return [];
  179. }
  180. }
  181. /**
  182. * Get the currently Nextcloud version
  183. * @return string
  184. */
  185. protected function getVersion() {
  186. if ($this->version === null) {
  187. $this->version = $this->config->getSystemValueString('version', '0.0.0');
  188. }
  189. return $this->version;
  190. }
  191. /**
  192. * Set the current Nextcloud version
  193. * @param string $version
  194. */
  195. public function setVersion(string $version) {
  196. $this->version = $version;
  197. }
  198. /**
  199. * Get the currently Nextcloud update channel
  200. * @return string
  201. */
  202. protected function getChannel() {
  203. if ($this->channel === null) {
  204. $this->channel = \OC_Util::getChannel();
  205. }
  206. return $this->channel;
  207. }
  208. /**
  209. * Set the current Nextcloud update channel
  210. * @param string $channel
  211. */
  212. public function setChannel(string $channel) {
  213. $this->channel = $channel;
  214. }
  215. protected function getEndpoint(): string {
  216. return $this->config->getSystemValueString('appstoreurl', 'https://apps.nextcloud.com/api/v1') . '/' . $this->endpointName;
  217. }
  218. }