Fetcher.php 7.7 KB

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