1
0

WeatherStatusService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 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 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 ? $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 (count($results) > 0) {
  245. return $results[0];
  246. }
  247. return ['error' => $this->l10n->t('No result.')];
  248. }
  249. /**
  250. * Get stored user location
  251. *
  252. * @return WeatherStatusLocationWithMode which contains coordinates, formatted address and current weather status mode
  253. */
  254. public function getLocation(): array {
  255. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  256. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  257. $address = $this->config->getUserValue($this->userId, Application::APP_ID, 'address', '');
  258. $mode = $this->config->getUserValue($this->userId, Application::APP_ID, 'mode', self::MODE_MANUAL_LOCATION);
  259. return [
  260. 'lat' => $lat,
  261. 'lon' => $lon,
  262. 'address' => $address,
  263. 'mode' => intval($mode),
  264. ];
  265. }
  266. /**
  267. * Get forecast for current location
  268. *
  269. * @return WeatherStatusForecast[]|array{error: string}|WeatherStatusSuccess which contains success state and filtered forecast data
  270. */
  271. public function getForecast(): array {
  272. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  273. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  274. $alt = $this->config->getUserValue($this->userId, Application::APP_ID, 'altitude', '');
  275. if (!is_numeric($alt)) {
  276. $alt = 0;
  277. }
  278. if (is_numeric($lat) && is_numeric($lon)) {
  279. return $this->forecastRequest(floatval($lat), floatval($lon), floatval($alt));
  280. } else {
  281. return ['success' => false];
  282. }
  283. }
  284. /**
  285. * Actually make the request to the forecast service
  286. *
  287. * @param float $lat Latitude of requested forecast, in decimal degree format
  288. * @param float $lon Longitude of requested forecast, in decimal degree format
  289. * @param float $altitude Altitude of requested forecast, in meter
  290. * @param int $nbValues Number of forecast values (hours)
  291. * @return WeatherStatusForecast[]|array{error: string} Filtered forecast data
  292. */
  293. private function forecastRequest(float $lat, float $lon, float $altitude, int $nbValues = 10): array {
  294. $params = [
  295. 'lat' => number_format($lat, 2),
  296. 'lon' => number_format($lon, 2),
  297. 'altitude' => $altitude,
  298. ];
  299. $url = 'https://api.met.no/weatherapi/locationforecast/2.0/compact';
  300. $weather = $this->requestJSON($url, $params);
  301. if (isset($weather['properties']) && isset($weather['properties']['timeseries']) && is_array($weather['properties']['timeseries'])) {
  302. return array_slice($weather['properties']['timeseries'], 0, $nbValues);
  303. }
  304. return ['error' => $this->l10n->t('Malformed JSON data.')];
  305. }
  306. /**
  307. * Make a HTTP GET request and parse JSON result.
  308. * Request results are cached until the 'Expires' response header says so
  309. *
  310. * @param string $url Base URL to query
  311. * @param array $params GET parameters
  312. * @return array which contains the error message or the parsed JSON result
  313. */
  314. private function requestJSON(string $url, array $params = []): array {
  315. $cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params));
  316. $cacheValue = $this->cache->get($cacheKey);
  317. if ($cacheValue !== null) {
  318. return $cacheValue;
  319. }
  320. try {
  321. $options = [
  322. 'headers' => [
  323. 'User-Agent' => 'NextcloudWeatherStatus/' . $this->version . ' nextcloud.com'
  324. ],
  325. ];
  326. $reqUrl = $url;
  327. if (count($params) > 0) {
  328. $paramsContent = http_build_query($params);
  329. $reqUrl = $url . '?' . $paramsContent;
  330. }
  331. $response = $this->client->get($reqUrl, $options);
  332. $body = $response->getBody();
  333. $headers = $response->getHeaders();
  334. $respCode = $response->getStatusCode();
  335. if ($respCode >= 400) {
  336. return ['error' => $this->l10n->t('Error')];
  337. } else {
  338. $json = json_decode($body, true);
  339. // default cache duration is one hour
  340. $cacheDuration = 60 * 60;
  341. if (isset($headers['Expires']) && count($headers['Expires']) > 0) {
  342. // if the Expires response header is set, use it to define cache duration
  343. $expireTs = (new \DateTime($headers['Expires'][0]))->getTimestamp();
  344. $nowTs = (new \DateTime())->getTimestamp();
  345. $duration = $expireTs - $nowTs;
  346. if ($duration > $cacheDuration) {
  347. $cacheDuration = $duration;
  348. }
  349. }
  350. $this->cache->set($cacheKey, $json, $cacheDuration);
  351. return $json;
  352. }
  353. } catch (\Exception $e) {
  354. $this->logger->warning($url . ' API error : ' . $e->getMessage(), ['exception' => $e]);
  355. return ['error' => $e->getMessage()];
  356. }
  357. }
  358. }