Skip to content

Commit

Permalink
Merge pull request #55 from LociStar/Weather2.0
Browse files Browse the repository at this point in the history
Weather2.0
  • Loading branch information
LociStar committed Feb 12, 2022
2 parents 026779d + 8282430 commit 9f1a184
Show file tree
Hide file tree
Showing 23 changed files with 795 additions and 118 deletions.
2 changes: 2 additions & 0 deletions WebAPI/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ build/

### VS Code ###
.vscode/

/src/main/resources/application.properties
8 changes: 4 additions & 4 deletions WebAPI/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
</parent>
<groupId>com.example</groupId>
<artifactId>WebAPI</artifactId>
<version>1.0.1</version>
<version>1.1.0</version>
<name>WebAPI</name>
<description>WebAPI</description>
<properties>
<java.version>11</java.version>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
Expand Down Expand Up @@ -48,7 +48,7 @@
<dependency>
<groupId>com.locibot.locibot</groupId>
<artifactId>locibot</artifactId>
<version>3.0.0</version>
<version>3.0.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
Expand All @@ -60,7 +60,7 @@
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
</dependencies>
</dependencies>

<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,81 +1,36 @@
package com.locibot.webapi.weatherData;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.prominence.openweathermap.api.OpenWeatherMapClient;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.OneCallResultOptions;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.locibot.locibot.data.credential.Credential;
import com.locibot.locibot.data.credential.CredentialManager;
import com.locibot.locibot.database.DatabaseManager;
import com.locibot.locibot.database.locations.entity.DBLocation;
import com.locibot.locibot.object.RequestHelper;
import com.locibot.locibot.utils.JWT.TokenVerification;
import com.locibot.webapi.weatherData.ptv.PTVResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import com.locibot.locibot.utils.weather.WeatherManager;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.time.Instant;
import java.util.Objects;

@Component
public class WeatherDataHandler {
public Mono<ServerResponse> weatherData(ServerRequest request) {

String token = request.queryParam("token").orElse("invalid login token");
String city = request.queryParam("city").orElse("Frankfurt");
String city = request.queryParam("city").orElse("XXX_No_City");
Double longitude = Double.parseDouble(request.queryParam("long").orElse("0"));
Double latitude = Double.parseDouble(request.queryParam("lat").orElse("0"));
WeatherManager weatherManager = new WeatherManager();

TokenVerification tokenVerification = new TokenVerification(token);

try {
if (tokenVerification.verify(Objects.requireNonNull(CredentialManager.get(Credential.JWT_SECRET)))) {
return DatabaseManager.getLocations().getLocation(city).flatMap(dbLocation -> {
//no Location found
if (dbLocation.getBean().getLatitude() == 0) {
return RequestHelper.fromUrl("https://api.myptv.com/geocoding/v1/locations/by-text?searchText=" + city + "&apiKey=" + CredentialManager.get(Credential.PTV))
.addHeaders("searchText", city)
.addHeaders("apiKey", CredentialManager.get(Credential.PTV))
.to(PTVResponse.class).flatMap(ptvResponse -> { //TODO: needs to be saved in a Database
Double latitude = ptvResponse.result().get(0).referencePosition().get("latitude");
Double longitude = ptvResponse.result().get(0).referencePosition().get("longitude");
DBLocation dbLocationNew = new DBLocation(city, longitude, latitude);
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(CredentialManager.get(Credential.OPENWEATHERMAP_API_KEY));
CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(latitude, longitude))
.language(Language.GERMAN)
.unitSystem(UnitSystem.METRIC)
.exclude(OneCallResultOptions.HOURLY, OneCallResultOptions.MINUTELY)
.retrieve()
.asJava();
return dbLocationNew.insert().then(ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new WeatherData(currentWeatherData))));
});
}
//location found
if (dbLocation.getWeatherData() != null) { //WeatherData in DB found
if (Instant.ofEpochMilli(dbLocation.getBean().getCreationTime()).isBefore(Instant.now().minusMillis(600000)))//Data too old
return saveDataToDB(dbLocation);
else
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(dbLocation.getWeatherData()));
} else {
return saveDataToDB(dbLocation);
}
return weatherManager.getSavedCurrentWeatherData(city, longitude, latitude).flatMap(data -> {
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(data));
});


}
} catch (Exception e) {
return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(new WeatherError("bad token")));
Expand All @@ -84,36 +39,5 @@ public Mono<ServerResponse> weatherData(ServerRequest request) {
return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(new WeatherError("fatal error")));
}

