Javadoc ! close #26

This commit is contained in:
Sebastien 2018-02-28 17:59:09 +01:00
parent 4279fe2666
commit af2c2d9632
76 changed files with 605 additions and 373 deletions

View File

@ -24,7 +24,7 @@ import org.apache.logging.log4j.Logger;
/** /**
* Created by seb65 on 19/10/2016. * Bot Listener
*/ */
public class BotListener extends ListenerAdapter { public class BotListener extends ListenerAdapter {
private AntiSpam antispam=new AntiSpam(); private AntiSpam antispam=new AntiSpam();

View File

@ -4,14 +4,32 @@ package net.Broken;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
/** /**
* Created by seb65 on 19/10/2016. * Interface that define command structure.
*/ */
public interface Commande { public interface Commande {
boolean called(String[] args, MessageReceivedEvent event); /**
* Main action of command
* @param args Command args.
* @param event Command MessageReceivedEvent
*/
void action(String[] args, MessageReceivedEvent event); void action(String[] args, MessageReceivedEvent event);
void executed(boolean success, MessageReceivedEvent event);
/**
* Determines if the command is usable whit private message
* @return boolean
*/
boolean isPrivateUsable(); boolean isPrivateUsable();
/**
* Determines if the command is usable only by admin user
* @return boolean
*/
boolean isAdminCmd(); boolean isAdminCmd();
/**
* Determines if the command is only usable on NSFW channels
* @return boolean
*/
boolean isNSFW(); boolean isNSFW();

View File

@ -13,13 +13,9 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
/** /**
* Created by Seb on 06/02/2017. * Command that return a random picture of cat.
*/ */
public class Cat implements Commande { public class Cat implements Commande {
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -63,11 +59,6 @@ public class Cat implements Commande {
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;

View File

@ -1,29 +1,18 @@
package net.Broken.Commands; package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.DayListener.DayListener; import net.Broken.Tools.DayListener.DayListener;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.ChannelType; import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
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 java.util.ArrayList; /**
import java.util.List; * Admin command to manually trigger daily action(s)
*/
public class DayTrigger implements Commande{ public class DayTrigger implements Commande{
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
if(!event.isFromType(ChannelType.PRIVATE)) if(!event.isFromType(ChannelType.PRIVATE))
@ -32,11 +21,6 @@ public class DayTrigger implements Commande{
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return true; return true;

View File

@ -8,13 +8,13 @@ import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/**
* Send standard internal error.
*/
public class Error implements Commande{ public class Error implements Commande{
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -24,11 +24,6 @@ public class Error implements Commande{
event.getTextChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue(); event.getTextChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue();
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return true; return true;

View File

@ -12,13 +12,12 @@ import org.apache.logging.log4j.Logger;
import java.util.List; import java.util.List;
/**
* Command to flush X last message on channel.
*/
public class Flush implements Commande{ public class Flush implements Commande{
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return true;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -54,11 +53,6 @@ public class Flush implements Commande{
} }
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;

View File

@ -2,7 +2,6 @@ package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.CommandInterface;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage; import net.Broken.Tools.PrivateMessage;
@ -23,15 +22,11 @@ import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* Created by seb65 on 23/10/2016. * Help Command.
*/ */
public class Help implements Commande { public class Help implements Commande {
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
private int cellLenght = 25; private int cellLenght = 25;
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return true;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -174,11 +169,6 @@ public class Help implements Commande {
} }
}
@Override
public void executed(boolean success, MessageReceivedEvent event) {
} }
@Override @Override

View File

@ -4,7 +4,6 @@ import net.Broken.Commande;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.exceptions.HierarchyException; import net.dv8tion.jda.core.exceptions.HierarchyException;
@ -17,12 +16,9 @@ import org.apache.logging.log4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* Created by seb65 on 20/10/2016.
*/
/** /**
* * Move Command
*/ */
public class Move implements Commande { public class Move implements Commande {
@ -34,14 +30,14 @@ public class Move implements Commande {
public GuildManager serveurManager; public GuildManager serveurManager;
public GuildController guildController; public GuildController guildController;
/** /** Perform a move (Reset is role and add target(s) role(s)
* *
* @param user * @param user User to move
* @param cible * @param cible Complete list of new role
* @param reset * @param reset
* @param serveur * @param serveur Guild
* @param serveurManager * @param serveurManager GuildManager
* @return * @return success
*/ */
public boolean exc(Member user, List<Role> cible , boolean reset, Guild serveur, GuildManager serveurManager) throws HierarchyException public boolean exc(Member user, List<Role> cible , boolean reset, Guild serveur, GuildManager serveurManager) throws HierarchyException
{ {
@ -77,13 +73,7 @@ public class Move implements Commande {
return erreur; return erreur;
} }
@Override /** Command handler
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
/**
* *
* @param args * @param args
* @param event * @param event
@ -188,16 +178,6 @@ public class Move implements Commande {
}
/**
*
* @param success
* @param event
*/
@Override
public void executed(boolean success, MessageReceivedEvent event) {
} }
@Override @Override

View File

@ -15,6 +15,10 @@ import org.apache.logging.log4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* Music commands
*/
public class Music implements Commande { public class Music implements Commande {
public AudioM audio; public AudioM audio;
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@ -22,11 +26,6 @@ public class Music implements Commande {
audio = new AudioM(MainBot.jda.getGuilds().get(0)); audio = new AudioM(MainBot.jda.getGuilds().get(0));
} }
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -157,11 +156,6 @@ public class Music implements Commande {
} }
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;

View File

@ -4,7 +4,7 @@ import net.Broken.Tools.Command.NumberedCommande;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
/** /**
* Created by seb65 on 07/11/2016. * Ass command, return random picture from les400culs.com
*/ */
public class Ass extends NumberedCommande { public class Ass extends NumberedCommande {

View File

@ -4,7 +4,7 @@ import net.Broken.Tools.Command.NumberedCommande;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
/** /**
* Created by seb65 on 07/11/2016. * Boobs command, return random picture from lesaintdesseins.fr
*/ */
public class Boobs extends NumberedCommande { public class Boobs extends NumberedCommande {

View File

@ -12,16 +12,12 @@ import java.io.IOException;
/** /**
* Created by seb65 on 11/11/2016. * Madame command that return random picture from dites.bonjourmadame.fr
*/ */
public class Madame implements Commande{ public class Madame implements Commande{
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
MessageReceivedEvent event; MessageReceivedEvent event;
public String HELP="T'es sérieux la?"; public String HELP="T'es sérieux la?";
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -63,11 +59,6 @@ public class Madame implements Commande{
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;
@ -83,8 +74,16 @@ public class Madame implements Commande{
return true; return true;
} }
/**
* Detect if picture link go to Tepeee
* @param url
* @return true is Tepeee link is detected
* @throws StringIndexOutOfBoundsException
* @throws IOException
*/
private boolean scanPageForTipeee(String url) throws StringIndexOutOfBoundsException, IOException{ private boolean scanPageForTipeee(String url) throws StringIndexOutOfBoundsException, IOException{
String content = FindContentOnWebPage.getUrlSource(url); String content = FindContentOnWebPage.getSourceUrl(url);
String imgClickLink = content.substring(content.indexOf("photo post")); String imgClickLink = content.substring(content.indexOf("photo post"));
imgClickLink = imgClickLink.substring(imgClickLink.indexOf("<a")); imgClickLink = imgClickLink.substring(imgClickLink.indexOf("<a"));
imgClickLink = imgClickLink.substring(imgClickLink.indexOf("\"")); imgClickLink = imgClickLink.substring(imgClickLink.indexOf("\""));

View File

@ -4,7 +4,7 @@ import net.Broken.Tools.Command.NumberedCommande;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
/** /**
* Created by seb65 on 07/11/2016. * Ass command, return random picture from feelation.com
*/ */
public class Pipe extends NumberedCommande { public class Pipe extends NumberedCommande {
public Pipe() { public Pipe() {

View File

@ -7,15 +7,11 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/** /**
* Created by seb65 on 10/11/2016. * TODO Remove this
*/ */
public class SM implements Commande { public class SM implements Commande {
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
public String HELP="T'es sérieux la?"; public String HELP="T'es sérieux la?";
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -30,11 +26,6 @@ public class SM implements Commande {
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;

View File

@ -8,18 +8,11 @@ import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import java.util.ArrayList;
import java.util.List;
/** /**
* Created by seb65 on 19/10/2016. * Command that return the Bot's ping
*/ */
public class Ping implements Commande { public class Ping implements Commande {
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return true;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -34,12 +27,6 @@ public class Ping implements Commande {
LogManager.getLogger().debug("pong"); LogManager.getLogger().debug("pong");
} }
@Override
public void executed(boolean success, MessageReceivedEvent event)
{
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return true; return true;

View File

@ -6,7 +6,6 @@ import net.Broken.Tools.AntiSpam;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.UserSpamUtils; import net.Broken.Tools.UserSpamUtils;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.Message;
@ -23,14 +22,10 @@ import java.util.Objects;
/** /**
* Created by seb65 on 27/10/2016. * Spam admin command
*/ */
public class Spam implements Commande { public class Spam implements Commande {
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) public void action(String[] args, MessageReceivedEvent event)
@ -76,12 +71,6 @@ public class Spam implements Commande {
} }
@Override
public void executed(boolean success, MessageReceivedEvent event)
{
}
@Override @Override
public boolean isPrivateUsable() { public boolean isPrivateUsable() {
return false; return false;

View File

@ -21,16 +21,12 @@ import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Created by sebastien on 13/03/17. * Spam Info Command
*/ */
public class SpamInfo implements Commande{ public class SpamInfo implements Commande{
private HashMap<User,MessageUpdater> threadHashMap = new HashMap<>(); private HashMap<User,MessageUpdater> threadHashMap = new HashMap<>();
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
@ -92,11 +88,6 @@ public class SpamInfo implements Commande{
}
@Override
public void executed(boolean success, MessageReceivedEvent event) {
} }
@Override @Override

View File

@ -6,6 +6,9 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
/**
* Entity for DB. Represent user who not yet confirmed her account.
*/
@Entity @Entity
public class PendingUserEntity { public class PendingUserEntity {
@Id @Id

View File

@ -5,6 +5,9 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
/**
* Entity for DB. Represent confirmed user account.
*/
@Entity @Entity
public class UserEntity { public class UserEntity {
@Id @Id

View File

@ -5,6 +5,9 @@ import org.springframework.data.repository.CrudRepository;
import java.util.List; import java.util.List;
/**
* Repository for PendingUserEntity
*/
public interface PendingUserRepository extends CrudRepository<PendingUserEntity, Integer> { public interface PendingUserRepository extends CrudRepository<PendingUserEntity, Integer> {
List<PendingUserEntity> findByJdaId(String jdaId); List<PendingUserEntity> findByJdaId(String jdaId);

View File

@ -5,6 +5,10 @@ import org.springframework.data.repository.CrudRepository;
import java.util.List; import java.util.List;
/**
* Repository for UserEntity
*/
public interface UserRepository extends CrudRepository<UserEntity, Integer>{ public interface UserRepository extends CrudRepository<UserEntity, Integer>{
List<UserEntity> findByName(String name); List<UserEntity> findByName(String name);
List<UserEntity> findByJdaId(String jdaId); List<UserEntity> findByJdaId(String jdaId);

View File

@ -18,9 +18,16 @@ import org.apache.logging.log4j.Logger;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.util.List; import java.util.List;
public class Init { public class Init {
static private Logger logger = LogManager.getLogger(); static private Logger logger = LogManager.getLogger();
/**
* Initialize all bot functionality
* @param token bot user token
* @param dev dev Mode or not
* @return JDA object
*/
static JDA initBot(String token, boolean dev){ static JDA initBot(String token, boolean dev){
boolean okInit; boolean okInit;
JDA jda = null; JDA jda = null;

View File

@ -5,7 +5,6 @@ import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage; import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserManager.UserRegister;
import net.Broken.Tools.UserSpamUtils; import net.Broken.Tools.UserSpamUtils;
import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.Permission;
@ -23,10 +22,9 @@ import org.springframework.stereotype.Controller;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
/** /**
* Created by seb65 on 19/10/2016. * Main Class
*/ */
@SpringBootApplication @SpringBootApplication
@Controller @Controller
@ -91,9 +89,10 @@ public class MainBot {
} }
/*************************************** /**
* Traitement de la commande * * Perform test (admin, NSFW and private usable or not) and execute command or not
***************************************/ * @param cmd Container whit all command info
*/
public static void handleCommand(CommandParser.CommandContainer cmd) public static void handleCommand(CommandParser.CommandContainer cmd)
{ {
//On verifie que la commande existe //On verifie que la commande existe
@ -114,13 +113,11 @@ public class MainBot {
{ {
commandes.get(cmd.commande).action(cmd.args, cmd.event); commandes.get(cmd.commande).action(cmd.args, cmd.event);
commandes.get(cmd.commande).executed(true, cmd.event);
} }
else if (!cmd.event.isFromType(ChannelType.PRIVATE)) else if (!cmd.event.isFromType(ChannelType.PRIVATE))
{ {
if(!cmdObj.isNSFW() || cmd.event.getTextChannel().isNSFW()){ if(!cmdObj.isNSFW() || cmd.event.getTextChannel().isNSFW()){
commandes.get(cmd.commande).action(cmd.args, cmd.event); commandes.get(cmd.commande).action(cmd.args, cmd.event);
commandes.get(cmd.commande).executed(true, cmd.event);
} }
else{ else{
Message msg = cmd.event.getTextChannel().sendMessage(cmd.event.getAuthor().getAsMention() + "\n:warning: **__Channel règlementé! Go sur over18!__**:warning: ").complete(); Message msg = cmd.event.getTextChannel().sendMessage(cmd.event.getAuthor().getAsMention() + "\n:warning: **__Channel règlementé! Go sur over18!__**:warning: ").complete();
@ -159,9 +156,11 @@ public class MainBot {
} }
/*******************************
* RAZ Compteur Spam *
*******************************/ /**
* TODO Change this, better use daylistener
*/
public static class ModoTimer extends Thread{ public static class ModoTimer extends Thread{

View File

@ -6,6 +6,17 @@ import net.Broken.RestApi.Data.CommandResponseData;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Represent RestApi command
*/
public interface CommandInterface { public interface CommandInterface {
/**
* Main action
* @param musicCommande Current guild music command
* @param data Received data
* @param user User who submit RestApi command
* @return HTTP Response
*/
ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user); ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user);
} }

View File

@ -8,6 +8,9 @@ import net.Broken.audio.WebLoadUtils;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Add track RestApi
*/
public class Add implements CommandInterface { public class Add implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {

View File

@ -10,6 +10,9 @@ import net.dv8tion.jda.core.entities.VoiceChannel;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Connect to vocal channel RestApi command
*/
public class Connect implements CommandInterface{ public class Connect implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {

View File

@ -4,23 +4,26 @@ import net.Broken.Commands.Music;
import net.Broken.RestApi.CommandInterface; import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Delete track RestApi command
*/
public class Dell implements CommandInterface { public class Dell implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {
if(data.url != null) { if(data.url != null) {
try { try {
if(musicCommande.getAudioManager().getMusicManager().scheduler.remove(data.url)){ if(musicCommande.getAudioManager().getGuildMusicManager().scheduler.remove(data.url)){
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} }
else else
return new ResponseEntity<>(new CommandResponseData(data.command,"URL not found"), HttpStatus.NOT_FOUND); return new ResponseEntity<>(new CommandResponseData(data.command,"URL not found"), HttpStatus.NOT_FOUND);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
} }
} }

View File

@ -10,6 +10,9 @@ import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Disconnect from vocal chanel RestApi Command
*/
public class Disconnect implements CommandInterface{ public class Disconnect implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {

View File

@ -4,19 +4,22 @@ import net.Broken.Commands.Music;
import net.Broken.RestApi.CommandInterface; import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Flush playlist RestApi Command
*/
public class Flush implements CommandInterface { public class Flush implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {
try { try {
musicCommande.getAudioManager().getMusicManager().scheduler.flush(); musicCommande.getAudioManager().getGuildMusicManager().scheduler.flush();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
} }
} }

View File

@ -4,19 +4,22 @@ import net.Broken.Commands.Music;
import net.Broken.RestApi.CommandInterface; import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Next Track RestApi command
*/
public class Next implements CommandInterface { public class Next implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {
try { try {
musicCommande.getAudioManager().getMusicManager().scheduler.nextTrack(); musicCommande.getAudioManager().getGuildMusicManager().scheduler.nextTrack();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
} }
} }

View File

@ -4,19 +4,22 @@ import net.Broken.Commands.Music;
import net.Broken.RestApi.CommandInterface; import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Pause track RestApi command
*/
public class Pause implements CommandInterface { public class Pause implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {
try { try {
musicCommande.getAudioManager().getMusicManager().scheduler.pause(); musicCommande.getAudioManager().getGuildMusicManager().scheduler.pause();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
} }
} }

View File

@ -4,19 +4,22 @@ import net.Broken.Commands.Music;
import net.Broken.RestApi.CommandInterface; import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Resume (play button) RestApi command
*/
public class Play implements CommandInterface { public class Play implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {
try { try {
musicCommande.getAudioManager().getMusicManager().scheduler.resume(); musicCommande.getAudioManager().getGuildMusicManager().scheduler.resume();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Not connected to vocal!"), HttpStatus.NOT_ACCEPTABLE);
} }
} }

View File

@ -9,6 +9,9 @@ import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Stop RestApi Command
*/
public class Stop implements CommandInterface { public class Stop implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) { public ResponseEntity<CommandResponseData> action(Music musicCommande, CommandPostData data, User user) {

View File

@ -1,11 +1,14 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
public class Chanel { /**
* Data for JSON Parsing
*/
public class ChanelData {
public String name; public String name;
public String id; public String id;
public int pos; public int pos;
public Chanel(String name, String id, int pos) { public ChanelData(String name, String id, int pos) {
this.name = name; this.name = name;
this.id = id; this.id = id;
this.pos = pos; this.pos = pos;

View File

@ -1,6 +1,8 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
/**
* Data for JSON Parsing
*/
public class CommandPostData { public class CommandPostData {
public String command; public String command;
public boolean onHead; public boolean onHead;

View File

@ -1,7 +1,9 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
/**
* Data for JSON Parsing
*/
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class CommandResponseData { public class CommandResponseData {
public String Commande; public String Commande;

View File

@ -5,7 +5,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackState; import com.sedmelluq.discord.lavaplayer.track.AudioTrackState;
/**
* Data for JSON Parsing
*/
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class CurrentMusicData { public class CurrentMusicData {
private final UserAudioTrackData info; private final UserAudioTrackData info;

View File

@ -3,7 +3,9 @@ package net.Broken.RestApi.Data;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import java.util.List; import java.util.List;
/**
* Data for JSON Parsing
*/
public class PlaylistData { public class PlaylistData {
private List<UserAudioTrackData> list; private List<UserAudioTrackData> list;

View File

@ -2,7 +2,9 @@ package net.Broken.RestApi.Data;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.audio.UserAudioTrack; import net.Broken.audio.UserAudioTrack;
/**
* Data for JSON Parsing
*/
public class UserAudioTrackData { public class UserAudioTrackData {
private String user; private String user;
private AudioTrackInfo audioTrackInfo; private AudioTrackInfo audioTrackInfo;
@ -14,7 +16,7 @@ public class UserAudioTrackData {
public UserAudioTrackData(UserAudioTrack userAudioTrack){ public UserAudioTrackData(UserAudioTrack userAudioTrack){
this.audioTrackInfo = userAudioTrack.getAudioTrack().getInfo(); this.audioTrackInfo = userAudioTrack.getAudioTrack().getInfo();
this.user = userAudioTrack.getSubmitedUser().getName(); this.user = userAudioTrack.getSubmittedUser().getName();
} }
public String getUser() { public String getUser() {

View File

@ -1,5 +1,8 @@
package net.Broken.RestApi.Data.UserManager; package net.Broken.RestApi.Data.UserManager;
/**
* Data for JSON Parsing
*/
public class CheckResposeData { public class CheckResposeData {
public boolean accepted; public boolean accepted;
public String name; public String name;

View File

@ -1,5 +1,8 @@
package net.Broken.RestApi.Data.UserManager; package net.Broken.RestApi.Data.UserManager;
/**
* Data for JSON Parsing
*/
public class ConfirmData { public class ConfirmData {
public String id; public String id;
public String checkToken; public String checkToken;

View File

@ -1,5 +1,8 @@
package net.Broken.RestApi.Data.UserManager; package net.Broken.RestApi.Data.UserManager;
/**
* Data for JSON Parsing
*/
public class UserConnectionData { public class UserConnectionData {
public boolean accepted; public boolean accepted;
public String token; public String token;

View File

@ -1,5 +1,8 @@
package net.Broken.RestApi.Data.UserManager; package net.Broken.RestApi.Data.UserManager;
/**
* Data for JSON Parsing
*/
public class UserInfoData { public class UserInfoData {
public String name; public String name;
public String password; public String password;

View File

@ -2,19 +2,15 @@ package net.Broken.RestApi;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.Commands.Music; import net.Broken.Commands.Music;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.Data.*; import net.Broken.RestApi.Data.*;
import net.Broken.RestApi.Data.UserManager.CheckResposeData;
import net.Broken.RestApi.Data.UserManager.UserInfoData;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.Exceptions.UserNotFoundException; import net.Broken.Tools.UserManager.UserUtils;
import net.Broken.Tools.UserManager.UserRegister;
import net.Broken.audio.FindGeneral; import net.Broken.audio.FindGeneral;
import net.Broken.audio.NotConectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.entities.VoiceChannel;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -22,7 +18,6 @@ import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@ -32,18 +27,18 @@ import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
// import net.Broken.DB.Repository.SavedPlaylistRepository; /**
* Rest Api Controller for /api/music
*/
@RestController @RestController
@RequestMapping("/api/music/") @RequestMapping("/api/music/")
public class MusicWebAPIController { public class MusicWebAPIController {
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
// @Autowired
// public SavedPlaylistRepository savedPlaylist;
@Autowired @Autowired
UserRepository userRepository; UserRepository userRepository;
UserRegister userRegister = UserRegister.getInstance(); UserUtils userUtils = UserUtils.getInstance();
@RequestMapping("/currentMusicInfo") @RequestMapping("/currentMusicInfo")
@ -52,15 +47,15 @@ public class MusicWebAPIController {
if(musicCommande.audio.getGuild().getAudioManager().isConnected()){ if(musicCommande.audio.getGuild().getAudioManager().isConnected()){
try { try {
AudioPlayer player = musicCommande.audio.getMusicManager().player; AudioPlayer player = musicCommande.audio.getGuildMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack(); AudioTrack currentTrack = player.getPlayingTrack();
if(currentTrack == null) if(currentTrack == null)
{ {
return new CurrentMusicData(null,0, "STOP",false); return new CurrentMusicData(null,0, "STOP",false);
} }
UserAudioTrackData uat = new UserAudioTrackData(musicCommande.audio.getMusicManager().scheduler.getCurrentPlayingTrack()); UserAudioTrackData uat = new UserAudioTrackData(musicCommande.audio.getGuildMusicManager().scheduler.getCurrentPlayingTrack());
return new CurrentMusicData(uat, currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused()); return new CurrentMusicData(uat, currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused());
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new CurrentMusicData(null,0, "STOP",false); return new CurrentMusicData(null,0, "STOP",false);
} }
}else }else
@ -74,9 +69,9 @@ public class MusicWebAPIController {
Music musicCommande = (Music) MainBot.commandes.get("music"); Music musicCommande = (Music) MainBot.commandes.get("music");
List<UserAudioTrackData> list = null; List<UserAudioTrackData> list = null;
try { try {
list = musicCommande.getAudioManager().getMusicManager().scheduler.getList(); list = musicCommande.getAudioManager().getGuildMusicManager().scheduler.getList();
return new PlaylistData(list); return new PlaylistData(list);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
return new PlaylistData(list); return new PlaylistData(list);
} }
} }
@ -87,7 +82,7 @@ public class MusicWebAPIController {
if(data.command != null) { if(data.command != null) {
if(data.token != null) { if(data.token != null) {
try { try {
UserEntity user = userRegister.getUserWithApiToken(userRepository, data.token); UserEntity user = userUtils.getUserWithApiToken(userRepository, data.token);
logger.info("receive command " + data.command + " from " + request.getRemoteAddr() + " USER: " + user.getName()); logger.info("receive command " + data.command + " from " + request.getRemoteAddr() + " USER: " + user.getName());
Music musicCommande = (Music) MainBot.commandes.get("music"); Music musicCommande = (Music) MainBot.commandes.get("music");
@ -115,35 +110,14 @@ public class MusicWebAPIController {
} }
@RequestMapping(value = "/getChanel", method = RequestMethod.GET) @RequestMapping(value = "/getChanel", method = RequestMethod.GET)
public List<Chanel> getChanel(){ public List<ChanelData> getChanel(){
List<Chanel> temp = new ArrayList<>(); List<ChanelData> temp = new ArrayList<>();
for(VoiceChannel aChanel : FindGeneral.find(MainBot.jda.getGuilds().get(0)).getVoiceChannels()){ for(VoiceChannel aChanel : FindGeneral.find(MainBot.jda.getGuilds().get(0)).getVoiceChannels()){
temp.add(new Chanel(aChanel.getName(),aChanel.getId(),aChanel.getPosition())); temp.add(new ChanelData(aChanel.getName(),aChanel.getId(),aChanel.getPosition()));
} }
return temp; return temp;
} }
// DB Test Ignore it
// @RequestMapping(value = "/test", method = RequestMethod.GET)
// public ResponseEntity<String> test(){
// SavedPlaylistEntity savedPlaylistEntity = new SavedPlaylistEntity();
// savedPlaylistEntity.setAutorName("Test");
// savedPlaylistEntity.setName("Playlist de test");
// savedPlaylist.save(savedPlaylistEntity);
// logger.info(savedPlaylistEntity);
// return new ResponseEntity<String>("OK",HttpStatus.OK);
// }
// @GetMapping(path="/all")
// public @ResponseBody Iterable<SavedPlaylistEntity> getAllUsers() {
// // This returns a JSON or XML with the users
// return savedPlaylist.findAll();
// }
} }

View File

@ -4,7 +4,6 @@ import net.Broken.DB.Entity.PendingUserEntity;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.PendingUserRepository; import net.Broken.DB.Repository.PendingUserRepository;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.UserManager.CheckResposeData; import net.Broken.RestApi.Data.UserManager.CheckResposeData;
import net.Broken.RestApi.Data.UserManager.ConfirmData; import net.Broken.RestApi.Data.UserManager.ConfirmData;
import net.Broken.RestApi.Data.UserManager.UserConnectionData; import net.Broken.RestApi.Data.UserManager.UserConnectionData;
@ -13,7 +12,7 @@ import net.Broken.Tools.UserManager.Exceptions.PasswordNotMatchException;
import net.Broken.Tools.UserManager.Exceptions.TokenNotMatch; import net.Broken.Tools.UserManager.Exceptions.TokenNotMatch;
import net.Broken.Tools.UserManager.Exceptions.UserAlreadyRegistered; import net.Broken.Tools.UserManager.Exceptions.UserAlreadyRegistered;
import net.Broken.Tools.UserManager.Exceptions.UserNotFoundException; import net.Broken.Tools.UserManager.Exceptions.UserNotFoundException;
import net.Broken.Tools.UserManager.UserRegister; import net.Broken.Tools.UserManager.UserUtils;
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;
@ -25,6 +24,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/**
* Rest Api controller for /api/userManagement
*/
@RestController @RestController
@RequestMapping("/api/userManagement") @RequestMapping("/api/userManagement")
public class UserManagerAPIController { public class UserManagerAPIController {
@ -38,14 +41,14 @@ public class UserManagerAPIController {
@Autowired @Autowired
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
UserRegister userRegister = UserRegister.getInstance(); UserUtils userUtils = UserUtils.getInstance();
@RequestMapping(value = "/preRegister", method = RequestMethod.POST) @RequestMapping(value = "/preRegister", method = RequestMethod.POST)
public ResponseEntity<CheckResposeData> command(@RequestBody UserInfoData data){ public ResponseEntity<CheckResposeData> command(@RequestBody UserInfoData data){
if(data != null && data.name != null) { if(data != null && data.name != null) {
try { try {
String id = userRegister.sendCheckToken(pendingUserRepository, userRepository, passwordEncoder, data); String id = userUtils.sendCheckToken(pendingUserRepository, userRepository, passwordEncoder, data);
return new ResponseEntity<>(new CheckResposeData(true, data.name, "Message sent", id), HttpStatus.OK); return new ResponseEntity<>(new CheckResposeData(true, data.name, "Message sent", id), HttpStatus.OK);
} catch (UserNotFoundException e) { } catch (UserNotFoundException e) {
logger.warn("User \"" + data.name + "\" not found!"); logger.warn("User \"" + data.name + "\" not found!");
@ -66,8 +69,8 @@ public class UserManagerAPIController {
public ResponseEntity<UserConnectionData> confirAccount(@RequestBody ConfirmData data){ public ResponseEntity<UserConnectionData> confirAccount(@RequestBody ConfirmData data){
//TODO move pending user to accepted and return right things //TODO move pending user to accepted and return right things
try { try {
PendingUserEntity pUser = userRegister.confirmCheckToken(pendingUserRepository, Integer.parseInt(data.id), data.checkToken); PendingUserEntity pUser = userUtils.confirmCheckToken(pendingUserRepository, Integer.parseInt(data.id), data.checkToken);
UserEntity user = new UserEntity(pUser, userRegister.generateApiToken()); UserEntity user = new UserEntity(pUser, userUtils.generateApiToken());
userRepository.save(user); userRepository.save(user);
pendingUserRepository.delete(pUser); pendingUserRepository.delete(pUser);
@ -84,7 +87,7 @@ public class UserManagerAPIController {
@RequestMapping(value = "/requestToken", method = RequestMethod.POST) @RequestMapping(value = "/requestToken", method = RequestMethod.POST)
public ResponseEntity<UserConnectionData> requestToken(@RequestBody UserInfoData data){ public ResponseEntity<UserConnectionData> requestToken(@RequestBody UserInfoData data){
try { try {
UserEntity user = userRegister.getUser(userRepository, passwordEncoder, data); UserEntity user = userUtils.getUser(userRepository, passwordEncoder, data);
return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK); return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK);
} catch (UserNotFoundException e) { } catch (UserNotFoundException e) {

View File

@ -17,22 +17,25 @@ import static java.lang.Thread.sleep;
/** /**
* Created by seb65 on 20/10/2016. * AntiSpam punishment system
*/ */
public class AntiSpam { public class AntiSpam {
public Move move = new Move();
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
public Move move = new Move();
public AntiSpam() { public AntiSpam() {
//Constructeur
} }
public void extermine(Member user, Guild serveur, GuildManager serveurManger, Boolean incrMulti, MessageReceivedEvent event){ /**
* Send user to Spam role
* @param user User to punish
* @param guild Guild
* @param guildManager GuildManager
* @param incrMulti True for increment punishment time
* @param event Message Received Event
*/
public void extermine(Member user, Guild guild, GuildManager guildManager, Boolean incrMulti, MessageReceivedEvent event){
try { try {
sleep(1000); sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -65,9 +68,9 @@ public class AntiSpam {
if(!MainBot.spamUtils.get(user.getUser()).isOnSpam()) if(!MainBot.spamUtils.get(user.getUser()).isOnSpam())
{ {
MainBot.spamUtils.get(user.getUser()).setOnSpam(true); MainBot.spamUtils.get(user.getUser()).setOnSpam(true);
List<Role> spm = serveur.getRolesByName("Spammer", false); List<Role> spm = guild.getRolesByName("Spammer", false);
try{ try{
move.exc(user, spm, true, serveur, serveurManger); move.exc(user, spm, true, guild, guildManager);
MainBot.spamUtils.get(user.getUser()).addMessage(event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamExtermine(user,MainBot.spamUtils.get(user.getUser()).getMultip())).complete()); MainBot.spamUtils.get(user.getUser()).addMessage(event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamExtermine(user,MainBot.spamUtils.get(user.getUser()).getMultip())).complete());
MainBot.spamUtils.get(user.getUser()).setMinuteur(new Minuteur(MainBot.spamUtils.get(user.getUser()).getMultip(), move.user, move.saveRoleUser, move.serveur, move.serveurManager,event)); MainBot.spamUtils.get(user.getUser()).setMinuteur(new Minuteur(MainBot.spamUtils.get(user.getUser()).getMultip(), move.user, move.saveRoleUser, move.serveur, move.serveurManager,event));
MainBot.spamUtils.get(user.getUser()).launchMinuteur(); MainBot.spamUtils.get(user.getUser()).launchMinuteur();
@ -89,6 +92,9 @@ public class AntiSpam {
} }
/**
* Timer to auto remove user from Spam role
*/
public class Minuteur extends Thread{ public class Minuteur extends Thread{
public TextChannel chanel; public TextChannel chanel;
public List<Role> saveRoleUser; public List<Role> saveRoleUser;

View File

@ -10,8 +10,16 @@ import org.reflections.util.ConfigurationBuilder;
import java.util.Set; import java.util.Set;
/**
* Find and load bot's command
*/
public class CommandLoader { public class CommandLoader {
private static Logger logger = LogManager.getLogger(); private static Logger logger = LogManager.getLogger();
/**
* Search all implemented Command interface class and add it to MainBot.commands HashMap
*/
public static void load(){ public static void load(){
logger.info("Loading Command..."); logger.info("Loading Command...");
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(

View File

@ -8,11 +8,18 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
/** /**
* Created by seb65 on 19/10/2016. *
*/ */
public class CommandParser { public class CommandParser {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
/**
* Parse raw received string.
* @param brt Raw command string.
* @param e Event
* @return Readable container that contain all useful data
*/
public CommandContainer parse(String brt, MessageReceivedEvent e) public CommandContainer parse(String brt, MessageReceivedEvent e)
{ {
ArrayList<String> split =new ArrayList<String>(); ArrayList<String> split =new ArrayList<String>();
@ -39,6 +46,10 @@ public class CommandParser {
return new CommandContainer(brut, sansTete, splitSansTete, commande, args, e); return new CommandContainer(brut, sansTete, splitSansTete, commande, args, e);
} }
/**
* Container
*/
public class CommandContainer{ public class CommandContainer{
public final String brut; public final String brut;
public final String sansTete; public final String sansTete;

View File

@ -2,7 +2,6 @@ package net.Broken.Tools.Command;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.LimitChecker; import net.Broken.Tools.LimitChecker;
import net.Broken.Tools.Redirection;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -12,18 +11,24 @@ import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
/** /**
* Created by seb65 on 07/11/2016. * Abstact class used for all command that need to find the max number of page on a web site.
*/ */
public abstract class NumberedCommande implements Commande{ public abstract class NumberedCommande implements Commande{
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
public String HELP="T'es sérieux la?"; private int minNumber = 1;
int minNumber = 1; private int maxNumber = -1;
int maxNumber = -1; private String baseURL;
String baseURL; private String divClass;
String divClass; private String htmlType;
String htmlType;
/**
* Default constructor
* @param logger Logger used for logs
* @param baseURL WebSite base url
* @param divClass DivClass to search to extract image
* @param htmlType HTML tag to extract image (img)
*/
public NumberedCommande(Logger logger, String baseURL, String divClass, String htmlType) { public NumberedCommande(Logger logger, String baseURL, String divClass, String htmlType) {
this.logger = logger; this.logger = logger;
this.baseURL = baseURL; this.baseURL = baseURL;
@ -38,11 +43,6 @@ public abstract class NumberedCommande implements Commande{
} }
} }
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
try try
@ -117,10 +117,5 @@ public abstract class NumberedCommande implements Commande{
} }
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
} }

View File

@ -9,30 +9,49 @@ import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
/** /**
* Created by seb65 on 09/11/2016. * Day change listener
*/ */
public class DayListener extends Thread { public class DayListener extends Thread {
private Logger logger = LogManager.getLogger();
private Calendar calendar; private Calendar calendar;
private int previousDay; private int previousDay;
private ArrayList<NewDayListener> listeners = new ArrayList<>();
private Logger logger = LogManager.getLogger();
/**
* List of listeners to need to be triggered
*/
private ArrayList<NewDayListener> listeners = new ArrayList<>();
private static DayListener INSTANCE = new DayListener();
/**
* Default private constructor
*/
private DayListener() { private DayListener() {
calendar = Calendar.getInstance(); calendar = Calendar.getInstance();
previousDay = calendar.get(GregorianCalendar.DAY_OF_MONTH); previousDay = calendar.get(GregorianCalendar.DAY_OF_MONTH);
} }
private static DayListener INSTANCE = new DayListener();
/**
* Singleton
* @return Unique DayListener instance.
*/
public static DayListener getInstance() public static DayListener getInstance()
{ {
return INSTANCE; return INSTANCE;
} }
/**
* Add Listener who will be triggered
* @param listener
*/
public void addListener(NewDayListener listener){ public void addListener(NewDayListener listener){
listeners.add(listener); listeners.add(listener);
} }
/**
* Trigger all listeners
*/
public void trigger(){ public void trigger(){
for(NewDayListener listener : listeners){ for(NewDayListener listener : listeners){
listener.onNewDay(); listener.onNewDay();
@ -40,6 +59,9 @@ public class DayListener extends Thread {
} }
/**
* Thread loop
*/
@Override @Override
public void run() { public void run() {
while(true) while(true)

View File

@ -9,8 +9,11 @@ import org.apache.logging.log4j.Logger;
import java.io.IOException; import java.io.IOException;
/**
* Daily Listener for DailyMadame
*/
public class DailyMadame implements NewDayListener{ public class DailyMadame implements NewDayListener{
Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
@Override @Override
public void onNewDay() { public void onNewDay() {
Redirection redirect = new Redirection(); Redirection redirect = new Redirection();

View File

@ -6,6 +6,9 @@ import net.dv8tion.jda.core.exceptions.RateLimitedException;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
/**
* Daily spam reset
*/
public class ResetSpam implements NewDayListener { public class ResetSpam implements NewDayListener {
@Override @Override
public void onNewDay() { public void onNewDay() {

View File

@ -1,5 +1,11 @@
package net.Broken.Tools.DayListener; package net.Broken.Tools.DayListener;
/**
* DayListener interface
*/
public interface NewDayListener { public interface NewDayListener {
/**
* Executed on new day
*/
void onNewDay(); void onNewDay();
} }

View File

@ -11,6 +11,9 @@ import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
/**
* Pre build Message Embed
*/
public class EmbedMessageUtils { public class EmbedMessageUtils {
public static MessageEmbed getUnknowCommand() { public static MessageEmbed getUnknowCommand() {
return new EmbedBuilder().setTitle(":warning: Commande inconnue! :warning:").setDescription(":arrow_right: Utilisez `//help` pour voirs les commandes disponible.").setColor(Color.orange).setFooter("bot.seb6596.ovh", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build(); return new EmbedBuilder().setTitle(":warning: Commande inconnue! :warning:").setDescription(":arrow_right: Utilisez `//help` pour voirs les commandes disponible.").setColor(Color.orange).setFooter("bot.seb6596.ovh", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();

View File

@ -6,12 +6,17 @@ import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
/**
* Created by sebastien on 10/05/17.
*/
public class FindContentOnWebPage { public class FindContentOnWebPage {
/**
* Find picture URL on webPage
* @param url Web Page URL
* @param divClass Div class where the picture is
* @param htmlType HTML tag of image (img)
* @return Picture URL
* @throws IOException
*/
public static String doYourJob(String url, String divClass, String htmlType) throws IOException { public static String doYourJob(String url, String divClass, String htmlType) throws IOException {
String source = getUrlSource(url); String source = getSourceUrl(url);
int divIndex = source.indexOf(divClass); int divIndex = source.indexOf(divClass);
String sub = source.substring(divIndex); String sub = source.substring(divIndex);
// System.out.println(sub); // System.out.println(sub);
@ -24,7 +29,13 @@ public class FindContentOnWebPage {
return split[0]; return split[0];
} }
public static String getUrlSource(String url) throws IOException { /**
* Get source code of web page
* @param url Web page URL
* @return Web page source as String
* @throws IOException
*/
public static String getSourceUrl(String url) throws IOException {
URL urlC = new URL(url); URL urlC = new URL(url);
URLConnection yc = urlC.openConnection(); URLConnection yc = urlC.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader( BufferedReader in = new BufferedReader(new InputStreamReader(

View File

@ -9,12 +9,19 @@ import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
/** /**
* Created by seb65 on 20/03/2017. * Find max webPage for web site like baseURL.com/number-2/
*/ */
public class LimitChecker { public class LimitChecker {
static Logger logger = LogManager.getLogger(); static Logger logger = LogManager.getLogger();
/**
* Check max page url for web site like baseURL.com/number-2/
* @param baseURL Base url without numbers
* @param minNumber Start number
* @return max Number
* @throws IOException
*/
public static int doYourJob(String baseURL, int minNumber) throws IOException { public static int doYourJob(String baseURL, int minNumber) throws IOException {
int number = minNumber; int number = minNumber;
URL u = null; URL u = null;

View File

@ -9,10 +9,14 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
/**
* Auto dell message util
*/
public class MessageTimeOut extends Thread{ public class MessageTimeOut extends Thread{
List<Message> messages; List<Message> messages;
int second; int second;
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
public MessageTimeOut(List<Message> messages, int second) { public MessageTimeOut(List<Message> messages, int second) {
this.messages = messages; this.messages = messages;
this.second = second; this.second = second;

View File

@ -14,7 +14,7 @@ import org.apache.logging.log4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* Created by Parayre on 24/10/2016. * Auto spam utils TODO Rebuild all this shit!
*/ */
public class Moderateur { public class Moderateur {
@ -25,7 +25,16 @@ public class Moderateur {
// Cette méthode récupère le dernier message est le rajoute à "historique" // Cette méthode récupère le dernier message est le rajoute à "historique"
// SI (spam) retourne 1 (si l'user spam) // SI (spam) retourne 1 (si l'user spam)
// SINON retourne 0 // SINON retourne 0
public int analyse(Member user, Guild serveur, GuildManager serveurManager, MessageReceivedEvent event){
/**
* Get last message and add it on history. After analyse for spam detection
* @param user User
* @param guild Guild
* @param guildManager Guild manager
* @param event Message received event
* @return 1 if detected as spam, else 0
*/
public int analyse(Member user, Guild guild, GuildManager guildManager, MessageReceivedEvent event){
ArrayList<Message> thisUserHistory = new ArrayList<>();//Creer tableau pour la copie ArrayList<Message> thisUserHistory = new ArrayList<>();//Creer tableau pour la copie
int i = 0; // variable de parcours de "historique" int i = 0; // variable de parcours de "historique"

View File

@ -6,14 +6,29 @@ import net.dv8tion.jda.core.entities.User;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/** /**
* Created by seb65 on 04/09/2017. * Private message utils
*/ */
public class PrivateMessage { public class PrivateMessage {
/**
* Auto open private channel and send message
* @param user User to send message
* @param message Message to send
* @param logger Logger
*/
public static void send(User user, String message, Logger logger){ public static void send(User user, String message, Logger logger){
user.openPrivateChannel().complete().sendMessage(message).queue(); user.openPrivateChannel().complete().sendMessage(message).queue();
} }
/**
* Auto open private channel and send message
* @param user User to send message
* @param message Message to send
* @param logger Logger
* @return Sended Message
*/
public static Message send(User user, MessageEmbed message, Logger logger){ public static Message send(User user, MessageEmbed message, Logger logger){
return user.openPrivateChannel().complete().sendMessage(message).complete(); return user.openPrivateChannel().complete().sendMessage(message).complete();

View File

@ -6,7 +6,7 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
/** /**
* Created by seb65 on 07/11/2016. * Redirection URL Util
*/ */
public class Redirection { public class Redirection {
@ -15,7 +15,12 @@ public class Redirection {
} }
/**
* Return Redirected URL
* @param urlString Source URL
* @return Redirected URL
* @throws IOException
*/
public String get(String urlString) throws IOException { public String get(String urlString) throws IOException {
URLConnection con = new URL(urlString).openConnection(); URLConnection con = new URL(urlString).openConnection();
//System.out.println( "orignal url: " + con.getURL() ); //System.out.println( "orignal url: " + con.getURL() );

View File

@ -15,6 +15,12 @@ public class ResourceLoader {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
/**
* Get file contents as string for resource folder
* @param fileName Requested file
* @return File contents as string
* @throws FileNotFoundException
*/
public String getFile(String fileName) throws FileNotFoundException { public String getFile(String fileName) throws FileNotFoundException {
StringBuilder result = new StringBuilder(""); StringBuilder result = new StringBuilder("");

View File

@ -8,6 +8,9 @@ import java.util.stream.IntStream;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
/**
* Utils to render table in block code
*/
public class TableRenderer { public class TableRenderer {
private int width; private int width;
@ -20,19 +23,31 @@ public class TableRenderer {
} }
/**
* Set Table header(s)
* @param header Header(s) as String
*/
public void setHeader(Object... header) { public void setHeader(Object... header) {
this.header = Arrays.asList(header); this.header = Arrays.asList(header);
if (header.length > this.width) if (header.length > this.width)
this.width = header.length; this.width = header.length;
} }
public void addRow(Object... header) { /**
List<Object> objects = Arrays.asList(header); * Add row to table
* @param content Content(s) as string
*/
public void addRow(Object... content) {
List<Object> objects = Arrays.asList(content);
table.add(objects); table.add(objects);
if (header.length > this.width) if (content.length > this.width)
this.width = header.length; this.width = content.length;
} }
/**
* Change default empty string
* @param str
*/
public void setEmptyString(String str) { public void setEmptyString(String str) {
this.empty = str; this.empty = str;
} }

View File

@ -14,8 +14,6 @@ import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
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.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -23,21 +21,37 @@ import java.security.SecureRandom;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
public class UserRegister { public class UserUtils {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private static UserRegister INSTANCE = new UserRegister();
private UserRegister(){} private static UserUtils INSTANCE = new UserUtils();
public static UserRegister getInstance(){ /**
* Private default constructor
*/
private UserUtils(){}
/**
* Singleton
* @return Unique UserUtils instance
*/
public static UserUtils getInstance(){
return INSTANCE; return INSTANCE;
} }
/**
* Check if user exist on Guild, if exist, generate and send checkTocken, create entry on PendingUser DB
* @param pendingUserRepository Pending user DB interface
* @param userRepository User DB interface
* @param passwordEncoder Password encoder
* @param userInfo Received data
* @return PendingUserEntity PK
* @throws UserNotFoundException User not found in guild
* @throws PasswordNotMatchException User already registered in PendingUser DB but password not match
* @throws UserAlreadyRegistered User already registered in User DB
*/
public String sendCheckToken(PendingUserRepository pendingUserRepository, UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfo) throws UserNotFoundException, PasswordNotMatchException, UserAlreadyRegistered { public String sendCheckToken(PendingUserRepository pendingUserRepository, UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfo) throws UserNotFoundException, PasswordNotMatchException, UserAlreadyRegistered {
logger.info("New registration for " + userInfo.name); logger.info("New registration for " + userInfo.name);
@ -102,6 +116,15 @@ public class UserRegister {
} }
/**
* Confirm user account
* @param pendingUserRepository Pending user DB interface
* @param id UserPendingEntity PK to cofirm
* @param checkToken received token
* @return PendingUserEntity
* @throws TokenNotMatch Given token not match
* @throws UserNotFoundException User not found in Pending user DB
*/
public PendingUserEntity confirmCheckToken(PendingUserRepository pendingUserRepository, int id, String checkToken ) throws TokenNotMatch, UserNotFoundException { public PendingUserEntity confirmCheckToken(PendingUserRepository pendingUserRepository, int id, String checkToken ) throws TokenNotMatch, UserNotFoundException {
PendingUserEntity pendingUser = pendingUserRepository.findOne(id); PendingUserEntity pendingUser = pendingUserRepository.findOne(id);
if(pendingUser != null) { if(pendingUser != null) {
@ -120,6 +143,15 @@ public class UserRegister {
return pendingUser; return pendingUser;
} }
/**
* Get user Entity
* @param userRepository User DB interface
* @param passwordEncoder Password encoder
* @param userInfoData Received data
* @return User Entity
* @throws UserNotFoundException User not found in User DB
* @throws PasswordNotMatchException Given password not match
*/
public UserEntity getUser(UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfoData) throws UserNotFoundException, PasswordNotMatchException { public UserEntity getUser(UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfoData) throws UserNotFoundException, PasswordNotMatchException {
List<UserEntity> users = userRepository.findByName(userInfoData.name); List<UserEntity> users = userRepository.findByName(userInfoData.name);
if(users.size()<1){ if(users.size()<1){
@ -140,6 +172,13 @@ public class UserRegister {
} }
} }
/**
* return token's UserEntity
* @param userRepository User DB interface
* @param token Received token
* @return User Entity
* @throws UnknownTokenException Can't find token on User DB
*/
public UserEntity getUserWithApiToken(UserRepository userRepository, String token) throws UnknownTokenException { public UserEntity getUserWithApiToken(UserRepository userRepository, String token) throws UnknownTokenException {
List<UserEntity> users = userRepository.findByApiToken(token); List<UserEntity> users = userRepository.findByApiToken(token);
if(users.size() > 0){ if(users.size() > 0){
@ -150,10 +189,18 @@ public class UserRegister {
} }
/**
* Generate API Token
* @return UUID String TODO Find something more secure
*/
public String generateApiToken(){ public String generateApiToken(){
return UUID.randomUUID().toString(); return UUID.randomUUID().toString();
} }
/**
* Generate short check token
* @return check token as string
*/
private String generateCheckToken(){ private String generateCheckToken(){
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
long longToken = Math.abs( random.nextLong() ); long longToken = Math.abs( random.nextLong() );

View File

@ -5,6 +5,9 @@ import net.dv8tion.jda.core.entities.Message;
import java.util.List; import java.util.List;
/**
* Spam info for one user
*/
public class UserSpamUtils { public class UserSpamUtils {
private AntiSpam.Minuteur minuteur; private AntiSpam.Minuteur minuteur;
private Member user; private Member user;

View File

@ -4,7 +4,6 @@ import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
@ -17,26 +16,42 @@ import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
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 javax.jws.soap.SOAPBinding;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class AudioM { public class AudioM {
/**
* Music manager for this guild
*/
private GuildMusicManager musicManager; private GuildMusicManager musicManager;
/**
* Audio player manager for this guild
*/
private AudioPlayerManager playerManager; private AudioPlayerManager playerManager;
/**
* Current voice chanel (null if not connected)
*/
private VoiceChannel playedChanel; private VoiceChannel playedChanel;
/**
* Time out for list message
*/
private int listTimeOut = 30; private int listTimeOut = 30;
/**
* Extrem limit for playlist
*/
private int listExtremLimit = 300; private int listExtremLimit = 300;
private Logger logger = LogManager.getLogger(); /**
* Current guild
*/
private Guild guild; private Guild guild;
private Logger logger = LogManager.getLogger();
@ -47,6 +62,14 @@ public class AudioM {
this.guild = guild; this.guild = guild;
} }
/**
* Load audio track from url, connect to chanel if not connected
* @param event
* @param voiceChannel Voice channel to connect if no connected
* @param trackUrl Audio track url
* @param playlistLimit Limit of playlist
* @param onHead True for adding audio track on top of playlist
*/
public void loadAndPlay(MessageReceivedEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) { public void loadAndPlay(MessageReceivedEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) {
GuildMusicManager musicManager = getGuildAudioPlayer(guild); GuildMusicManager musicManager = getGuildAudioPlayer(guild);
playedChanel = voiceChannel; playedChanel = voiceChannel;
@ -109,6 +132,13 @@ public class AudioM {
}); });
} }
/**
* Load playlist to playlist
* @param playlist Loaded playlist
* @param playlistLimit Playlist limit
* @param user User who have submitted the playlist
* @param onHead True for adding audio track on top of playlist
*/
public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead){ public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead){
int i = 0; int i = 0;
List<AudioTrack> tracks = playlist.getTracks(); List<AudioTrack> tracks = playlist.getTracks();
@ -135,6 +165,14 @@ public class AudioM {
return musicManager; return musicManager;
} }
/**
* Add single track to playlist, auto-connect if not connected to vocal chanel
* @param guild guild
* @param channel Chanel for auto-connect
* @param musicManager Guild music manager
* @param track Track to add to playlist
* @param onHead True for adding audio track on top of playlist
*/
public void play(Guild guild, VoiceChannel channel, GuildMusicManager musicManager, UserAudioTrack track,boolean onHead) { public void play(Guild guild, VoiceChannel channel, GuildMusicManager musicManager, UserAudioTrack track,boolean onHead) {
if(!guild.getAudioManager().isConnected()) if(!guild.getAudioManager().isConnected())
guild.getAudioManager().openAudioConnection(channel); guild.getAudioManager().openAudioConnection(channel);
@ -144,66 +182,66 @@ public class AudioM {
musicManager.scheduler.addNext(track); musicManager.scheduler.addNext(track);
} }
/**
* Skip current track
* @param event
*/
public void skipTrack(MessageReceivedEvent event) { public void skipTrack(MessageReceivedEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
musicManager.scheduler.nextTrack(); musicManager.scheduler.nextTrack();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Musique suivante!")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Musique suivante!")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, message, event.getMessage()).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
/**
* Pause current track
* @param event
*/
public void pause(MessageReceivedEvent event) { public void pause(MessageReceivedEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
musicManager.scheduler.pause(); musicManager.scheduler.pause();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Musique en pause !")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Musique en pause !")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
/**
* Resume paused track
* @param event
*/
public void resume (MessageReceivedEvent event) { public void resume (MessageReceivedEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
musicManager.scheduler.resume(); musicManager.scheduler.resume();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Reprise de la piste en cour !")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Reprise de la piste en cour !")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
/**
* Print current played track info
* @param event
*/
public void info(MessageReceivedEvent event) { public void info(MessageReceivedEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
AudioTrackInfo info = musicManager.scheduler.getInfo(); AudioTrackInfo info = musicManager.scheduler.getInfo();
UserAudioTrack userAudioTrack = musicManager.scheduler.getCurrentPlayingTrack(); UserAudioTrack userAudioTrack = musicManager.scheduler.getCurrentPlayingTrack();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk(info.title+"\n"+info.uri+"\nSubmitted by: "+userAudioTrack.getSubmitedUser().getName())).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk(info.title + "\n" + info.uri + "\nSubmitted by: " + userAudioTrack.getSubmittedUser().getName())).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
public void flush(MessageReceivedEvent event){ public void flush(MessageReceivedEvent event){
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
musicManager.scheduler.flush(); musicManager.scheduler.flush();
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("RAZ de la playlist!")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("RAZ de la playlist!")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
/**
* Print current playlist content
* @param event
*/
public void list(MessageReceivedEvent event){ public void list(MessageReceivedEvent event){
GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild()); GuildMusicManager musicManager = getGuildAudioPlayer(event.getGuild());
List<UserAudioTrackData> list = musicManager.scheduler.getList(); List<UserAudioTrackData> list = musicManager.scheduler.getList();
@ -220,14 +258,16 @@ public class AudioM {
} }
} }
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Playlist:\n\n"+resp.toString())).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Playlist:\n\n"+resp.toString())).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, listTimeOut).start();
} }
/**
* Called by //add, only if already connected
* @param event
* @param url Audio track url
* @param playListLimit Limit of playlist
* @param onHead True for adding audio track on top of playlist
*/
public void add(MessageReceivedEvent event, String url, int playListLimit, boolean onHead) { public void add(MessageReceivedEvent event, String url, int playListLimit, boolean onHead) {
if(playedChanel != null){ if(playedChanel != null){
loadAndPlay(event,playedChanel, url, playListLimit,onHead); loadAndPlay(event,playedChanel, url, playListLimit,onHead);
@ -235,29 +275,27 @@ public class AudioM {
else else
{ {
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicError("Aucune lecture en cour!")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicError("Aucune lecture en cour!")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
} }
/**
* Stop current playing track and flush playlist
* @param event
*/
public void stop (MessageReceivedEvent event) { public void stop (MessageReceivedEvent event) {
musicManager.scheduler.stop(); musicManager.scheduler.stop();
musicManager.scheduler.flush(); musicManager.scheduler.flush();
if (event != null) { if (event != null) {
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Arret de la musique!")).complete(); Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicOk("Arret de la musique!")).complete();
List<Message> messages = new ArrayList<Message>(){{ new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), message).start();
add(message);
add(event.getMessage());
}};
new MessageTimeOut(messages, MainBot.messageTimeOut).start();
} }
} }
/**
* Stop current playing track and flush playlist (no confirmation message)
*/
public void stop () { public void stop () {
GuildMusicManager musicManager = getGuildAudioPlayer(guild); GuildMusicManager musicManager = getGuildAudioPlayer(guild);
@ -267,11 +305,11 @@ public class AudioM {
guild.getAudioManager().closeAudioConnection(); guild.getAudioManager().closeAudioConnection();
} }
public GuildMusicManager getMusicManager() throws NullMusicManager, NotConectedException { public GuildMusicManager getGuildMusicManager() throws NullMusicManager, NotConnectedException {
if( musicManager == null) if( musicManager == null)
throw new NullMusicManager(); throw new NullMusicManager();
else if( playedChanel == null) else if( playedChanel == null)
throw new NotConectedException(); throw new NotConnectedException();
return musicManager; return musicManager;
} }

View File

@ -8,9 +8,17 @@ import org.apache.logging.log4j.Logger;
import java.util.List; import java.util.List;
/**
* Used to find general voice channels
*/
public class FindGeneral { public class FindGeneral {
static Logger logger = LogManager.getLogger(); static Logger logger = LogManager.getLogger();
/**
* Search for 🤖 char on category name, if this category can't be find, auto create it
* @param guild Current guild
* @return General Category
*/
public static Category find(Guild guild){ public static Category find(Guild guild){
List<Category> categories = guild.getCategories(); List<Category> categories = guild.getCategories();
Category finded = null; Category finded = null;
@ -27,6 +35,11 @@ public class FindGeneral {
} }
/**
* Create default category "🤖 Salons Vocaux 🤖", and create basic voice channel on it.
* @param guild Current guild
* @return Brand new General Category
*/
private static Category create(Guild guild){ private static Category create(Guild guild){
logger.info("Can't find general voice chanel, creating it!"); logger.info("Can't find general voice chanel, creating it!");
Channel temp = guild.getController().createCategory("\uD83E\uDD16 Salons Vocaux \uD83E\uDD16").complete(); Channel temp = guild.getController().createCategory("\uD83E\uDD16 Salons Vocaux \uD83E\uDD16").complete();

View File

@ -1,4 +0,0 @@
package net.Broken.audio;
public class NotConectedException extends Exception {
}

View File

@ -0,0 +1,8 @@
package net.Broken.audio;
/**
* Not connected Exception (Voice Channel)
*/
public class NotConnectedException extends Exception {
}

View File

@ -1,4 +1,7 @@
package net.Broken.audio; package net.Broken.audio;
/**
* Null music manager
*/
public class NullMusicManager extends Exception { public class NullMusicManager extends Exception {
} }

View File

@ -12,9 +12,7 @@ import org.apache.logging.log4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
/** /**
* This class schedules tracks for the audio player. It contains the queue of tracks. * This class schedules tracks for the audio player. It contains the queue of tracks.
@ -51,6 +49,11 @@ public class TrackScheduler extends AudioEventAdapter {
currentPlayingTrack = track; currentPlayingTrack = track;
} }
} }
/**
* Add track on top of playlist
* @param track
*/
public void addNext(UserAudioTrack track) { public void addNext(UserAudioTrack track) {
// Calling startTrack with the noInterrupt set to true will start the track only if nothing is currently playing. If // Calling startTrack with the noInterrupt set to true will start the track only if nothing is currently playing. If
// something is playing, it returns false and does nothing. In that case the player was already playing so this // something is playing, it returns false and does nothing. In that case the player was already playing so this
@ -63,6 +66,7 @@ public class TrackScheduler extends AudioEventAdapter {
} }
} }
public void pause() { public void pause() {
player.setPaused(true); player.setPaused(true);
} }
@ -72,6 +76,7 @@ public class TrackScheduler extends AudioEventAdapter {
} }
public void stop(){ public void stop(){
player.stopTrack(); player.stopTrack();
this.currentPlayingTrack = null; this.currentPlayingTrack = null;
@ -89,7 +94,7 @@ public class TrackScheduler extends AudioEventAdapter {
Object[] test = queue.toArray(); Object[] test = queue.toArray();
for(Object track: test){ for(Object track: test){
UserAudioTrack casted = (UserAudioTrack) track; UserAudioTrack casted = (UserAudioTrack) track;
temp.add(new UserAudioTrackData(casted.getSubmitedUser().getName(), casted.getAudioTrack().getInfo())); temp.add(new UserAudioTrackData(casted.getSubmittedUser().getName(), casted.getAudioTrack().getInfo()));
} }
return temp; return temp;
} }
@ -106,7 +111,7 @@ public class TrackScheduler extends AudioEventAdapter {
for(UserAudioTrack track : queue){ for(UserAudioTrack track : queue){
if(track.getAudioTrack().getInfo().uri.equals(uri)){ if(track.getAudioTrack().getInfo().uri.equals(uri)){
if(!queue.remove(track)) { if(!queue.remove(track)) {
logger.info("Delete failure!"); logger.error("Delete failure!");
return false; return false;
} else { } else {
logger.info("Delete succeful"); logger.info("Delete succeful");

View File

@ -3,6 +3,9 @@ package net.Broken.audio;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
/**
* Container that link AudioTrack to who submit it (User)
*/
public class UserAudioTrack{ public class UserAudioTrack{
private User user; private User user;
private AudioTrack audioTrack; private AudioTrack audioTrack;
@ -12,7 +15,7 @@ public class UserAudioTrack{
this.audioTrack = audioTrack; this.audioTrack = audioTrack;
} }
public User getSubmitedUser() { public User getSubmittedUser() {
return user; return user;
} }

View File

@ -14,25 +14,34 @@ import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
/**
* Interface between WebApi and Music bot for submitting track
*/
public class WebLoadUtils { public class WebLoadUtils {
ResponseEntity<CommandResponseData> response; ResponseEntity<CommandResponseData> response;
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
public WebLoadUtils(Music musicCommande, CommandPostData data, User user){ /**
AudioPlayerManager playerM = musicCommande.getAudioManager().getPlayerManager(); * Submit a track or playlist to Music bot
* @param musicCommand The current guild music command.
* @param data Received data from API
* @param user User who submit the track
*/
public WebLoadUtils(Music musicCommand, CommandPostData data, User user){
AudioPlayerManager playerM = musicCommand.getAudioManager().getPlayerManager();
try { try {
AudioM audioM = musicCommande.getAudioManager(); AudioM audioM = musicCommand.getAudioManager();
playerM.loadItemOrdered(musicCommande.getAudioManager().getMusicManager(), data.url, new AudioLoadResultHandler() { playerM.loadItemOrdered(musicCommand.getAudioManager().getGuildMusicManager(), data.url, new AudioLoadResultHandler() {
@Override @Override
public void trackLoaded(AudioTrack track) { public void trackLoaded(AudioTrack track) {
logger.info("Single Track detected from web!"); logger.info("Single Track detected from web!");
try { try {
UserAudioTrack userAudioTrack = new UserAudioTrack(user, track); //TODO UserAudioTrack userAudioTrack = new UserAudioTrack(user, track); //TODO
audioM.play(audioM.getGuild(), audioM.getPlayedChanel(), audioM.getMusicManager(), userAudioTrack, data.onHead); audioM.play(audioM.getGuild(), audioM.getPlayedChanel(), audioM.getGuildMusicManager(), userAudioTrack, data.onHead);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK); response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK);
} catch (NullMusicManager | NotConectedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException nullMusicManager) {
nullMusicManager.printStackTrace(); nullMusicManager.printStackTrace();
} }
@ -64,11 +73,15 @@ public class WebLoadUtils {
while(response == null) while(response == null)
Thread.sleep(10); Thread.sleep(10);
} catch (NullMusicManager | NotConectedException | InterruptedException nullMusicManager) { } catch (NullMusicManager | NotConnectedException | InterruptedException nullMusicManager) {
nullMusicManager.printStackTrace(); nullMusicManager.printStackTrace();
} }
} }
/**
* Wait for the end of submit process and return ResponseEntity
* @return HTTP Response
*/
public ResponseEntity<CommandResponseData> getResponse(){ public ResponseEntity<CommandResponseData> getResponse(){
while(response == null) { while(response == null) {
try { try {

View File

@ -4,6 +4,9 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
/**
* Web page controller for index
*/
@Controller @Controller
public class GeneralWebView { public class GeneralWebView {
@RequestMapping("/") @RequestMapping("/")

View File

@ -4,6 +4,9 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
/**
* Web page controller for /music page
*/
@Controller @Controller
public class MusicWebView { public class MusicWebView {
@RequestMapping("/music") @RequestMapping("/music")

View File

@ -8,6 +8,9 @@ import org.springframework.web.servlet.resource.ContentVersionStrategy;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import org.springframework.web.servlet.resource.VersionResourceResolver; import org.springframework.web.servlet.resource.VersionResourceResolver;
/**
* Configuration for js auto versioning
*/
@Configuration @Configuration
public class MvcApplication extends WebMvcConfigurerAdapter { public class MvcApplication extends WebMvcConfigurerAdapter {

View File

@ -6,8 +6,11 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* WebPage Controller for /register
*/
@Controller @Controller
public class ResisterWebView { public class RegisterWebView {
@RequestMapping("/register") @RequestMapping("/register")
public String music(@RequestParam(value="id", required = true, defaultValue = "") String id, Model model){ public String music(@RequestParam(value="id", required = true, defaultValue = "") String id, Model model){
model.addAttribute("id", id); model.addAttribute("id", id);