From e1efbafe4511d50fedd1e51e6405412813addd52 Mon Sep 17 00:00:00 2001 From: Giacomo Date: Wed, 12 Sep 2018 22:59:20 +0200 Subject: [PATCH] Musich! - added working class for retrieving videos ID and playing them - added a test for it - added some dependencies (SWT and NativeSwing) --- build.gradle | 6 ++ src/main/java/main/Main.java | 23 +---- src/main/java/support/Musich.java | 131 +++++++++++++++++++++++++++-- src/test/java/test/TestMusich.java | 34 ++++++++ 4 files changed, 165 insertions(+), 29 deletions(-) create mode 100644 src/test/java/test/TestMusich.java diff --git a/build.gradle b/build.gradle index 0a4781d..402ebbf 100644 --- a/build.gradle +++ b/build.gradle @@ -47,4 +47,10 @@ dependencies { // objectMapper for fitbitdata compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.5' // maybe duplicate in google-api + + // YOUTUBE VIDEO + compile 'org.eclipse.swt:org.eclipse.swt.win32.win32.x86_64:4.3' //Winzozz + // compile 'org.eclipse.swt:org.eclipse.swt.gtk.linux.x86_64:4.3' //Linuzuzz + compile group: 'com.hynnet', name: 'DJNativeSwing', version: '1.0.0' + compile group: 'com.hynnet', name: 'DJNativeSwing-SWT', version: '1.0.0' } diff --git a/src/main/java/main/Main.java b/src/main/java/main/Main.java index 99bc8c8..e716729 100644 --- a/src/main/java/main/Main.java +++ b/src/main/java/main/Main.java @@ -9,10 +9,6 @@ import support.database.Database; import support.database.LocalDB; import support.database.RemoteDB; -import java.awt.*; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Calendar; import java.util.HashMap; import java.util.List; @@ -35,6 +31,7 @@ public class Main { private static Fitbit fitbit = null; private static Sensor sensor = null; private static Database database = null; + private static Musich musich = null; /** * Funzione principale, qui si creano tutte le classi che verranno utilizzate.
@@ -51,24 +48,6 @@ public class Main { * @param args */ public static void main(String[] args) { - List urls = Musich.getVideosId("musica rilassante"); - - try { - String url = Musich.SEARCH_URL + urls.get(0); - System.out.println(url); - Process p = Runtime.getRuntime().exec(new String[] {"start chrome", "\"" + url + "\"" }); - - p.wait( 10 * 1000); // 10 sec - - p.destroy(); - - } catch (Exception e) { - e.printStackTrace(); - } - - if(true) - return; - Map arguments = getArgsMap(args); // list of arguments to use in the classes diff --git a/src/main/java/support/Musich.java b/src/main/java/support/Musich.java index 9006877..c6126e3 100644 --- a/src/main/java/support/Musich.java +++ b/src/main/java/support/Musich.java @@ -1,8 +1,11 @@ package support; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import chrriis.dj.nativeswing.swtimpl.NativeInterface; +import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser; +import javax.swing.*; +import java.awt.*; +import java.awt.event.WindowEvent; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; @@ -10,17 +13,52 @@ import java.util.List; import java.util.Map; /** - * Created by 20015159 on 11/09/2018. + * Classe che serve a far partire un video di youtube in una frame */ public class Musich { - public static final String SEARCH_URL = "https://www.youtube.com/watch?v="; - + /** + * L'url da dove possiamo pescare i dati di youtube dei video + */ private static final String API_URL = "https://www.googleapis.com/youtube/v3/search?"; + /** + * La key necessaria per prendere i dati da youtube, (per ora abbiamo usato la key di Dawit di SeniorAssistant)
+ * Tra l'altro l'ho presa a caso... quindi boh. + */ private static final String KEY = "AIzaSyCtCK0EPR3k_hEEyar0PeY5v9E9UyTX4TM"; - public static List getVideosId(String search) { - final int maxResult = 5; + /** + * IL thread che ha fatto partire il frame corrente + */ + private Thread currentThread; + /** + * Il frame (ovvero la windows) che e' attualmente attiva + */ + private JFrame currentFrame; + + /** + * Serve ad inizializzare la libreria SWT di eclipse e chrriis.dj + */ + public Musich() { + /* + * Viene mandato questo errore in console, pero' boh... solo ogni tanto: + * Exception "java.lang.ClassNotFoundException: com/intellij/codeInsight/editorActions/FoldingData"while constructing DataFlavor for: application/x-java-jvm-local-objectref; class=com.intellij.codeInsight.editorActions.FoldingData + * A volte ne tira tante, a volte nessuna. + * Sta' di fatto che per quanto ne so non compromette il funzionamento. + * Al massimo usare un logger che dice di ignorare questo errore nel log + */ + NativeInterface.initialize(); + NativeInterface.open(); + NativeInterface.runEventPump(); // this should be called at the end of main (it said this but who cares) + } + + /** + * Serve ad avere una lista di id dei video che corrispondono alle keyword indicate nella ricerca + * @param search la ricerca da fare su youtube + * @param maxResult quanti risultati si vuole avere + * @return una lista di id dei video che corrispondono alla ricerca + */ + public static List getVideosId(String search, final int maxResult) { try { search = URLEncoder.encode(search, "UTF-8"); } catch (UnsupportedEncodingException e) { @@ -45,4 +83,83 @@ public class Musich { return videosId; } + /** + * Serve ad avere una lista di id dei video che corrispondono alle keyword indicate nella ricerca
+ * La lista conterra' i primi 5 id dei video trovati. + * @param search la ricerca da fare su youtube + * @return una lista di id dei video che corrispondono alla ricerca + */ + public List getVideosId(String search) { + return Musich.getVideosId(search, 5); + } + + /** + * Dato l'id di un video viene fatta partire un frame contenente il video richiesto + * @param videoId l'id del video da far vedere + * @param seconds da quanti secondi bisogna far partire il video + */ + public void play(final String videoId, int seconds) { + this.stop(); + currentThread = new Thread( () -> { + currentFrame = new JFrame("YouTube Viewer"); + + SwingUtilities.invokeLater(() -> { + JWebBrowser browser = new JWebBrowser(); + browser.setBarsVisible(false); + browser.navigate(getYoutubeLink(videoId, seconds)); + + currentFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + currentFrame.getContentPane().add(browser, BorderLayout.CENTER); + currentFrame.setSize(800, 600); + currentFrame.setLocationByPlatform(true); + currentFrame.setVisible(true); + }); + + // don't forget to properly close native components + Runtime.getRuntime().addShutdownHook(new Thread(() -> NativeInterface.close())); + }, "NativeInterface"); + + currentThread.start(); + } + + /** + * Dato l'id di un video viene fatta partire un frame contenente il video richiesto + * @param videoId l'id del video da far vedere + */ + public void play(final String videoId) { + play(videoId, 0); + } + + /** + * Serve a far partire un video a caso tra quelli che corrispondono alle keyword indicate nella ricerca + * @param search la ricerca da fare su youtube + * @param maxResult fra quanti risultati deve scegliere + */ + public void playRandom(String search, int maxResult) { + this.play(getVideosId(search, maxResult).get((int)(Math.random()*maxResult))); + } + + /** + * Ferma il video che e' in riprduzione in questo momento.
+ * Se non ce ne sono, amen... non fa nulla. + */ + public void stop() { + if(currentThread != null) { + currentThread.interrupt(); + currentFrame.dispatchEvent(new WindowEvent(currentFrame, WindowEvent.WINDOW_CLOSING)); + + currentThread = null; + currentFrame = null; + } + } + + /** + * Ricevi il link di youtube del video a partire dal suo ID + * @param videoId l'id del video + * @param seconds i secondi dall'inizio del video (0 o negativi e viene ignorato) + * @return una stringa + */ + public static String getYoutubeLink(String videoId, int seconds) { + return videoId==null? "":"https://www.youtube.com/watch?v=" + videoId + (seconds>0? "&t="+seconds:""); + } } diff --git a/src/test/java/test/TestMusich.java b/src/test/java/test/TestMusich.java new file mode 100644 index 0000000..80ba880 --- /dev/null +++ b/src/test/java/test/TestMusich.java @@ -0,0 +1,34 @@ +package test; + +import org.junit.Test; +import support.Musich; + +public class TestMusich { + + @Test + public void test() { + Musich musich = new Musich(); + musich.playRandom("fairy tail motivational soundtrack", 10); + waitAndPrint(20); + musich.play("X9di06iCmuw", 114); + waitAndPrint(60); + musich.stop(); + waitAndPrint(10); + musich.stop(); + } + + public void waitAndPrint(Integer seconds) { + if(seconds != null) synchronized (seconds) { + try { + for(int i=seconds; i>0; i--) { + System.out.println("Tempo rimanente: " + i); + seconds.wait(1000); // 1 sec + } + System.out.println("Finito"); + + } catch (Exception e) { + System.out.println("INTERRUPTED " + e.getMessage()); + } + } + } +}