Browse Source

reworked the DBController

* some tasks are now done at the SourcesController
* use PrepareStatement
* generall clean up
Seil0 1 week ago
parent
commit
c3a148b267

+ 11
- 4
src/main/java/kellerkinder/HomeFlix/application/MainWindowController.java View File

@@ -166,7 +166,7 @@ public class MainWindowController {
166 166
 	private boolean autoplay = false;
167 167
 
168 168
 	private final String version = "0.7.0";
169
-	private final String buildNumber = "163";
169
+	private final String buildNumber = "165";
170 170
 	private final String versionName = "toothless dragon";
171 171
 	private String btnStyle;
172 172
 	private String color;
@@ -214,7 +214,7 @@ public class MainWindowController {
214 214
 		initActions();
215 215
 		dbController.init();
216 216
 		
217
-		posterModeStartup(); // TODO testing
217
+//		posterModeStartup(); // TODO testing
218 218
 	}
219 219
 	
220 220
 	// Initialize general UI elements
@@ -550,7 +550,7 @@ public class MainWindowController {
550 550
 		directoryChooser.setTitle(bundle.getString("addDirectory"));
551 551
 		File selectedFolder = directoryChooser.showDialog(main.getPrimaryStage());
552 552
 		if (selectedFolder != null && selectedFolder.exists()) {
553
-			mainWindowController.addSource(selectedFolder.getPath(), "local");
553
+			addSource(selectedFolder.getPath(), "local");
554 554
 		} else {
555 555
 			LOGGER.error("The selected folder dosen't exist!");
556 556
 		}
@@ -563,7 +563,6 @@ public class MainWindowController {
563 563
 		File selectedFile = fileChooser.showOpenDialog(main.getPrimaryStage());
564 564
 		if (selectedFile != null && selectedFile.exists()) {
565 565
 			addSource(selectedFile.getPath(), "stream");
566
-			dbController.refreshDataBase();
567 566
 		} else {
568 567
 			LOGGER.error("The selected file dosen't exist!");
569 568
 		}
@@ -605,6 +604,8 @@ public class MainWindowController {
605 604
 	 * add data from films-list to films-table
606 605
 	 */
607 606
 	public void addFilmsToTable(ObservableList<FilmTabelDataType> elementsList) {
607
+		
608
+		System.out.println(elementsList.size());
608 609
 
609 610
 		for (FilmTabelDataType element : elementsList) {
610 611
 			
@@ -667,6 +668,12 @@ public class MainWindowController {
667 668
 		} catch (IOException e) {
668 669
 			LOGGER.error(e);
669 670
 		}
671
+		
672
+		// clear old sources list/table
673
+		getSourcesList().clear();
674
+		getSourceRoot().getChildren().clear();
675
+		// update the database and all films from the database
676
+		dbController.refreshDataBase();
670 677
 	}
671 678
 	
672 679
 	/**

+ 134
- 282
src/main/java/kellerkinder/HomeFlix/controller/DBController.java View File

@@ -18,11 +18,11 @@
18 18
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 19
  * MA 02110-1301, USA.
20 20
  */
21
+
21 22
 package kellerkinder.HomeFlix.controller;
22 23
 
23 24
 import java.io.File;
24 25
 import java.io.FileNotFoundException;
25
-import java.io.FileReader;
26 26
 import java.io.IOException;
27 27
 import java.net.URLConnection;
28 28
 import java.sql.Connection;
@@ -37,11 +37,6 @@ import java.util.List;
37 37
 import org.apache.logging.log4j.LogManager;
38 38
 import org.apache.logging.log4j.Logger;
39 39
 
40
-import com.eclipsesource.json.Json;
41
-import com.eclipsesource.json.JsonArray;
42
-import com.eclipsesource.json.JsonObject;
43
-import com.eclipsesource.json.JsonValue;
44
-
45 40
 import javafx.collections.ObservableList;
46 41
 import javafx.scene.Node;
47 42
 import javafx.scene.image.Image;
@@ -51,9 +46,9 @@ import javafx.scene.text.FontWeight;
51 46
 import javafx.scene.text.Text;
52 47
 import kellerkinder.HomeFlix.application.Main;
53 48
 import kellerkinder.HomeFlix.application.MainWindowController;
49
+import kellerkinder.HomeFlix.datatypes.DatabaseDataType;
54 50
 import kellerkinder.HomeFlix.datatypes.FilmTabelDataType;
55 51
 import kellerkinder.HomeFlix.datatypes.OMDbAPIResponseDataType;
56
-import kellerkinder.HomeFlix.datatypes.SourceDataType;
57 52
 
58 53
 public class DBController {
59 54
 	
@@ -62,8 +57,8 @@ public class DBController {
62 57
 	private String DB_PATH;
63 58
 	private Image favorite_black = new Image("icons/ic_favorite_black_18dp_1x.png");
64 59
 	private Image favorite_border_black = new Image("icons/ic_favorite_border_black_18dp_1x.png");
65
-	private List<String> filmsdbStreamURL = new ArrayList<String>(); // contains all films stored in the database
66
-	private List<String> filmsStreamURL = new ArrayList<String>(); // contains all films from the sources
60
+	private List<DatabaseDataType> databaseStream = new ArrayList<DatabaseDataType>(); // contains all films stored in the database
61
+	private List<DatabaseDataType> sourceStreams = new ArrayList<DatabaseDataType>(); // contains all films from the sources
67 62
 	private Connection connection = null;
68 63
 	private static final Logger LOGGER = LogManager.getLogger(DBController.class.getName());
69 64
 	
@@ -136,7 +131,9 @@ public class DBController {
136 131
 			Statement stmt = connection.createStatement();
137 132
 			ResultSet rs = stmt.executeQuery("SELECT * FROM films");
138 133
 			while (rs.next()) {
139
-				filmsdbStreamURL.add(rs.getString("streamUrl"));
134
+				databaseStream.add(new DatabaseDataType(rs.getString("streamUrl"),
135
+						rs.getString("title"), rs.getString("season"), rs.getString("episode"),
136
+						rs.getInt("favorite"), rs.getBoolean("cached"), rs.getDouble("currentTime")));
140 137
 			}
141 138
 			stmt.close();
142 139
 			rs.close();
@@ -146,57 +143,11 @@ public class DBController {
146 143
 	}
147 144
 	
148 145
 	/**
149
-	 * load sources from sources.json
150
-	 * if mode == local, get all files and series-folder from the directory
151
-	 * else mode must be streaming, read all entries from the streaming file 
146
+	 * load all sources
152 147
 	 */
153 148
 	private void loadSources() {
154
-		// remove sources from table
155
-		mainWindowController.getSourcesList().removeAll(mainWindowController.getSourcesList());
156
-		mainWindowController.getSourceRoot().getChildren().removeAll(mainWindowController.getSourceRoot().getChildren());
157
-		
158
-		try {
159
-			JsonArray sources = Json.parse(new FileReader(main.getDirectory() + "/sources.json")).asArray();
160
-			for (JsonValue source : sources) {
161
-				String path = source.asObject().getString("path", "");
162
-				String mode = source.asObject().getString("mode", "");
163
-				mainWindowController.addSourceToTable(path, mode); // add source to source-table
164
-				
165
-				if (mode.equals("local")) {
166
-					for (File file : new File(path).listFiles()) {
167
-						if (file.isFile() && isVideoFile(file.getPath())) {
168
-							filmsStreamURL.add(file.getPath());
169
-						} else if(file.isDirectory()) {
170
-							// get all folders (series)
171
-							for (File season : file.listFiles()) {
172
-								if (season.isDirectory()) {
173
-									for (File episode : season.listFiles()) {
174
-										if (!filmsdbStreamURL.contains(episode.getPath())) {
175
-											filmsStreamURL.add(episode.getPath());
176
-										}
177
-									}
178
-								}
179
-							}
180
-						}
181
-					}
182
-					LOGGER.info("added files from: " + path);
183
-				} else {
184
-					// getting all entries from the streaming lists
185
-					try {
186
-						JsonObject object = Json.parse(new FileReader(path)).asObject();
187
-						JsonArray items = object.get("entries").asArray();
188
-						for (JsonValue item : items) {
189
-							filmsStreamURL.add(item.asObject().getString("streamUrl", ""));
190
-						}
191
-						LOGGER.info("added films from: " + path);
192
-					} catch (IOException e) {
193
-						LOGGER.error(e);
194
-					}
195
-				}
196
-			}
197
-		} catch (Exception e) {
198
-			e.printStackTrace();
199
-		}
149
+		SourcesController sourcesController = new SourcesController(main, mainWindowController);
150
+		sourceStreams = sourcesController.loadSources();
200 151
 	}
201 152
 	
202 153
 	/**
@@ -204,22 +155,18 @@ public class DBController {
204 155
 	 * order entries by title
205 156
 	 */
206 157
 	private void loadDataToFilmsList() {
158
+		ImageView imageView;
207 159
 		LOGGER.info("loading data to mwc ...");
208 160
 		try {
209 161
 			//load local Data
210 162
 			Statement stmt = connection.createStatement(); 
211
-			ResultSet rs = stmt.executeQuery("SELECT * FROM films ORDER BY title"); 
163
+			ResultSet rs = stmt.executeQuery("SELECT * FROM films ORDER BY title");
164
+			
212 165
 			while (rs.next()) {
213
-//				System.out.println(rs.getString("title") + "Season:"  + rs.getString("season") + ":");
214
-				if (rs.getBoolean("favorite") == true) {
215
-					mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"),
216
-							rs.getString("title"), rs.getString("season"), rs.getString("episode") ,rs.getBoolean("favorite"),
217
-							rs.getBoolean("cached"), new ImageView(favorite_black)));
218
-				} else {
219
-					mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"),
220
-							rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
221
-							rs.getBoolean("cached"), new ImageView(favorite_border_black)));
222
-				}
166
+				imageView = rs.getBoolean("favorite") ? new ImageView(favorite_black) : new ImageView(favorite_border_black);
167
+				mainWindowController.getFilmsList().add(new FilmTabelDataType(rs.getString("streamUrl"),
168
+						rs.getString("title"), rs.getString("season"), rs.getString("episode") ,rs.getBoolean("favorite"),
169
+						rs.getBoolean("cached"), imageView));
223 170
 			}
224 171
 			stmt.close();
225 172
 			rs.close();		
@@ -237,24 +184,20 @@ public class DBController {
237 184
 	 * @param index of the film in LocalFilms list
238 185
 	 */
239 186
 	public void refresh(String streamUrl, int indexList) {
240
-		LOGGER.info("refresh ...");
187
+		LOGGER.info("refresh data for " + streamUrl);
241 188
 		try {
242
-			Statement stmt = connection.createStatement();
243
-			ResultSet rs = stmt.executeQuery("SELECT * FROM films WHERE streamUrl = \"" + streamUrl + "\";");
189
+			PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE streamUrl = ?");
190
+			ps.setString(1, streamUrl);
191
+			ResultSet rs = ps.executeQuery();
244 192
 			
245 193
 			while (rs.next()) {
246
-				if (rs.getBoolean("favorite") == true) {
247
-					mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"),
248
-							rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
249
-							rs.getBoolean("cached"), new ImageView(favorite_black)));
250
-				} else {
251
-					mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"),
252
-							rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
253
-							rs.getBoolean("cached"), new ImageView(favorite_border_black)));
254
-				}
194
+				ImageView imageView = rs.getBoolean("favorite") ? new ImageView(favorite_black) : new ImageView(favorite_border_black);
195
+				mainWindowController.getFilmsList().set(indexList, new FilmTabelDataType(rs.getString("streamUrl"),
196
+						rs.getString("title"), rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
197
+						rs.getBoolean("cached"), imageView));
255 198
 			}
256 199
 			rs.close();
257
-			stmt.close();
200
+			ps.close();
258 201
 		} catch (Exception e) {
259 202
 			LOGGER.error("Ups! error while refreshing mwc!", e);
260 203
 		} 
@@ -269,14 +212,13 @@ public class DBController {
269 212
 		LOGGER.info("refreshing the Database ...");
270 213
 		
271 214
 		// clean all ArraLists
272
-		filmsdbStreamURL.clear();
273
-		filmsStreamURL.clear();
215
+		databaseStream.clear();
216
+		sourceStreams.clear();
274 217
 		
275 218
 		loadSources(); // reload all sources
276 219
 		loadDatabase(); // reload all films saved in the DB
277 220
 		
278
-		LOGGER.info("films in directory: " + filmsStreamURL.size());
279
-		LOGGER.info("filme in db: " + filmsdbStreamURL.size());
221
+		LOGGER.info("filme in db: " + databaseStream.size());
280 222
 		
281 223
 		try {
282 224
 			checkAddEntry();
@@ -285,7 +227,7 @@ public class DBController {
285 227
 			LOGGER.error("Error while refreshing the database", e);
286 228
 		}
287 229
 		
288
-		// clear the FilmsList and FilmRoot chlidren
230
+		// clear the FilmsList and FilmRoot children
289 231
 		mainWindowController.getFilmsList().clear();
290 232
 		mainWindowController.getFilmRoot().getChildren().clear();
291 233
 		
@@ -294,25 +236,32 @@ public class DBController {
294 236
 
295 237
 	/**
296 238
 	 * check if there are any entries that have been removed from the film-directory
239
+	 * @throws SQLException 
297 240
 	 */
298
-	private void checkRemoveEntry() {
241
+	private void checkRemoveEntry() throws SQLException {
242
+		PreparedStatement ps = connection.prepareStatement("DELETE FROM films WHERE streamUrl = ?");
299 243
 		LOGGER.info("checking for entrys to remove to DB ...");
300
-		try {
301
-			Statement stmt = connection.createStatement();
244
+		
245
+		for (DatabaseDataType dbStreamEntry : databaseStream) {
246
+			// if the directory doen't contain the entry form the database, remove it
302 247
 			
303
-			for (String entry : filmsdbStreamURL) {
304
-				// if the directory doen't contain the entry form the db, remove it
305
-				if (!filmsStreamURL.contains(entry)) {
306
-					stmt.executeUpdate("delete from films where streamUrl = \"" + entry + "\"");
307
-					connection.commit();
308
-					LOGGER.info("removed \"" + entry + "\" from database");
309
-				}
248
+			// if sourceStreams has a item where StreamUrl equals dbStreamEntry.getStreamUrl() return it, else null
249
+			DatabaseDataType result = sourceStreams.stream()
250
+					.filter(x -> dbStreamEntry.getStreamUrl().equals(x.getStreamUrl()))
251
+					.findAny()
252
+					.orElse(null);
253
+			
254
+			// if the result is null, the file is missing, remove it from the database
255
+			if (result == null) {
256
+				ps.setString(1, dbStreamEntry.getStreamUrl());
257
+				ps.addBatch();
258
+				LOGGER.info("removed \"" + dbStreamEntry.getTitle() + "\" from database");
310 259
 			}
311
-
312
-			stmt.close();
313
-		} catch (Exception e) {
314
-			LOGGER.error(e);
315 260
 		}
261
+		
262
+		ps.executeBatch();
263
+		connection.commit();
264
+		ps.close();
316 265
 	}
317 266
 	
318 267
 	/**
@@ -325,114 +274,33 @@ public class DBController {
325 274
 		PreparedStatement ps = connection.prepareStatement("insert into films values (?, ?, ?, ?, ?, ?, ?)");
326 275
 		LOGGER.info("checking for entrys to add to DB ...");
327 276
 		
328
-		// source is a single source of the sources list
329
-		for (SourceDataType source : mainWindowController.getSourcesList()) {
330
-			// if it's a local source check the folder for new film
331
-			if (source.getMode().equals("local")) {
332
-				for (File file : new File(source.getPath()).listFiles()) {
333
-					String mimeType = URLConnection.guessContentTypeFromName(file.getPath());
334
-					// if file is file and has mime type "video"
335
-					if (file.isFile() && mimeType != null && mimeType.contains("video")) {
336
-						// get all files (films)
337
-						if (!filmsdbStreamURL.contains(file.getPath())) {					
338
-							ps.setString(1, file.getPath());
339
-							ps.setString(2, cutOffEnd(file.getName()));
340
-							ps.setString(3, "");
341
-							ps.setString(4, "");
342
-							ps.setInt(5, 0);
343
-							ps.setBoolean(6, false);
344
-							ps.setDouble(7, 0);
345
-							ps.addBatch(); // adds the entry
346
-							LOGGER.info("Added \"" + file.getName() + "\" to database");
347
-							filmsdbStreamURL.add(file.getPath());
348
-						}
349
-					} else if (file.isDirectory()) {
350
-						// get all folders (series)
351
-						int sn = 1;
352
-						for (File season : file.listFiles()) {
353
-							if (season.isDirectory()) {
354
-								int ep = getLastEpisode(cutOffEnd(file.getName()), Integer.toString(sn)) + 1;
355
-								for (File episode : season.listFiles()) {
356
-									if (!filmsdbStreamURL.contains(episode.getPath())) {		
357
-										ps.setString(1, episode.getPath().replace("'", "''"));
358
-										ps.setString(2, cutOffEnd(file.getName())); // the title is the series root folder's name
359
-										ps.setString(3, Integer.toString(sn));
360
-										ps.setString(4, Integer.toString(ep));
361
-										ps.setInt(5, 0);
362
-										ps.setBoolean(6, false);
363
-										ps.setDouble(7, 0);
364
-										ps.addBatch(); // adds the entry				
365
-										LOGGER.info("Added \"" + file.getName() + "\", Episode: " + episode.getName() + " to database");
366
-										filmsStreamURL.add(episode.getPath());
367
-										filmsdbStreamURL.add(episode.getPath());
368
-										ep++;
369
-									}
370
-								}
371
-								sn++;
372
-							}
373
-						}
374
-					}
375
-					
376
-				}
377
-			} else {
378
-				// if it's a streaming source check the file for new films
379
-				for (String entry : filmsStreamURL) {
380
-					if (!filmsdbStreamURL.contains(entry)) {
381
-						JsonArray items = Json.parse(new FileReader(source.getPath())).asObject().get("entries").asArray();
382
-						// for each item, check if it's the needed
383
-						for (JsonValue item : items) {
384
-							String streamUrl = item.asObject().getString("streamUrl", "");
385
-							String title = item.asObject().getString("title", "");
386
-							
387
-							// if it's the needed add it to the database
388
-							if (streamUrl.equals(entry)) {
389
-								ps.setString(1, streamUrl);
390
-								ps.setString(2, title);
391
-								ps.setString(3, item.asObject().getString("season", ""));
392
-								ps.setString(4, item.asObject().getString("episode", ""));
393
-								ps.setInt(5, 0);
394
-								ps.setBoolean(6, false);
395
-								ps.setDouble(7, 0);
396
-								ps.addBatch(); // adds the entry
397
-								LOGGER.info("Added \"" + title + "\" to database");
398
-								filmsdbStreamURL.add(streamUrl);
399
-							}
400
-						}
401
-					}
402
-				}
403
-				ps.executeBatch();
404
-				connection.commit();
405
-				ps.close();
277
+		// new
278
+		for (DatabaseDataType sourceStreamEntry : sourceStreams) {
279
+			
280
+			// if databaseStream has a item where StreamUrl equals sourceStreamEntry.getStreamUrl() return it, else null
281
+			DatabaseDataType result = databaseStream.stream()
282
+					.filter(x -> sourceStreamEntry.getStreamUrl().equals(x.getStreamUrl()))
283
+					.findAny()
284
+					.orElse(null);
285
+			
286
+			// if the result is null, the entry is missing, add it to the database
287
+			if (result == null) {
288
+				ps.setString(1, sourceStreamEntry.getStreamUrl());
289
+				ps.setString(2, sourceStreamEntry.getTitle());
290
+				ps.setString(3, sourceStreamEntry.getSeason());
291
+				ps.setString(4, sourceStreamEntry.getEpisode());
292
+				ps.setInt(5, sourceStreamEntry.getFavorite());
293
+				ps.setBoolean(6, sourceStreamEntry.getCached());
294
+				ps.setDouble(7, sourceStreamEntry.getCurrentTime());
295
+				ps.addBatch(); // adds the entry
296
+				LOGGER.info("Added \"" + sourceStreamEntry.getTitle() + "\" to database");
297
+				databaseStream.add(sourceStreamEntry);
406 298
 			}
407 299
 		}
408
-	}
409
-	
410
-	/**
411
-	 * gets the last episode of a season of a given series
412
-	 * @param seriesTitle the actual series
413
-	 * @param season      the actual season
414
-	 * @return the last episode number
415
-	 */
416
-	private int getLastEpisode(String seriesTitle, String season) {
417
-		int lastEpisode = 0;
418
-		try {
419
-			Statement stmt = connection.createStatement();
420
-			PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE title = ? AND season = ?");
421
-			ps.setString(1, seriesTitle);
422
-			ps.setString(2, season);
423
-			ResultSet rs = ps.executeQuery();
424
-
425
-			while (rs.next()) {
426
-				if (Integer.parseInt(rs.getString("episode")) > lastEpisode)
427
-					lastEpisode = Integer.parseInt(rs.getString("episode"));
428
-			}
429
-			stmt.close();
430
-			rs.close();
431
-		} catch (SQLException e) {
432
-			LOGGER.error("An error occured, while printing all entries", e);
433
-		}
434
-
435
-		return lastEpisode;
300
+		
301
+		ps.executeBatch();
302
+		connection.commit();
303
+		ps.close();
436 304
 	}
437 305
 	
438 306
 	/**
@@ -453,8 +321,8 @@ public class DBController {
453 321
 				System.out.println(rs.getString("cached"));
454 322
 				System.out.println(rs.getString("currentTime") + "\n");
455 323
 			}
456
-			stmt.close();
457 324
 			rs.close();
325
+			stmt.close();	
458 326
 		} catch (SQLException e) {
459 327
 			LOGGER.error("An error occured, while printing all entries", e);
460 328
 		}
@@ -467,10 +335,11 @@ public class DBController {
467 335
 	public void dislike(String streamUrl) {
468 336
 		LOGGER.info("dislike " + streamUrl);
469 337
 		try {
470
-			Statement stmt = connection.createStatement();
471
-			stmt.executeUpdate("UPDATE films SET favorite=0 WHERE streamUrl=\"" + streamUrl + "\";");
338
+			PreparedStatement ps = connection.prepareStatement("UPDATE films SET favorite = 0 WHERE streamUrl = ?");
339
+			ps.setString(1, streamUrl);
340
+			ps.executeUpdate();
472 341
 			connection.commit();
473
-			stmt.close();
342
+			ps.close();
474 343
 		} catch (SQLException e) {
475 344
 			LOGGER.error("Ups! an error occured!", e);
476 345
 		}
@@ -483,10 +352,11 @@ public class DBController {
483 352
 	public void like(String streamUrl) {
484 353
 		LOGGER.info("like " + streamUrl);
485 354
 		try {
486
-			Statement stmt = connection.createStatement();
487
-			stmt.executeUpdate("UPDATE films SET favorite = 1 WHERE streamUrl = \"" + streamUrl + "\";");
355
+			PreparedStatement ps = connection.prepareStatement("UPDATE films SET favorite = 1 WHERE streamUrl = ?");
356
+			ps.setString(1, streamUrl);
357
+			ps.executeUpdate();
488 358
 			connection.commit();
489
-			stmt.close();
359
+			ps.close();
490 360
 		} catch (SQLException e) {
491 361
 			LOGGER.error("Ups! an error occured!", e);
492 362
 		}
@@ -498,10 +368,11 @@ public class DBController {
498 368
 	 */
499 369
 	public void setCached(String streamUrl) {
500 370
 		try {
501
-			Statement stmt = connection.createStatement();
502
-			stmt.executeUpdate("UPDATE films SET cached = 1 WHERE streamUrl = \"" + streamUrl + "\";");
371
+			PreparedStatement ps = connection.prepareStatement("UPDATE films SET cached = 1 WHERE streamUrl = ?");
372
+			ps.setString(1, streamUrl);
373
+			ps.executeUpdate();
503 374
 			connection.commit();
504
-			stmt.close();
375
+			ps.close();
505 376
 		} catch (SQLException e) {
506 377
 			LOGGER.error("Ups! an error occured!", e);
507 378
 		}
@@ -563,11 +434,12 @@ public class DBController {
563 434
 	public boolean searchCacheByURL(String streamUrl) {
564 435
 		boolean retValue = false;
565 436
 		try {
566
-			Statement stmt = connection.createStatement();
567
-			ResultSet rs = stmt.executeQuery("SELECT * FROM cache WHERE streamUrl = \"" + streamUrl + "\";");
437
+			PreparedStatement ps = connection.prepareStatement("SELECT * FROM cache WHERE streamUrl = ?");
438
+			ps.setString(1, streamUrl);
439
+			ResultSet rs = ps.executeQuery();
568 440
 			retValue = rs.next();
569 441
 			rs.close();
570
-			stmt.close();
442
+			ps.close();
571 443
 		} catch (Exception e) {
572 444
 			LOGGER.error("Ups! error while getting the current time!", e);
573 445
 		}
@@ -581,8 +453,9 @@ public class DBController {
581 453
 	 */
582 454
 	public void readCache(String streamUrl) {
583 455
 		try {
584
-			Statement stmt = connection.createStatement();
585
-			ResultSet rs = stmt.executeQuery("SELECT * FROM cache WHERE streamUrl=\"" + streamUrl + "\";");
456
+			PreparedStatement ps = connection.prepareStatement("SELECT * FROM cache WHERE streamUrl = ?");
457
+			ps.setString(1, streamUrl);
458
+			ResultSet rs = ps.executeQuery();
586 459
 			Font font = Font.font("System", FontWeight.BOLD, (int) Math.round(mainWindowController.getFontSize()));
587 460
 			ObservableList<Node> textFlow = mainWindowController.getTextFlow().getChildren();	
588 461
 			ArrayList<Text> nameText = new ArrayList<Text>();
@@ -650,8 +523,8 @@ public class DBController {
650 523
 				LOGGER.error("No Poster found, useing default.");
651 524
 			}
652 525
 			
653
-			stmt.close();
654 526
 			rs.close();
527
+			ps.close();
655 528
 		} catch (SQLException e) {
656 529
 			LOGGER.error("Ups! an error occured!", e);
657 530
 		}
@@ -686,14 +559,15 @@ public class DBController {
686 559
 	 * @return {@link Double} currentTime in ms
687 560
 	 */
688 561
 	public double getCurrentTime(String streamUrl) {
689
-		LOGGER.info("currentTime: " + streamUrl);
562
+		LOGGER.info("get currentTime: " + streamUrl);
690 563
 		double currentTime = 0;
691 564
 		try {
692
-			Statement stmt = connection.createStatement();
693
-			ResultSet rs = stmt.executeQuery("SELECT * FROM films WHERE streamUrl = \"" + streamUrl + "\";");
565
+			PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE streamUrl = ?");
566
+			ps.setString(1, streamUrl);
567
+			ResultSet rs = ps.executeQuery();
694 568
 			currentTime = rs.getDouble("currentTime");
695 569
 			rs.close();
696
-			stmt.close();
570
+			ps.close();
697 571
 		} catch (Exception e) {
698 572
 			LOGGER.error("Ups! error while getting the current time!", e);
699 573
 		} 
@@ -707,69 +581,55 @@ public class DBController {
707 581
 	 * @param currentTime	currentTime in ms of the film
708 582
 	 */
709 583
 	public void setCurrentTime(String streamUrl, double currentTime) {
710
-		LOGGER.info("currentTime: " + streamUrl);
584
+		LOGGER.info("set currentTime: " + streamUrl);
711 585
 		try {
712
-			Statement stmt = connection.createStatement();
713
-			stmt.executeUpdate("UPDATE films SET currentTime=" + currentTime + " WHERE streamUrl=\"" + streamUrl + "\";");
586
+			PreparedStatement ps = connection.prepareStatement("UPDATE films SET currentTime = ? WHERE streamUrl = ?");
587
+			ps.setDouble(1, currentTime);
588
+			ps.setString(2, streamUrl);
589
+			ps.executeUpdate();
714 590
 			connection.commit();
715
-			stmt.close();
591
+			ps.close();
716 592
 		} catch (SQLException e) {
717
-			LOGGER.error("Ups! an error occured!", e);
593
+			LOGGER.error("Ups! error while updateing the current time!", e);
718 594
 		}
719 595
 	}
720 596
 	
721 597
 	/**
722
-	 * get the next episode of a 
723
-	 * @param title	URL of the film
724
-	 * @param nextEp	number of the next episode
598
+	 * get the next episode of a series
599
+	 * @param title		title of the film
600
+	 * @param episode	episode currently played
725 601
 	 * @return {@link FilmTabelDataType} the next episode as object
726 602
 	 */
727 603
 	public FilmTabelDataType getNextEpisode(String title, int episode, int season) {
728 604
 		FilmTabelDataType nextFilm = null;
729
-		ResultSet rs;
730
-		int nextEpisode = 3000;
731 605
 		
732 606
 		try {
733
-			Statement stmt = connection.createStatement();
607
+			// try to get a new episode of the current season
608
+			PreparedStatement ps = connection.prepareStatement("SELECT * FROM films WHERE title = ?  AND season = ? AND episode = ?");
609
+			ps.setString(1, title);
610
+			ps.setString(2, Integer.toString(season));
611
+			ps.setString(3, Integer.toString(episode + 1));
612
+			ResultSet rs = ps.executeQuery();
734 613
 			
735
-			rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\" AND season = \"" + season + "\";");
736
-			while(rs.next()) {
737
-				int rsEpisode = Integer.parseInt(rs.getString("episode"));
738
-				if (rsEpisode > episode && rsEpisode < nextEpisode) {
739
-					// fitting episode found in current season, if rsEpisode < nextEpisode -> nextEpisode = rsEpisode
740
-					nextEpisode = rsEpisode;
741
-					nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"),
742
-							rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
743
-							rs.getBoolean("cached"), new ImageView());
744
-				}
614
+			/*  if that fails get the next season and try to get a episode there,
615
+			 *  we need to test only for the next season, first episode,
616
+			 *  any other entry would not exist in the database
617
+			 */
618
+			if(!rs.next()) {
619
+				ps.setString(1, title);
620
+				ps.setString(2, Integer.toString(season + 1));
621
+				ps.setString(3, Integer.toString(1));
622
+				rs = ps.executeQuery();
623
+				if(!rs.next()) return nextFilm; // if we haven't found anything return an empty object
745 624
 			}
746 625
 			
747
-			if (nextFilm == null) {
748
-				int nextSeason = 3000;
749
-				rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\";");
750
-				while(rs.next()) {
751
-					int rsSeason = Integer.parseInt(rs.getString("season"));
752
-					if (rsSeason > season && rsSeason < nextSeason) {
753
-						nextSeason = rsSeason;
754
-					}
755
-				}
756
-				
757
-				if (nextSeason != 3000) {
758
-					rs = stmt.executeQuery("SELECT * FROM films WHERE title = \"" + title + "\" AND season = \"" + season + "\";");
759
-					while(rs.next()) {
760
-						int rsEpisode = Integer.parseInt(rs.getString("episode"));
761
-						if (rsEpisode > episode && rsEpisode < nextEpisode) {
762
-							// fitting episode found in current season, if rsEpisode < nextEpisode -> nextEpisode = rsEpisode
763
-							nextEpisode = rsEpisode;
764
-							nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"),
765
-									rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
766
-									rs.getBoolean("cached"), new ImageView());
767
-						}
768
-					}
769
-				}
770
-			}
626
+			// at this point we have found the correct episode
627
+			nextFilm = new FilmTabelDataType(rs.getString("streamUrl"), rs.getString("title"),
628
+					rs.getString("season"), rs.getString("episode"), rs.getBoolean("favorite"),
629
+					rs.getBoolean("cached"), new ImageView());
630
+			
771 631
 			rs.close();
772
-			stmt.close();
632
+			ps.close();
773 633
 		} catch (Exception e) {
774 634
 			LOGGER.error("Ups! error while getting next episode!", e);
775 635
 		}
@@ -810,14 +670,6 @@ public class DBController {
810 670
 		return nextFilm;
811 671
 	}
812 672
 	
813
-	// removes the ending
814
-	private String cutOffEnd(String str) {
815
-		if (str == null) return null;
816
-		int pos = str.lastIndexOf(".");
817
-		if (pos == -1) return str;
818
-		return str.substring(0, pos);
819
-	}
820
-	
821 673
 	/**
822 674
 	 * check if a file is a video
823 675
 	 * @param path the path to the file

+ 165
- 0
src/main/java/kellerkinder/HomeFlix/controller/SourcesController.java View File

@@ -0,0 +1,165 @@
1
+/**
2
+ * Project-HomeFlix
3
+ *
4
+ * Copyright 2016-2018  <@Seil0>
5
+ * 
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ * 
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+ * GNU General Public License for more details.
15
+ * 
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
+ * MA 02110-1301, USA.
20
+ * 
21
+ */
22
+
23
+package kellerkinder.HomeFlix.controller;
24
+
25
+import java.io.File;
26
+import java.io.FileReader;
27
+import java.io.IOException;
28
+import java.nio.file.Files;
29
+import java.util.ArrayList;
30
+import java.util.List;
31
+
32
+import org.apache.logging.log4j.LogManager;
33
+import org.apache.logging.log4j.Logger;
34
+
35
+import com.eclipsesource.json.Json;
36
+import com.eclipsesource.json.JsonArray;
37
+import com.eclipsesource.json.JsonObject;
38
+import com.eclipsesource.json.JsonValue;
39
+
40
+import kellerkinder.HomeFlix.application.Main;
41
+import kellerkinder.HomeFlix.application.MainWindowController;
42
+import kellerkinder.HomeFlix.datatypes.DatabaseDataType;
43
+
44
+public class SourcesController {
45
+	
46
+	private MainWindowController mainWindowController;
47
+	private Main main;
48
+	private List<DatabaseDataType> sourceStreams = new ArrayList<DatabaseDataType>();
49
+	private static final Logger LOGGER = LogManager.getLogger(SourcesController.class.getName());
50
+	
51
+	public SourcesController(Main main, MainWindowController mainWindowController) {	
52
+		this.main = main;
53
+		this.mainWindowController = mainWindowController;
54
+	}
55
+	
56
+	/**
57
+	 * load all local and streaming sources and add them to a list
58
+	 */
59
+	public List<DatabaseDataType> loadSources() {
60
+		
61
+		try {
62
+			// create a JsonArray, containing all sources, add each source to the mwc, get all films from it
63
+			JsonArray sources = Json.parse(new FileReader(main.getDirectory() + "/sources.json")).asArray();
64
+			for (JsonValue source : sources) {
65
+				String path = source.asObject().getString("path", "");
66
+				String mode = source.asObject().getString("mode", "");
67
+				mainWindowController.addSourceToTable(path, mode); // add loaded source to source-table TODO this should be done in mwc
68
+				
69
+				if (mode.equals("local"))
70
+					addLocalSource(path);
71
+				if (mode.equals("stream"))
72
+					addStreamSource(path);
73
+			}
74
+		} catch (Exception e) {
75
+			e.printStackTrace();
76
+		}
77
+		
78
+		LOGGER.info("films in directory: " + sourceStreams.size());
79
+		
80
+		return sourceStreams;
81
+	}
82
+	/** 
83
+	 * for each file in source path
84
+	 * check whether it's valid file or a directory (series)
85
+	 * if it's valid or a series add it to the sourceStreams
86
+	 * @param	a local source path (a directory)
87
+	 */
88
+	private void addLocalSource(String path) {
89
+
90
+		int oldSize = sourceStreams.size();
91
+		for (File file : new File(path).listFiles()) {
92
+			// if it's valid file add it to the sourceStreams
93
+			if (isValidFile(file)) {
94
+				sourceStreams.add(new DatabaseDataType(file.getPath(), cutOffEnd(file.getName()), "", "", 0, false, 0.0));
95
+			} else if(file.isDirectory()) {
96
+				// get all directories (series), root and season must be directories
97
+				int sn = 1;
98
+				for (File season : file.listFiles()) {
99
+					if (season.isDirectory()) {
100
+						int ep = 1;
101
+						for (File episode : season.listFiles()) {
102
+							// check whether the episode is a valid file
103
+							if (isValidFile(episode)) {
104
+								sourceStreams.add(new DatabaseDataType(episode.getPath(), cutOffEnd(file.getName()),
105
+										Integer.toString(sn), Integer.toString(ep), 0, false, 0.0));
106
+								ep++;
107
+							}
108
+						}
109
+						sn++;
110
+					}
111
+				}
112
+			}
113
+		}
114
+		
115
+		LOGGER.info("added " + (sourceStreams.size() - oldSize) + " local files from: " + path);
116
+	}
117
+	
118
+	private void addStreamSource(String path) {
119
+		// getting all entries from the streaming lists
120
+		try {
121
+			JsonObject object = Json.parse(new FileReader(path)).asObject();
122
+			JsonArray items = object.get("entries").asArray();
123
+			for (JsonValue item : items) {
124
+				sourceStreams.add(new DatabaseDataType(item.asObject().getString("streamUrl", ""),
125
+						item.asObject().getString("title", ""),
126
+						item.asObject().getString("season", ""),
127
+						item.asObject().getString("episode", ""), 0, false, 0.0));
128
+			}
129
+			LOGGER.info("added " + items.size() +" stream entries from: " + path);
130
+		} catch (IOException e) {
131
+			LOGGER.error(e);
132
+		}
133
+		
134
+		
135
+	}
136
+	
137
+	/**
138
+	 * check if a file is a valid file (is video and file)
139
+	 * @param file the actual file
140
+	 * @return true if it's valid, else false
141
+	 */
142
+	private boolean isValidFile(File file) {
143
+		try {
144
+			String mimeType = Files.probeContentType(file.toPath());
145
+			if (file.isFile() && mimeType != null && (mimeType.startsWith("video") || mimeType.contains("matroska"))) {
146
+				return true;
147
+			} else {
148
+//				System.out.println(file.getPath() + " mime type: " + mimeType);
149
+			}
150
+		} catch (IOException e) {
151
+			LOGGER.error(e);
152
+		}
153
+		
154
+		return false;
155
+	}
156
+
157
+	// removes the ending
158
+	private String cutOffEnd(String str) {
159
+		if (str == null) return null;
160
+		int pos = str.lastIndexOf(".");
161
+		if (pos == -1) return str;
162
+		return str.substring(0, pos);
163
+	}
164
+	
165
+}

+ 101
- 0
src/main/java/kellerkinder/HomeFlix/datatypes/DatabaseDataType.java View File

@@ -0,0 +1,101 @@
1
+/**
2
+ * Project-HomeFlix
3
+ *
4
+ * Copyright 2016-2018  <@Seil0>
5
+ * 
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ * 
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+ * GNU General Public License for more details.
15
+ * 
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
+ * MA 02110-1301, USA.
20
+ * 
21
+ */
22
+
23
+package kellerkinder.HomeFlix.datatypes;
24
+
25
+public class DatabaseDataType {
26
+	
27
+	private String streamUrl;
28
+	private String title;
29
+	private String season;
30
+	private String episode;
31
+	private int favorite;
32
+	private Boolean cached;
33
+	private double currentTime;
34
+	
35
+	public DatabaseDataType(String streamUrl, String title, String season, String episode, int favorite, Boolean cached, double currentTime) {
36
+		this.streamUrl = streamUrl;
37
+		this.title = title;
38
+		this.season = season;
39
+		this.episode = episode;
40
+		this.favorite = favorite;
41
+		this.cached = cached;
42
+		this.currentTime = currentTime;
43
+	}
44
+
45
+	public String getStreamUrl() {
46
+		return streamUrl;
47
+	}
48
+
49
+	public void setStreamUrl(String streamUrl) {
50
+		this.streamUrl = streamUrl;
51
+	}
52
+
53
+	public String getTitle() {
54
+		return title;
55
+	}
56
+
57
+	public void setTitle(String title) {
58
+		this.title = title;
59
+	}
60
+
61
+	public String getSeason() {
62
+		return season;
63
+	}
64
+
65
+	public void setSeason(String season) {
66
+		this.season = season;
67
+	}
68
+
69
+	public String getEpisode() {
70
+		return episode;
71
+	}
72
+
73
+	public void setEpisode(String episode) {
74
+		this.episode = episode;
75
+	}
76
+
77
+	public int getFavorite() {
78
+		return favorite;
79
+	}
80
+
81
+	public void setFavorite(int favorite) {
82
+		this.favorite = favorite;
83
+	}
84
+
85
+	public Boolean getCached() {
86
+		return cached;
87
+	}
88
+
89
+	public void setCached(Boolean cached) {
90
+		this.cached = cached;
91
+	}
92
+
93
+	public double getCurrentTime() {
94
+		return currentTime;
95
+	}
96
+
97
+	public void setCurrentTime(double currentTime) {
98
+		this.currentTime = currentTime;
99
+	}
100
+
101
+}

+ 1
- 0
src/main/java/kellerkinder/HomeFlix/player/PlayerController.java View File

@@ -19,6 +19,7 @@
19 19
  * MA 02110-1301, USA.
20 20
  * 
21 21
  */
22
+
22 23
 package kellerkinder.HomeFlix.player;
23 24
 
24 25
 import java.io.File;

Loading…
Cancel
Save