Can now change setting on web page

This commit is contained in:
Sebastien 2018-09-24 18:43:19 +03:00
parent e70fb4e266
commit 6c442d8bfa
7 changed files with 301 additions and 25 deletions

View File

@ -7,6 +7,7 @@ import net.Broken.MainBot;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.SettingsUtils;
import net.Broken.audio.AudioM; import net.Broken.audio.AudioM;
import net.Broken.audio.NotConnectedException; import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager; import net.Broken.audio.NullMusicManager;
@ -37,7 +38,7 @@ public class Settings implements Commande {
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
if(args.length == 0){ if(args.length == 0){
GuildPreferenceEntity guildPref = getPreference(event.getGuild()); GuildPreferenceEntity guildPref = SettingsUtils.getInstance().getPreference(event.getGuild());
MessageEmbed message = EmbedMessageUtils.getPref(guildPref); MessageEmbed message = EmbedMessageUtils.getPref(guildPref);
event.getTextChannel().sendMessage(message).complete(); event.getTextChannel().sendMessage(message).complete();
@ -89,22 +90,8 @@ public class Settings implements Commande {
} }
private GuildPreferenceEntity getPreference(Guild guild){
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
logger.info("Generate default pref for " + guild.getName());
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
guildPref = guildPrefList.get(0);
return guildPref;
}
private void set(MessageReceivedEvent event, String key, String value){ private void set(MessageReceivedEvent event, String key, String value){
GuildPreferenceEntity pref = getPreference(event.getGuild()); GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(event.getGuild());
switch (key){ switch (key){
case "anti_spam": case "anti_spam":
value = value.replaceAll(" ", ""); value = value.replaceAll(" ", "");

View File

@ -0,0 +1,7 @@
package net.Broken.RestApi.Data.Settings;
import java.util.List;
public class ListPostSetting {
public List<PostSetSettings> settings;
}

View File

@ -0,0 +1,6 @@
package net.Broken.RestApi.Data.Settings;
public class PostSetSettings {
public String id;
public String val;
}

View File

@ -6,6 +6,8 @@ import net.Broken.DB.Repository.GuildPreferenceRepository;
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.Settings.GetSettingsData; import net.Broken.RestApi.Data.Settings.GetSettingsData;
import net.Broken.RestApi.Data.Settings.ListPostSetting;
import net.Broken.RestApi.Data.Settings.PostSetSettings;
import net.Broken.RestApi.Data.Settings.Value; import net.Broken.RestApi.Data.Settings.Value;
import net.Broken.Tools.SettingsUtils; import net.Broken.Tools.SettingsUtils;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
@ -21,10 +23,7 @@ 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.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.RegEx; import javax.annotation.RegEx;
import java.util.ArrayList; import java.util.ArrayList;
@ -34,7 +33,13 @@ import java.util.List;
@RequestMapping("/api") @RequestMapping("/api")
public class SettingAPIController { public class SettingAPIController {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
final
UserRepository userRepository;
@Autowired
public SettingAPIController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(value = "/settings", method = RequestMethod.GET) @RequestMapping(value = "/settings", method = RequestMethod.GET)
@ -49,4 +54,34 @@ public class SettingAPIController {
} }
} }
@RequestMapping(value = "/settings", method = RequestMethod.POST)
public ResponseEntity<String> setSetting(@CookieValue("token") String token, @CookieValue("guild") String guild, @RequestBody ListPostSetting settings){
SettingsUtils settingUtils = SettingsUtils.getInstance();
if(settingUtils.checkPermission(token, guild)){
Guild jdaGuild = MainBot.jda.getGuildById(guild);
try {
UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository,token);
logger.info(user.getName() + " change config of " + jdaGuild.getName());
} catch (UnknownTokenException e) {
e.printStackTrace();
}
if(settingUtils.setSettings(jdaGuild, settings.settings)){
return new ResponseEntity<>(HttpStatus.OK);
}else{
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
else{
logger.warn("Try to change setting, UNAUTHORIZED. TOKEN: " + token + " GUILD: " + guild);
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
} }

View File

@ -7,6 +7,7 @@ import net.Broken.DB.Repository.PendingPwdResetRepository;
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.Settings.GetSettingsData; import net.Broken.RestApi.Data.Settings.GetSettingsData;
import net.Broken.RestApi.Data.Settings.PostSetSettings;
import net.Broken.RestApi.Data.Settings.Value; import net.Broken.RestApi.Data.Settings.Value;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
@ -29,7 +30,7 @@ import java.util.List;
public class SettingsUtils { public class SettingsUtils {
private static SettingsUtils INSTANCE; private static SettingsUtils INSTANCE;
Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
public static SettingsUtils getInstance(){ public static SettingsUtils getInstance(){
return (INSTANCE == null) ? new SettingsUtils() : INSTANCE; return (INSTANCE == null) ? new SettingsUtils() : INSTANCE;
@ -152,6 +153,106 @@ public class SettingsUtils {
} }
public boolean setSettings(Guild guild, List<PostSetSettings> settings){
GuildPreferenceEntity pref = getPreference(guild);
for (PostSetSettings setting : settings){
String value = setting.val;
logger.debug(setting.id + " : " + value);
switch (setting.id) {
case "anti_spam":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setAntiSpam(result);
pref = guildPreferenceRepository.save(pref);
} else {
logger.error("anti_spam error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "default_role":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setDefaultRole(result);
pref = guildPreferenceRepository.save(pref);
} else {
logger.error("default_role error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "default_role_id":
try {
Role role = guild.getRoleById(value);
if (role != null) {
pref.setDefaultRoleId(role.getId());
pref = guildPreferenceRepository.save(pref);
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
logger.error("default_role_id error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "welcome":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setWelcome(result);
pref = guildPreferenceRepository.save(pref);
} else {
logger.error("welcome error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "welcome_chanel_id":
try {
TextChannel chanel = guild.getTextChannelById(value);
if (chanel != null) {
pref.setWelcomeChanelID(chanel.getId());
pref = guildPreferenceRepository.save(pref);
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
logger.error("welcome_chanel_id error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "welcome_message":
pref.setWelcomeMessage(value);
pref = guildPreferenceRepository.save(pref);
break;
case "daily_madame":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setDailyMadame(result);
pref = guildPreferenceRepository.save(pref);
} else {
logger.error("daily_madame error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
}
}
return true;
}
private List<Value> getTextChannels(Guild guild){ private List<Value> getTextChannels(Guild guild){
List<Value> channels = new ArrayList<>(); List<Value> channels = new ArrayList<>();
@ -168,4 +269,17 @@ public class SettingsUtils {
} }
return roles; return roles;
} }
public GuildPreferenceEntity getPreference(Guild guild){
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
logger.info("Generate default pref for " + guild.getName());
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
guildPref = guildPrefList.get(0);
return guildPref;
}
} }

View File

@ -1,3 +1,64 @@
var post_json = {settings : []};
$(document).ready(function(){ $(document).ready(function(){
$('select').formSelect(); $('select').formSelect();
modal_loading = $('#modal_loading');
modal_loading.modal({
dismissible: false
});
$('#sendBtn').click(function () {
var select = $('.collect-select');
select.each(function(){
var val = $(this).find("select").val();
var id = $(this).attr("id");
if(val != null){
post_json["settings"].push({"id" : id, "val" : val});
}
});
var switch_collected = $('.collect-switch');
switch_collected.each(function(){
var val = $(this).is(':checked').toString();
var id = $(this).attr("id");
if(val != null){
post_json["settings"].push({"id" : id, "val" : val});
}
});
var text = $('.collect-text');
text.each(function(){
var val = $(this).val();
var id = $(this).attr("id");
if(val != null){
post_json["settings"].push({"id" : id, "val" : val});
}
});
modal_loading.modal('open');
$.ajax({
type: "POST",
contentType: 'application/json',
url: "/api/settings",
data: JSON.stringify(post_json)
}).done(function (data) {
console.log("ok");
M.toast({html: '<i class="small material-icons" style="margin-right: 0.3em">done</i>Save Successful ! ', classes: 'rounded green'});
modal_loading.modal('close');
}).fail(function (data) {
console.log(data);
modal_loading.modal('close');
M.toast({html: '<i class="small material-icons" style="margin-right: 0.3em">report</i>Save Failed ! ', classes: 'rounded red'});
});
})
}); });

View File

@ -33,6 +33,7 @@
<div class="section no-pad-bot main" id="index-banner"> <div class="section no-pad-bot main" id="index-banner">
<h2 class="center" th:text="${guild_name}"></h2>
<div th:each="setting : ${settings}"> <div th:each="setting : ${settings}">
<div class="section row"> <div class="section row">
<div class="col l6 offset-l3 m10 offset-m1 s10 offset-s1"> <div class="col l6 offset-l3 m10 offset-m1 s10 offset-s1">
@ -40,21 +41,21 @@
<div class="switch" th:if="${setting.type.toString() == 'BOOL'}"> <div class="switch" th:if="${setting.type.toString() == 'BOOL'}">
<label> <label>
Off Off
<input type="checkbox" th:checked="${setting.current}"/> <input class="collect-switch" type="checkbox" th:id="${setting.id}" th:checked="${setting.current}"/>
<span class="lever"></span> <span class="lever"></span>
On On
</label> </label>
</div> </div>
<div class="input-field col l12 m12 s12" th:if="${setting.type.toString() == 'LIST'}"> <div th:id="${setting.id}" class="input-field col l12 m12 s12 collect-select" th:if="${setting.type.toString() == 'LIST'}">
<select> <select>
<option disabled="disabled" th:selected="${setting.current} == ' '" value="" >Choose your option</option> <option disabled="disabled" th:selected="${setting.current} == ' '" value="" >Choose your option</option>
<option th:each="val : ${setting.values}" th:value="${val.id}" th:text="${#strings.capitalize(val.name)}" th:selected="${setting.current} == ${val.id}"></option> <option th:each="val : ${setting.values}" th:value="${val.id}" th:text="${#strings.capitalize(val.name)}" th:selected="${setting.current} == ${val.id}"></option>
</select> </select>
</div> </div>
<div class="input-field col l12 m12 s12" th:if="${setting.type.toString() == 'STRING'}"> <div class="input-field col l12 m12 s12 collect" th:if="${setting.type.toString() == 'STRING'}">
<input placeholder="Use @name variable" th:value="${setting.current}" id="first_name" type="text" class="validate"/> <input th:id="${setting.id}" placeholder="Use @name variable" th:value="${setting.current}" id="first_name" type="text" class="validate collect-text"/>
</div> </div>
</div> </div>
@ -66,7 +67,72 @@
</div> </div>
<div class="row">
<div class="col s12 center">
<a id="sendBtn" class="waves-effect waves-light btn green">Save<i class="material-icons left">save</i></a>
</div>
</div>
</div>
<div id="modal_loading" class="modal valign-wrapper">
<div class="modal-content" >
<div class="row center">
<h3 class="col l12 m12 s12 center">Please wait</h3>
</div>
<div class="row center" >
<div class="preloader-wrapper big active">
<div class="spinner-layer spinner-blue">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
<div class="spinner-layer spinner-red">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
<div class="spinner-layer spinner-yellow">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
<div class="spinner-layer spinner-green">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</div>
</div>
</div> </div>