WeatherStatusService.php 14 KB

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