Merge from BrokenFire/devel

Implement music control web page!
This commit is contained in:
Sébastien Clément 2017-12-28 17:22:23 +01:00 committed by GitHub
commit c1c1390185
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 20311 additions and 66 deletions

View File

@ -36,5 +36,8 @@ dependencies {
compile group: 'org.json', name: 'json', version: '20160810'
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('com.jayway.jsonpath:json-path')
compile("org.springframework.boot:spring-boot-starter-thymeleaf") {
exclude group:"org.springframework.boot", module: "spring-boot-starter-logging"
}
}

View File

@ -1,6 +1,6 @@
#Mon Dec 11 22:24:31 CET 2017
#Wed Dec 20 20:07:15 CET 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip

View File

@ -101,7 +101,7 @@ public class Move implements Commande {
if(userL.size()<1 ||roleL.size()<1)
{
logger.info("Mentionnement Incorect.");
logger.warn("Mentionnement Incorect.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("Utilisateur ou Role mal mentioner.")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
@ -118,7 +118,7 @@ public class Move implements Commande {
{
logger.info("Autorisation suffisante, deplacement autorisé");
logger.info("Utilisateur trouvée");
logger.debug("Utilisateur trouvée");
try {
boolean erreur=this.exc(user,roleL,true,serveur,serveur.getManager());
if(erreur)
@ -169,7 +169,7 @@ public class Move implements Commande {
}
else
{
logger.info("Autorisation insuffisante, deplacement refusé");
logger.warn("Autorisation insuffisante, deplacement refusé");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("Vous n'avez pas l'autorisation de faicre ça!")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);

View File

@ -5,6 +5,7 @@ import net.Broken.MainBot;
import net.Broken.Outils.EmbedMessageUtils;
import net.Broken.Outils.MessageTimeOut;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
@ -18,8 +19,8 @@ import java.util.List;
public class Music implements Commande {
public AudioM audio;
Logger logger = LogManager.getLogger();
public Music() {
audio = new AudioM();
public Music(Guild guild) {
audio = new AudioM(guild);
}
@Override

View File

@ -24,7 +24,7 @@ public class Init {
static JDA initBot(String token, boolean dev){
boolean okInit;
JDA jda = null;
logger.info("-------------------INITIALISATION-------------------");
logger.debug("-------------------INITIALISATION-------------------");
//Bot démarrer sans token
if (token == null) {
@ -54,7 +54,7 @@ public class Init {
MainBot.commandes.put("spam", new Spam());
MainBot.commandes.put("spaminfo", new SpamInfo());
MainBot.commandes.put("flush", new Flush());
MainBot.commandes.put("music", new Music());
MainBot.commandes.put("music", new Music(jda.getGuilds().get(0)));
if (!dev) {
MainBot.commandes.put("ass", new Ass());
@ -75,32 +75,32 @@ public class Init {
//on recupere les utilisateur
List<Member> utilisateurCo = serveur.getMembers();
logger.info("Utilisatieur connecté: ");
logger.info("Utilisatieur connecté: "+utilisateurCo.size());
for (Member anUtilisateurCo : utilisateurCo)
{
if (anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.ONLINE))
logger.info("\t*" + anUtilisateurCo.getEffectiveName());
logger.debug("\t*" + anUtilisateurCo.getEffectiveName());
}
logger.info("Utilisatieur absent: ");
logger.debug("Utilisatieur absent: ");
for (Member anUtilisateurCo : utilisateurCo)
{
if (anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.DO_NOT_DISTURB))
logger.info("\t*" + anUtilisateurCo.getEffectiveName());
logger.debug("\t*" + anUtilisateurCo.getEffectiveName());
}
logger.info("Utilisatieur hors ligne: ");
logger.debug("Utilisatieur hors ligne: ");
for (Member anUtilisateurCo : utilisateurCo)
{
if (anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.OFFLINE))
logger.info("\t*" + anUtilisateurCo.getEffectiveName());
logger.debug("\t*" + anUtilisateurCo.getEffectiveName());
}
MainBot.ModoTimer modotimer = new MainBot.ModoTimer();
modotimer.start();
DayListener dayListener = new DayListener();
dayListener.start();
logger.info("-----------------FIN INITIALISATION-----------------");
logger.debug("-----------------FIN INITIALISATION-----------------");
jda.getPresence().setGame(Game.of("Statut: Ok!"));

View File

@ -14,6 +14,7 @@ import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.HashMap;
@ -22,6 +23,7 @@ import java.util.HashMap;
* Created by seb65 on 19/10/2016.
*/
@SpringBootApplication
@Controller
public class MainBot {
public static final CommandParser parser =new CommandParser();
@ -38,11 +40,9 @@ public class MainBot {
public static void main(String[] args) {
logger.trace("trace");
logger.debug("debug");
logger.info("info");
logger.warn("warn");
logger.error("error");
logger.info("=======================================");
logger.info("--------------Starting Bot-------------");
logger.info("=======================================");
boolean dev = false;
String token = null;
@ -118,10 +118,7 @@ public class MainBot {
public static class ModoTimer extends Thread{
public ModoTimer()
{
}
public ModoTimer(){}
@Override

View File

@ -0,0 +1,9 @@
package net.Broken.RestApi.Data;
public class CommandPostData {
public String command;
public boolean onHead;
public String url;
public int playlistLimit;
}

View File

@ -0,0 +1,14 @@
package net.Broken.RestApi.Data;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommandResponseData {
public String Commande;
public String Message;
public CommandResponseData(String commande, String message) {
Commande = commande;
Message = message;
}
}

View File

@ -0,0 +1,18 @@
package net.Broken.RestApi.Data;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import java.util.List;
public class PlaylistData {
private List<AudioTrackInfo> list;
public PlaylistData(List<AudioTrackInfo> list) {
this.list = list;
}
public List<AudioTrackInfo> getList() {
return list;
}
}

View File

@ -1,31 +1,119 @@
package net.Broken.RestApi;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.Commandes.Music;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.RestApi.Data.CurrentMusicData;
import net.Broken.RestApi.Data.PlaylistData;
import net.Broken.audio.AudioM;
import net.Broken.audio.NotConectedException;
import net.Broken.audio.NullMusicManager;
import net.Broken.audio.WebLoadUtils;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/music/")
public class MusicWebController {
Logger logger = LogManager.getLogger();
@RequestMapping("/currentMusicInfo")
public CurrentMusicData test(){
Music musicCommande = (Music) MainBot.commandes.get("music");
try {
AudioPlayer player = musicCommande.audio.getMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack();
if(currentTrack == null)
{
if(musicCommande.audio.getGuild().getAudioManager().isConnected()){
try {
AudioPlayer player = musicCommande.audio.getMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack();
if(currentTrack == null)
{
return new CurrentMusicData(null,0, "STOP",false);
}
return new CurrentMusicData(currentTrack.getInfo(),currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused());
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new CurrentMusicData(null,0, "STOP",false);
}
return new CurrentMusicData(currentTrack.getInfo(),currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused());
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new CurrentMusicData(null,0, "STOP",false);
}else
{
return new CurrentMusicData(null,0, "DISCONNECTED",false);
}
}
@RequestMapping("/getPlaylist")
public PlaylistData getPlaylist(){
Music musicCommande = (Music) MainBot.commandes.get("music");
List<AudioTrackInfo> list = null;
try {
list = musicCommande.getAudioManager().getMusicManager().scheduler.getList();
return new PlaylistData(list);
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new PlaylistData(list);
}
}
@RequestMapping(value = "/command", method = RequestMethod.POST)
public ResponseEntity<CommandResponseData> command(@RequestBody CommandPostData data){
if(data.command != null) {
logger.info("receive command: " + data.command);
Music musicCommande = (Music) MainBot.commandes.get("music");
switch (data.command) {
case "PLAY":
try {
musicCommande.getAudioManager().getMusicManager().scheduler.resume();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
}
case "PAUSE":
try {
musicCommande.getAudioManager().getMusicManager().scheduler.pause();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
}
case "NEXT":
try {
musicCommande.getAudioManager().getMusicManager().scheduler.nextTrack();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
}
case "STOP":
musicCommande.getAudioManager().stop((MessageReceivedEvent) null);
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
case "ADD":
return new WebLoadUtils(musicCommande ,data).getResponse();
}
}
else
logger.info("Null");
return new ResponseEntity<>(new CommandResponseData(null, null), HttpStatus.NO_CONTENT);
}
}

View File

@ -31,28 +31,34 @@ public class AudioM {
private int listTimeOut = 30;
private int listExtremLimit = 300;
private Logger logger = LogManager.getLogger();
private Guild guild;
public AudioM() {
public AudioM(Guild guild) {
this.playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager);
this.guild = guild;
}
public void loadAndPlay(MessageReceivedEvent event, VoiceChannel voiceChannel, final String trackUrl,int playlistLimit,boolean onHead) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
public void loadAndPlay(MessageReceivedEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) {
GuildMusicManager musicManager = getGuildAudioPlayer(guild);
playedChanel = voiceChannel;
playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
logger.info("Single Track detected!");
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Ajout de "+track.getInfo().title+" à la file d'attente!")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
play(event.getGuild(), voiceChannel, musicManager, track, onHead);
play(guild, voiceChannel, musicManager, track, onHead);
}
@Override
@ -66,13 +72,10 @@ public class AudioM {
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
int i = 0;
for(AudioTrack track : playlist.getTracks()){
play(event.getGuild(), voiceChannel, musicManager, track,onHead);
i++;
if((i>=playlistLimit && i!=-1) || i>listExtremLimit)
break;
}
playListLoader(playlist, playlistLimit, onHead);
}
@ -101,7 +104,15 @@ public class AudioM {
});
}
public void playListLoader(AudioPlaylist playlist,int playlistLimit, boolean onHead){
int i = 0;
for(AudioTrack track : playlist.getTracks()){
play(guild, playedChanel, musicManager, track, onHead);
i++;
if((i>=playlistLimit && i!=-1) || i>listExtremLimit)
break;
}
}
private GuildMusicManager getGuildAudioPlayer(Guild guild) {
@ -114,7 +125,7 @@ public class AudioM {
return musicManager;
}
private void play(Guild guild, VoiceChannel channel, GuildMusicManager musicManager, AudioTrack track,boolean onHead) {
public void play(Guild guild, VoiceChannel channel, GuildMusicManager musicManager, AudioTrack track,boolean onHead) {
if(!guild.getAudioManager().isConnected())
guild.getAudioManager().openAudioConnection(channel);
if(!onHead)
@ -223,16 +234,17 @@ public class AudioM {
public void stop (MessageReceivedEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
musicManager.scheduler.stop();
playedChanel = null;
event.getGuild().getAudioManager().closeAudioConnection();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Arret de la musique!")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
musicManager.scheduler.flush();
if (event != null) {
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Arret de la musique!")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
}
}
public void stop (GuildVoiceLeaveEvent event) {
@ -251,6 +263,14 @@ public class AudioM {
return musicManager;
}
public Guild getGuild() {
return guild;
}
public AudioPlayerManager getPlayerManager() {
return playerManager;
}
public VoiceChannel getPlayedChanel() {
return playedChanel;
}
}

View File

@ -24,7 +24,6 @@ public class GuildMusicManager {
player = manager.createPlayer();
scheduler = new TrackScheduler(player);
player.addListener(scheduler);
}
/**

View File

@ -0,0 +1,82 @@
package net.Broken.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.Broken.Commandes.Music;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.TreeMap;
public class WebLoadUtils {
ResponseEntity<CommandResponseData> response;
Logger logger = LogManager.getLogger();
public WebLoadUtils(Music musicCommande, CommandPostData data){
AudioPlayerManager playerM = musicCommande.getAudioManager().getPlayerManager();
try {
AudioM audioM = musicCommande.getAudioManager();
playerM.loadItemOrdered(musicCommande.getAudioManager().getMusicManager(), data.url, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
logger.info("Single Track detected from web!");
try {
audioM.play(audioM.getGuild(), audioM.getPlayedChanel(), audioM.getMusicManager(), track, data.onHead);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) {
nullMusicManager.printStackTrace();
}
}
@Override
public void playlistLoaded(AudioPlaylist playlist) {
logger.info("Playlist detected from web! Limit: " + data.playlistLimit);
audioM.playListLoader(playlist,data.playlistLimit,data.onHead);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK);
}
@Override
public void noMatches() {
logger.warn("Cant find media ! (web)");
response = new ResponseEntity<>(new CommandResponseData("ADD", "Can't find media!"), HttpStatus.NOT_FOUND);
}
@Override
public void loadFailed(FriendlyException exception) {
logger.error("Cant load media ! (web)");
response = new ResponseEntity<>(new CommandResponseData("ADD", "Cant load media !"), HttpStatus.INTERNAL_SERVER_ERROR);
}
});
while(response == null)
Thread.sleep(10);
} catch (NullMusicManager | NotConectedException | InterruptedException nullMusicManager) {
nullMusicManager.printStackTrace();
}
}
public ResponseEntity<CommandResponseData> getResponse(){
while(response == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return response;
}
}

View File

@ -0,0 +1,13 @@
package net.Broken.webView;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MusicWebView {
@RequestMapping("/music")
public String music(Model model){
return "music";
}
}

View File

@ -1,26 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error">
<Configuration status="error" packages="com.coralogix.sdk.appenders">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<!--<PatternLayout pattern="[%d{HH:mm:ss.SSS}]%highlight{[%-5level]}{FATAL=red blink, ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}[%-30.30c{1.}]: %highlight{%msg%n}{FATAL=red blink, ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}" />-->
<PatternLayout pattern="[%d{HH:mm:ss.SSS}][%-5level][%-30.30c{1.}]: %msg%n" />
<PatternLayout pattern="[%d{HH:mm:ss.SSS}]%highlight{[%-5level]}{FATAL=red blink, ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}[%-30.30c{1.}]: %highlight{%msg%n}{FATAL=red blink, ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}" />
</Console>
<!--<RollingFile name="RollingFile" fileName="/logs/curent.log"
filePattern="/logs/$${date:yyyy-MM}/discordBot-%d{yyyy-MM-dd-HH}-%i.log.gz">
<RollingFile name="RollingFile" fileName="./logs/curent.log"
filePattern="./logs/$${date:yyyy-MM}/discordBot-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<Pattern>[%d{yyy-MM-dd ~ HH:mm:ss.SSS}][%-5level]%logger{36}: %msg%n</Pattern>
<Pattern>[%d{yyy-MM-dd ~ HH:mm:ss.SSS}][%-5level]%-30.30c{1.}: %msg%n</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy minSize="1B"/>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>-->
</RollingFile>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="RollingFile" level="info" />
<AppenderRef ref="Console" level="info"/>
<!--<AppenderRef ref="RollingFile" level="info"/>-->
<AppenderRef ref="RollingFile" level="info"/>
</Root>
</Loggers>
</Configuration>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,10 @@
.nav-wrapper{
margin-right: 1%;
margin-left: 1%;
width: 100%;
}
.collapsible-body{
padding: 0px;
}

View File

@ -0,0 +1,6 @@
[Dolphin]
Timestamp=2017,12,24,15,16,6
Version=4
[Settings]
HiddenFilesShown=true

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Discord Bot</title>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body class="blue-grey lighten-5" >
<nav class="blue-grey darken-4 z-depth-3" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="#" class="brand-logo">Discord Bot</a>
<ul class="right hide-on-med-and-down">
<li class="active">
<a href="/" data-target="slide-out" class="sidenav-trigger">Home</a>
</li>
<li>
<a href="/music" >Music Control</a>
</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li class="active">
<a href="/" data-target="slide-out" class="sidenav-trigger">Home</a>
</li>
<li>
<a href="/music" data-target="slide-out" class="sidenav-trigger">Music Control</a>
</li>
</ul>
<a href="#" data-activates="nav-mobile" class="button-collapse-1 button-collapse"><i class="material-icons">menu</i></a>
</div>
</nav>
<div class="section no-pad-bot main" id="index-banner">
</div>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/materialize.js"></script>
<script src="js/init.js"></script>
</body>
</html>

View File

@ -0,0 +1,310 @@
var savedPlaylist;
var error = false;
var state;
$(document).ready(function() {
setInterval("getCurentMusic()",1000);
// the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
$('.modal').modal();
$('.button-collapse-1').sideNav({
menuWidth: 400, // Default is 300
edge: 'right', // Choose the horizontal origin
closeOnClick: false, // Closes side-nav on <a> clicks, useful for Angular/Meteor
draggable: true // Choose whether you can drag to open on touch screens,
});
var height = $( window ).height();
$('#btn_play').click(function () {
switch (state){
case "PLAYING":
sendCommand(JSON.stringify({ command: "PAUSE"}))
break;
case "PAUSE":
sendCommand(JSON.stringify({ command: "PLAY"}))
break;
}
})
$('#btn_next').click(function () {
sendCommand(JSON.stringify({ command: "NEXT"}));
})
$('#btn_stop').click(function () {
sendCommand(JSON.stringify({ command: "STOP"}));
})
$('.dropdown-button').dropdown({
inDuration: 300,
outDuration: 225,
constrainWidth: false, // Does not change width of dropdown to that of the activator
hover: false, // Activate on hover
gutter: 0, // Spacing from edge
belowOrigin: false, // Displays dropdown below the button
alignment: 'left', // Displays dropdown with edge aligned to the left of button
stopPropagation: false // Stops event propagation
}
);
$('#input_link').on("input", function () {
if($('#input_link').val() == ""){
if (!$('#btn_add_bottom').hasClass("disabled")) {
$('#btn_add_bottom').addClass("disabled");
}
if (!$('#btn_add_top').hasClass("disabled")) {
$('#btn_add_top').addClass("disabled");
}
}
else{
if ($('#btn_add_bottom').hasClass("disabled")) {
$('#btn_add_bottom').removeClass("disabled");
}
if ($('#btn_add_top').hasClass("disabled")) {
$('#btn_add_top').removeClass("disabled");
}
}
});
$('#btn_add_top').click(function () {
var command = {
command: "ADD",
url: $('#input_link').val(),
playlistLimit: $('#limit_range').val(),
onHead: true
};
sendCommand(JSON.stringify(command));
})
$('#btn_add_bottom').click(function () {
var command = {
command: "ADD",
url: $('#input_link').val(),
playlistLimit: $('#limit_range').val(),
onHead: false
};
sendCommand(JSON.stringify(command));
})
})
function getCurentMusic() {
$.get("api/music/currentMusicInfo", function (data) {
}).done(function (data) {
// alert( "second success" );
// console.log(data);
state = data.state;
switch (data.state) {
case "STOP":
$('#music_text').text("Connected on Vocal Channel");
if (!$('#btn_info').hasClass("indeterminate")) {
$('#btn_info').addClass("determinate").removeClass("indeterminate");
}
$('#music_progress').width("0%");
$('#btn_play').children().text("play_arrow");
if (!$('#btn_stop').hasClass("disabled")) {
$('#btn_stop').addClass("disabled");
}
if (!$('#btn_info').hasClass("disabled")) {
$('#btn_info').addClass("disabled");
}
if ($('#add_btn').hasClass("disabled")) {
$('#add_btn').removeClass("disabled");
}
$('#music_img').attr("src","/img/no_music.jpg");
break;
case "PLAYING":
$('#btn_play').children().text("pause");
updateControl(data);
break;
case "PAUSE":
$('#btn_play').children().text("play_arrow");
updateControl(data);
break;
case "LOADING":
if (!$('#btn_info').hasClass("determinate")) {
$('#btn_info').addClass("indeterminate").removeClass("determinate");
}
break;
case "DISCONNECTED":
$('#music_text').text("Disconnected from Vocal");
if (!$('#btn_info').hasClass("indeterminate")) {
$('#btn_info').addClass("determinate").removeClass("indeterminate");
}
$('#music_progress').width("0%");
$('#btn_play').children().text("play_arrow");
if (!$('#btn_play').hasClass("disabled")) {
$('#btn_play').addClass("disabled");
}
if (!$('#btn_stop').hasClass("disabled")) {
$('#btn_stop').addClass("disabled");
}
if (!$('#btn_next').hasClass("disabled")) {
$('#btn_next').addClass("disabled");
}
if (!$('#btn_info').hasClass("disabled")) {
$('#btn_info').addClass("disabled");
}
if (!$('#add_btn').hasClass("disabled")) {
$('#add_btn').addClass("disabled");
}
$('#music_img').attr("src","/img/disconnected.png");
break;
}
getPlayList();
})
.fail(function (data) {
if(!error){
alert("Connection lost, I keep trying to refresh!");
error = true;
}
})
}
function getPlayList() {
$.get("api/music/getPlaylist", function (data) {
}).done(function (data) {
data = data.list;
if(data != null && data.length != 0){
var noUpdate = comparePlaylist(data, savedPlaylist);
if(!noUpdate){
savedPlaylist = data;
$('#playlist_list').empty();
data.forEach(function(element){
var template = $('#playlist_template').clone();
template.removeAttr("id");
template.removeAttr("style");
var content = template.html();
content = content.replace("@title", element.title);
content = content.replace("@author", element.author);
content = content.replace("@lenght", msToTime(element.length));
content = content.replace("@url", element.uri)
template.html(content);
$('#playlist_list').append(template);
});
}
}
else
$('#playlist_list').empty();
});
}
function updateModal(data){
$('#modal_title').text("Title: "+ data.info.title);
$('#modal_author').text("Author: "+ data.info.author);
$('#modal_lenght').text("Duration: "+ msToTime(data.info.length));
$('#modal_url').text("URL: "+ data.info.uri);
}
function updateControl(data){
$('#music_text').text(data.info.title);
var percent = (data.currentPos / data.info.length) * 100;
// console.log(percent)
if (!$('#btn_info').hasClass("indeterminate")) {
$('#btn_info').addClass("determinate").removeClass("indeterminate");
}
$('#music_progress').width(percent + "%");
if ($('#btn_play').hasClass("disabled")) {
$('#btn_play').removeClass("disabled");
}
if ($('#btn_stop').hasClass("disabled")) {
$('#btn_stop').removeClass("disabled");
}
if ($('#btn_info').hasClass("disabled")) {
$('#btn_info').removeClass("disabled");
}
if ($('#add_btn').hasClass("disabled")) {
$('#add_btn').removeClass("disabled");
}
if ($('#btn_next').hasClass("disabled")) {
$('#btn_next').removeClass("disabled");
}
$('#music_img').attr("src","http://img.youtube.com/vi/"+data.info.identifier+"/hqdefault.jpg");
updateModal(data);
}
function sendCommand(commandStr){
$.ajax({
type: "POST",
dataType: 'json',
contentType: 'application/json',
url: "/api/music/command",
data: commandStr,
success: function (data) {
console.log(data);
}
}).fail(function (data) {
console.log(data);
alert(data.responseJSON.Message);
});
}
function comparePlaylist(list1, list2){
if(list1 == null || list2 == null){
return false;
}
if(list1.length != list2.length){
return false;
}
for(var i = 0; i++; i < list1.length){
if(list1[i].uri != list2[i].uri)
return false
}
return true;
}
function msToTime(duration) {
var milliseconds = parseInt((duration%1000)/100)
, seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
if(hours > 0 )
return hours + ":" + minutes + ":" + seconds;
else
return minutes + ":" + seconds;
}

10021
src/main/resources/static/js/materialize.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,10 @@
<li>
<div class="collapsible-header"><i class="material-icons">drag_handle</i><h6 class="truncate">@title</h6></div>
<div class="collapsible-body">
<ul class="collection">
<li class="collection-item">Author: @author</li>
<li class="collection-item">Duration: @lenght</li>
<li class="collection-item">URL: <a>@url</a></li>
</ul>
</div>
</li>

View File

@ -0,0 +1,181 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Discord Bot - Music Control</title>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body class="blue-grey lighten-5" >
<nav class="blue-grey darken-4 z-depth-3" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="#" class="brand-logo">Discord Bot</a>
<ul class="right hide-on-med-and-down">
<li >
<a href="/" data-target="slide-out" class="sidenav-trigger">Home</a>
</li>
<li class="active">
<a href="/music" >Music Control</a>
</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li >
<a href="/" data-target="slide-out" class="sidenav-trigger">Home</a>
</li>
<li class="active">
<a href="/music" data-target="slide-out" class="sidenav-trigger">Music Control</a>
</li>
</ul>
<a href="#" data-activates="nav-mobile" class="button-collapse-1 button-collapse"><i class="material-icons">menu</i></a>
</div>
</nav>
<div class="section no-pad-bot main" id="index-banner">
<div class="row">
<div class="col s8">
<div class="row center" >
<img class="responsive-img z-depth-3" id="music_img" style="max-width: 30%" src=""/>
</div>
<h4 class="center" id="music_text"></h4>
<div class="row center">
<div class="progress col s6 offset-s3 z-depth-3">
<div class="determinate" id="music_progress" style="width: 0%"></div>
</div>
</div>
<div class="row center">
<div class="col s2 offset-s3 center">
<a class="btn-large blue-grey darken-4 z-depth-3 waves-effect waves-light" id="btn_stop">
<i class="material-icons medium">stop</i>
</a>
</div>
<div class="col s2 center">
<a class="btn-large blue-grey darken-4 z-depth-3 waves-effect waves-light" id="btn_play">
<i class="material-icons medium">play_arrow</i>
</a>
</div>
<div class="col s2 center">
<a class="btn-large blue-grey darken-4 z-depth-3 waves-effect waves-light" id="btn_next">
<i class="material-icons">skip_next</i>
</a>
</div>
</div>
<div class="row center">
<div class="col offset-s5 s2 center">
<a class="btn blue-grey darken-4 z-depth-3 waves-effect waves-light modal-trigger" href="#modal1" id="btn_info">
<i class="material-icons">info</i>
</a>
</div>
</div>
</div>
<div class="col s4" >
<table>
<thead>
<tr>
<th style="padding: 0px;">
<div class="row center valign-wrapper" style="margin: 0px">
<div class="col s5 center"><h5>Playlist</h5></div>
<div class="col s5 offset-s2 center">
<!-- Modal Trigger -->
<a class="waves-effect waves-light btn modal-trigger blue-grey darken-4" id="add_btn" href="#modalAdd">Add</a>
<!-- Modal Structure -->
<div id="modalAdd" class="modal disabled">
<div class="modal-content" style="padding-bottom: 0px">
<div class="row" style="margin-bottom: 0px">
<h3 class="col s12"> Add Music</h3>
<form class="col s12">
<div class="row" style="margin-bottom: 0px">
<div class="input-field col s12" style="padding-left: 0px; padding-right: 0px">
<!--<i class="material-icons prefix">link</i>-->
<input id="input_link" type="text" class="validate"/>
<label for="input_link">Link</label>
</div>
</div>
<div class="row" style="margin-bottom: 0px">
<div class="col s12 center">
Playlist Limit
</div>
</div>
<div class="row" style="margin-bottom: 0px">
<p class="range-field">
<input type="range" id="limit_range" min="1" max="300" step="1" value="30" />
</p>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Cancel</a>
<a href="#!" id="btn_add_top" class="modal-action modal-close waves-effect waves-green btn-flat disabled">Add On Top</a>
<a href="#!" id="btn_add_bottom" class="modal-action modal-close waves-effect waves-green btn-flat disabled">Add On Bottom</a>
</div>
</div>
</div>
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul id="playlist_list" class="collapsible popout" data-collapsible="accordion" style="margin: 0px">
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Playlist -->
<!-- Modal Structure -->
<div id="modal1" class="modal bottom-sheet">
<div class="modal-content">
<ul class="collection">
<li class="collection-item " id="modal_title"></li>
<li class="collection-item " id="modal_author"></li>
<li class="collection-item " id="modal_lenght"></li>
<li class="collection-item " id="modal_url"></li>
</ul>
</div>
</div>
</div>
<li id="playlist_template" style="visibility: hidden">
<div class="collapsible-header"><i class="material-icons">drag_handle</i>@title</div>
<div class="collapsible-body">
<ul class="collection">
<li class="collection-item">Author: @author</li>
<li class="collection-item">Duration: @lenght</li>
<li class="collection-item">URL: <a>@url</a></li>
</ul>
</div>
</li>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/materialize.js"></script>
<script src="js/init.js"></script>
</body>
</html>