WeatherStatusService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 OCP\Accounts\IAccountManager;
  28. use OCP\Accounts\PropertyDoesNotExistException;
  29. use OCP\App\IAppManager;
  30. use OCP\Http\Client\IClient;
  31. use OCP\Http\Client\IClientService;
  32. use OCP\ICache;
  33. use OCP\ICacheFactory;
  34. use OCP\IConfig;
  35. use OCP\IL10N;
  36. use OCP\ILogger;
  37. use OCP\IUserManager;
  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. 'q' => $address,
  287. 'format' => 'json',
  288. 'addressdetails' => '1',
  289. 'extratags' => '1',
  290. 'namedetails' => '1',
  291. 'limit' => '1',
  292. ];
  293. $url = 'https://nominatim.openstreetmap.org/search';
  294. $results = $this->requestJSON($url, $params);
  295. if (count($results) > 0) {
  296. return $results[0];
  297. }
  298. return ['error' => $this->l10n->t('No result.')];
  299. }
  300. /**
  301. * Get stored user location
  302. *
  303. * @return array which contains coordinates, formatted address and current weather status mode
  304. */
  305. public function getLocation(): array {
  306. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  307. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  308. $address = $this->config->getUserValue($this->userId, Application::APP_ID, 'address', '');
  309. $mode = $this->config->getUserValue($this->userId, Application::APP_ID, 'mode', self::MODE_MANUAL_LOCATION);
  310. return [
  311. 'lat' => $lat,
  312. 'lon' => $lon,
  313. 'address' => $address,
  314. 'mode' => intval($mode),
  315. ];
  316. }
  317. /**
  318. * Get forecast for current location
  319. *
  320. * @return array which contains success state and filtered forecast data
  321. */
  322. public function getForecast(): array {
  323. $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
  324. $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
  325. $alt = $this->config->getUserValue($this->userId, Application::APP_ID, 'altitude', '');
  326. if (!is_numeric($alt)) {
  327. $alt = 0;
  328. }
  329. if (is_numeric($lat) && is_numeric($lon)) {
  330. return $this->forecastRequest(floatval($lat), floatval($lon), floatval($alt));
  331. } else {
  332. return ['success' => false];
  333. }
  334. }
  335. /**
  336. * Actually make the request to the forecast service
  337. *
  338. * @param float $lat Latitude of requested forecast, in decimal degree format
  339. * @param float $lon Longitude of requested forecast, in decimal degree format
  340. * @param float $altitude Altitude of requested forecast, in meter
  341. * @param int $nbValues Number of forecast values (hours)
  342. * @return array Filtered forecast data
  343. */
  344. private function forecastRequest(float $lat, float $lon, float $altitude, int $nbValues = 10): array {
  345. $params = [
  346. 'lat' => number_format($lat, 2),
  347. 'lon' => number_format($lon, 2),
  348. 'altitude' => $altitude,
  349. ];
  350. $url = 'https://api.met.no/weatherapi/locationforecast/2.0/compact';
  351. $weather = $this->requestJSON($url, $params);
  352. if (isset($weather['properties']) && isset($weather['properties']['timeseries']) && is_array($weather['properties']['timeseries'])) {
  353. return array_slice($weather['properties']['timeseries'], 0, $nbValues);
  354. }
  355. return ['error' => $this->l10n->t('Malformed JSON data.')];
  356. }
  357. /**
  358. * Make a HTTP GET request and parse JSON result.
  359. * Request results are cached until the 'Expires' response header says so
  360. *
  361. * @param string $url Base URL to query
  362. * @param array $params GET parameters
  363. * @return array which contains the error message or the parsed JSON result
  364. */
  365. private function requestJSON(string $url, array $params = []): array {
  366. $cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params));
  367. $cacheValue = $this->cache->get($cacheKey);
  368. if ($cacheValue !== null) {
  369. return $cacheValue;
  370. }
  371. try {
  372. $options = [
  373. 'headers' => [
  374. 'User-Agent' => 'NextcloudWeatherStatus/' . $this->version . ' nextcloud.com'
  375. ],
  376. ];
  377. $reqUrl = $url;
  378. if (count($params) > 0) {
  379. $paramsContent = http_build_query($params);
  380. $reqUrl = $url . '?' . $paramsContent;
  381. }
  382. $response = $this->client->get($reqUrl, $options);
  383. $body = $response->getBody();
  384. $headers = $response->getHeaders();
  385. $respCode = $response->getStatusCode();
  386. if ($respCode >= 400) {
  387. return ['error' => $this->l10n->t('Error')];
  388. } else {
  389. $json = json_decode($body, true);
  390. // default cache duration is one hour
  391. $cacheDuration = 60 * 60;
  392. if (isset($headers['Expires']) && count($headers['Expires']) > 0) {
  393. // if the Expires response header is set, use it to define cache duration
  394. $expireTs = (new \DateTime($headers['Expires'][0]))->getTimestamp();
  395. $nowTs = (new \DateTime())->getTimestamp();
  396. $duration = $expireTs - $nowTs;
  397. if ($duration > $cacheDuration) {
  398. $cacheDuration = $duration;
  399. }
  400. }
  401. $this->cache->set($cacheKey, $json, $cacheDuration);
  402. return $json;
  403. }
  404. } catch (\Exception $e) {
  405. $this->logger->warning($url . 'API error : ' . $e, ['app' => Application::APP_ID]);
  406. return ['error' => $e->getMessage()];
  407. }
  408. }
  409. }