WeatherStatusService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\WeatherStatus\Service;
  8. use OCA\WeatherStatus\AppInfo\Application;
  9. use OCA\WeatherStatus\ResponseDefinitions;
  10. use OCP\Accounts\IAccountManager;
  11. use OCP\Accounts\PropertyDoesNotExistException;
  12. use OCP\App\IAppManager;
  13. use OCP\Http\Client\IClient;
  14. use OCP\Http\Client\IClientService;
  15. use OCP\ICache;
  16. use OCP\ICacheFactory;
  17. use OCP\IConfig;
  18. use OCP\IL10N;
  19. use OCP\IUserManager;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * Class WeatherStatusService
  23. *
  24. * @package OCA\WeatherStatus\Service
  25. *
  26. * @psalm-import-type WeatherStatusForecast from ResponseDefinitions
  27. * @psalm-import-type WeatherStatusSuccess from ResponseDefinitions
  28. * @psalm-import-type WeatherStatusLocationWithSuccess from ResponseDefinitions
  29. * @psalm-import-type WeatherStatusLocationWithMode from ResponseDefinitions
  30. */
  31. class WeatherStatusService {
  32. public const MODE_BROWSER_LOCATION = 1;
  33. public const MODE_MANUAL_LOCATION = 2;
  34. private IClient $client;
  35. private ICache $cache;
  36. private string $version;
  37. public function __construct(
  38. private IClientService $clientService,
  39. private IConfig $config,
  40. private IL10N $l10n,
  41. private LoggerInterface $logger,
  42. private IAccountManager $accountManager,
  43. private IUserManager $userManager,
  44. private IAppManager $appManager,
  45. private ICacheFactory $cacheFactory,
  46. private ?string $userId,
  47. ) {
  48. $this->version = $appManager->getAppVersion(Application::APP_ID);
  49. $this->client = $clientService->newClient();
  50. $this->cache = $cacheFactory->createDistributed('weatherstatus');
  51. }
  52. /**
  53. * Change the weather status mode. There are currently 2 modes:
  54. * - ask the browser
  55. * - use the user defined address
  56. * @param int $mode New mode
  57. * @return WeatherStatusSuccess success state
  58. */
  59. public function setMode(int $mode): array {
  60. $this->config->setUserValue($this->userId, Application::APP_ID, 'mode', strval($mode));
  61. return ['success' => true];
  62. }
  63. /**
  64. * Get favorites list
  65. * @return list<string>
  66. */
  67. public function getFavorites(): array {
  68. $favoritesJson = $this->config->getUserValue($this->userId, Application::APP_ID, 'favorites', '');
  69. return json_decode($favoritesJson, true) ?: [];
  70. }
  71. /**
  72. * Set favorites list
  73. * @param list<string> $favorites
  74. * @return WeatherStatusSuccess success state
  75. */
  76. public function setFavorites(array $favorites): array {
  77. $this->config->setUserValue($this->userId, Application::APP_ID, 'favorites', json_encode($favorites));
  78. return ['success' => true];
  79. }
  80. /**
  81. * Try to use the address set in user personal settings as weather location
  82. *
  83. * @return WeatherStatusLocationWithSuccess with success state and address information
  84. */
  85. public function usePersonalAddress(): array {
  86. $account = $this->accountManager->getAccount($this->userManager->get($this->userId));
  87. try {
  88. $address = $account->getProperty('address')->getValue();
  89. } catch (PropertyDoesNotExistException $e) {
  90. return ['success' => false];
  91. }
  92. if ($address === '') {
  93. return ['success' => false];
  94. }
  95. return $this->setAddress($address);
  96. }
  97. /**
  98. * Set address and resolve it to get coordinates
  99. * or directly set coordinates and get address with reverse geocoding
  100. *
  101. * @param string|null $address Any approximative or exact address
  102. * @param float|null $lat Latitude in decimal degree format
  103. * @param float|null $lon Longitude in decimal degree format
  104. * @return WeatherStatusLocationWithSuccess with success state and address information
  105. */
  106. public function setLocation(?string $address, ?float $lat, ?float $lon): array {
  107. if (!is_null($lat) && !is_null($lon)) {
  108. // store coordinates
  109. $this->config->setUserValue($this->userId, Application::APP_ID, 'lat', strval($lat));
  110. $this->config->setUserValue($this->userId, Application::APP_ID, 'lon', strval($lon));
  111. // resolve and store formatted address
  112. $address = $this->resolveLocation($lat, $lon);
  113. $address = $address ?: $this->l10n->t('Unknown address');
  114. $this->config->setUserValue($this->userId, Application::APP_ID, 'address', $address);
  115. // get and store altitude
  116. $altitude = $this->getAltitude($lat, $lon);
  117. $this->config->setUserValue($this->userId, Application::APP_ID, 'altitude', strval($altitude));
  118. return [
  119. 'address' => $address,
  120. 'success' => true,
  121. ];
  122. } elseif ($address) {
  123. return $this->setAddress($address);
  124. } else {
  125. return ['success' => false];
  126. }
  127. }
  128. /**
  129. * Provide address information from coordinates
  130. *
  131. * @param float $lat Latitude in decimal degree format
  132. * @param float $lon Longitude in decimal degree format
  133. */
  134. private function resolveLocation(float $lat, float $lon): ?string {
  135. $params = [
  136. 'lat' => number_format($lat, 2),
  137. 'lon' => number_format($lon, 2),
  138. 'addressdetails' => 1,
  139. 'format' => 'json',
  140. ];
  141. $url = 'https://nominatim.openstreetmap.org/reverse';
  142. $result = $this->requestJSON($url, $params);
  143. return $this->formatOsmAddress($result);
  144. }
  145. /**
  146. * Get altitude from coordinates
  147. *
  148. * @param float $lat Latitude in decimal degree format
  149. * @param float $lon Longitude in decimal degree format
  150. * @return float altitude in meter
  151. */
  152. private function getAltitude(float $lat, float $lon): float {
  153. $params = [
  154. 'locations' => $lat . ',' . $lon,
  155. ];
  156. $url = 'https://api.opentopodata.org/v1/srtm30m';
  157. $result = $this->requestJSON($url, $params);
  158. $altitude = 0;
  159. if (isset($result['results']) && is_array($result['results']) && count($result['results']) > 0
  160. && is_array($result['results'][0]) && isset($result['results'][0]['elevation'])) {
  161. $altitude = floatval($result['results'][0]['elevation']);
  162. }
  163. return $altitude;
  164. }
  165. /**
  166. * @return string Formatted address from JSON nominatim result
  167. */
  168. private function formatOsmAddress(array $json): ?string {
  169. if (isset($json['address']) && isset($json['display_name'])) {
  170. $jsonAddr = $json['address'];
  171. $cityAddress = '';
  172. // priority : city, town, village, municipality
  173. if (isset($jsonAddr['city'])) {
  174. $cityAddress .= $jsonAddr['city'];
  175. } elseif (isset($jsonAddr['town'])) {
  176. $cityAddress .= $jsonAddr['town'];
  177. } elseif (isset($jsonAddr['village'])) {
  178. $cityAddress .= $jsonAddr['village'];
  179. } elseif (isset($jsonAddr['municipality'])) {
  180. $cityAddress .= $jsonAddr['municipality'];
  181. } else {
  182. return $json['display_name'];
  183. }
  184. // post code
  185. if (isset($jsonAddr['postcode'])) {
  186. $cityAddress .= ', ' . $jsonAddr['postcode'];
  187. }
  188. // country
  189. if (isset($jsonAddr['country'])) {
  190. $cityAddress .= ', ' . $jsonAddr['country'];
  191. return $cityAddress;
  192. } else {
  193. return $json['display_name'];
  194. }
  195. } elseif (isset($json['display_name'])) {
  196. return $json['display_name'];
  197. }
  198. return null;
  199. }
  200. /**
  201. * Set address and resolve it to get coordinates
  202. *
  203. * @param string $address Any approximative or exact address
  204. * @return WeatherStatusLocationWithSuccess with success state and address information (coordinates and formatted address)
  205. */
  206. public function setAddress(string $address): array {
  207. $addressInfo = $this->searchForAddress($address);
  208. if (isset($addressInfo['display_name']) && isset($addressInfo['lat']) && isset($addressInfo['lon'])) {
  209. $formattedAddress = $this->formatOsmAddress($addressInfo);
  210. $this->config->setUserValue($this->userId, Application::APP_ID, 'address', $formattedAddress);
  211. $this->config->setUserValue($this->userId, Application::APP_ID, 'lat', strval($addressInfo['lat']));
  212. $this->config->setUserValue($this->userId, Application::APP_ID, 'lon', strval($addressInfo['lon']));
  213. $this->config->setUserValue($this->userId, Application::APP_ID, 'mode', strval(self::MODE_MANUAL_LOCATION));
  214. // get and store altitude
  215. $altitude = $this->getAltitude(floatval($addressInfo['lat']), floatval($addressInfo['lon']));
  216. $this->config->setUserValue($this->userId, Application::APP_ID, 'altitude', strval($altitude));
  217. return [
  218. 'lat' => $addressInfo['lat'],
  219. 'lon' => $addressInfo['lon'],
  220. 'address' => $formattedAddress,
  221. 'success' => true,
  222. ];
  223. } else {
  224. return ['success' => false];
  225. }
  226. }
  227. /**
  228. * Ask nominatim information about an unformatted address
  229. *
  230. * @param string Unformatted address
  231. * @return array{display_name?: string, lat?: string, lon?: string, error?: string} Full Nominatim result for the given address
  232. */
  233. private function searchForAddress(string $address): array {
  234. $params = [
  235. 'q' => $address,
  236. 'format' => 'json',
  237. 'addressdetails' => '1',
  238. 'extratags' => '1',
  239. 'namedetails' => '1',
  240. 'limit' => '1',
  241. ];
  242. $url = 'https://nominatim.openstreetmap.org/search';
  243. $results = $this->requestJSON($url, $params);
  244. if ($results['error'] !== null) {
  245. return $results;
  246. }
  247. if (count($results) > 0) {
  248. return $results[0];
  249. }
  250. return ['error' => $this->l10n->t('No result.')];
  251. }
  252. /**
  253. * Get stored user location
  254. *
  255. * @return WeatherStatusLocationWithMode which contains coordinates, formatted address and current weather status mode
  256. */
  257. public function getLocation(): array {
  258. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  259. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  260. $address = $this->config->getUserValue($this->userId, Application::APP_ID, 'address', '');
  261. $mode = $this->config->getUserValue($this->userId, Application::APP_ID, 'mode', self::MODE_MANUAL_LOCATION);
  262. return [
  263. 'lat' => $lat,
  264. 'lon' => $lon,
  265. 'address' => $address,
  266. 'mode' => intval($mode),
  267. ];
  268. }
  269. /**
  270. * Get forecast for current location
  271. *
  272. * @return list<WeatherStatusForecast>|array{error: string}|WeatherStatusSuccess which contains success state and filtered forecast data
  273. */
  274. public function getForecast(): array {
  275. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  276. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  277. $alt = $this->config->getUserValue($this->userId, Application::APP_ID, 'altitude', '');
  278. if (!is_numeric($alt)) {
  279. $alt = 0;
  280. }
  281. if (is_numeric($lat) && is_numeric($lon)) {
  282. return $this->forecastRequest(floatval($lat), floatval($lon), floatval($alt));
  283. } else {
  284. return ['success' => false];
  285. }
  286. }
  287. /**
  288. * Actually make the request to the forecast service
  289. *
  290. * @param float $lat Latitude of requested forecast, in decimal degree format
  291. * @param float $lon Longitude of requested forecast, in decimal degree format
  292. * @param float $altitude Altitude of requested forecast, in meter
  293. * @param int $nbValues Number of forecast values (hours)
  294. * @return list<WeatherStatusForecast>|array{error: string} Filtered forecast data
  295. */
  296. private function forecastRequest(float $lat, float $lon, float $altitude, int $nbValues = 10): array {
  297. $params = [
  298. 'lat' => number_format($lat, 2),
  299. 'lon' => number_format($lon, 2),
  300. 'altitude' => $altitude,
  301. ];
  302. $url = 'https://api.met.no/weatherapi/locationforecast/2.0/compact';
  303. $weather = $this->requestJSON($url, $params);
  304. if (isset($weather['properties']) && isset($weather['properties']['timeseries']) && is_array($weather['properties']['timeseries'])) {
  305. return array_slice($weather['properties']['timeseries'], 0, $nbValues);
  306. }
  307. return ['error' => $this->l10n->t('Malformed JSON data.')];
  308. }
  309. /**
  310. * Make a HTTP GET request and parse JSON result.
  311. * Request results are cached until the 'Expires' response header says so
  312. *
  313. * @param string $url Base URL to query
  314. * @param array $params GET parameters
  315. * @return array which contains the error message or the parsed JSON result
  316. */
  317. private function requestJSON(string $url, array $params = []): array {
  318. $cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params));
  319. $cacheValue = $this->cache->get($cacheKey);
  320. if ($cacheValue !== null) {
  321. return $cacheValue;
  322. }
  323. try {
  324. $options = [
  325. 'headers' => [
  326. 'User-Agent' => 'NextcloudWeatherStatus/' . $this->version . ' nextcloud.com'
  327. ],
  328. ];
  329. $reqUrl = $url;
  330. if (count($params) > 0) {
  331. $paramsContent = http_build_query($params);
  332. $reqUrl = $url . '?' . $paramsContent;
  333. }
  334. $response = $this->client->get($reqUrl, $options);
  335. $body = $response->getBody();
  336. $headers = $response->getHeaders();
  337. $respCode = $response->getStatusCode();
  338. if ($respCode >= 400) {
  339. return ['error' => $this->l10n->t('Error')];
  340. } else {
  341. $json = json_decode($body, true);
  342. // default cache duration is one hour
  343. $cacheDuration = 60 * 60;
  344. if (isset($headers['Expires']) && count($headers['Expires']) > 0) {
  345. // if the Expires response header is set, use it to define cache duration
  346. $expireTs = (new \DateTime($headers['Expires'][0]))->getTimestamp();
  347. $nowTs = (new \DateTime())->getTimestamp();
  348. $duration = $expireTs - $nowTs;
  349. if ($duration > $cacheDuration) {
  350. $cacheDuration = $duration;
  351. }
  352. }
  353. $this->cache->set($cacheKey, $json, $cacheDuration);
  354. return $json;
  355. }
  356. } catch (\Exception $e) {
  357. $this->logger->warning($url . ' API error : ' . $e->getMessage(), ['exception' => $e]);
  358. return ['error' => $e->getMessage()];
  359. }
  360. }
  361. }