WeatherStatusService.php 13 KB

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