WeatherStatusService.php 14 KB

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