Refactored to have a working caching system even when searching for a film

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2020-10-28 16:54:17 +01:00
parent 6228fc9248
commit 920bc47f85
3 changed files with 36 additions and 39 deletions

View File

@ -11,11 +11,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import xyz.vallat.louis.commands.*;
import xyz.vallat.louis.database.FilmManager;
import xyz.vallat.louis.omdb.OMDBClient;
import xyz.vallat.louis.database.DBManager;
import xyz.vallat.louis.env.EnvironmentVariables;
import xyz.vallat.louis.subtitles.OpenSubtitles;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
@ -37,9 +36,7 @@ public class MovieQuoteBot {
commands.put("download", new Download(PREFIX + "download"));
}
public static void main(String[] args) throws InterruptedException, ParseException, IOException {
OMDBClient.getMovie("Surrogates", false);
/*
public static void main(String[] args) {
DBManager.testConnection();
DBManager.initDatabase();
OpenSubtitles.login();
@ -53,7 +50,6 @@ public class MovieQuoteBot {
}));
discordClient.onDisconnect().block();
*/
}
private static void registerDiscordCommands() {

View File

@ -39,6 +39,7 @@ public final class FilmManager {
}
public static void importFilm(Movie movie) throws ImportationException {
logger.debug("Importing movie with imdb id '{}'.", movie.getImdbID());
try (Connection connection = DBManager.getConnection()) {
String insert = "INSERT INTO films(imdb_id, title, year, film_type, poster_link) VALUES(?, ?, ?, ?, ?);";
try (PreparedStatement stmt = connection.prepareStatement(insert, RETURN_GENERATED_KEYS)) {
@ -62,12 +63,14 @@ public final class FilmManager {
}
public static Movie getMovieFromTitleOrImdbId(String value, boolean isId) {
logger.debug("Getting movie with '{}' as {}.", value, isId ? "IMDB id" : "title");
Movie movie = null;
try (Connection connection = DBManager.getConnection()) {
String query = "SELECT id, imdb_id, title, year, film_type, poster_link " +
"FROM films WHERE " + (isId ? "imdb_id" : "title") + " = ?;";
"FROM films WHERE " + (isId ? "imdb_id" : "title") + " = ? AND film_type = ?;";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, value);
stmt.setString(2, "movie");
stmt.execute();
ResultSet results = stmt.getResultSet();
if (results.next()) {
@ -80,6 +83,7 @@ public final class FilmManager {
movie.setId(results.getInt("id"));
if (results.getObject("year") != null)
movie.setYear(results.getInt("year"));
logger.debug("Found movie with id '{}'.", movie.getId());
}
}
} catch (SQLException e) {

View File

@ -39,22 +39,18 @@ public final class OMDBClient {
List<Movie> movies = new ArrayList<>();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(ENDPOINT + "?apikey=" + API_KEY + "&type=movie&s=" + URLEncoder.encode(name, StandardCharsets.UTF_8)))
.uri(URI.create(ENDPOINT + "?apikey=" + API_KEY + "&type=movie" +
"&s=" + URLEncoder.encode(name, StandardCharsets.UTF_8)))
.build();
logger.debug("Calling url '{}'.", request.uri());
HttpResponse<String> response = getHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
JsonObject object = JsonParser.parseString(response.body()).getAsJsonObject();
if (object.get("Response").getAsBoolean()) {
for (JsonElement jsonElement : object.get("Search").getAsJsonArray()) {
JsonObject jsonMovie = (JsonObject) jsonElement;
if (jsonMovie.get(IMDB_KEY) == null || jsonMovie.get(TITLE_KEY) == null) continue;
Movie movie = new Movie(
jsonMovie.get(TITLE_KEY).getAsString(),
jsonMovie.get(IMDB_KEY).getAsString(),
jsonMovie.get(TYPE_KEY).getAsString(),
jsonMovie.get(POSTER_KEY).getAsString().equals("N/A") ? null : jsonMovie.get(POSTER_KEY).getAsString()
);
movie.setYear(Integer.parseInt(jsonMovie.get(YEAR_KEY).getAsString().substring(0, 4)));
Movie movie = getMovieFromJson(jsonMovie);
if (movie == null) continue;
movies.add(movie);
}
} else
@ -78,35 +74,36 @@ public final class OMDBClient {
.build();
HttpResponse<String> response = getHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
movie = getMovieFromJson(response.body());
JsonObject jsonMovie = JsonParser.parseString(response.body()).getAsJsonObject();
if (jsonMovie.get("Response").getAsBoolean()) {
movie = getMovieFromJson(jsonMovie);
} else
logger.error("OMDB API returned an error: {}", jsonMovie.get("Error").getAsString());
} else
logger.error("Querying the results gave this code: {}.", response.statusCode());
return movie;
}
private static Movie getMovieFromJson(String json) {
private static Movie getMovieFromJson(JsonObject jsonMovie) {
Movie movie = null;
JsonObject jsonMovie = JsonParser.parseString(json).getAsJsonObject();
if (jsonMovie.get("Response").getAsBoolean()) {
if (jsonMovie.get(IMDB_KEY) != null && jsonMovie.get(TITLE_KEY) != null) {
movie = new Movie(
jsonMovie.get(TITLE_KEY).getAsString(),
jsonMovie.get(IMDB_KEY).getAsString(),
jsonMovie.get(TYPE_KEY).getAsString(),
jsonMovie.get(POSTER_KEY).getAsString().equals("N/A") ? null : jsonMovie.get(POSTER_KEY).getAsString()
);
movie.setYear(Integer.parseInt(jsonMovie.get(YEAR_KEY).getAsString()
.substring(0, Math.min(4, jsonMovie.get(YEAR_KEY).getAsString().length()))));
try {
if (jsonMovie.get(IMDB_KEY) != null && jsonMovie.get(TITLE_KEY) != null) {
movie = new Movie(
jsonMovie.get(TITLE_KEY).getAsString(),
jsonMovie.get(IMDB_KEY).getAsString(),
jsonMovie.get(TYPE_KEY).getAsString(),
jsonMovie.get(POSTER_KEY).getAsString().equals("N/A") ? null : jsonMovie.get(POSTER_KEY).getAsString()
);
movie.setYear(Integer.parseInt(jsonMovie.get(YEAR_KEY).getAsString()
.substring(0, Math.min(4, jsonMovie.get(YEAR_KEY).getAsString().length()))));
try {
if (FilmManager.getMovieFromTitleOrImdbId(movie.getImdbID(), true) == null)
FilmManager.importFilm(movie);
} catch (ImportationException e) {
logger.error("Cannot import the movie with title '{}' and IMDB id '{}'.",
movie.getTitle(), movie.getImdbID());
logger.warn("Please fix this issue quickly as this could cause problems due to the OMDB limitations.");
}
} catch (ImportationException e) {
logger.error("Cannot import the movie with title '{}' and IMDB id '{}'.",
movie.getTitle(), movie.getImdbID());
logger.warn("Please fix this issue quickly as this could cause problems due to the OMDB limitations.");
}
} else
logger.error("OMDB API returned an error: {}", jsonMovie.get("Error").getAsString());
}
return movie;
}