From c3a148b2679915bf16b1caacec45a49273ae8ae3 Mon Sep 17 00:00:00 2001 From: Seil0 Date: Tue, 4 Dec 2018 22:31:11 +0100 Subject: [PATCH] reworked the DBController * some tasks are now done at the SourcesController * use PrepareStatement * generall clean up --- .../application/MainWindowController.java | 15 +- .../HomeFlix/controller/DBController.java | 416 ++++++------------ .../controller/SourcesController.java | 165 +++++++ .../HomeFlix/datatypes/DatabaseDataType.java | 101 +++++ .../HomeFlix/player/PlayerController.java | 1 + 5 files changed, 412 insertions(+), 286 deletions(-) create mode 100644 src/main/java/kellerkinder/HomeFlix/controller/SourcesController.java create mode 100644 src/main/java/kellerkinder/HomeFlix/datatypes/DatabaseDataType.java diff --git a/src/main/java/kellerkinder/HomeFlix/application/MainWindowController.java b/src/main/java/kellerkinder/HomeFlix/application/MainWindowController.java index 95aea3d..8370c8d 100644 --- a/src/main/java/kellerkinder/HomeFlix/application/MainWindowController.java +++ b/src/main/java/kellerkinder/HomeFlix/application/MainWindowController.java @@ -166,7 +166,7 @@ public class MainWindowController { private boolean autoplay = false; private final String version = "0.7.0"; - private final String buildNumber = "163"; + private final String buildNumber = "165"; private final String versionName = "toothless dragon"; private String btnStyle; private String color; @@ -214,7 +214,7 @@ public class MainWindowController { initActions(); dbController.init(); - posterModeStartup(); // TODO testing +// posterModeStartup(); // TODO testing } // Initialize general UI elements @@ -550,7 +550,7 @@ public class MainWindowController { directoryChooser.setTitle(bundle.getString("addDirectory")); File selectedFolder = directoryChooser.showDialog(main.getPrimaryStage()); if (selectedFolder != null && selectedFolder.exists()) { - mainWindowController.addSource(selectedFolder.getPath(), "local"); + addSource(selectedFolder.getPath(), "local"); } else { LOGGER.error("The selected folder dosen't exist!"); } @@ -563,7 +563,6 @@ public class MainWindowController { File selectedFile = fileChooser.showOpenDialog(main.getPrimaryStage()); if (selectedFile != null && selectedFile.exists()) { addSource(selectedFile.getPath(), "stream"); - dbController.refreshDataBase(); } else { LOGGER.error("The selected file dosen't exist!"); } @@ -605,6 +604,8 @@ public class MainWindowController { * add data from films-list to films-table */ public void addFilmsToTable(ObservableList elementsList) { + + System.out.println(elementsList.size()); for (FilmTabelDataType element : elementsList) { @@ -667,6 +668,12 @@ public class MainWindowController { } catch (IOException e) { LOGGER.error(e); } + + // clear old sources list/table + getSourcesList().clear(); + getSourceRoot().getChildren().clear(); + // update the database and all films from the database + dbController.refreshDataBase(); } /** diff --git a/src/main/java/kellerkinder/HomeFlix/controller/DBController.java b/src/main/java/kellerkinder/HomeFlix/controller/DBController.java index 87ea8af..fcd332c 100644 --- a/src/main/java/kellerkinder/HomeFlix/controller/DBController.java +++ b/src/main/java/kellerkinder/HomeFlix/controller/DBController.java @@ -18,11 +18,11 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ + package kellerkinder.HomeFlix.controller; import java.io.File; import java.io.FileNotFoundException; -import java.io.FileReader; import java.io.IOException; import java.net.URLConnection; import java.sql.Connection; @@ -37,11 +37,6 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import com.eclipsesource.json.Json; -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.image.Image; @@ -51,9 +46,9 @@ import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import kellerkinder.HomeFlix.application.Main; import kellerkinder.HomeFlix.application.MainWindowController; +import kellerkinder.HomeFlix.datatypes.DatabaseDataType; import kellerkinder.HomeFlix.datatypes.FilmTabelDataType; import kellerkinder.HomeFlix.datatypes.OMDbAPIResponseDataType; -import kellerkinder.HomeFlix.datatypes.SourceDataType; public class DBController { @@ -62,8 +57,8 @@ public class DBController { private String DB_PATH; private Image favorite_black = new Image("icons/ic_favorite_black_18dp_1x.png"); private Image favorite_border_black = new Image("icons/ic_favorite_border_black_18dp_1x.png"); - private List filmsdbStreamURL = new ArrayList(); // contains all films stored in the database - private List filmsStreamURL = new ArrayList(); // contains all films from the sources + private List databaseStream = new ArrayList(); // contains all films stored in the database + private List sourceStreams = new ArrayList(); // contains all films from the sources private Connection connection = null; private static final Logger LOGGER = LogManager.getLogger(DBController.class.getName()); @@ -136,7 +131,9 @@ public class DBController { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM films"); while (rs.next()) { - filmsdbStreamURL.add(rs.getString("streamUrl")); + databaseStream.add(new DatabaseDataType(rs.getString("streamUrl"), + rs.getString("title"), rs.getString("season"), rs.getString("episode"), + rs.getInt("favorite"), rs.getBoolean("cached"), rs.getDouble("currentTime"))); } stmt.close(); rs.close(); @@ -146,57 +143,11 @@ public class DBController { } /** - * load sources from sources.json - * if mode == local, get all files and series-folder from the directory - * else mode must be streaming, read all entries from the streaming file + * load all sources */ private void loadSources() { - // remove sources from table - mainWindowController.getSourcesList().removeAll(mainWindowController.getSourcesList()); - mainWindowController.getSourceRoot().getChildren().removeAll(mainWindowController.getSourceRoot().getChildren()); - - try { - JsonArray sources = Json.parse(new FileReader(main.getDirectory() + "/sources.json")).asArray(); - for (JsonValue source : sources) { - String path = source.asObject().getString("path", ""); - String mode = source.asObject().getString("mode", ""); - mainWindowController.addSourceToTable(path, mode); // add source to source-table - - if (mode.equals("local")) { - for (File file : new File(path).listFiles()) { - if (file.isFile() && isVideoFile(file.getPath())) { - filmsStreamURL.add(file.getPath()); - } else if(file.isDirectory()) { - // get all folders (series) - for (File season : file.listFiles()) { - if (season.isDirectory()) { - for (File episode : season.listFiles()) { - if (!filmsdbStreamURL.contains(episode.getPath())) { - filmsStreamURL.add(episode.getPath()); - } - } - } - } - } - } - LOGGER.info("added files from: " + path); - } else { - // getting all entries from the streaming lists - try { - JsonObject object = Json.parse(new FileReader(path)).asObject(); - JsonArray items = object.get("entries").asArray(); - for (JsonValue item : items) { - filmsStreamURL.add(item.asObject().getString("streamUrl", "")); - } - LOGGER.info("added films from: " + path); - } catch (IOException e) { - LOGGER.error(e); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } + SourcesController sourcesController = new SourcesController(main, mainWindowController); + sourceStreams = sourcesController.loadSources(); } /** @@ -204,22 +155,18 @@ public class DBController { * order entries by title */ private void loadDataToFilmsList() { + ImageView imageView; LOGGER.info("loading data to mwc ..."); try { //load local Data Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM films ORDER BY title"); + ResultSet rs = stmt.executeQuery("SELECT * FROM films ORDER BY title"); + while (rs.next()) { -// System.out.println(rs.getString("title") + "Season:" + rs.getString("season") + ":"); - if (rs.getBoolean("favorite") == true) { - mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"), - rs.getString("title"), rs.getString("season"), rs.getString("episode") ,rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView(favorite_black))); - } else { - mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"), - rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView(favorite_border_black))); - } + imageView = rs.getBoolean("favorite") ? new ImageView(favorite_black) : new ImageView(favorite_border_black); + mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"), + rs.getString("title"), rs.getString("season"), rs.getString("episode") ,rs.getBoolean("favorite"), + rs.getBoolean("cached"), imageView)); } stmt.close(); rs.close(); @@ -237,24 +184,20 @@ public class DBController { * @param index of the film in LocalFilms list */ public void refresh(String streamUrl, int indexList) { - LOGGER.info("refresh ..."); + LOGGER.info("refresh data for " + streamUrl); try { - Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM films WHERE streamUrl = \"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ResultSet rs = ps.executeQuery(); while (rs.next()) { - if (rs.getBoolean("favorite") == true) { - mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"), - rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView(favorite_black))); - } else { - mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"), - rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView(favorite_border_black))); - } + ImageView imageView = rs.getBoolean("favorite") ? new ImageView(favorite_black) : new ImageView(favorite_border_black); + mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"), + rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), + rs.getBoolean("cached"), imageView)); } rs.close(); - stmt.close(); + ps.close(); } catch (Exception e) { LOGGER.error("Ups! error while refreshing mwc!", e); } @@ -269,14 +212,13 @@ public class DBController { LOGGER.info("refreshing the Database ..."); // clean all ArraLists - filmsdbStreamURL.clear(); - filmsStreamURL.clear(); + databaseStream.clear(); + sourceStreams.clear(); loadSources(); // reload all sources loadDatabase(); // reload all films saved in the DB - LOGGER.info("films in directory: " + filmsStreamURL.size()); - LOGGER.info("filme in db: " + filmsdbStreamURL.size()); + LOGGER.info("filme in db: " + databaseStream.size()); try { checkAddEntry(); @@ -285,7 +227,7 @@ public class DBController { LOGGER.error("Error while refreshing the database", e); } - // clear the FilmsList and FilmRoot chlidren + // clear the FilmsList and FilmRoot children mainWindowController.getFilmsList().clear(); mainWindowController.getFilmRoot().getChildren().clear(); @@ -294,25 +236,32 @@ public class DBController { /** * check if there are any entries that have been removed from the film-directory + * @throws SQLException */ - private void checkRemoveEntry() { + private void checkRemoveEntry() throws SQLException { + PreparedStatement ps = connection.prepareStatement("DELETE FROM films WHERE streamUrl = ?"); LOGGER.info("checking for entrys to remove to DB ..."); - try { - Statement stmt = connection.createStatement(); + + for (DatabaseDataType dbStreamEntry : databaseStream) { + // if the directory doen't contain the entry form the database, remove it - for (String entry : filmsdbStreamURL) { - // if the directory doen't contain the entry form the db, remove it - if (!filmsStreamURL.contains(entry)) { - stmt.executeUpdate("delete from films where streamUrl = \"" + entry + "\""); - connection.commit(); - LOGGER.info("removed \"" + entry + "\" from database"); - } + // if sourceStreams has a item where StreamUrl equals dbStreamEntry.getStreamUrl() return it, else null + DatabaseDataType result = sourceStreams.stream() + .filter(x -> dbStreamEntry.getStreamUrl().equals(x.getStreamUrl())) + .findAny() + .orElse(null); + + // if the result is null, the file is missing, remove it from the database + if (result == null) { + ps.setString(1, dbStreamEntry.getStreamUrl()); + ps.addBatch(); + LOGGER.info("removed \"" + dbStreamEntry.getTitle() + "\" from database"); } - - stmt.close(); - } catch (Exception e) { - LOGGER.error(e); } + + ps.executeBatch(); + connection.commit(); + ps.close(); } /** @@ -325,114 +274,33 @@ public class DBController { PreparedStatement ps = connection.prepareStatement("insert into films values (?, ?, ?, ?, ?, ?, ?)"); LOGGER.info("checking for entrys to add to DB ..."); - // source is a single source of the sources list - for (SourceDataType source : mainWindowController.getSourcesList()) { - // if it's a local source check the folder for new film - if (source.getMode().equals("local")) { - for (File file : new File(source.getPath()).listFiles()) { - String mimeType = URLConnection.guessContentTypeFromName(file.getPath()); - // if file is file and has mime type "video" - if (file.isFile() && mimeType != null && mimeType.contains("video")) { - // get all files (films) - if (!filmsdbStreamURL.contains(file.getPath())) { - ps.setString(1, file.getPath()); - ps.setString(2, cutOffEnd(file.getName())); - ps.setString(3, ""); - ps.setString(4, ""); - ps.setInt(5, 0); - ps.setBoolean(6, false); - ps.setDouble(7, 0); - ps.addBatch(); // adds the entry - LOGGER.info("Added \"" + file.getName() + "\" to database"); - filmsdbStreamURL.add(file.getPath()); - } - } else if (file.isDirectory()) { - // get all folders (series) - int sn = 1; - for (File season : file.listFiles()) { - if (season.isDirectory()) { - int ep = getLastEpisode(cutOffEnd(file.getName()), Integer.toString(sn)) + 1; - for (File episode : season.listFiles()) { - if (!filmsdbStreamURL.contains(episode.getPath())) { - ps.setString(1, episode.getPath().replace("'", "''")); - ps.setString(2, cutOffEnd(file.getName())); // the title is the series root folder's name - ps.setString(3, Integer.toString(sn)); - ps.setString(4, Integer.toString(ep)); - ps.setInt(5, 0); - ps.setBoolean(6, false); - ps.setDouble(7, 0); - ps.addBatch(); // adds the entry - LOGGER.info("Added \"" + file.getName() + "\", Episode: " + episode.getName() + " to database"); - filmsStreamURL.add(episode.getPath()); - filmsdbStreamURL.add(episode.getPath()); - ep++; - } - } - sn++; - } - } - } - - } - } else { - // if it's a streaming source check the file for new films - for (String entry : filmsStreamURL) { - if (!filmsdbStreamURL.contains(entry)) { - JsonArray items = Json.parse(new FileReader(source.getPath())).asObject().get("entries").asArray(); - // for each item, check if it's the needed - for (JsonValue item : items) { - String streamUrl = item.asObject().getString("streamUrl", ""); - String title = item.asObject().getString("title", ""); - - // if it's the needed add it to the database - if (streamUrl.equals(entry)) { - ps.setString(1, streamUrl); - ps.setString(2, title); - ps.setString(3, item.asObject().getString("season", "")); - ps.setString(4, item.asObject().getString("episode", "")); - ps.setInt(5, 0); - ps.setBoolean(6, false); - ps.setDouble(7, 0); - ps.addBatch(); // adds the entry - LOGGER.info("Added \"" + title + "\" to database"); - filmsdbStreamURL.add(streamUrl); - } - } - } - } - ps.executeBatch(); - connection.commit(); - ps.close(); + // new + for (DatabaseDataType sourceStreamEntry : sourceStreams) { + + // if databaseStream has a item where StreamUrl equals sourceStreamEntry.getStreamUrl() return it, else null + DatabaseDataType result = databaseStream.stream() + .filter(x -> sourceStreamEntry.getStreamUrl().equals(x.getStreamUrl())) + .findAny() + .orElse(null); + + // if the result is null, the entry is missing, add it to the database + if (result == null) { + ps.setString(1, sourceStreamEntry.getStreamUrl()); + ps.setString(2, sourceStreamEntry.getTitle()); + ps.setString(3, sourceStreamEntry.getSeason()); + ps.setString(4, sourceStreamEntry.getEpisode()); + ps.setInt(5, sourceStreamEntry.getFavorite()); + ps.setBoolean(6, sourceStreamEntry.getCached()); + ps.setDouble(7, sourceStreamEntry.getCurrentTime()); + ps.addBatch(); // adds the entry + LOGGER.info("Added \"" + sourceStreamEntry.getTitle() + "\" to database"); + databaseStream.add(sourceStreamEntry); } } - } - - /** - * gets the last episode of a season of a given series - * @param seriesTitle the actual series - * @param season the actual season - * @return the last episode number - */ - private int getLastEpisode(String seriesTitle, String season) { - int lastEpisode = 0; - try { - Statement stmt = connection.createStatement(); - PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE title = ? AND season = ?"); - ps.setString(1, seriesTitle); - ps.setString(2, season); - ResultSet rs = ps.executeQuery(); - - while (rs.next()) { - if (Integer.parseInt(rs.getString("episode")) > lastEpisode) - lastEpisode = Integer.parseInt(rs.getString("episode")); - } - stmt.close(); - rs.close(); - } catch (SQLException e) { - LOGGER.error("An error occured, while printing all entries", e); - } - - return lastEpisode; + + ps.executeBatch(); + connection.commit(); + ps.close(); } /** @@ -453,8 +321,8 @@ public class DBController { System.out.println(rs.getString("cached")); System.out.println(rs.getString("currentTime") + "\n"); } - stmt.close(); rs.close(); + stmt.close(); } catch (SQLException e) { LOGGER.error("An error occured, while printing all entries", e); } @@ -467,10 +335,11 @@ public class DBController { public void dislike(String streamUrl) { LOGGER.info("dislike " + streamUrl); try { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("UPDATE films SET favorite=0 WHERE streamUrl=\"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("UPDATE films SET favorite = 0 WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ps.executeUpdate(); connection.commit(); - stmt.close(); + ps.close(); } catch (SQLException e) { LOGGER.error("Ups! an error occured!", e); } @@ -483,10 +352,11 @@ public class DBController { public void like(String streamUrl) { LOGGER.info("like " + streamUrl); try { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("UPDATE films SET favorite = 1 WHERE streamUrl = \"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("UPDATE films SET favorite = 1 WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ps.executeUpdate(); connection.commit(); - stmt.close(); + ps.close(); } catch (SQLException e) { LOGGER.error("Ups! an error occured!", e); } @@ -498,10 +368,11 @@ public class DBController { */ public void setCached(String streamUrl) { try { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("UPDATE films SET cached = 1 WHERE streamUrl = \"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("UPDATE films SET cached = 1 WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ps.executeUpdate(); connection.commit(); - stmt.close(); + ps.close(); } catch (SQLException e) { LOGGER.error("Ups! an error occured!", e); } @@ -563,11 +434,12 @@ public class DBController { public boolean searchCacheByURL(String streamUrl) { boolean retValue = false; try { - Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM cache WHERE streamUrl = \"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("SELECT * FROM cache WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ResultSet rs = ps.executeQuery(); retValue = rs.next(); rs.close(); - stmt.close(); + ps.close(); } catch (Exception e) { LOGGER.error("Ups! error while getting the current time!", e); } @@ -581,8 +453,9 @@ public class DBController { */ public void readCache(String streamUrl) { try { - Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM cache WHERE streamUrl=\"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("SELECT * FROM cache WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ResultSet rs = ps.executeQuery(); Font font = Font.font("System", FontWeight.BOLD, (int) Math.round(mainWindowController.getFontSize())); ObservableList textFlow = mainWindowController.getTextFlow().getChildren(); ArrayList nameText = new ArrayList(); @@ -650,8 +523,8 @@ public class DBController { LOGGER.error("No Poster found, useing default."); } - stmt.close(); rs.close(); + ps.close(); } catch (SQLException e) { LOGGER.error("Ups! an error occured!", e); } @@ -686,14 +559,15 @@ public class DBController { * @return {@link Double} currentTime in ms */ public double getCurrentTime(String streamUrl) { - LOGGER.info("currentTime: " + streamUrl); + LOGGER.info("get currentTime: " + streamUrl); double currentTime = 0; try { - Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM films WHERE streamUrl = \"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE streamUrl = ?"); + ps.setString(1, streamUrl); + ResultSet rs = ps.executeQuery(); currentTime = rs.getDouble("currentTime"); rs.close(); - stmt.close(); + ps.close(); } catch (Exception e) { LOGGER.error("Ups! error while getting the current time!", e); } @@ -707,69 +581,55 @@ public class DBController { * @param currentTime currentTime in ms of the film */ public void setCurrentTime(String streamUrl, double currentTime) { - LOGGER.info("currentTime: " + streamUrl); + LOGGER.info("set currentTime: " + streamUrl); try { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("UPDATE films SET currentTime=" + currentTime + " WHERE streamUrl=\"" + streamUrl + "\";"); + PreparedStatement ps = connection.prepareStatement("UPDATE films SET currentTime = ? WHERE streamUrl = ?"); + ps.setDouble(1, currentTime); + ps.setString(2, streamUrl); + ps.executeUpdate(); connection.commit(); - stmt.close(); + ps.close(); } catch (SQLException e) { - LOGGER.error("Ups! an error occured!", e); + LOGGER.error("Ups! error while updateing the current time!", e); } } /** - * get the next episode of a - * @param title URL of the film - * @param nextEp number of the next episode + * get the next episode of a series + * @param title title of the film + * @param episode episode currently played * @return {@link FilmTabelDataType} the next episode as object */ public FilmTabelDataType getNextEpisode(String title, int episode, int season) { FilmTabelDataType nextFilm = null; - ResultSet rs; - int nextEpisode = 3000; try { - Statement stmt = connection.createStatement(); + // try to get a new episode of the current season + PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE title = ? AND season = ? AND episode = ?"); + ps.setString(1, title); + ps.setString(2, Integer.toString(season)); + ps.setString(3, Integer.toString(episode + 1)); + ResultSet rs = ps.executeQuery(); - rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\" AND season = \"" + season + "\";"); - while(rs.next()) { - int rsEpisode = Integer.parseInt(rs.getString("episode")); - if (rsEpisode > episode && rsEpisode < nextEpisode) { - // fitting episode found in current season, if rsEpisode < nextEpisode -> nextEpisode = rsEpisode - nextEpisode = rsEpisode; - nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"), - rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView()); - } + /* if that fails get the next season and try to get a episode there, + * we need to test only for the next season, first episode, + * any other entry would not exist in the database + */ + if(!rs.next()) { + ps.setString(1, title); + ps.setString(2, Integer.toString(season + 1)); + ps.setString(3, Integer.toString(1)); + rs = ps.executeQuery(); + if(!rs.next()) return nextFilm; // if we haven't found anything return an empty object } - if (nextFilm == null) { - int nextSeason = 3000; - rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\";"); - while(rs.next()) { - int rsSeason = Integer.parseInt(rs.getString("season")); - if (rsSeason > season && rsSeason < nextSeason) { - nextSeason = rsSeason; - } - } - - if (nextSeason != 3000) { - rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\" AND season = \"" + season + "\";"); - while(rs.next()) { - int rsEpisode = Integer.parseInt(rs.getString("episode")); - if (rsEpisode > episode && rsEpisode < nextEpisode) { - // fitting episode found in current season, if rsEpisode < nextEpisode -> nextEpisode = rsEpisode - nextEpisode = rsEpisode; - nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"), - rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), - rs.getBoolean("cached"), new ImageView()); - } - } - } - } + // at this point we have found the correct episode + nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"), + rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"), + rs.getBoolean("cached"), new ImageView()); + rs.close(); - stmt.close(); + ps.close(); } catch (Exception e) { LOGGER.error("Ups! error while getting next episode!", e); } @@ -810,14 +670,6 @@ public class DBController { return nextFilm; } - // removes the ending - private String cutOffEnd(String str) { - if (str == null) return null; - int pos = str.lastIndexOf("."); - if (pos == -1) return str; - return str.substring(0, pos); - } - /** * check if a file is a video * @param path the path to the file diff --git a/src/main/java/kellerkinder/HomeFlix/controller/SourcesController.java b/src/main/java/kellerkinder/HomeFlix/controller/SourcesController.java new file mode 100644 index 0000000..a875e67 --- /dev/null +++ b/src/main/java/kellerkinder/HomeFlix/controller/SourcesController.java @@ -0,0 +1,165 @@ +/** + * Project-HomeFlix + * + * Copyright 2016-2018 <@Seil0> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +package kellerkinder.HomeFlix.controller; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.eclipsesource.json.Json; +import com.eclipsesource.json.JsonArray; +import com.eclipsesource.json.JsonObject; +import com.eclipsesource.json.JsonValue; + +import kellerkinder.HomeFlix.application.Main; +import kellerkinder.HomeFlix.application.MainWindowController; +import kellerkinder.HomeFlix.datatypes.DatabaseDataType; + +public class SourcesController { + + private MainWindowController mainWindowController; + private Main main; + private List sourceStreams = new ArrayList(); + private static final Logger LOGGER = LogManager.getLogger(SourcesController.class.getName()); + + public SourcesController(Main main, MainWindowController mainWindowController) { + this.main = main; + this.mainWindowController = mainWindowController; + } + + /** + * load all local and streaming sources and add them to a list + */ + public List loadSources() { + + try { + // create a JsonArray, containing all sources, add each source to the mwc, get all films from it + JsonArray sources = Json.parse(new FileReader(main.getDirectory() + "/sources.json")).asArray(); + for (JsonValue source : sources) { + String path = source.asObject().getString("path", ""); + String mode = source.asObject().getString("mode", ""); + mainWindowController.addSourceToTable(path, mode); // add loaded source to source-table TODO this should be done in mwc + + if (mode.equals("local")) + addLocalSource(path); + if (mode.equals("stream")) + addStreamSource(path); + } + } catch (Exception e) { + e.printStackTrace(); + } + + LOGGER.info("films in directory: " + sourceStreams.size()); + + return sourceStreams; + } + /** + * for each file in source path + * check whether it's valid file or a directory (series) + * if it's valid or a series add it to the sourceStreams + * @param a local source path (a directory) + */ + private void addLocalSource(String path) { + + int oldSize = sourceStreams.size(); + for (File file : new File(path).listFiles()) { + // if it's valid file add it to the sourceStreams + if (isValidFile(file)) { + sourceStreams.add(new DatabaseDataType(file.getPath(), cutOffEnd(file.getName()), "", "", 0, false, 0.0)); + } else if(file.isDirectory()) { + // get all directories (series), root and season must be directories + int sn = 1; + for (File season : file.listFiles()) { + if (season.isDirectory()) { + int ep = 1; + for (File episode : season.listFiles()) { + // check whether the episode is a valid file + if (isValidFile(episode)) { + sourceStreams.add(new DatabaseDataType(episode.getPath(), cutOffEnd(file.getName()), + Integer.toString(sn), Integer.toString(ep), 0, false, 0.0)); + ep++; + } + } + sn++; + } + } + } + } + + LOGGER.info("added " + (sourceStreams.size() - oldSize) + " local files from: " + path); + } + + private void addStreamSource(String path) { + // getting all entries from the streaming lists + try { + JsonObject object = Json.parse(new FileReader(path)).asObject(); + JsonArray items = object.get("entries").asArray(); + for (JsonValue item : items) { + sourceStreams.add(new DatabaseDataType(item.asObject().getString("streamUrl", ""), + item.asObject().getString("title", ""), + item.asObject().getString("season", ""), + item.asObject().getString("episode", ""), 0, false, 0.0)); + } + LOGGER.info("added " + items.size() +" stream entries from: " + path); + } catch (IOException e) { + LOGGER.error(e); + } + + + } + + /** + * check if a file is a valid file (is video and file) + * @param file the actual file + * @return true if it's valid, else false + */ + private boolean isValidFile(File file) { + try { + String mimeType = Files.probeContentType(file.toPath()); + if (file.isFile() && mimeType != null && (mimeType.startsWith("video") || mimeType.contains("matroska"))) { + return true; + } else { +// System.out.println(file.getPath() + " mime type: " + mimeType); + } + } catch (IOException e) { + LOGGER.error(e); + } + + return false; + } + + // removes the ending + private String cutOffEnd(String str) { + if (str == null) return null; + int pos = str.lastIndexOf("."); + if (pos == -1) return str; + return str.substring(0, pos); + } + +} diff --git a/src/main/java/kellerkinder/HomeFlix/datatypes/DatabaseDataType.java b/src/main/java/kellerkinder/HomeFlix/datatypes/DatabaseDataType.java new file mode 100644 index 0000000..053f80b --- /dev/null +++ b/src/main/java/kellerkinder/HomeFlix/datatypes/DatabaseDataType.java @@ -0,0 +1,101 @@ +/** + * Project-HomeFlix + * + * Copyright 2016-2018 <@Seil0> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +package kellerkinder.HomeFlix.datatypes; + +public class DatabaseDataType { + + private String streamUrl; + private String title; + private String season; + private String episode; + private int favorite; + private Boolean cached; + private double currentTime; + + public DatabaseDataType(String streamUrl, String title, String season, String episode, int favorite, Boolean cached, double currentTime) { + this.streamUrl = streamUrl; + this.title = title; + this.season = season; + this.episode = episode; + this.favorite = favorite; + this.cached = cached; + this.currentTime = currentTime; + } + + public String getStreamUrl() { + return streamUrl; + } + + public void setStreamUrl(String streamUrl) { + this.streamUrl = streamUrl; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSeason() { + return season; + } + + public void setSeason(String season) { + this.season = season; + } + + public String getEpisode() { + return episode; + } + + public void setEpisode(String episode) { + this.episode = episode; + } + + public int getFavorite() { + return favorite; + } + + public void setFavorite(int favorite) { + this.favorite = favorite; + } + + public Boolean getCached() { + return cached; + } + + public void setCached(Boolean cached) { + this.cached = cached; + } + + public double getCurrentTime() { + return currentTime; + } + + public void setCurrentTime(double currentTime) { + this.currentTime = currentTime; + } + +} diff --git a/src/main/java/kellerkinder/HomeFlix/player/PlayerController.java b/src/main/java/kellerkinder/HomeFlix/player/PlayerController.java index 52f2741..4b244bf 100644 --- a/src/main/java/kellerkinder/HomeFlix/player/PlayerController.java +++ b/src/main/java/kellerkinder/HomeFlix/player/PlayerController.java @@ -19,6 +19,7 @@ * MA 02110-1301, USA. * */ + package kellerkinder.HomeFlix.player; import java.io.File;