Compare commits

..

No commits in common. "606d2233613cb3a5e06c061021a59fed5c6a925f" and "4677b9582270c5b7d98d663f3cd11943c509fc91" have entirely different histories.

15 changed files with 331 additions and 187 deletions

View File

@ -5,6 +5,9 @@ name: Build
on: on:
push: push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs: jobs:
build-gradle: build-gradle:
@ -35,6 +38,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- build-gradle - build-gradle
if: github.ref == 'refs/heads/master'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -56,24 +60,10 @@ jobs:
username: ${{ github.repository_owner }} username: ${{ github.repository_owner }}
password: ${{ secrets.CR_PAT }} password: ${{ secrets.CR_PAT }}
- name: Get branch name
id: branch-name
uses: tj-actions/branch-names@v5.2
- name: Set tag master
if: steps.branch-name.outputs.current_branch == 'master'
run: |
echo "tag=latest" >> $GITHUB_ENV
- name: Set tag
if: steps.branch-name.outputs.current_branch != 'master'
run: |
echo "tag=${{ steps.branch-name.outputs.current_branch }}" >> $GITHUB_ENV
- name: Build and push Docker - name: Build and push Docker
uses: docker/build-push-action@v2 uses: docker/build-push-action@v2
with: with:
push: true push: true
context: . context: .
tags: "ghcr.io/sebclem/claptrapbot:${{ env.tag }}" tags: ghcr.io/sebclem/claptrapbot:latest
file: ./Dockerfile file: ./Dockerfile

View File

@ -1,6 +1,5 @@
{ {
"extends": [ "extends": [
"config:base" "config:base"
], ]
"commitMessageSuffix": "[skip ci]"
} }

View File

@ -40,16 +40,14 @@ public class GuildController {
@GetMapping("/{guildId}/voiceChannels") @GetMapping("/{guildId}/voiceChannels")
@PreAuthorize("isInGuild(#guildId)") @PreAuthorize("isInGuild(#guildId)")
public List<Channel> getVoiceChannels(@PathVariable String guildId, Authentication authentication){ public List<Channel> getVoiceChannels(@PathVariable String guildId){
JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return guildService.getVoiceChannel(guildId);
return guildService.getVoiceChannel(guildId, principal.user().getDiscordId());
} }
@GetMapping("/{guildId}/textChannels") @GetMapping("/{guildId}/textChannels")
@PreAuthorize("isInGuild(#guildId)") @PreAuthorize("isInGuild(#guildId)")
public List<Channel> getTextChannels(@PathVariable String guildId, Authentication authentication){ public List<Channel> getTextChannels(@PathVariable String guildId){
JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return guildService.getTextChannel(guildId);
return guildService.getTextChannel(guildId, principal.user().getDiscordId());
} }
@GetMapping("/{guildId}/roles") @GetMapping("/{guildId}/roles")

View File

@ -1,10 +1,11 @@
package net.Broken.Api.Controllers; package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Settings.SettingGroup; import net.Broken.Api.Data.Settings.SettingGroup;
import net.Broken.Api.Data.Settings.Value;
import net.Broken.Api.Services.SettingService; import net.Broken.Api.Services.SettingService;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
@ -22,10 +23,4 @@ public class SettingController {
public List<SettingGroup> getSettingDescription(){ public List<SettingGroup> getSettingDescription(){
return settingService.getSettingDescription(); return settingService.getSettingDescription();
} }
@GetMapping("/{guildId}/values")
@PreAuthorize("isInGuild(#guildId) && canManageGuild(#guildId)")
public List<Value> getSettingValues(@PathVariable String guildId){
return settingService.getValues(guildId);
}
} }

View File

@ -1,4 +1,4 @@
package net.Broken.Api.Data.Guild; package net.Broken.Api.Data.Guild;
public record Guild(String id, String name, String iconUrl, boolean canManage) { public record Guild(String id, String name, String iconUrl) {
} }

View File

@ -1,4 +0,0 @@
package net.Broken.Api.Data.Settings;
public record Value(String id, String value) {
}

View File

