Compare commits

...

4 Commits

Author SHA1 Message Date
606d223361
🔨 Add canManage to guild list 2022-06-11 19:06:04 +02:00
ccb0c6eee8
🤖 Change ci 2022-06-11 18:44:40 +02:00
239781fbbd
🔨 Add value endpoint 2022-06-11 17:25:21 +02:00
17102a9e95
🔨 Return only visible voice/text channels 2022-06-11 17:24:45 +02:00
15 changed files with 187 additions and 331 deletions

View File

@ -5,9 +5,6 @@ name: Build
on: on:
push: push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs: jobs:
build-gradle: build-gradle:
@ -38,7 +35,6 @@ 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
@ -60,10 +56,24 @@ 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:latest tags: "ghcr.io/sebclem/claptrapbot:${{ env.tag }}"
file: ./Dockerfile file: ./Dockerfile

View File

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

View File

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

View File

@ -1,11 +1,10 @@
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.web.bind.annotation.CrossOrigin; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
@ -23,4 +22,10 @@ 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) { public record Guild(String id, String name, String iconUrl, boolean canManage) {
} }

View File

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

View File

@ -3,7 +3,9 @@ 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;
@ -29,6 +31,16 @@ 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,6 +6,8 @@ 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;
@ -14,41 +16,51 @@ 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) {
guildList.add(new Guild(guild.getId(), guild.getName(), guild.getIconUrl())); boolean canManage = guild.getMember(discordUser).hasPermission(
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){ public List<Channel> getVoiceChannel(String guildId, String userId) {
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()) {
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); if (member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName()));
}
} }
return voiceChannels; return voiceChannels;
} }
public List<Channel> getTextChannel(String guildId){ public List<Channel> getTextChannel(String guildId, String userId) {
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()) {
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); if (member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) {
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,7 +1,13 @@
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;
@ -10,6 +16,14 @@ 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());
@ -112,4 +126,81 @@ 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.List; import java.util.Optional;
/** /**
@ -213,15 +213,13 @@ public class BotListener extends ListenerAdapter {
} }
private GuildPreferenceEntity getPreference(Guild guild) { private GuildPreferenceEntity getPreference(Guild guild) {
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); Optional<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref; if (guildPref.isEmpty()) {
if (guildPrefList.isEmpty()) {
logger.info("[" + guild.getName() + "] : Generate default pref"); logger.info("[" + guild.getName() + "] : Generate default pref");
guildPref = GuildPreferenceEntity.getDefault(guild); return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId()));
guildPref = guildPreferenceRepository.save(guildPref); } else{
} else return guildPref.get();
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.Entity; import javax.persistence.*;
import javax.persistence.GeneratedValue; import java.util.ArrayList;
import javax.persistence.GenerationType; import java.util.List;
import javax.persistence.Id;
@Entity @Entity
public class GuildPreferenceEntity { public class GuildPreferenceEntity {
@ -13,10 +13,9 @@ 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;
@ -35,7 +34,6 @@ 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,
@ -46,7 +44,6 @@ 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;
@ -62,9 +59,8 @@ public class GuildPreferenceEntity {
} }
public static GuildPreferenceEntity getDefault(Guild guild) { public static GuildPreferenceEntity getDefault(String guildId) {
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() {
@ -83,14 +79,6 @@ 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.List; import java.util.Optional;
public interface GuildPreferenceRepository extends CrudRepository<GuildPreferenceEntity, Integer> { public interface GuildPreferenceRepository extends CrudRepository<GuildPreferenceEntity, Integer> {
List<GuildPreferenceEntity> findByGuildId(String id); Optional<GuildPreferenceEntity> findByGuildId(String id);
} }

View File

@ -1,73 +0,0 @@
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,6 +18,7 @@ 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
@ -58,8 +59,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());
List<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); Optional<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId());
if (guildPref.size() > 0 && guildPref.get(0).isDailyMadame()) { if (guildPref.isPresent() && guildPref.get().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;
@ -76,8 +77,6 @@ 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,113 +37,6 @@ 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
* *
@ -174,87 +67,6 @@ 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()) {
@ -298,14 +110,9 @@ public class SettingsUtils {
} }
public GuildPreferenceEntity getPreference(Guild guild) { public GuildPreferenceEntity getPreference(Guild guild) {
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{
GuildPreferenceEntity guildPref;
if (guildPrefList.isEmpty()) {
logger.info("Generate default pref for " + guild.getName()); logger.info("Generate default pref for " + guild.getName());
guildPref = GuildPreferenceEntity.getDefault(guild); return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId()));
guildPreferenceRepository.save(guildPref); });
} else
guildPref = guildPrefList.get(0);
return guildPref;
} }
} }