Reduce loading time after commands on music page

This commit is contained in:
Sebastien 2018-11-29 15:58:41 +02:00
parent b01f8721da
commit 1a368f8f38
3 changed files with 212 additions and 144 deletions

View File

@ -0,0 +1,11 @@
package net.Broken.RestApi.Data;
public class AllMusicInfoData {
public CurrentMusicData currentMusic;
public PlaylistData playlist;
public AllMusicInfoData(CurrentMusicData currentMusic, PlaylistData playlist) {
this.currentMusic = currentMusic;
this.playlist = playlist;
}
}

View File

@ -17,6 +17,7 @@ import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeTools; import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.entities.VoiceChannel;
import org.apache.http.HttpResponse;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -59,7 +60,6 @@ public class MusicWebAPIController {
logger.trace("currentMusicInfo for " + guild.getName()); logger.trace("currentMusicInfo for " + guild.getName());
} }
Music musicCommande = (Music) MainBot.commandes.get("music");
if(guild.getAudioManager().isConnected()){ if(guild.getAudioManager().isConnected()){
AudioPlayer player = AudioM.getInstance(guild).getGuildMusicManager().player; AudioPlayer player = AudioM.getInstance(guild).getGuildMusicManager().player;
@ -92,7 +92,58 @@ public class MusicWebAPIController {
return new ResponseEntity<>(new PlaylistData(list), HttpStatus.OK); return new ResponseEntity<>(new PlaylistData(list), HttpStatus.OK);
} }
// TODO change token to cookie
@RequestMapping("/getAllInfo")
public ResponseEntity<AllMusicInfoData> getAllInfo(@RequestParam(value = "guild") String guildId, @CookieValue("token") String token){
if(token != null) {
Guild guild = MainBot.jda.getGuildById(guildId);
if(guild == null ){
logger.warn("All info without guild!");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
logger.trace("All info from USER: " + user.getName() + " GUILD: " + guild.getName());
PlaylistData list = new PlaylistData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getList());
CurrentMusicData musicData;
if(guild.getAudioManager().isConnected()){
AudioPlayer player = AudioM.getInstance(guild).getGuildMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack();
if(currentTrack == null)
{
musicData = new CurrentMusicData(null,0, "STOP",false, AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow());
}
else{
UserAudioTrackData uat = new UserAudioTrackData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getCurrentPlayingTrack());
musicData = new CurrentMusicData(uat, currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused(), AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow());
}
}else
{
musicData = new CurrentMusicData(null,0, "DISCONNECTED",false, false);
}
return new ResponseEntity<>(new AllMusicInfoData(musicData, list),HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("All info with unknown token");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
else{
logger.warn("All Info without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
@RequestMapping(value = "/command", method = RequestMethod.POST) @RequestMapping(value = "/command", method = RequestMethod.POST)
public ResponseEntity<CommandResponseData> command(@RequestBody CommandPostData data, HttpServletRequest request, @RequestParam(value = "guild") String guildId, @CookieValue("token") String token){ public ResponseEntity<CommandResponseData> command(@RequestBody CommandPostData data, HttpServletRequest request, @RequestParam(value = "guild") String guildId, @CookieValue("token") String token){

View File

@ -1,5 +1,3 @@
//import * as M from "./materialize";
let savedPlaylist; let savedPlaylist;
let error = false; let error = false;
let state; let state;
@ -14,6 +12,7 @@ let btn_flush;
let btn_add; let btn_add;
let switchAutoFlow; let switchAutoFlow;
let loadingFlag = true; let loadingFlag = true;
let musicLoadFlag = false;
let guild; let guild;
let interval; let interval;
@ -31,7 +30,6 @@ $(document).ready(function () {
switchAutoFlow = $("#autoflow"); switchAutoFlow = $("#autoflow");
M.Modal.init($('#modalAdd').get(0)); M.Modal.init($('#modalAdd').get(0));
$('#modal_current_info').modal(); $('#modal_current_info').modal();
@ -45,7 +43,6 @@ $(document).ready(function () {
modal_loading.open(); modal_loading.open();
$('.dropdown-button').dropdown({ $('.dropdown-button').dropdown({
inDuration: 300, inDuration: 300,
outDuration: 225, outDuration: 225,
@ -58,27 +55,29 @@ $(document).ready(function () {
}); });
listeners(); listeners();
getCurentMusic();
interval = setInterval("getCurentMusic()", 1000); interval = setInterval("getCurentMusic()", 1000);
} }
}); });
function getCurentMusic() { function getCurentMusic() {
$.get("api/music/currentMusicInfo?guild=" + guild, function (data) { $.get("api/music/getAllInfo?guild=" + guild, function (data) {
}).done(function (data) { }).done(function (data) {
if (error) { if (error) {
error = false; error = false;
M.Toast.dismissAll(); M.Toast.dismissAll();
} }
state = data.state; state = data.currentMusic.state;
switch (data.state) { switch (data.currentMusic.state) {
case "STOP": case "STOP":
disconected = false; disconected = false;
$('#modalChanels').modal('close'); $('#modalChanels').modal('close');
$('#music_text').text("Connected on Vocal Channel"); $('#music_text').text("Connected on Vocal Channel");
if (!$('#btn_info').hasClass("indeterminate")) { if (!$('#music_progress').hasClass("determinate")) {
$('#btn_info').addClass("determinate").removeClass("indeterminate"); $('#music_progress').addClass("determinate").removeClass("indeterminate");
} }
$('#music_progress').width("0%"); $('#music_progress').width("0%");
if (Cookies.get('token') !== undefined) { if (Cookies.get('token') !== undefined) {
@ -105,7 +104,7 @@ function getCurentMusic() {
$('#current_time').text("00:00"); $('#current_time').text("00:00");
btn_play.removeClass("amber"); btn_play.removeClass("amber");
btn_play.addClass("green"); btn_play.addClass("green");
if(savedPlaylist != null){ if (savedPlaylist != null) {
$('#playlist_list').empty(); $('#playlist_list').empty();
savedPlaylist = null; savedPlaylist = null;
} }
@ -118,7 +117,7 @@ function getCurentMusic() {
btn_play.children().text("pause"); btn_play.children().text("pause");
btn_play.removeClass("green"); btn_play.removeClass("green");
btn_play.addClass("amber"); btn_play.addClass("amber");
updateControl(data); updateControl(data.currentMusic);
break; break;
@ -129,22 +128,28 @@ function getCurentMusic() {
btn_play.removeClass("amber"); btn_play.removeClass("amber");
btn_play.addClass("green"); btn_play.addClass("green");
btn_play.addClass("green"); btn_play.addClass("green");
updateControl(data); updateControl(data.currentMusic);
break; break;
case "LOADING": case "LOADING":
disconected = false; disconected = false;
$('#modalChanels').modal('close'); $('#modalChanels').modal('close');
if (!$('#btn_info').hasClass("determinate")) { updateControl(data.currentMusic);
$('#btn_info').addClass("indeterminate").removeClass("determinate"); if ($('#music_progress').hasClass("determinate")) {
$('#music_progress').addClass("indeterminate").removeClass("determinate");
}
if(!musicLoadFlag){
clearInterval(interval);
interval = setInterval("getCurentMusic()", 200);
musicLoadFlag = true;
} }
break; break;
case "DISCONNECTED": case "DISCONNECTED":
$('#music_text').text("Disconnected from Vocal"); $('#music_text').text("Disconnected from Vocal");
if (!$('#btn_info').hasClass("indeterminate")) { if (!$('#music_progress').hasClass("determinate")) {
$('#btn_info').addClass("determinate").removeClass("indeterminate"); $('#music_progress').addClass("determinate").removeClass("indeterminate");
} }
$('#music_progress').width("0%"); $('#music_progress').width("0%");
@ -167,102 +172,98 @@ function getCurentMusic() {
} }
clearInterval(interval); clearInterval(interval);
if(savedPlaylist != null){ if (savedPlaylist != null) {
$('#playlist_list').empty(); $('#playlist_list').empty();
savedPlaylist = null; savedPlaylist = null;
} }
break; break;
} }
if (switchAutoFlow.is(':checked') != data.autoflow) if (switchAutoFlow.is(':checked') !== data.currentMusic.autoflow)
switchAutoFlow.prop('checked', data.autoflow); switchAutoFlow.prop('checked', data.currentMusic.autoflow);
if(data.state !== "DISCONNECTED" && data.state !== "STOP") if (data.currentMusic.state !== "DISCONNECTED" && data.currentMusic.state !== "STOP"){
getPlayList(); getPlayList(data.playlist.list);
else{ if(data.currentMusic.state !== "LOADING"){
$(".ctl-btn").removeClass("disabled");
if(musicLoadFlag){
clearInterval(interval);
interval = setInterval("getCurentMusic()", 1000);
musicLoadFlag = false;
}
}
}
else {
if (loadingFlag) { if (loadingFlag) {
modal_loading.close(); modal_loading.close();
loadingFlag = false; loadingFlag = false;
} }
} $(".ctl-btn").removeClass("disabled");
if(musicLoadFlag){
}) clearInterval(interval);
.fail(function (data) { interval = setInterval("getCurentMusic()", 1000);
if (!error) { musicLoadFlag = false;
error = true;
console.error("Connection lost, I keep trying to refresh!");
M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Connection Lost!",
classes: 'red',
displayLength: 99999999
});
}
})
}
function getPlayList() {
$.get("api/music/getPlaylist?guild=" + guild, 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.audioTrackInfo.title);
content = content.replace("@author", element.audioTrackInfo.author);
content = content.replace("@lenght", msToTime(element.audioTrackInfo.length));
content = content.replace(/@url/g, element.audioTrackInfo.uri);
content = content.replace(/@user/g, element.user);
template.html(content);
$('#playlist_list').append(template);
$('.collapsible').collapsible();
});
$(".btn_dell_playlist").click(function () {
var command = {
command: "DELL",
url: $(this).attr("data_url")
};
sendCommand(command, true);
});
} }
} }
else {
$('#playlist_list').empty();
savedPlaylist = {};
}
if (loadingFlag) {
modal_loading.close();
loadingFlag = false;
}
$(".ctl-btn").removeClass("disabled");
}).fail(function (data) { }).fail(function (data) {
if (!error) { if (!error) {
error = true;
console.error("Connection lost, I keep trying to refresh!");
M.toast({ M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Connection Lost!", html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Connection Lost!",
classes: 'red', classes: 'red',
displayLength: 99999999 displayLength: 99999999
}); });
error = true;
}
if (loadingFlag) {
modal_loading.close();
loadingFlag = false;
} }
}); })
}
function getPlayList(data) {
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.audioTrackInfo.title);
content = content.replace("@author", element.audioTrackInfo.author);
content = content.replace("@lenght", msToTime(element.audioTrackInfo.length));
content = content.replace(/@url/g, element.audioTrackInfo.uri);
content = content.replace(/@user/g, element.user);
template.html(content);
$('#playlist_list').append(template);
$('.collapsible').collapsible();
});
$(".btn_dell_playlist").click(function () {
var command = {
command: "DELL",
url: $(this).attr("data_url")
};
sendCommand(command, true);
});
}
}
else {
$('#playlist_list').empty();
savedPlaylist = {};
}
if (loadingFlag) {
modal_loading.close();
loadingFlag = false;
}
} }
@ -311,33 +312,40 @@ function updateModal(data) {
} }
function updateControl(data) { function updateControl(data) {
$('#music_text').text(data.info.audioTrackInfo.title);
var percent = (data.currentPos / data.info.audioTrackInfo.length) * 100; if($('#music_text').text() !== data.info.audioTrackInfo.title){
if (!$('#music_progress').hasClass("indeterminate")) { $('#music_text').text(data.info.audioTrackInfo.title);
$('#music_progress').addClass("determinate").removeClass("indeterminate");
} }
var percent = (data.currentPos / data.info.audioTrackInfo.length) * 100;
$('#music_progress').width(percent + "%"); $('#music_progress').width(percent + "%");
if (Cookies.get('token') !== undefined) { if(data.state !== "LOADING"){
enableBtn(btn_play); if (Cookies.get('token') !== undefined) {
enableBtn(btn_stop); enableBtn(btn_play);
enableBtn(btn_info); enableBtn(btn_stop);
enableBtn(btn_add); enableBtn(btn_info);
enableBtn(btn_flush); enableBtn(btn_add);
enableBtn(btn_next); enableBtn(btn_flush);
enableBtn(btn_disconnect_music); enableBtn(btn_next);
} enableBtn(btn_disconnect_music);
else { }
disableBtn(btn_play); else {
disableBtn(btn_stop); disableBtn(btn_play);
disableBtn(btn_info); disableBtn(btn_stop);
disableBtn(btn_add); disableBtn(btn_info);
disableBtn(btn_flush); disableBtn(btn_add);
disableBtn(btn_next); disableBtn(btn_flush);
disableBtn(btn_disconnect_music); disableBtn(btn_next);
disableBtn(btn_disconnect_music);
}
if (!$('#music_progress').hasClass("determinate")) {
$('#music_progress').addClass("determinate").removeClass("indeterminate");
}
} }
$('#music_img').attr("src", "https://img.youtube.com/vi/" + data.info.audioTrackInfo.identifier + "/hqdefault.jpg"); $('#music_img').attr("src", "https://img.youtube.com/vi/" + data.info.audioTrackInfo.identifier + "/hqdefault.jpg");
$('#total_time').text(msToTime(data.info.audioTrackInfo.length)); $('#total_time').text(msToTime(data.info.audioTrackInfo.length));
$('#current_time').text(msToTime(data.currentPos)); $('#current_time').text(msToTime(data.currentPos));
@ -346,7 +354,8 @@ function updateControl(data) {
function sendCommand(command, modal) { function sendCommand(command, modal) {
clearInterval(interval); clearInterval(interval);
if(modal){ interval = null;
if (modal) {
modal_loading.open(); modal_loading.open();
} }
@ -360,9 +369,12 @@ function sendCommand(command, modal) {
data: JSON.stringify(command), data: JSON.stringify(command),
success: function (data) { success: function (data) {
loadingFlag = true; loadingFlag = true;
getCurentMusic();
if(interval != null)
clearInterval(interval);
interval = setInterval("getCurentMusic()", 1000); interval = setInterval("getCurentMusic()", 1000);
if(command.command === "ADD"){ if (command.command === "ADD") {
M.toast({ M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>check_circle</i> Video added to playlist!", html: " <i class=\"material-icons\" style='margin-right: 10px'>check_circle</i> Video added to playlist!",
classes: 'green', classes: 'green',
@ -381,7 +393,7 @@ function sendCommand(command, modal) {
Cookies.remove('name'); Cookies.remove('name');
location.reload(); location.reload();
} }
else{ else {
M.toast({ M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Command fail!", html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Command fail!",
classes: 'red', classes: 'red',
@ -409,7 +421,6 @@ function comparePlaylist(list1, list2) {
} }
function search() { function search() {
let input_search = $('#input_search'); let input_search = $('#input_search');
let list = $("#search_result"); let list = $("#search_result");
@ -422,20 +433,19 @@ function search() {
$.get("/api/music/search?query=" + input_search.val(), (data) => { $.get("/api/music/search?query=" + input_search.val(), (data) => {
list.empty(); list.empty();
data.forEach((item)=>{ data.forEach((item) => {
let html = let html =
"<li class=\"collection-item avatar\">" + "<li class=\"collection-item avatar\">" +
" <img src=\""+item["imageUrl"]+"\" alt=\"\" class=\"\">" + " <img src=\"" + item["imageUrl"] + "\" alt=\"\" class=\"\">" +
" <a class=\"title truncate\" href='https://youtube.com/watch?v="+item["id"]+"' target=\"_blank\"><b>"+item["title"]+"</b></a>" + " <a class=\"title truncate\" href='https://youtube.com/watch?v=" + item["id"] + "' target=\"_blank\"><b>" + item["title"] + "</b></a>" +
" <p class='truncate grey-text text-darken-1'>"+item["channelTittle"]+ " &#9553 "+ item["publishedAt"].substr(0, item["publishedAt"].indexOf('T'))+" <br>" + ytTimeToTime(item["duration"]) + " <p class='truncate grey-text text-darken-1'>" + item["channelTittle"] + " &#9553 " + item["publishedAt"].substr(0, item["publishedAt"].indexOf('T')) + " <br>" + ytTimeToTime(item["duration"]) +
" </p>" + " </p>" +
" <a href=\"#!\" class=\"secondary-content btn waves-effect waves-light green add-btn-list scale-transition\" id='"+item["id"]+"'><i class=\"material-icons \">add_circle_outline</i></a>" + " <a href=\"#!\" class=\"secondary-content btn waves-effect waves-light green add-btn-list scale-transition\" id='" + item["id"] + "'><i class=\"material-icons \">add_circle_outline</i></a>" +
" </div>" + " </div>" +
"</li>"; "</li>";
list.append(html) list.append(html)
}); });
@ -448,14 +458,14 @@ function search() {
enableBtn($('#btn_search')); enableBtn($('#btn_search'));
input_search.removeAttr("disabled"); input_search.removeAttr("disabled");
}).fail( (data)=>{ }).fail((data) => {
if(data.status === 401){ if (data.status === 401) {
M.toast({ M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Unauthorized, please re-login.", html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Unauthorized, please re-login.",
classes: 'red', classes: 'red',
displayLength: 99999999 displayLength: 99999999
}); });
}else{ } else {
M.toast({ M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i>Internal server error, please contact dev.", html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i>Internal server error, please contact dev.",
classes: 'red', classes: 'red',
@ -473,9 +483,9 @@ function search() {
} }
function addListClick(event){ function addListClick(event) {
let button; let button;
if(event.target.nodeName === "I"){ if (event.target.nodeName === "I") {
button = event.target.parentNode; button = event.target.parentNode;
} }
else else
@ -495,20 +505,20 @@ function ytTimeToTime(duration) {
let hours; let hours;
let minutes; let minutes;
let seconds; let seconds;
if(duration === "PT0S") if (duration === "PT0S")
return "&#x1F534 LIVE"; return "&#x1F534 LIVE";
if(duration.includes("H")) if (duration.includes("H"))
hours = parseInt(duration.match(/\d*H/)[0].replace("H",""), 10); hours = parseInt(duration.match(/\d*H/)[0].replace("H", ""), 10);
else else
hours = 0; hours = 0;
if(duration.includes("M")) if (duration.includes("M"))
minutes = parseInt(duration.match(/\d*M/)[0].replace("M",""), 10); minutes = parseInt(duration.match(/\d*M/)[0].replace("M", ""), 10);
else else
minutes = 0; minutes = 0;
if(duration.includes("S")) if (duration.includes("S"))
seconds = parseInt(duration.match(/\d*S/)[0].replace("S",""), 10); seconds = parseInt(duration.match(/\d*S/)[0].replace("S", ""), 10);
else else
seconds = 0; seconds = 0;
@ -522,8 +532,6 @@ function ytTimeToTime(duration) {
} }
function msToTime(duration) { function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100) var milliseconds = parseInt((duration % 1000) / 100)
, seconds = parseInt((duration / 1000) % 60) , seconds = parseInt((duration / 1000) % 60)
@ -545,21 +553,21 @@ function listeners() {
$('#btn_play').click(function () { $('#btn_play').click(function () {
switch (state) { switch (state) {
case "PLAYING": case "PLAYING":
sendCommand({command: "PAUSE"}, false); sendCommand({command: "PAUSE"}, true);
break; break;
case "PAUSE": case "PAUSE":
sendCommand({command: "PLAY"}, false); sendCommand({command: "PLAY"}, true);
break; break;
default: default:
sendCommand({command: "PLAY"}, false); sendCommand({command: "PLAY"}, true);
} }
}); });
$('#btn_search').click(search); $('#btn_search').click(search);
$("form").submit(function(e) { $("form").submit(function (e) {
e.preventDefault(); e.preventDefault();
search(); search();
}); });
@ -582,8 +590,6 @@ function listeners() {
}); });
$('#modalChanels').change(function () { $('#modalChanels').change(function () {
if ($('#btn_ok_channel').hasClass("disabled")) { if ($('#btn_ok_channel').hasClass("disabled")) {
$('#btn_ok_channel').removeClass("disabled"); $('#btn_ok_channel').removeClass("disabled");