123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396 |
- <?php
- declare(strict_types=1);
- namespace OCA\WeatherStatus\Service;
- use OCA\WeatherStatus\AppInfo\Application;
- use OCP\Accounts\IAccountManager;
- use OCP\Accounts\PropertyDoesNotExistException;
- use OCP\App\IAppManager;
- use OCP\Http\Client\IClient;
- use OCP\Http\Client\IClientService;
- use OCP\ICache;
- use OCP\ICacheFactory;
- use OCP\IConfig;
- use OCP\IL10N;
- use OCP\IUserManager;
- use Psr\Log\LoggerInterface;
- class WeatherStatusService {
- public const MODE_BROWSER_LOCATION = 1;
- public const MODE_MANUAL_LOCATION = 2;
- private IClient $client;
- private ICache $cache;
- private string $version;
- public function __construct(
- private IClientService $clientService,
- private IConfig $config,
- private IL10N $l10n,
- private LoggerInterface $logger,
- private IAccountManager $accountManager,
- private IUserManager $userManager,
- private IAppManager $appManager,
- private ICacheFactory $cacheFactory,
- private ?string $userId
- ) {
- $this->version = $appManager->getAppVersion(Application::APP_ID);
- $this->client = $clientService->newClient();
- $this->cache = $cacheFactory->createDistributed('weatherstatus');
- }
-
- public function setMode(int $mode): array {
- $this->config->setUserValue($this->userId, Application::APP_ID, 'mode', strval($mode));
- return ['success' => true];
- }
-
- public function getFavorites(): array {
- $favoritesJson = $this->config->getUserValue($this->userId, Application::APP_ID, 'favorites', '');
- return json_decode($favoritesJson, true) ?: [];
- }
-
- public function setFavorites(array $favorites): array {
- $this->config->setUserValue($this->userId, Application::APP_ID, 'favorites', json_encode($favorites));
- return ['success' => true];
- }
-
- public function usePersonalAddress(): array {
- $account = $this->accountManager->getAccount($this->userManager->get($this->userId));
- try {
- $address = $account->getProperty('address')->getValue();
- } catch (PropertyDoesNotExistException $e) {
- return ['success' => false];
- }
- if ($address === '') {
- return ['success' => false];
- }
- return $this->setAddress($address);
- }
-
- public function setLocation(?string $address, ?float $lat, ?float $lon): array {
- if (!is_null($lat) && !is_null($lon)) {
-
- $this->config->setUserValue($this->userId, Application::APP_ID, 'lat', strval($lat));
- $this->config->setUserValue($this->userId, Application::APP_ID, 'lon', strval($lon));
-
- $address = $this->resolveLocation($lat, $lon);
- $address = $address ? $address : $this->l10n->t('Unknown address');
- $this->config->setUserValue($this->userId, Application::APP_ID, 'address', $address);
-
- $altitude = $this->getAltitude($lat, $lon);
- $this->config->setUserValue($this->userId, Application::APP_ID, 'altitude', strval($altitude));
- return [
- 'address' => $address,
- 'success' => true,
- ];
- } elseif ($address) {
- return $this->setAddress($address);
- } else {
- return ['success' => false];
- }
- }
-
- private function resolveLocation(float $lat, float $lon): ?string {
- $params = [
- 'lat' => number_format($lat, 2),
- 'lon' => number_format($lon, 2),
- 'addressdetails' => 1,
- 'format' => 'json',
- ];
- $url = 'https://nominatim.openstreetmap.org/reverse';
- $result = $this->requestJSON($url, $params);
- return $this->formatOsmAddress($result);
- }
-
- private function getAltitude(float $lat, float $lon): float {
- $params = [
- 'locations' => $lat . ',' . $lon,
- ];
- $url = 'https://api.opentopodata.org/v1/srtm30m';
- $result = $this->requestJSON($url, $params);
- $altitude = 0;
- if (isset($result['results']) && is_array($result['results']) && count($result['results']) > 0
- && is_array($result['results'][0]) && isset($result['results'][0]['elevation'])) {
- $altitude = floatval($result['results'][0]['elevation']);
- }
- return $altitude;
- }
-
- private function formatOsmAddress(array $json): ?string {
- if (isset($json['address']) && isset($json['display_name'])) {
- $jsonAddr = $json['address'];
- $cityAddress = '';
-
- if (isset($jsonAddr['city'])) {
- $cityAddress .= $jsonAddr['city'];
- } elseif (isset($jsonAddr['town'])) {
- $cityAddress .= $jsonAddr['town'];
- } elseif (isset($jsonAddr['village'])) {
- $cityAddress .= $jsonAddr['village'];
- } elseif (isset($jsonAddr['municipality'])) {
- $cityAddress .= $jsonAddr['municipality'];
- } else {
- return $json['display_name'];
- }
-
- if (isset($jsonAddr['postcode'])) {
- $cityAddress .= ', ' . $jsonAddr['postcode'];
- }
-
- if (isset($jsonAddr['country'])) {
- $cityAddress .= ', ' . $jsonAddr['country'];
- return $cityAddress;
- } else {
- return $json['display_name'];
- }
- } elseif (isset($json['display_name'])) {
- return $json['display_name'];
- }
- return null;
- }
-
- public function setAddress(string $address): array {
- $addressInfo = $this->searchForAddress($address);
- if (isset($addressInfo['display_name']) && isset($addressInfo['lat']) && isset($addressInfo['lon'])) {
- $formattedAddress = $this->formatOsmAddress($addressInfo);
- $this->config->setUserValue($this->userId, Application::APP_ID, 'address', $formattedAddress);
- $this->config->setUserValue($this->userId, Application::APP_ID, 'lat', strval($addressInfo['lat']));
- $this->config->setUserValue($this->userId, Application::APP_ID, 'lon', strval($addressInfo['lon']));
- $this->config->setUserValue($this->userId, Application::APP_ID, 'mode', strval(self::MODE_MANUAL_LOCATION));
-
- $altitude = $this->getAltitude(floatval($addressInfo['lat']), floatval($addressInfo['lon']));
- $this->config->setUserValue($this->userId, Application::APP_ID, 'altitude', strval($altitude));
- return [
- 'lat' => $addressInfo['lat'],
- 'lon' => $addressInfo['lon'],
- 'address' => $formattedAddress,
- 'success' => true,
- ];
- } else {
- return ['success' => false];
- }
- }
-
- private function searchForAddress(string $address): array {
- $params = [
- 'q' => $address,
- 'format' => 'json',
- 'addressdetails' => '1',
- 'extratags' => '1',
- 'namedetails' => '1',
- 'limit' => '1',
- ];
- $url = 'https://nominatim.openstreetmap.org/search';
- $results = $this->requestJSON($url, $params);
- if (count($results) > 0) {
- return $results[0];
- }
- return ['error' => $this->l10n->t('No result.')];
- }
-
- public function getLocation(): array {
- $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
- $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
- $address = $this->config->getUserValue($this->userId, Application::APP_ID, 'address', '');
- $mode = $this->config->getUserValue($this->userId, Application::APP_ID, 'mode', self::MODE_MANUAL_LOCATION);
- return [
- 'lat' => $lat,
- 'lon' => $lon,
- 'address' => $address,
- 'mode' => intval($mode),
- ];
- }
-
- public function getForecast(): array {
- $lat = $this->config->getUserValue($this->userId, Application::APP_ID, 'lat', '');
- $lon = $this->config->getUserValue($this->userId, Application::APP_ID, 'lon', '');
- $alt = $this->config->getUserValue($this->userId, Application::APP_ID, 'altitude', '');
- if (!is_numeric($alt)) {
- $alt = 0;
- }
- if (is_numeric($lat) && is_numeric($lon)) {
- return $this->forecastRequest(floatval($lat), floatval($lon), floatval($alt));
- } else {
- return ['success' => false];
- }
- }
-
- private function forecastRequest(float $lat, float $lon, float $altitude, int $nbValues = 10): array {
- $params = [
- 'lat' => number_format($lat, 2),
- 'lon' => number_format($lon, 2),
- 'altitude' => $altitude,
- ];
- $url = 'https://api.met.no/weatherapi/locationforecast/2.0/compact';
- $weather = $this->requestJSON($url, $params);
- if (isset($weather['properties']) && isset($weather['properties']['timeseries']) && is_array($weather['properties']['timeseries'])) {
- return array_slice($weather['properties']['timeseries'], 0, $nbValues);
- }
- return ['error' => $this->l10n->t('Malformed JSON data.')];
- }
-
- private function requestJSON(string $url, array $params = []): array {
- $cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params));
- $cacheValue = $this->cache->get($cacheKey);
- if ($cacheValue !== null) {
- return $cacheValue;
- }
- try {
- $options = [
- 'headers' => [
- 'User-Agent' => 'NextcloudWeatherStatus/' . $this->version . ' nextcloud.com'
- ],
- ];
- $reqUrl = $url;
- if (count($params) > 0) {
- $paramsContent = http_build_query($params);
- $reqUrl = $url . '?' . $paramsContent;
- }
- $response = $this->client->get($reqUrl, $options);
- $body = $response->getBody();
- $headers = $response->getHeaders();
- $respCode = $response->getStatusCode();
- if ($respCode >= 400) {
- return ['error' => $this->l10n->t('Error')];
- } else {
- $json = json_decode($body, true);
-
- $cacheDuration = 60 * 60;
- if (isset($headers['Expires']) && count($headers['Expires']) > 0) {
-
- $expireTs = (new \DateTime($headers['Expires'][0]))->getTimestamp();
- $nowTs = (new \DateTime())->getTimestamp();
- $duration = $expireTs - $nowTs;
- if ($duration > $cacheDuration) {
- $cacheDuration = $duration;
- }
- }
- $this->cache->set($cacheKey, $json, $cacheDuration);
- return $json;
- }
- } catch (\Exception $e) {
- $this->logger->warning($url . ' API error : ' . $e->getMessage(), ['exception' => $e]);
- return ['error' => $e->getMessage()];
- }
- }
- }
|