@NotNull
private Mono<? extends ServerResponse> saveDataToDB(DBLocation dbLocation) {
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(CredentialManager.get(Credential.OPENWEATHERMAP_API_KEY));
CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(dbLocation.getBean().getLatitude(), dbLocation.getBean().getLongitude()))
.language(Language.GERMAN)
.unitSystem(UnitSystem.METRIC)
.exclude(OneCallResultOptions.HOURLY, OneCallResultOptions.MINUTELY)
.retrieve()
.asJava();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String data = "";
try {
data = mapper.writeValueAsString(currentWeatherData);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return dbLocation.setWeather("{\"data\":" + data + "}").then(ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new WeatherData(currentWeatherData))));
}

@Bean
public ObjectMapper defaultMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


@Configuration(proxyBeanMethods = false)
public class weatherDataRouter {
public class WeatherDataRouter {

@Bean
public RouterFunction<ServerResponse> weatherDataRoute(WeatherDataHandler weatherDataHandler) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.locibot.webapi.weatherForecast;

import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;

public class WeatherForecast {
private final Forecast data;

public WeatherForecast(Forecast data) {
this.data = data;
}

public Forecast getData() {
return data;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.locibot.webapi.weatherForecast;

public class WeatherForecastError {
private final String error;

public WeatherForecastError(String errorType) {
this.error = errorType;
}

public String getError() {
return error;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.locibot.webapi.weatherForecast;

import com.locibot.locibot.data.credential.Credential;
import com.locibot.locibot.data.credential.CredentialManager;
import com.locibot.locibot.utils.JWT.TokenVerification;
import com.locibot.locibot.utils.weather.WeatherManager;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
public class WeatherForecastHandler {
public Mono<ServerResponse> weatherForecast(ServerRequest request) {

String token = request.queryParam("token").orElse("invalid login token");
String city = request.queryParam("city").orElse("XXX_No_City");
Double longitude = Double.parseDouble(request.queryParam("long").orElse("0"));
Double latitude = Double.parseDouble(request.queryParam("lat").orElse("0"));
WeatherManager weatherManager = new WeatherManager();

TokenVerification tokenVerification = new TokenVerification(token);

try {
if (tokenVerification.verify(Objects.requireNonNull(CredentialManager.get(Credential.JWT_SECRET)))) {
return weatherManager.getSaved5DayWeatherData(city, longitude, latitude).flatMap(data -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(data)));
}
} catch (Exception e) {
return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(new WeatherForecastError("bad token")));
}

return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(new WeatherForecastError("fatal error")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.locibot.webapi.weatherForecast;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration(proxyBeanMethods = false)
public class WeatherForecastRouter {
@Bean
public RouterFunction<ServerResponse> weatherForecastRoute(WeatherForecastHandler weatherForecastHandler) {

return RouterFunctions.route()
.GET("/weatherForecast", weatherForecastHandler::weatherForecast) //, RequestPredicates.queryParam("token", t -> true)
.build();
}
}
8 changes: 0 additions & 8 deletions WebAPI/src/main/resources/application.properties

This file was deleted.

11 changes: 10 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.locibot.locibot</groupId>
<artifactId>locibot</artifactId>
<version>3.0.0</version>
<version>3.0.2</version>
<name>LociBot</name>
<url>https://github.com/LociStar/Organizer</url>
<description>
Expand Down Expand Up @@ -258,5 +258,14 @@
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public Mono<?> execute(Context context) {
DatabaseManager.getGuilds().getDBMember(context.getGuildId(), context.getAuthorId()).flatMap(member ->
{
try {
return context.createFollowupMessageEphemeral("A Link will be created.").then(context.editFollowupMessage("One moment pls").flatMap(Message::delete))
return context.editFollowupMessage("A Link will be created.").flatMap(Message::delete)
.then(context.createFollowupMessage(InteractionFollowupCreateSpec.builder()
.ephemeral(true)
.content("Use the link to login on Organizer-Website")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

public class I18nManager {

public static final Locale[] LOCALES = {Locale.ENGLISH, Locale.FRENCH};
public static final Locale[] LOCALES = {Locale.ENGLISH, Locale.GERMAN};

private static final Map<Locale, ResourceBundle> GLOBAL_BUNDLES = I18nManager.initialize("i18n", LOCALES);
private static final Map<Locale, ResourceBundle> SPAM_BUNDLES = I18nManager.initialize("spam", LOCALES);
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/locibot/locibot/data/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ public class Config {
public static final String DATABASE_NAME = PROPERTIES.getProperty("database.name");
public static final long OWNER_GUILD_ID = Long.parseLong(PROPERTIES.getProperty("owner.guild.id"));

public static final long WEATHER_DATA = Long.parseLong(PROPERTIES.getProperty("weather.data.time"));
public static final long FIVE_DAY_WEATHER_DATA = Long.parseLong(PROPERTIES.getProperty("weather.fiveDayData.time"));

private static Properties loadProperties() {
final Properties properties = new Properties();
try (final InputStream inputStream = Thread.currentThread().getContextClassLoader()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,25 @@ public class DBLocationBean implements Bean {
@Nullable
@JsonProperty("creationTime")
private long creationTime;
@Nullable
@JsonProperty("fiveDayWeatherData")
private String fiveDayWeatherData;
@Nullable
@JsonProperty("fiveDayCreationTime")
private long fiveDayCreationTime;

public DBLocationBean(String name, double longitude, double latitude, @Nullable String weatherData, @Nullable long creationTime) {
public DBLocationBean(String name, double longitude, double latitude, @Nullable String weatherData, @Nullable long creationTime, @Nullable String fiveDayWeatherData, @Nullable long fiveDayCreationTime) {
this.name = name;
this.longitude = longitude;
this.latitude = latitude;
this.weatherData = weatherData;
this.creationTime = creationTime;
this.fiveDayWeatherData = fiveDayWeatherData;
this.fiveDayCreationTime = fiveDayCreationTime;
}

public DBLocationBean(String name, double longitude, double latitude) {
this(name, longitude, latitude, null, 0L);
this(name, longitude, latitude, null, 0L, null, 0L);
}

public DBLocationBean() {
Expand All @@ -53,4 +61,13 @@ public String getWeatherData() {
public long getCreationTime() {
return creationTime;
}

@Nullable
public String getFiveDayWeatherData() {
return fiveDayWeatherData;
}

public long getFiveDayCreationTime() {
return fiveDayCreationTime;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,29 @@ public Mono<UpdateResult> setWeather(String data) {
.doOnTerminate(() -> DatabaseManager.getLocations().invalidateCache(this.getBean().getName()));
}

public Mono<UpdateResult> set5DayWeather(String data) {
return Mono.from(DatabaseManager.getLocations()
.getCollection()
.updateOne(
Filters.eq("_id", this.getBean().getName()),
List.of(Updates.set("fiveDayWeatherData", data),
Updates.set("fiveDayCreationTime", Instant.now().toEpochMilli())),
new UpdateOptions().upsert(true)))
.doOnSubscribe(__ -> {
LocationsCollection.LOGGER.debug("[DBLocation {}] Location update: {}", this.getBean().getName(), data + " ");
Telemetry.DB_REQUEST_COUNTER.labels(DatabaseManager.getLocations().getName()).inc();
})
.doOnNext(result -> LocationsCollection.LOGGER.trace("[DBLocation {}] Location update result: {}",
this.getBean().getName(), result))
.doOnTerminate(() -> DatabaseManager.getLocations().invalidateCache(this.getBean().getName()));
}

public String getWeatherData() {
return this.getBean().getWeatherData();
}
public String get5DayWeatherData() {
return this.getBean().getFiveDayWeatherData();
}

@Override
public Mono<Void> insert() {
Expand Down
Loading

0 comments on commit 9f1a184

Please sign in to comment.