Merge branch 'devel'

This commit is contained in:
Sebastien 2018-11-22 16:22:52 +02:00
commit 2ff0de5dce
10 changed files with 124 additions and 114 deletions

View File

@ -3,6 +3,7 @@ package net.Broken.DB.Entity;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import net.Broken.Tools.UserManager.UserUtils; import net.Broken.Tools.UserManager.UserUtils;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.persistence.*; import javax.persistence.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -40,10 +41,11 @@ public class UserEntity {
this.apiToken = apiToken; this.apiToken = apiToken;
} }
public UserEntity(User user){ public UserEntity(User user, PasswordEncoder passwordEncoder){
this.name = user.getName(); this.name = user.getName();
this.jdaId = user.getId(); this.jdaId = user.getId();
this.apiToken = UserUtils.getInstance().generateApiToken(); this.apiToken = UserUtils.getInstance().generateApiToken();
this.password = passwordEncoder.encode(UserUtils.getInstance().generateCheckToken());
} }
public String getPassword() { public String getPassword() {

View File

@ -34,7 +34,7 @@ public class Init {
* @param dev dev Mode or not * @param dev dev Mode or not
* @return JDA object * @return JDA object
*/ */
static JDA initJda(String token, boolean dev){ static JDA initJda(String token){
JDA jda = null; JDA jda = null;
logger.debug("-------------------INITIALISATION-------------------"); logger.debug("-------------------INITIALISATION-------------------");

View File

@ -53,25 +53,12 @@ public class MainBot {
logger.info("--------------Starting Bot-------------"); logger.info("--------------Starting Bot-------------");
logger.info("======================================="); logger.info("=======================================");
if(System.getenv("DEV")!= null){
dev = Boolean.parseBoolean(System.getenv("DEV"));
}
String token = System.getenv("TOKEN");
String token = null; jda = Init.initJda(token);
int i = 0;
for(String aArg: args){
logger.debug(aArg);
if(aArg.startsWith("--") || aArg.startsWith("-")){
aArg = aArg.replaceAll("-","");
if(aArg.equals("dev") || aArg.equals("d")){
dev = true;
}
}
i++;
}
token = System.getenv("TOKEN");
jda = Init.initJda(token, dev);
if(System.getenv("dev")!= null){
dev = true;
}
ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args); ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args);
@ -85,14 +72,6 @@ public class MainBot {
Init.polish(jda); Init.polish(jda);
ready = true; ready = true;
} }
/** /**

View File

@ -128,7 +128,7 @@ public class UserManagerAPIController {
@RequestMapping(value = "/oauthLogin", method = RequestMethod.POST) @RequestMapping(value = "/oauthLogin", method = RequestMethod.POST)
public ResponseEntity<UserConnectionData> oauthLogin(@RequestParam(value = "token") String discordToken){ public ResponseEntity<UserConnectionData> oauthLogin(@RequestParam(value = "token") String discordToken){
logger.debug(discordToken); logger.debug(discordToken);
UserEntity user = Oauth.getInstance().getUserEntity(discordToken, userRepository); UserEntity user = Oauth.getInstance().getUserEntity(discordToken, userRepository, passwordEncoder);
logger.info("OAuth login for " + user.getName()); logger.info("OAuth login for " + user.getName());
return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK); return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK);

View File

@ -40,7 +40,7 @@ public class LimitChecker {
} }
number-=400; number-=400;
redirected = false; redirected = false;
logger.trace("First pass: "+number); logger.debug("First pass: "+number);
while(!redirected ) while(!redirected )
{ {
String origin = baseURL+number+"-2/"; String origin = baseURL+number+"-2/";
@ -53,7 +53,7 @@ public class LimitChecker {
} }
number-=90; number-=90;
redirected = false; redirected = false;
logger.trace("Second pass: "+number); logger.debug("Second pass: "+number);
while(!redirected ) while(!redirected )
{ {
String origin = baseURL+number+"-2/"; String origin = baseURL+number+"-2/";
@ -66,7 +66,7 @@ public class LimitChecker {
} }
number-=9; number-=9;
redirected = false; redirected = false;
logger.trace("Third pass: "+number); logger.debug("Third pass: "+number);
while(!redirected ) while(!redirected )
{ {
String origin = baseURL+number+"-2/"; String origin = baseURL+number+"-2/";
@ -78,7 +78,7 @@ public class LimitChecker {
redirected = true; redirected = true;
} }
number-=1; number-=1;
logger.trace("Final pass: "+number); logger.debug("Final pass: "+number);
return number; return number;

View File

@ -6,6 +6,7 @@ import net.Broken.MainBot;
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.json.JSONObject; import org.json.JSONObject;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@ -53,13 +54,13 @@ public class Oauth {
} }
public UserEntity getUserEntity(String token, UserRepository userRepository){ public UserEntity getUserEntity(String token, UserRepository userRepository, PasswordEncoder passwordEncoder){
String discorId = getUserId(token); String discorId = getUserId(token);
List<UserEntity> userEntitys = userRepository.findByJdaId(discorId); List<UserEntity> userEntitys = userRepository.findByJdaId(discorId);
if(userEntitys.size() != 0){ if(userEntitys.size() != 0){
return userEntitys.get(0); return userEntitys.get(0);
}else{ }else{
UserEntity user = new UserEntity(MainBot.jda.getUserById(discorId)); UserEntity user = new UserEntity(MainBot.jda.getUserById(discorId), passwordEncoder);
user = userRepository.save(user); user = userRepository.save(user);
return user; return user;
} }

View File

@ -1,18 +1,21 @@
var savedPlaylist; //import * as M from "./materialize";
var error = false;
var state; let savedPlaylist;
var disconected = false; let error = false;
var modal_loading; let state;
var btn_play; let disconected = false;
var btn_stop; let modal_loading;
var btn_next; let btn_play;
var btn_info; let btn_stop;
var btn_disconnect; let btn_next;
var btn_flush; let btn_info;
var btn_add; let btn_disconnect_music;
var switchAutoFlow; let btn_flush;
var loadingFlag = false; let btn_add;
var guild; let switchAutoFlow;
let loadingFlag = true;
let guild;
let interval;
$(document).ready(function () { $(document).ready(function () {
if (Cookies.get('guild') !== undefined) { if (Cookies.get('guild') !== undefined) {
@ -22,13 +25,12 @@ $(document).ready(function () {
btn_stop = $('#btn_stop'); btn_stop = $('#btn_stop');
btn_next = $('#btn_next'); btn_next = $('#btn_next');
btn_info = $('#btn_info'); btn_info = $('#btn_info');
btn_disconnect = $('#btn_disconnect'); btn_disconnect_music = $('#btn_disconnect');
btn_flush = $('#flush_btn'); btn_flush = $('#flush_btn');
btn_add = $('#add_btn'); btn_add = $('#add_btn');
switchAutoFlow = $("#autoflow"); switchAutoFlow = $("#autoflow");
setInterval("getCurentMusic()", 1000);
M.Modal.init($('#modalAdd').get(0)); M.Modal.init($('#modalAdd').get(0));
@ -38,10 +40,10 @@ $(document).ready(function () {
dismissible: false // Modal can be dismissed by clicking outside of the modal dismissible: false // Modal can be dismissed by clicking outside of the modal
}); });
modal_loading = $('#modal_loading');
modal_loading.modal({ modal_loading = M.Modal.init($('#modal_loading').get(0), {dismissible: false});
dismissible: false modal_loading.open();
});
$('.dropdown-button').dropdown({ $('.dropdown-button').dropdown({
@ -56,6 +58,8 @@ $(document).ready(function () {
}); });
listeners(); listeners();
interval = setInterval("getCurentMusic()", 1000);
} }
}); });
@ -84,7 +88,7 @@ function getCurentMusic() {
enableBtn(btn_flush); enableBtn(btn_flush);
enableBtn(btn_play); enableBtn(btn_play);
enableBtn(btn_next); enableBtn(btn_next);
enableBtn(btn_disconnect); enableBtn(btn_disconnect_music);
} }
else { else {
disableBtn(btn_play); disableBtn(btn_play);
@ -93,7 +97,7 @@ function getCurentMusic() {
disableBtn(btn_add); disableBtn(btn_add);
disableBtn(btn_flush); disableBtn(btn_flush);
disableBtn(btn_next); disableBtn(btn_next);
disableBtn(btn_disconnect); disableBtn(btn_disconnect_music);
} }
btn_play.children().text("play_arrow"); btn_play.children().text("play_arrow");
$('#music_img').attr("src", "/img/no_music.jpg"); $('#music_img').attr("src", "/img/no_music.jpg");
@ -148,7 +152,7 @@ function getCurentMusic() {
disableBtn(btn_add); disableBtn(btn_add);
disableBtn(btn_flush); disableBtn(btn_flush);
disableBtn(btn_next); disableBtn(btn_next);
disableBtn(btn_disconnect); disableBtn(btn_disconnect_music);
$('#music_img').attr("src", "/img/disconnected.png"); $('#music_img').attr("src", "/img/disconnected.png");
if (Cookies.get('token') != undefined) { if (Cookies.get('token') != undefined) {
@ -158,12 +162,19 @@ function getCurentMusic() {
} }
} }
clearInterval(interval);
break; break;
} }
if (switchAutoFlow.is(':checked') != data.autoflow) if (switchAutoFlow.is(':checked') != data.autoflow)
switchAutoFlow.prop('checked', data.autoflow); switchAutoFlow.prop('checked', data.autoflow);
if(data.state !== "DISCONNECTED" && data.state !== "STOP")
getPlayList(); getPlayList();
else{
if (loadingFlag) {
modal_loading.close();
loadingFlag = false;
}
}
}) })
.fail(function (data) { .fail(function (data) {
@ -187,7 +198,6 @@ function getPlayList() {
data = data.list; data = data.list;
if (data != null && data.length != 0) { if (data != null && data.length != 0) {
var noUpdate = comparePlaylist(data, savedPlaylist); var noUpdate = comparePlaylist(data, savedPlaylist);
// console.log("List up to date : "+noUpdate);
if (!noUpdate) { if (!noUpdate) {
savedPlaylist = data; savedPlaylist = data;
$('#playlist_list').empty(); $('#playlist_list').empty();
@ -213,7 +223,7 @@ function getPlayList() {
command: "DELL", command: "DELL",
url: $(this).attr("data_url") url: $(this).attr("data_url")
}; };
sendCommand(command); sendCommand(command, true);
}); });
@ -224,7 +234,7 @@ function getPlayList() {
savedPlaylist = {}; savedPlaylist = {};
} }
if (loadingFlag) { if (loadingFlag) {
modal_loading.modal('close'); modal_loading.close();
loadingFlag = false; loadingFlag = false;
} }
@ -239,7 +249,7 @@ function getPlayList() {
error = true; error = true;
} }
if (loadingFlag) { if (loadingFlag) {
modal_loading.modal('close'); modal_loading.close();
loadingFlag = false; loadingFlag = false;
} }
@ -250,7 +260,7 @@ function getPlayList() {
function getChannels() { function getChannels() {
$.get("api/music/getChanel?guild=" + guild, function (data) { $.get("api/music/getChanel?guild=" + guild, function (data) {
}).done(function (data) { }).done(function (data) {
console.log(data);
$('#channelForm').empty(); $('#channelForm').empty();
data.forEach(function (element) { data.forEach(function (element) {
var template = $('#radioTemplate').clone(); var template = $('#radioTemplate').clone();
@ -294,7 +304,6 @@ function updateModal(data) {
function updateControl(data) { function updateControl(data) {
$('#music_text').text(data.info.audioTrackInfo.title); $('#music_text').text(data.info.audioTrackInfo.title);
var percent = (data.currentPos / data.info.audioTrackInfo.length) * 100; var percent = (data.currentPos / data.info.audioTrackInfo.length) * 100;
// console.log(percent)
if (!$('#music_progress').hasClass("indeterminate")) { if (!$('#music_progress').hasClass("indeterminate")) {
$('#music_progress').addClass("determinate").removeClass("indeterminate"); $('#music_progress').addClass("determinate").removeClass("indeterminate");
} }
@ -307,7 +316,7 @@ function updateControl(data) {
enableBtn(btn_add); enableBtn(btn_add);
enableBtn(btn_flush); enableBtn(btn_flush);
enableBtn(btn_next); enableBtn(btn_next);
enableBtn(btn_disconnect); enableBtn(btn_disconnect_music);
} }
else { else {
disableBtn(btn_play); disableBtn(btn_play);
@ -316,20 +325,23 @@ function updateControl(data) {
disableBtn(btn_add); disableBtn(btn_add);
disableBtn(btn_flush); disableBtn(btn_flush);
disableBtn(btn_next); disableBtn(btn_next);
disableBtn(btn_disconnect); disableBtn(btn_disconnect_music);
} }
$('#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");
// console.log(data);
$('#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));
updateModal(data); updateModal(data);
} }
function sendCommand(command) { function sendCommand(command, stopRefresh) {
modal_loading.modal('open'); if(stopRefresh){
// console.log(command); clearInterval(interval);
modal_loading.open();
}
$.ajax({ $.ajax({
type: "POST", type: "POST",
dataType: 'json', dataType: 'json',
@ -337,15 +349,22 @@ function sendCommand(command) {
url: "/api/music/command?guild=" + guild, url: "/api/music/command?guild=" + guild,
data: JSON.stringify(command), data: JSON.stringify(command),
success: function (data) { success: function (data) {
console.log(data);
loadingFlag = true; loadingFlag = true;
getCurentMusic(); if(stopRefresh)
interval = setInterval("getCurentMusic()", 1000);
if(command.command === "ADD"){
M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>check_circle</i> Video added to playlist!",
classes: 'green',
displayLength: 5000
});
}
} }
}).fail(function (data) { }).fail(function (data) {
console.log(data); console.log(data);
modal_loading.modal('close'); modal_loading.close();
if (data.responseJSON.error === "token") { if (data.responseJSON.error === "token") {
Cookies.remove('token'); Cookies.remove('token');
Cookies.remove('name'); Cookies.remove('name');
@ -365,14 +384,13 @@ function comparePlaylist(list1, list2) {
if (list1 == null || list2 == null) { if (list1 == null || list2 == null) {
return false; return false;
} }
if (list1.length !== list2.length) { if (list1.length !== list2.length) {
return false; return false;
} }
for (var i = 0; i++; i < list1.length) { for (let i = 0; i < list1.length; i++) {
if (list1[i].uri !== list2[i].uri) if (list1[i].audioTrackInfo.uri !== list2[i].audioTrackInfo.uri)
return false return false
} }
return true; return true;
@ -381,17 +399,16 @@ function comparePlaylist(list1, list2) {
function search() { function search() {
let query = $('#input_search').val(); let input_search = $('#input_search');
let list = $("#search_result"); let list = $("#search_result");
let load = $("#search_load"); let load = $("#search_load");
disableBtn($('#btn_search')); disableBtn($('#btn_search'));
// list.addClass("hide"); input_search.attr('disabled', 'disabled');
list.removeClass("scale-in"); list.removeClass("scale-in");
load.removeClass("hide"); load.removeClass("hide");
load.addClass("scale-in"); load.addClass("scale-in");
$.get("/api/music/search?query=" + query, (data) => { $.get("/api/music/search?query=" + input_search.val(), (data) => {
// console.log(data);
list.empty(); list.empty();
data.forEach((item)=>{ data.forEach((item)=>{
@ -417,10 +434,31 @@ function search() {
load.addClass("hide"); load.addClass("hide");
list.addClass("scale-in"); list.addClass("scale-in");
enableBtn($('#btn_search')); enableBtn($('#btn_search'));
input_search.removeAttr("disabled");
input_search.focus();
}).fail( (data)=>{
if(data.status === 401){
M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i> Unauthorized, please re-login.",
classes: 'red',
displayLength: 99999999
});
}else{
M.toast({
html: " <i class=\"material-icons\" style='margin-right: 10px'>warning</i>Internal server error, please contact dev.",
classes: 'red',
displayLength: 99999999
}); });
}
list.empty();
load.removeClass("scale-in");
load.addClass("hide");
enableBtn($('#btn_search'));
enableBtn(input_search);
});
} }
@ -440,7 +478,7 @@ function addListClick(event){
playlistLimit: $('#limit_range').val(), playlistLimit: $('#limit_range').val(),
onHead: !$('#bottom').is(':checked') onHead: !$('#bottom').is(':checked')
}; };
sendCommand(command); sendCommand(command, false);
} }
function ytTimeToTime(duration) { function ytTimeToTime(duration) {
@ -497,39 +535,32 @@ function listeners() {
$('#btn_play').click(function () { $('#btn_play').click(function () {
switch (state) { switch (state) {
case "PLAYING": case "PLAYING":
sendCommand({command: "PAUSE"}); sendCommand({command: "PAUSE"}, true);
break; break;
case "PAUSE": case "PAUSE":
sendCommand({command: "PLAY"}); sendCommand({command: "PLAY"}, true);
break; break;
default: default:
sendCommand({command: "PLAY"}); 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();
}); });
$('#btn_next').click(function () { $('#btn_next').click(function () {
sendCommand({command: "NEXT"}); sendCommand({command: "NEXT"},true);
}); });
$('#btn_stop').click(function () { $('#btn_stop').click(function () {
sendCommand({command: "STOP"}); sendCommand({command: "STOP"}, true);
}); });
$('#input_link').on("input", function () {
if ($('#input_link').val() == "") {
disableBtn($('#btn_add'));
}
else {
enableBtn($('#btn_add'));
}
});
$('#input_search').on("input", function () { $('#input_search').on("input", function () {
if ($('#input_search').val() == "") { if ($('#input_search').val() == "") {
@ -540,14 +571,6 @@ function listeners() {
} }
}); });
$('#add_btn').click(function () {
if ($('#input_search').val() == "") {
disableBtn($('#btn_search'));
}
else {
enableBtn($('#btn_search'));
}
});
@ -561,7 +584,7 @@ function listeners() {
var command = { var command = {
command: "FLUSH" command: "FLUSH"
}; };
sendCommand(command); sendCommand(command, true);
}); });
$('#btn_ok_channel').click(function () { $('#btn_ok_channel').click(function () {
@ -570,20 +593,19 @@ function listeners() {
command: "CONNECT", command: "CONNECT",
chanelId: $('input[name=vocalRadio]:checked').val() chanelId: $('input[name=vocalRadio]:checked').val()
}; };
sendCommand(command); sendCommand(command, true);
}); });
$('#btn_disconnect').click(function () { $('#btn_disconnect').click(function () {
sendCommand({command: "DISCONNECT"}) sendCommand({command: "DISCONNECT"}, true)
}); });
switchAutoFlow.click(function () { switchAutoFlow.click(function () {
// console.log(switchAutoFlow.is(':checked'));
if (switchAutoFlow.is(':checked')) { if (switchAutoFlow.is(':checked')) {
sendCommand({command: 'AUTOFLOWON'}) sendCommand({command: 'AUTOFLOWON'}, false)
} }
else else
sendCommand({command: 'AUTOFLOWOFF'}) sendCommand({command: 'AUTOFLOWOFF'}, false)
}); });
} }

View File

@ -100,6 +100,7 @@ function disconnected() {
function tryConnection() { function tryConnection() {
var request = { name: input_name.val(), password: input_psw.val()}; var request = { name: input_name.val(), password: input_psw.val()};
$.ajax({ $.ajax({
type: "POST", type: "POST",
@ -175,7 +176,12 @@ function navListeners() {
$('.nav-change-guild').click(function () { $('.nav-change-guild').click(function () {
Cookies.remove('guild'); Cookies.remove('guild');
window.location.reload(true); window.location.reload(true);
}) });
$("#login_form").submit(function(e){
e.preventDefault();
tryConnection();
});
} }
function getGuild(){ function getGuild(){

View File

@ -123,7 +123,7 @@
</div> </div>
</div> </div>
<div class="row center" style="margin-bottom: 0px"> <div class="row center" style="margin-bottom: 0px">
<form name="login_form" id="login_form" action="javascript:void(0);" onsubmit="tryConnection()"> <form name="login_form" id="login_form">
<div class="row" style="margin-bottom: 0px"> <div class="row" style="margin-bottom: 0px">
<div class="input-field col l6 offset-l3 m10 offset-m1 s10 offset-s1"> <div class="input-field col l6 offset-l3 m10 offset-m1 s10 offset-s1">
<i class="material-icons prefix">account_box</i> <i class="material-icons prefix">account_box</i>

View File

@ -59,7 +59,7 @@
<div class="row"> <div class="row">
<div class="col l8 s12 m12"> <div class="col l8 s12 m12">
<div class="row center" > <div class="row center" >
<img class="responsive-img z-depth-3" id="music_img" style="max-width: 30%" src=""/> <img class="responsive-img z-depth-3" id="music_img" style="max-width: 30%" src="/img/disconnected.png"/>
</div> </div>
<h4 class="center" id="music_text"></h4> <h4 class="center" id="music_text"></h4>
<div class="row center" style="margin-bottom: 0px"> <div class="row center" style="margin-bottom: 0px">