@ -3,9 +3,7 @@ package net.Broken.Api.Security.Expression;
import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.Tools.CacheTools; import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import okhttp3.Cache; import okhttp3.Cache;
import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
@ -31,16 +29,6 @@ public class CustomMethodSecurityExpressionRoot
return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild); return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild);
} }
public boolean canManageGuild(String guildId){
JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal();
Member member = MainBot.jda.getGuildById(guildId).getMemberById(jwtPrincipal.user().getDiscordId());
return member.hasPermission(
Permission.MANAGE_SERVER,
Permission.MANAGE_PERMISSIONS,
Permission.MANAGE_CHANNEL
);
}
@Override @Override
public void setFilterObject(Object filterObject) { public void setFilterObject(Object filterObject) {
this.filterObject = filterObject; this.filterObject = filterObject;

View File

@ -6,8 +6,6 @@ import net.Broken.Api.Data.Guild.Role;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.Tools.CacheTools; import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -16,51 +14,41 @@ import java.util.List;
@Service @Service
public class GuildService { public class GuildService {
public List<Guild> getMutualGuilds(UserEntity user) { public List<Guild> getMutualGuilds(UserEntity user){
User discordUser = CacheTools.getJdaUser(user); User discordUser = CacheTools.getJdaUser(user);
List<net.dv8tion.jda.api.entities.Guild> mutualGuilds = discordUser.getMutualGuilds(); List<net.dv8tion.jda.api.entities.Guild> mutualGuilds = discordUser.getMutualGuilds();
List<Guild> guildList = new ArrayList<>(); List<Guild> guildList = new ArrayList<>();
for (net.dv8tion.jda.api.entities.Guild guild : mutualGuilds) { for (net.dv8tion.jda.api.entities.Guild guild : mutualGuilds){
boolean canManage = guild.getMember(discordUser).hasPermission( guildList.add(new Guild(guild.getId(), guild.getName(), guild.getIconUrl()));
Permission.MANAGE_SERVER,
Permission.MANAGE_PERMISSIONS,
Permission.MANAGE_CHANNEL
);
guildList.add(new Guild(guild.getId(), guild.getName(), guild.getIconUrl(), canManage));
} }
return guildList; return guildList;
} }
public List<Channel> getVoiceChannel(String guildId, String userId) { public List<Channel> getVoiceChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>(); List<Channel> voiceChannels = new ArrayList<>();
for (net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()) { for(net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()){
if (member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName()));
} }
}
return voiceChannels; return voiceChannels;
} }
public List<Channel> getTextChannel(String guildId, String userId) { public List<Channel> getTextChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>(); List<Channel> voiceChannels = new ArrayList<>();
for (net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()) { for(net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()){
if (member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName()));
} }
}
return voiceChannels; return voiceChannels;
} }
public List<Role> getRole(String guildId) { public List<Role> getRole(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Role> roles = new ArrayList<>(); List<Role> roles = new ArrayList<>();
for (net.dv8tion.jda.api.entities.Role role : guild.getRoles()) { for(net.dv8tion.jda.api.entities.Role role : guild.getRoles()){
if (!role.isManaged()) { if(!role.isManaged()){
roles.add(new Role(role.getId(), role.getName())); roles.add(new Role(role.getId(), role.getName()));
} }
} }

View File

@ -1,13 +1,7 @@
package net.Broken.Api.Services; package net.Broken.Api.Services;
import liquibase.pro.packaged.V;
import net.Broken.Api.Data.Settings.SettingDescriber; import net.Broken.Api.Data.Settings.SettingDescriber;
import net.Broken.Api.Data.Settings.SettingGroup; import net.Broken.Api.Data.Settings.SettingGroup;
import net.Broken.Api.Data.Settings.Value;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
@ -16,14 +10,6 @@ import java.util.List;
@Service @Service
public class SettingService { public class SettingService {
public final GuildPreferenceRepository preferenceRepository;
private final Logger logger = LogManager.getLogger();
public SettingService(GuildPreferenceRepository preferenceRepository) {
this.preferenceRepository = preferenceRepository;
}
public List<SettingGroup> getSettingDescription() { public List<SettingGroup> getSettingDescription() {
List<SettingGroup> toReturn = new ArrayList<>(); List<SettingGroup> toReturn = new ArrayList<>();
toReturn.add(getWelcomeGroup()); toReturn.add(getWelcomeGroup());
@ -126,81 +112,4 @@ public class SettingService {
mainField, mainField,
fields); fields);
} }
public List<Value> getValues(String guildId) {
GuildPreferenceEntity pref = preferenceRepository.findByGuildId(guildId).orElseGet(() -> {
logger.info("[API] : Generate default guild pref");
return preferenceRepository.save(GuildPreferenceEntity.getDefault(guildId));
});
List<Value> values = new ArrayList<>(getWelcomeValues(pref));
values.addAll(getDefaultRoleValues(pref));
values.addAll(getDailyValues(pref));
values.addAll(getAutoVoiceChannelValues(pref));
return values;
}
private List<Value> getWelcomeValues(GuildPreferenceEntity pref) {
List<Value> toReturn = new ArrayList<>();
toReturn.add(new Value(
"welcome_enable",
String.valueOf(pref.isWelcome())
)
);
toReturn.add(new Value(
"welcome_chanel_id",
pref.getWelcomeChanelID()
)
);
toReturn.add(new Value(
"welcome_message",
pref.getWelcomeMessage()
)
);
return toReturn;
}
private List<Value> getDefaultRoleValues(GuildPreferenceEntity pref) {
List<Value> toReturn = new ArrayList<>();
toReturn.add(new Value(
"default_role",
String.valueOf(pref.isDefaultRole())
)
);
toReturn.add(new Value(
"default_role_id",
pref.getDefaultRoleId()
)
);
return toReturn;
}
private List<Value> getDailyValues(GuildPreferenceEntity pref) {
List<Value> toReturn = new ArrayList<>();
toReturn.add(new Value(
"daily_madame",
String.valueOf(pref.isDefaultRole())
)
);
return toReturn;
}
private List<Value> getAutoVoiceChannelValues(GuildPreferenceEntity pref) {
List<Value> toReturn = new ArrayList<>();
toReturn.add(new Value(
"auto_voice",
String.valueOf(pref.isAutoVoice())
)
);
toReturn.add(new Value(
"auto_voice_base_channel",
pref.getAutoVoiceChannelID()
)
);
toReturn.add(new Value(
"auto_voice_channel_title",
pref.getAutoVoiceChannelTitle()
)
);
return toReturn;
}
} }

View File

@ -27,7 +27,7 @@ import org.springframework.context.ApplicationContext;
import java.awt.*; import java.awt.*;
import java.util.HashMap; import java.util.HashMap;
import java.util.Optional; import java.util.List;
/** /**
@ -213,13 +213,15 @@ public class BotListener extends ListenerAdapter {
} }
private GuildPreferenceEntity getPreference(Guild guild) { private GuildPreferenceEntity getPreference(Guild guild) {
Optional<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
if (guildPref.isEmpty()) { GuildPreferenceEntity guildPref;
if (guildPrefList.isEmpty()) {
logger.info("[" + guild.getName() + "] : Generate default pref"); logger.info("[" + guild.getName() + "] : Generate default pref");
return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId())); guildPref = GuildPreferenceEntity.getDefault(guild);
} else{ guildPref = guildPreferenceRepository.save(guildPref);
return guildPref.get(); } else
} guildPref = guildPrefList.get(0);
return guildPref;
} }

View File

@ -1,11 +1,11 @@
package net.Broken.DB.Entity; package net.Broken.DB.Entity;
import net.Broken.Api.Data.Settings.Value;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import javax.persistence.*; import javax.persistence.Entity;
import java.util.ArrayList; import javax.persistence.GeneratedValue;
import java.util.List; import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity @Entity
public class GuildPreferenceEntity { public class GuildPreferenceEntity {
@ -13,9 +13,10 @@ public class GuildPreferenceEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(unique=true)
private String guildId; private String guildId;
private boolean antiSpam;
private boolean welcome; private boolean welcome;
private String welcomeMessage; private String welcomeMessage;
@ -34,6 +35,7 @@ public class GuildPreferenceEntity {
public GuildPreferenceEntity(String guildId, public GuildPreferenceEntity(String guildId,
boolean antiSpam,
boolean welcome, boolean welcome,
String welcomeMessage, String welcomeMessage,
String welcomeChanelID, String welcomeChanelID,
@ -44,6 +46,7 @@ public class GuildPreferenceEntity {
String autoVoiceChannelID, String autoVoiceChannelID,
String autoVoiceChannelTitle) { String autoVoiceChannelTitle) {
this.guildId = guildId; this.guildId = guildId;
this.antiSpam = antiSpam;
this.welcome = welcome; this.welcome = welcome;
this.welcomeMessage = welcomeMessage; this.welcomeMessage = welcomeMessage;
this.welcomeChanelID = welcomeChanelID; this.welcomeChanelID = welcomeChanelID;
@ -59,8 +62,9 @@ public class GuildPreferenceEntity {
} }
public static GuildPreferenceEntity getDefault(String guildId) { public static GuildPreferenceEntity getDefault(Guild guild) {
return new GuildPreferenceEntity(guildId, false, "Welcome to this awesome server @name! ", " ", false, " ", true, false, " ", " ");
return new GuildPreferenceEntity(guild.getId(), false, false, "Welcome to this awesome server @name! ", " ", false, " ", true, false, " ", " ");
} }
public Integer getId() { public Integer getId() {
@ -79,6 +83,14 @@ public class GuildPreferenceEntity {
this.guildId = guildId; this.guildId = guildId;
} }
public boolean isAntiSpam() {
return antiSpam;
}
public void setAntiSpam(boolean antiSpam) {
this.antiSpam = antiSpam;
}
public boolean isWelcome() { public boolean isWelcome() {
return welcome; return welcome;
} }

View File

@ -3,9 +3,9 @@ package net.Broken.DB.Repository;
import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Entity.GuildPreferenceEntity;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import java.util.Optional; import java.util.List;
public interface GuildPreferenceRepository extends CrudRepository<GuildPreferenceEntity, Integer> { public interface GuildPreferenceRepository extends CrudRepository<GuildPreferenceEntity, Integer> {
Optional<GuildPreferenceEntity> findByGuildId(String id); List<GuildPreferenceEntity> findByGuildId(String id);
} }

View File

@ -0,0 +1,73 @@
package net.Broken.RestApi;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.Settings.GetSettingsData;
import net.Broken.RestApi.Data.Settings.ListPostSetting;
import net.Broken.Tools.SettingsUtils;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.UserUtils;
import net.dv8tion.jda.api.entities.Guild;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
@RestController
@RequestMapping("/api")
public class SettingAPIController {
final
UserRepository userRepository;
private Logger logger = LogManager.getLogger();
@Autowired
public SettingAPIController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(value = "/settings", method = RequestMethod.GET)
public ResponseEntity<ArrayList<GetSettingsData>> getSettings(@CookieValue("token") String token, @CookieValue("guild") String guild) {
SettingsUtils settingUtils = SettingsUtils.getInstance();
if (settingUtils.checkPermission(token, guild)) {
Guild jdaGuild = MainBot.jda.getGuildById(guild);
return new ResponseEntity<>(settingUtils.extractSettings(jdaGuild), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
@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.getUsername() + " 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

@ -18,7 +18,6 @@ import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.Optional;
/** /**
* Daily Listener for DailyMadame * Daily Listener for DailyMadame
@ -59,8 +58,8 @@ public class DailyMadame implements NewDayListener {
for (Guild guild : guilds) { for (Guild guild : guilds) {
TextChannel chanel = null; TextChannel chanel = null;
logger.debug(guild.getName()); logger.debug(guild.getName());
Optional<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); List<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId());
if (guildPref.isPresent() && guildPref.get().isDailyMadame()) { if (guildPref.size() > 0 && guildPref.get(0).isDailyMadame()) {
for (TextChannel iterator : guild.getTextChannels()) { for (TextChannel iterator : guild.getTextChannels()) {
if (iterator.isNSFW() && iterator.canTalk()) { if (iterator.isNSFW() && iterator.canTalk()) {
chanel = iterator; chanel = iterator;
@ -77,6 +76,8 @@ public class DailyMadame implements NewDayListener {
logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!"); logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!");
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
logger.catching(e); logger.catching(e);

View File

@ -37,6 +37,113 @@ public class SettingsUtils {
return (INSTANCE == null) ? new SettingsUtils() : INSTANCE; return (INSTANCE == null) ? new SettingsUtils() : INSTANCE;
} }
/**
* Extract all settings for displaying on webpage
*
* @param guild The guild
* @return All formatted settings
*/
public ArrayList<GetSettingsData> extractSettings(Guild guild) {
ArrayList<GetSettingsData> list = new ArrayList<>();
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if (guildPrefList.isEmpty()) {
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
} else
guildPref = guildPrefList.get(0);
list.add(new GetSettingsData(
"Enable Welcome Message",
null,
"welcome",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isWelcome())
));
list.add(new GetSettingsData(
"Welcome Message chanel",
null,
"welcome_chanel_id",
GetSettingsData.TYPE.LIST,
getTextChannels(guild),
guildPref.getWelcomeChanelID()
));
list.add(new GetSettingsData(
"Welcome Message",
null,
"welcome_message",
GetSettingsData.TYPE.STRING,
null,
guildPref.getWelcomeMessage()
));
list.add(new GetSettingsData(
"Enable Default Role",
null,
"default_role",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isDefaultRole())
));
list.add(new GetSettingsData(
"Default Role",
null,
"default_role_id",
GetSettingsData.TYPE.LIST,
getRoles(guild),
guildPref.getDefaultRoleId()
));
list.add(new GetSettingsData(
"Enable Anti Spam",
null,
"anti_spam",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isAntiSpam())
));
list.add(new GetSettingsData(
"Enable Daily Madame Message",
null,
"daily_madame",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isDailyMadame())
));
list.add(new GetSettingsData(
"Enable Auto Create Voice Chanel",
null,
"auto_voice",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isAutoVoice())
));
list.add(new GetSettingsData(
"Base Voice Channel For Auto Create",
"If someone joint this channel, a new voice channel will be created with the same settings.",
"auto_voice_base_channel",
GetSettingsData.TYPE.LIST,
getVoiceChannels(guild, null),
guildPref.getAutoVoiceChannelID()
));
list.add(new GetSettingsData(
"Auto Created Voice Channel title",
"Auto created voice channel will use this title, @count will be replaced by the channel count.",
"auto_voice_channel_title",
GetSettingsData.TYPE.STRING,
null,
guildPref.getAutoVoiceChannelTitle()
));
return list;
}
/** /**
* Check if the user have the permission to set settings * Check if the user have the permission to set settings
* *
@ -67,6 +174,87 @@ 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":
boolean result_as = Boolean.parseBoolean(value);
pref.setAntiSpam(result_as);
break;
case "default_role":
boolean result_df = Boolean.parseBoolean(value);
pref.setDefaultRole(result_df);
pref = guildPreferenceRepository.save(pref);
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":
boolean result_w = Boolean.parseBoolean(value);
pref.setWelcome(result_w);
break;
case "welcome_chanel_id":
try {
TextChannel channel = guild.getTextChannelById(value);
if (channel != null) {
pref.setWelcomeChanelID(channel.getId());
} 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);
break;
case "daily_madame":
boolean result_dm = Boolean.parseBoolean(value);
pref.setDailyMadame(result_dm);
break;
case "auto_voice":
boolean result_av = Boolean.parseBoolean(value);
pref.setAutoVoice(result_av);
break;
case "auto_voice_base_channel":
VoiceChannel channel = guild.getVoiceChannelById(value);
if (channel == null) {
logger.error("voices_channels error, bad ID.");
return false;
} else
pref.setAutoVoiceChannelID(channel.getId());
break;
case "auto_voice_channel_title":
pref.setAutoVoiceChannelTitle(value);
break;
}
}
guildPreferenceRepository.save(pref);
return true;
}
private List<Value> getTextChannels(Guild guild) { private List<Value> getTextChannels(Guild guild) {
List<Value> channels = new ArrayList<>(); List<Value> channels = new ArrayList<>();
for (TextChannel channel : guild.getTextChannels()) { for (TextChannel channel : guild.getTextChannels()) {
@ -110,9 +298,14 @@ public class SettingsUtils {
} }
public GuildPreferenceEntity getPreference(Guild guild) { public GuildPreferenceEntity getPreference(Guild guild) {
return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{ List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if (guildPrefList.isEmpty()) {
logger.info("Generate default pref for " + guild.getName()); logger.info("Generate default pref for " + guild.getName());
return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId())); guildPref = GuildPreferenceEntity.getDefault(guild);
}); guildPreferenceRepository.save(guildPref);
} else
guildPref = guildPrefList.get(0);
return guildPref;
} }
} }