file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
DiscordToMinecraftChatConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/DiscordToMinecraftChatConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.DiscordIgnoresConfig;
import com.discordsrv.common.config.main.generic.MentionsConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;
@ConfigSerializable
public class DiscordToMinecraftChatConfig {
public boolean enabled = true;
@Comment("The Discord to Minecraft message format for regular users and bots")
public String format = "[[color:#5865F2]Discord[color]] [hover:show_text:Username: @%user_tag%\nRoles: %user_roles:', '|text:'[color:gray][italics:on]None[color][italics]'%]%user_color%%user_effective_server_name%[color][hover]%message_reply% » %message%%message_attachments%";
@Comment("The Discord to Minecraft message format for webhook messages (if enabled)")
public String webhookFormat = "[[color:#5865F2]Discord[color]] [hover:show_text:Bot message]%user_effective_name%[hover] » %message%%message_attachments%";
@Comment("Format for a single attachment in the %message_attachments% placeholder")
public String attachmentFormat = " [hover:show_text:Open %file_name% in browser][click:open_url:%file_url%][color:green][[color:white]%file_name%[color:green]][color][click][hover]";
@Comment("Format for the %message_reply% placeholder, when the message is a reply to another message")
public String replyFormat = " [hover:show_text:%message%][click:open_url:%message_jump_url%]replying to %user_color|text:''%%user_effective_server_name|user_effective_name%[color][click][hover]";
// TODO: more info on regex pairs (String#replaceAll)
@Comment("Regex filters for Discord message contents (this is the %message% part of the \"format\" option)")
@Untranslated(Untranslated.Type.VALUE)
public Map<Pattern, String> contentRegexFilters = new LinkedHashMap<Pattern, String>() {{
put(Pattern.compile("\\n{2,}"), "\n");
}};
@Comment("Users, bots, roles and webhooks to ignore")
public DiscordIgnoresConfig ignores = new DiscordIgnoresConfig();
@Comment("The representations of Discord mentions in-game")
public MentionsConfig mentions = new MentionsConfig();
@Comment("How should unicode emoji be shown in-game:\n"
+ "- hide: hides emojis in-game\n"
+ "- show: shows emojis in-game as is (emojis may not be visible without resource packs)\n"
//+ "- name: shows the name of the emoji in-game (for example :smiley:)"
)
public EmojiBehaviour unicodeEmojiBehaviour = EmojiBehaviour.HIDE;
public enum EmojiBehaviour {
HIDE,
SHOW
// TODO: add and implement name
}
@Comment("The amount of milliseconds to delay processing Discord messages, if the message is deleted in that time it will not be processed.\n"
+ "This can be used together with Discord moderation bots, to filter forwarded messages")
public long delayMillis = 0L;
}
| 4,012 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MirroringConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/MirroringConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels;
import com.discordsrv.common.config.main.generic.DiscordIgnoresConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class MirroringConfig {
public boolean enabled = true;
@Comment("Users, bots, roles and webhooks to ignore when mirroring")
public DiscordIgnoresConfig ignores = new DiscordIgnoresConfig();
@Comment("The format of the username of mirrored messages\n"
+ "It's recommended to include some special character if in-game messages use webhooks,\n"
+ "in order to prevent Discord users and in-game players with the same name being grouped together")
public String usernameFormat = "%user_effective_server_name|user_effective_name% \uD83D\uDD03";
@Comment("The format when a message is a reply.\n"
+ "%message% will be replaced with the message content\n"
+ "%message_jump_url% will be replaced with the url to the replied message in the channel the message is sent in")
public String replyFormat = "[In reply to %user_effective_server_name|user_effective_name%](%message_jump_url%)\n%message%";
@Comment("Attachment related options")
public AttachmentConfig attachments = new AttachmentConfig();
@ConfigSerializable
public static class AttachmentConfig {
@Comment("Maximum size (in kB) to download and re-upload, set to 0 for unlimited or -1 to disable re-uploading.\n"
+ "The default value is -1 (disabled)\n\n"
+ "When this is enabled, files smaller than the specified limit are downloaded and then re-uploaded to each mirror channel individually.\n"
+ "Please consider limiting the users allowed to attach files if this is enabled,\n"
+ "as spam of large files may result in a lot of downstream and upstream data usage")
public int maximumSizeKb = -1;
@Comment("If attachments should be placed into a embed in mirrored messages instead of re-uploading")
public boolean embedAttachments = true;
}
}
| 3,012 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
LeaveMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/LeaveMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class LeaveMessageConfig implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor("%player_display_name% left", null, "%player_avatar_url%")
.setColor(0xFF5555)
.build()
);
@Comment("If the \"%1\" permission should determine if leave messages are sent")
@Constants.Comment("discordsrv.silentquit")
public boolean enableSilentPermission = true;
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
| 2,245 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
StartMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/StartMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class StartMessageConfig implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.setContent(":arrow_forward: **The server has started**");
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
| 1,656 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
JoinMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/JoinMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.events.message.receive.game.JoinMessageReceiveEvent;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class JoinMessageConfig implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor("%player_display_name% joined", null, "%player_avatar_url%")
.setColor(0x55FF55)
.build()
);
@Comment("If the \"%1\" permission should determine if join messages are sent")
@Constants.Comment("discordsrv.silentjoin")
public boolean enableSilentPermission = true;
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
@Nullable
public FirstJoin firstJoin() {
// Returns null if first join is unavailable
return null;
}
public final IMessageConfig getForEvent(JoinMessageReceiveEvent event) {
FirstJoin firstJoin = firstJoin();
return firstJoin != null && event.isFirstJoin() ? firstJoin : this;
}
@ConfigSerializable
public static class FirstJoin implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor("%player_display_name% joined for the first time", null, "%player_avatar_url%")
.setColor(0xFFAA00)
.build()
);
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
}
| 3,496 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerSwitchMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/proxy/ServerSwitchMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.proxy;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class ServerSwitchMessageConfig implements IMessageConfig {
public boolean enabled = false;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor(
"%player_display_name% switched from %from_server% to %to_server%",
null,
"%player_avatar_url%"
)
.setColor(0x5555FF)
.build()
);
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
| 2,116 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/ChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base;
import com.discordsrv.common.config.main.generic.DestinationConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public class ChannelConfig extends BaseChannelConfig implements IChannelConfig {
public ChannelConfig() {
initialize();
}
@Setting(nodeFromParent = true)
public DestinationConfig destination = new DestinationConfig();
@Override
public DestinationConfig destination() {
return destination;
}
}
| 1,453 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
IChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/IChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base;
import com.discordsrv.common.config.main.generic.DestinationConfig;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
public interface IChannelConfig {
String DEFAULT_KEY = "default";
DestinationConfig destination();
default void initialize() {
// Clear everything besides channelIds by default (these will be filled back in by Configurate if they are in the config itself)
Class<?> clazz = getClass();
while (clazz != null) {
for (Field field : clazz.getFields()) {
int modifiers = field.getModifiers();
if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) {
continue;
}
try {
field.set(this, null);
} catch (IllegalAccessException ignored) {}
}
clazz = clazz.getSuperclass();
}
}
class Serializer implements TypeSerializer<BaseChannelConfig> {
private final ObjectMapper.Factory mapperFactory;
private final Class<?> baseConfigClass;
private final Class<?> configClass;
public Serializer(ObjectMapper.Factory mapperFactory, Class<?> baseConfigClass, Class<?> configClass) {
this.mapperFactory = mapperFactory;
this.baseConfigClass = baseConfigClass;
this.configClass = configClass;
}
@Override
public BaseChannelConfig deserialize(Type type, ConfigurationNode node) throws SerializationException {
return (BaseChannelConfig) mapperFactory.asTypeSerializer()
.deserialize(
ChannelConfig.DEFAULT_KEY.equals(node.key()) ? baseConfigClass : configClass,
node
);
}
@Override
public void serialize(Type type, @Nullable BaseChannelConfig obj, ConfigurationNode node) throws SerializationException {
if (obj == null) {
node.set(null);
return;
}
mapperFactory.asTypeSerializer().serialize(
ChannelConfig.DEFAULT_KEY.equals(node.key()) ? baseConfigClass : configClass,
obj,
node
);
}
}
}
| 3,572 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
BaseChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/BaseChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base;
import com.discordsrv.common.config.configurate.annotation.Order;
import com.discordsrv.common.config.main.channels.*;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class BaseChannelConfig {
@Order(0)
public MinecraftToDiscordChatConfig minecraftToDiscord = new MinecraftToDiscordChatConfig();
@Order(0)
public DiscordToMinecraftChatConfig discordToMinecraft = new DiscordToMinecraftChatConfig();
public JoinMessageConfig joinMessages() {
return new JoinMessageConfig();
}
@Order(2)
public LeaveMessageConfig leaveMessages = new LeaveMessageConfig();
@Order(20)
public StartMessageConfig startMessage = new StartMessageConfig();
@Order(20)
public StopMessageConfig stopMessage = new StopMessageConfig();
@Order(30)
@Comment("Settings for synchronizing messages between the defined Discord channels and threads")
public MirroringConfig mirroring = new MirroringConfig();
@Order(50)
public ChannelLockingConfig channelLocking = new ChannelLockingConfig();
}
| 2,044 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ProxyChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/proxy/ProxyChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base.proxy;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.config.main.generic.DestinationConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public class ProxyChannelConfig extends ProxyBaseChannelConfig implements IChannelConfig {
public ProxyChannelConfig() {
initialize();
}
@Setting(nodeFromParent = true)
public DestinationConfig destination = new DestinationConfig();
@Override
public DestinationConfig destination() {
return destination;
}
}
| 1,545 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ProxyBaseChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/proxy/ProxyBaseChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base.proxy;
import com.discordsrv.common.config.configurate.annotation.Order;
import com.discordsrv.common.config.main.channels.JoinMessageConfig;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.proxy.ServerSwitchMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class ProxyBaseChannelConfig extends BaseChannelConfig {
@Order(1)
public JoinMessageConfig joinMessages = new JoinMessageConfig();
@Order(3)
public ServerSwitchMessageConfig serverSwitchMessages = new ServerSwitchMessageConfig();
@Override
public JoinMessageConfig joinMessages() {
return joinMessages;
}
}
| 1,632 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerBaseChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/server/ServerBaseChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base.server;
import com.discordsrv.common.config.configurate.annotation.Order;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.server.AwardMessageConfig;
import com.discordsrv.common.config.main.channels.server.DeathMessageConfig;
import com.discordsrv.common.config.main.channels.server.ServerJoinMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class ServerBaseChannelConfig extends BaseChannelConfig {
@Order(1)
public ServerJoinMessageConfig joinMessages = new ServerJoinMessageConfig();
@Order(3)
@Comment("Advancement/Achievement message configuration")
public AwardMessageConfig awardMessages = new AwardMessageConfig();
@Order(3)
public DeathMessageConfig deathMessages = new DeathMessageConfig();
@Override
public ServerJoinMessageConfig joinMessages() {
return joinMessages;
}
}
| 1,929 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerChannelConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/base/server/ServerChannelConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.base.server;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.config.main.generic.DestinationConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public class ServerChannelConfig extends ServerBaseChannelConfig implements IChannelConfig {
public ServerChannelConfig() {
initialize();
}
@Setting(nodeFromParent = true)
public DestinationConfig destination = new DestinationConfig();
@Override
public DestinationConfig destination() {
return destination;
}
}
| 1,549 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
AwardMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/server/AwardMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.server;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class AwardMessageConfig implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor(
"%award_title|text:'{player_name} made the advancement {award_name}'%",
null,
"%player_avatar_url%"
)
.setColor(1)
.build()
);
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
| 2,106 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerJoinMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/server/ServerJoinMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.server;
import com.discordsrv.common.config.configurate.annotation.Order;
import com.discordsrv.common.config.main.channels.JoinMessageConfig;
import org.jetbrains.annotations.Nullable;
public class ServerJoinMessageConfig extends JoinMessageConfig {
@Order(10)
public FirstJoin firstJoin = new FirstJoin();
@Override
public @Nullable FirstJoin firstJoin() {
return firstJoin;
}
}
| 1,294 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DeathMessageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/server/DeathMessageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.main.channels.server;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class DeathMessageConfig implements IMessageConfig {
public boolean enabled = true;
@Untranslated(Untranslated.Type.VALUE)
public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder()
.addEmbed(
DiscordMessageEmbed.builder()
.setAuthor("%message%", null, "%player_avatar_url%")
.setColor(1)
.build()
);
@Override
public boolean enabled() {
return enabled;
}
@Override
public SendableDiscordMessage.Builder format() {
return format;
}
}
| 1,909 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
StorageConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/connection/StorageConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.connection;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
@ConfigSerializable
public class StorageConfig {
@Comment("The storage backend to use.\n\n"
+ "- H2\n"
+ "- MySQL\n"
+ "- MariaDB")
public String backend = "H2";
@Comment("SQL table prefix")
public String sqlTablePrefix = "discordsrv_";
@Comment("Connection options for remote databases (MySQL, MariaDB)")
public Remote remote = new Remote();
@Comment("Extra connection properties for database drivers")
public Map<String, String> driverProperties = new LinkedHashMap<String, String>() {{
put("useSSL", "false");
}};
public Properties getDriverProperties() {
Properties properties = new Properties();
for (Map.Entry<String, String> property : driverProperties.entrySet()) {
String key = property.getKey();
String value = property.getValue();
if (value.equals("true")) {
properties.put(key, true);
} else if (value.equals("false")) {
properties.put(key, false);
} else {
properties.put(key, value);
}
}
return properties;
}
public static class Remote {
@Comment("The database address.\n"
+ "Uses the default port (MySQL: 3306)\n"
+ "for the database if a port isn't specified in the \"address:port\" format\n"
+ "Please make sure the port for your database is open and your firewall(s) allow(s) connections from the server to the database")
public String databaseAddress = "localhost";
@Comment("The name of the database")
public String databaseName = "minecraft";
@Comment("The database username and password")
public String username = "root";
public String password = "";
@Comment("Connection pool options. Don't touch these unless you know what you're doing")
public Pool poolOptions = new Pool();
}
public static class Pool {
@Comment("The maximum amount of concurrent connections to keep to the database")
public int maximumPoolSize = 5;
@Comment("The minimum amount of concurrent connections to keep to the database")
public int minimumPoolSize = 2;
@Comment("How frequently to attempt to keep connections alive, in order to prevent being timed out by the database or network infrastructure.\n"
+ "The time is specified in milliseconds. Use 0 to disable keepalive."
+ "The default is 0 (disabled)")
public long keepaliveTime = 0;
@Comment("The maximum time a connection will be kept open in milliseconds.\n"
+ "The time is specified in milliseconds. Must be at least 30000ms (30 seconds)"
+ "The default is 1800000ms (30 minutes)")
public long maximumLifetime = 1800000;
}
}
| 4,002 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
BotConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/connection/BotConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.connection;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class BotConfig {
@Comment("The Discord bot token from https://discord.com/developers/applications\n"
+ "Requires a connection to: discord.com, gateway.discord.gg, cdn.discordapp.com\n"
+ "Privacy Policy: https://discord.com/privacy Terms: https://discord.com/developers/docs/policies-and-agreements/developer-terms-of-service")
public String token = "Token here";
}
| 1,445 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
UpdateConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/connection/UpdateConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.connection;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.update.UpdateChecker;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public class UpdateConfig {
@Setting(value = "notification-enabled")
@Comment("On/off for notifications when a new version of DiscordSRV is available")
public boolean notificationEnabled = true;
@Setting(value = "notification-ingame")
@Comment("If players with the %1 permission should receive\n"
+ "a update notification upon joining if there is a update available")
@Constants.Comment("discordsrv.updatenotification")
public boolean notificationInGame = true;
@Setting(value = "enable-first-party-api-for-notifications")
@Comment("Whether the DiscordSRV download API should be used for update checks\n"
+ "Requires a connection to: %1")
@Constants.Comment(UpdateChecker.DOWNLOAD_SERVICE_DOMAIN)
public boolean firstPartyNotification = true;
@Setting(value = "github")
public GitHub github = new GitHub();
@Setting(value = "security")
public Security security = new Security();
@ConfigSerializable
public static class GitHub {
@Setting(value = "enabled")
@Comment("Whether the GitHub API should be used for update checks\n"
+ "This will be the secondary API if both first party and GitHub sources are enabled\n"
+ "Requires a connection to: %1")
@Constants.Comment(UpdateChecker.GITHUB_API_DOMAIN)
public boolean enabled = true;
@Setting(value = "api-token")
@Comment("The GitHub API token used for authenticating to the GitHub api,\n"
+ "if this isn't specified the API will be used 'anonymously'\n"
+ "The token only requires read permission to %1 releases, workflows and commits")
@Constants.Comment(UpdateChecker.GITHUB_REPOSITORY)
public String apiToken = "";
}
@ConfigSerializable
public static class Security {
@Setting(value = "enabled")
@Comment("Uses the DiscordSRV download API to check if the version of DiscordSRV\n"
+ "being used is vulnerable to known vulnerabilities, disabling the plugin if it is.\n"
+ "Requires a connection to: %1\n"
+ "\n"
+ "WARNING! DO NOT TURN THIS OFF UNLESS YOU KNOW WHAT YOU'RE DOING AND STAY UP-TO-DATE")
@Constants.Comment(UpdateChecker.DOWNLOAD_SERVICE_DOMAIN)
public boolean enabled = true;
@Setting(value = "force")
@Comment("If the security check needs to be completed for DiscordSRV to enable,\n"
+ "if the security check cannot be performed, DiscordSRV will be disabled if this option is set to true")
public boolean force = false;
}
}
| 3,896 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ConnectionConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/connection/ConnectionConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.connection;
import com.discordsrv.common.config.Config;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.config.main.MainConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public class ConnectionConfig implements Config {
public static final String FILE_NAME = "connections.yaml";
@Constants({MainConfig.FILE_NAME, "443", "https/wss"})
public static final String HEADER = "DiscordSRV's configuration file for connections to different external services.\n"
+ "This file is intended to contain connection details to services in order to keep them out of the %1\n"
+ "and to serve as a easy way to identify and control what external connections are being used.\n"
+ "\n"
+ "All domains listed as \"Requires a connection to\" require port %2 (%3) unless otherwise specified\n"
+ "\n"
+ " ABSOLUTELY DO NOT SEND THIS FILE TO ANYONE - IT ONLY CONTAINS SECRETS\n";
@Override
public final String getFileName() {
return FILE_NAME;
}
public BotConfig bot = new BotConfig();
public StorageConfig storage = new StorageConfig();
public MinecraftAuthConfig minecraftAuth = new MinecraftAuthConfig();
public UpdateConfig update = new UpdateConfig();
}
| 2,231 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MinecraftAuthConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/connection/MinecraftAuthConfig.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.connection;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public class MinecraftAuthConfig {
@Comment("If minecraftauth.me connections are allowed for Discord linking (when linked-accounts.provider is \"auto\" or \"minecraftauth\").\n"
+ "Requires a connection to: minecraftauth.me\n"
+ "Privacy Policy: https://minecraftauth.me/privacy")
public boolean allow = true;
@Comment("minecraftauth.me token for checking subscription, following and membership statuses for required linking\n"
+ "You can get the token from https://minecraftauth.me/api/token whilst logged in (please keep in mind that the token resets every time you visit that page)")
public String token = "";
}
| 1,707 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Untranslated.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/annotation/Untranslated.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies that the given option will be partially or completely undocumented.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Untranslated {
/**
* Specifies which part of this option will be undocumented. The default value is {@link Type#FULL}.
* @return the {@link Type} specifying the parts that will be undocumented
*/
Type value() default Type.FULL;
enum Type {
/**
* The option's value, and it's comment will be undocumented.
*/
FULL(true, true),
/**
* Only the comment of the option is undocumented.
*/
COMMENT(true, false),
/**
* Only the option's value will be undocumented.
*/
VALUE(false, true);
private final boolean comment;
private final boolean value;
Type(boolean comment, boolean value) {
this.comment = comment;
this.value = value;
}
public boolean isComment() {
return comment;
}
public boolean isValue() {
return value;
}
}
}
| 2,196 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DefaultOnly.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/annotation/DefaultOnly.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Prevents the annotated options from being (partially) merged into existing configs (only being added to new configs).
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DefaultOnly {
/**
* The children that are whitelisted/blacklisted based on {@link #whitelist()},
* if this is empty the entire option will be blacklisted from being merged into existing configs.
*/
String[] value() default {};
/**
* Only the provided {@link #value()} otherwise everything except the provided {@link #value()}.
*/
boolean whitelist() default true;
}
| 1,673 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Constants.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/annotation/Constants.java | package com.discordsrv.common.config.configurate.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A config annotation that should be used to define config (comment) parts that should not be translated,
* remaining the same for all languages (for example, config option names referenced in comments, urls, etc.).
* <p>
* Replacements are {@code %i} where {@code i} start counting up from {@code 1}.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Constants {
String[] value() default {};
int[] intValue() default {};
/**
* Needs to go after {@link org.spongepowered.configurate.objectmapping.meta.Comment}.
*/
@Retention(RetentionPolicy.RUNTIME)
@interface Comment {
String[] value() default {};
int[] intValue() default {};
}
}
| 850 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Order.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/annotation/Order.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Manually determines the position of the option in the config, everything is ordered {@code 0} by default,
* and will go in the order they are defined.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Order {
/**
* Lowest to highest.
* @return the order value of the option
*/
int value();
}
| 1,413 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
OrderedFieldDiscovererProxy.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/fielddiscoverer/OrderedFieldDiscovererProxy.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.fielddiscoverer;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.objectmapping.FieldData;
import org.spongepowered.configurate.objectmapping.FieldDiscoverer;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.util.CheckedFunction;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.AnnotatedType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Proxy for {@link com.discordsrv.common.config.configurate.annotation.Order}.
* @param <T> T of proxied {@link FieldDiscoverer}
*/
public class OrderedFieldDiscovererProxy<T> implements FieldDiscoverer<T> {
private final FieldDiscoverer<T> fieldDiscoverer;
private final Comparator<FieldCollectorData<T, ?>> order;
public OrderedFieldDiscovererProxy(FieldDiscoverer<T> fieldDiscoverer, Comparator<FieldCollectorData<T, ?>> order) {
this.fieldDiscoverer = fieldDiscoverer;
this.order = order;
}
@Override
public @Nullable <V> InstanceFactory<T> discover(AnnotatedType target, FieldCollector<T, V> collector) throws SerializationException {
List<FieldCollectorData<T, V>> data = new ArrayList<>();
FieldCollector<T, V> fieldCollector = (name, type, annotations, deserializer, serializer) ->
data.add(new FieldCollectorData<>(name, type, annotations, deserializer, serializer));
InstanceFactory<T> instanceFactory = fieldDiscoverer.discover(target, fieldCollector);
if (instanceFactory == null) {
return null;
}
data.sort(order);
for (FieldCollectorData<T, V> field : data) {
collector.accept(field.name, field.type, field.annotations, field.deserializer, field.serializer);
}
return instanceFactory;
}
public static class FieldCollectorData<T, V> {
private final String name;
private final AnnotatedType type;
private final AnnotatedElement annotations;
private final FieldData.Deserializer<T> deserializer;
private final CheckedFunction<V, Object, Exception> serializer;
public FieldCollectorData(String name, AnnotatedType type, AnnotatedElement annotations,
FieldData.Deserializer<T> deserializer,
CheckedFunction<V, Object, Exception> serializer) {
this.name = name;
this.type = type;
this.annotations = annotations;
this.deserializer = deserializer;
this.serializer = serializer;
}
public String name() {
return name;
}
public AnnotatedType type() {
return type;
}
public AnnotatedElement annotations() {
return annotations;
}
}
}
| 3,768 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MessagesConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/MessagesConfigManager.java | package com.discordsrv.common.config.configurate.manager;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.main.MainConfig;
import com.discordsrv.common.config.messages.MessagesConfig;
import com.discordsrv.common.exception.ConfigException;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public abstract class MessagesConfigManager<C extends MessagesConfig> {
private final Map<Locale, MessagesConfigSingleManager<C>> configs = new LinkedHashMap<>();
private final DiscordSRV discordSRV;
private final Logger logger;
public MessagesConfigManager(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
this.logger = new NamedLogger(discordSRV, "MESSAGES_CONFIG");
}
public abstract C createConfiguration();
public Map<Locale, MessagesConfigSingleManager<C>> getAllManagers() {
return Collections.unmodifiableMap(configs);
}
public MessagesConfigSingleManager<C> getManager(Locale locale) {
synchronized (configs) {
return configs.get(locale);
}
}
public Path directory() {
return discordSRV.dataDirectory().resolve("messages");
}
public void load() throws ConfigException {
synchronized (configs) {
configs.clear();
MainConfig config = discordSRV.config();
if (config == null) {
throw new ConfigException("MainConfig not available");
}
if (config.messages.multiple) {
try {
Path messagesDirectory = directory();
if (!Files.exists(messagesDirectory)) {
Files.createDirectory(messagesDirectory);
}
List<Locale> existing = new ArrayList<>();
try (Stream<Path> paths = Files.list(messagesDirectory)) {
paths.forEach(path -> {
String fileName = path.getFileName().toString();
String[] parts = fileName.split("\\.", 2);
if (parts.length != 2 || !parts[1].equals("yaml")) {
logger.warning("Unexpected messages file: " + fileName + " (invalid language code or not .yaml)");
return;
}
Locale locale = Locale.forLanguageTag(parts[0]);
if (locale == null) {
logger.warning("Unexpected messages file: " + fileName + " (unknown locale)");
return;
}
configs.put(locale, new MessagesConfigSingleManager<>(discordSRV, this, locale, true));
existing.add(locale);
});
}
if (config.messages.loadAllDefaults) {
// TODO: load all default default locales missing
}
} catch (Throwable t) {
throw new ConfigException("Failed to initialize messages configs", t);
}
} else {
Locale defaultLocale = discordSRV.defaultLocale();
configs.put(defaultLocale, new MessagesConfigSingleManager<>(discordSRV, this, defaultLocale, false));
}
for (Map.Entry<Locale, MessagesConfigSingleManager<C>> entry : configs.entrySet()) {
entry.getValue().load();
}
}
}
}
| 3,730 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MessagesConfigSingleManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/MessagesConfigSingleManager.java | package com.discordsrv.common.config.configurate.manager;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.manager.abstraction.TranslatedConfigManager;
import com.discordsrv.common.config.configurate.manager.loader.YamlConfigLoaderProvider;
import com.discordsrv.common.config.messages.MessagesConfig;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.util.Locale;
public class MessagesConfigSingleManager<C extends MessagesConfig>
extends TranslatedConfigManager<C, YamlConfigurationLoader>
implements YamlConfigLoaderProvider {
private final MessagesConfigManager<C> aggregateManager;
private final Locale locale;
private final boolean multi;
protected MessagesConfigSingleManager(DiscordSRV discordSRV, MessagesConfigManager<C> aggregateManager, Locale locale, boolean multi) {
super(discordSRV);
this.aggregateManager = aggregateManager;
this.locale = locale;
this.multi = multi;
}
@Override
public String fileName() {
if (multi) {
return aggregateManager.directory().resolve(locale.getISO3Language() + ".yaml").toString();
}
return MessagesConfig.FILE_NAME;
}
@Override
public Locale locale() {
return locale;
}
@Override
public C createConfiguration() {
return aggregateManager.createConfiguration();
}
}
| 1,445 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MainConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/MainConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.manager.abstraction.TranslatedConfigManager;
import com.discordsrv.common.config.configurate.manager.loader.YamlConfigLoaderProvider;
import com.discordsrv.common.config.main.MainConfig;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.lang.reflect.Field;
import java.nio.file.Path;
public abstract class MainConfigManager<C extends MainConfig>
extends TranslatedConfigManager<C, YamlConfigurationLoader>
implements YamlConfigLoaderProvider {
public MainConfigManager(DiscordSRV discordSRV) {
super(discordSRV);
}
protected MainConfigManager(Path dataDirectory) {
super(dataDirectory);
}
@Override
protected Field headerField() throws ReflectiveOperationException {
return MainConfig.class.getField("HEADER");
}
@Override
public String fileName() {
return MainConfig.FILE_NAME;
}
}
| 1,884 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ConnectionConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/ConnectionConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.manager.abstraction.TranslatedConfigManager;
import com.discordsrv.common.config.configurate.manager.loader.YamlConfigLoaderProvider;
import com.discordsrv.common.config.connection.ConnectionConfig;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.lang.reflect.Field;
import java.nio.file.Path;
public abstract class ConnectionConfigManager<C extends ConnectionConfig>
extends TranslatedConfigManager<C, YamlConfigurationLoader>
implements YamlConfigLoaderProvider {
public ConnectionConfigManager(DiscordSRV discordSRV) {
super(discordSRV);
}
protected ConnectionConfigManager(Path dataDirectory) {
super(dataDirectory);
}
@Override
protected Field headerField() throws ReflectiveOperationException {
return ConnectionConfig.class.getField("HEADER");
}
@Override
public String fileName() {
return ConnectionConfig.FILE_NAME;
}
}
| 1,932 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
TranslatedConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/abstraction/TranslatedConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.abstraction;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.Config;
import com.discordsrv.common.exception.ConfigException;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public abstract class TranslatedConfigManager<T extends Config, LT extends AbstractConfigurationLoader<CommentedConfigurationNode>>
extends ConfigurateConfigManager<T, LT> {
private final DiscordSRV discordSRV;
private String header;
public TranslatedConfigManager(DiscordSRV discordSRV) {
super(discordSRV);
this.discordSRV = discordSRV;
}
protected TranslatedConfigManager(Path dataDirectory) {
super(dataDirectory, null);
this.discordSRV = null;
}
public Locale locale() {
return discordSRV.defaultLocale();
}
@Override
public void load() throws ConfigException {
super.reload();
translate();
super.save();
}
@Override
protected String header() {
if (header != null) {
return header;
}
return super.header();
}
@Override
protected @Nullable ConfigurationNode getTranslation() throws ConfigurateException {
ConfigurationNode translation = getTranslationRoot();
if (translation == null) {
return null;
}
translation = translation.copy();
translation.node("_comments").set(null);
return translation;
}
@SuppressWarnings("unchecked")
public void translate() throws ConfigException {
T config = config();
if (config == null) {
return;
}
try {
ConfigurationNode translationRoot = getTranslationRoot();
if (translationRoot == null) {
return;
}
String fileIdentifier = config.getFileName();
ConfigurationNode translation = translationRoot.node(fileIdentifier);
ConfigurationNode comments = translationRoot.node(fileIdentifier + "_comments");
CommentedConfigurationNode node = loader().createNode();
this.header = comments.node("$header").getString();
save(config, (Class<T>) config.getClass(), node);
translateNode(node, translation, comments);
} catch (ConfigurateException e) {
throw new ConfigException(e);
}
}
private ConfigurationNode getTranslationRoot() throws ConfigurateException {
if (discordSRV == null) {
return null;
}
String languageCode = locale().getLanguage();
String countryCode = locale().getCountry();
ClassLoader classLoader = discordSRV.getClass().getClassLoader();
URL resourceURL = classLoader.getResource("translations/" + languageCode + "_" + countryCode + ".yaml");
if (resourceURL == null) {
resourceURL = classLoader.getResource("translations/" + languageCode + ".yaml");
}
if (resourceURL == null) {
return null;
}
return YamlConfigurationLoader.builder().url(resourceURL).build().load();
}
private void translateNode(
CommentedConfigurationNode node,
ConfigurationNode translations,
ConfigurationNode commentTranslations
) throws SerializationException {
List<Object> path = new ArrayList<>(Arrays.asList(node.path().array()));
String translation = translations.node(path).getString();
if (translation != null) {
node.set(translation);
}
path.add("_comment");
String commentTranslation = commentTranslations.node(path).getString();
if (commentTranslation != null) {
node.comment(commentTranslation);
}
for (CommentedConfigurationNode child : node.childrenMap().values()) {
translateNode(child, translations, commentTranslations);
}
}
}
| 5,363 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ProxyConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/abstraction/ProxyConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.abstraction;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.manager.MainConfigManager;
import com.discordsrv.common.config.main.MainConfig;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.config.main.channels.base.proxy.ProxyBaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.proxy.ProxyChannelConfig;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
public abstract class ProxyConfigManager<T extends MainConfig> extends MainConfigManager<T> {
public ProxyConfigManager(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public IChannelConfig.Serializer getChannelConfigSerializer(ObjectMapper.Factory mapperFactory) {
return new IChannelConfig.Serializer(mapperFactory, ProxyBaseChannelConfig.class, ProxyChannelConfig.class);
}
}
| 1,798 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ConfigurateConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/abstraction/ConfigurateConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.abstraction;
import com.discordsrv.api.color.Color;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.config.configurate.annotation.DefaultOnly;
import com.discordsrv.common.config.configurate.annotation.Order;
import com.discordsrv.common.config.configurate.fielddiscoverer.OrderedFieldDiscovererProxy;
import com.discordsrv.common.config.configurate.manager.loader.ConfigLoaderProvider;
import com.discordsrv.common.config.configurate.serializer.*;
import com.discordsrv.common.config.helper.MinecraftMessage;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.ChannelConfig;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.exception.ConfigException;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.configurate.*;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.FieldDiscoverer;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Processor;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.util.NamingScheme;
import org.spongepowered.configurate.util.NamingSchemes;
import org.spongepowered.configurate.yaml.ScalarStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public abstract class ConfigurateConfigManager<T, LT extends AbstractConfigurationLoader<CommentedConfigurationNode>>
implements ConfigManager<T>, ConfigLoaderProvider<LT> {
public static ThreadLocal<Boolean> CLEAN_MAPPER = ThreadLocal.withInitial(() -> false);
public static NamingScheme NAMING_SCHEME = in -> {
in = Character.toLowerCase(in.charAt(0)) + in.substring(1);
in = NamingSchemes.LOWER_CASE_DASHED.coerce(in);
return in;
};
private final Path filePath;
private final Logger logger;
private final ObjectMapper.Factory objectMapper;
private final ObjectMapper.Factory cleanObjectMapper;
private LT loader;
protected T configuration;
public ConfigurateConfigManager(DiscordSRV discordSRV) {
this(discordSRV.dataDirectory(), new NamedLogger(discordSRV, "CONFIG"));
}
protected ConfigurateConfigManager(Path dataDirectory, Logger logger) {
this.filePath = dataDirectory.resolve(fileName());
this.logger = logger;
this.objectMapper = objectMapperBuilder(true).build();
this.cleanObjectMapper = cleanObjectMapperBuilder().build();
}
public Path filePath() {
return filePath;
}
public LT loader() {
if (loader == null) {
loader = createLoader(filePath(), nodeOptions(true)).build();
}
return loader;
}
@Override
public T config() {
return configuration;
}
public abstract String fileName();
protected Field headerField() throws ReflectiveOperationException {
return null;
}
protected String header() {
try {
Field headerField = headerField();
return headerField != null ? (String) headerField.get(null) : null;
} catch (ReflectiveOperationException e) {
return null;
}
}
protected String[] headerConstants() {
try {
Field headerField = headerField();
if (headerField == null) {
return new String[0];
}
Constants constants = headerField.getAnnotation(Constants.class);
if (constants == null) {
return new String[0];
}
return constants.value();
} catch (ReflectiveOperationException e) {
return new String[0];
}
}
public IChannelConfig.Serializer getChannelConfigSerializer(ObjectMapper.Factory mapperFactory) {
return new IChannelConfig.Serializer(mapperFactory, BaseChannelConfig.class, ChannelConfig.class);
}
@SuppressWarnings("unchecked") // Special Class cast
public ConfigurationOptions configurationOptions(ObjectMapper.Factory objectMapper, boolean headerSubstitutions) {
String header = header();
if (header != null && headerSubstitutions) {
header = doSubstitution(header, headerConstants());
}
return ConfigurationOptions.defaults()
.header(header)
.shouldCopyDefaults(false)
.implicitInitialization(false)
.serializers(builder -> {
builder.register(String.class, new TypeSerializer<String>() {
@Override
public String deserialize(Type type, ConfigurationNode node) {
return node.getString();
}
@Override
public void serialize(Type type, @org.checkerframework.checker.nullness.qual.Nullable String obj, ConfigurationNode node) {
RepresentationHint<ScalarStyle> hint = YamlConfigurationLoader.SCALAR_STYLE;
ScalarStyle style = node.hint(hint);
if (style == hint.defaultValue()) {
// Set scalar style for strings to double quotes, by default
node = node.hint(hint, ScalarStyle.DOUBLE_QUOTED);
}
node.raw(obj);
}
});
builder.register(BaseChannelConfig.class, getChannelConfigSerializer(objectMapper));
//noinspection unchecked
builder.register((Class<Enum<?>>) (Object) Enum.class, new EnumSerializer(logger));
builder.register(Color.class, new ColorSerializer());
builder.register(Pattern.class, new PatternSerializer());
builder.register(DiscordMessageEmbed.Builder.class, new DiscordMessageEmbedSerializer(NAMING_SCHEME));
builder.register(DiscordMessageEmbed.Field.class, new DiscordMessageEmbedSerializer.FieldSerializer(NAMING_SCHEME));
builder.register(SendableDiscordMessage.Builder.class, new SendableDiscordMessageSerializer(NAMING_SCHEME));
builder.register(MinecraftMessage.class, new MinecraftMessageSerializer());
// give Configurate' serializers the ObjectMapper mapper
builder.register(type -> {
String typeName = type.getTypeName();
return typeName.startsWith("com.discordsrv")
&& !typeName.startsWith("com.discordsrv.dependencies")
&& !typeName.contains(".serializer");
}, objectMapper.asTypeSerializer());
});
}
public ConfigurationOptions nodeOptions(boolean headerSubstitutions) {
return configurationOptions(objectMapper(), headerSubstitutions);
}
public ConfigurationOptions cleanNodeOptions() {
return configurationOptions(cleanObjectMapper(), true);
}
@SuppressWarnings("unchecked")
public ObjectMapper.Factory.Builder commonObjectMapperBuilder(boolean commentSubstitutions) {
Comparator<OrderedFieldDiscovererProxy.FieldCollectorData<Object, ?>> fieldOrder = Comparator.comparingInt(data -> {
Order order = data.annotations().getAnnotation(Order.class);
return order != null ? order.value() : 0;
});
return ObjectMapper.factoryBuilder()
.defaultNamingScheme(NAMING_SCHEME)
.addDiscoverer(new OrderedFieldDiscovererProxy<>((FieldDiscoverer<Object>) FieldDiscoverer.emptyConstructorObject(), fieldOrder))
.addDiscoverer(new OrderedFieldDiscovererProxy<>((FieldDiscoverer<Object>) FieldDiscoverer.record(), fieldOrder))
.addProcessor(Constants.Comment.class, (data, fieldType) -> (value, destination) -> {
// This needs to go before comment processing.
if (commentSubstitutions && destination instanceof CommentedConfigurationNode) {
String comment = ((CommentedConfigurationNode) destination).comment();
if (StringUtils.isEmpty(comment)) {
logger.error(
Arrays.stream(destination.path().array()).map(Object::toString).collect(Collectors.joining(", "))
+ " is not commented but has comment constants! (make sure @Constants.Comment is below @Comment)"
);
return;
}
((CommentedConfigurationNode) destination).comment(
doSubstitution(comment, getValues(data.value(), data.intValue()))
);
}
})
.addProcessor(Constants.class, (data, fieldType) -> (value, destination) -> {
String[] values = getValues(data.value(), data.intValue());
if (values.length == 0) {
return;
}
String optionValue = destination.getString();
if (optionValue == null) {
return;
}
try {
destination.set(doSubstitution(destination.getString(), values));
} catch (SerializationException e) {
throw new RuntimeException(e);
}
});
}
private String[] getValues(String[] value, int[] intValue) {
List<String> values = new ArrayList<>(Arrays.asList(value));
for (int i : intValue) {
values.add(String.valueOf(i));
}
return values.toArray(new String[0]);
}
private static String doSubstitution(String input, String[] values) {
for (int i = 0; i < values.length; i++) {
input = input.replace("%" + (i + 1), values[i]);
}
return input;
}
public ObjectMapper.Factory.Builder objectMapperBuilder(boolean commentSubstitutions) {
return commonObjectMapperBuilder(commentSubstitutions)
.addProcessor(Comment.class, (data, fieldType) -> {
Processor<Object> processor = Processor.comments().make(data, fieldType);
return (value, destination) -> {
processor.process(value, destination);
if (destination instanceof CommentedConfigurationNode) {
String comment = ((CommentedConfigurationNode) destination).comment();
if (comment != null) {
// Yaml doesn't render empty lines correctly, so we add a space when there are double line breaks
((CommentedConfigurationNode) destination).comment(comment.replace("\n\n", "\n \n"));
}
}
};
});
}
protected ObjectMapper.Factory.Builder cleanObjectMapperBuilder() {
return commonObjectMapperBuilder(true)
.addProcessor(DefaultOnly.class, (data, value) -> (value1, destination) -> {
String[] children = data.value();
boolean whitelist = data.whitelist();
if (children.length == 0) {
try {
destination.set(null);
} catch (SerializationException e) {
e.printStackTrace();
}
return;
}
List<String> list = Arrays.asList(children);
for (Map.Entry<Object, ? extends ConfigurationNode> entry : destination.childrenMap().entrySet()) {
Object key = entry.getKey();
if (!(key instanceof String)) {
continue;
}
if (list.contains(entry.getKey()) == whitelist) {
continue;
}
try {
entry.getValue().set(null);
} catch (SerializationException e) {
e.printStackTrace();
}
}
});
}
public ObjectMapper.Factory objectMapper() {
return objectMapper;
}
public ObjectMapper.Factory cleanObjectMapper() {
return cleanObjectMapper;
}
/**
* Gets the default config given the default object from {@link #createConfiguration()}
* @param defaultConfig the object
* @param cleanMapper if options that are marked with {@link DefaultOnly} or serializers that make use of {@link #CLEAN_MAPPER} should be excluded from the node
* @return the node with the values from the object
* @throws SerializationException if serialization fails
*/
private CommentedConfigurationNode getDefault(T defaultConfig, boolean cleanMapper) throws SerializationException {
try {
if (cleanMapper) {
CLEAN_MAPPER.set(true);
}
return getDefault(defaultConfig, cleanMapper ? cleanObjectMapper() : objectMapper());
} finally {
if (cleanMapper) {
CLEAN_MAPPER.set(false);
}
}
}
public CommentedConfigurationNode getDefaultNode(ObjectMapper.Factory mapperFactory) throws ConfigurateException {
return getDefault(createConfiguration(), mapperFactory);
}
@SuppressWarnings("unchecked")
private CommentedConfigurationNode getDefault(T defaultConfig, ObjectMapper.Factory mapperFactory) throws SerializationException {
CommentedConfigurationNode node = CommentedConfigurationNode.root(cleanNodeOptions());
mapperFactory.get((Class<T>) defaultConfig.getClass()).save(defaultConfig, node);
return node;
}
@Nullable
protected ConfigurationNode getTranslation() throws ConfigurateException {
return null;
}
@Override
public void load() throws ConfigException {
reload();
save();
}
@SuppressWarnings("unchecked")
@Override
public void reload() throws ConfigException {
T defaultConfig = createConfiguration();
try {
CommentedConfigurationNode node;
if (filePath().toFile().exists()) {
// Config file exists, load from that
node = loader().load();
ConfigurationNode translation = getTranslation();
if (translation != null) {
// Merge translation
node.mergeFrom(translation);
}
// Apply defaults that may not be there
node.mergeFrom(getDefault(defaultConfig, true));
} else {
node = getDefault(defaultConfig, false);
}
this.configuration = objectMapper()
.get((Class<T>) defaultConfig.getClass())
.load(node);
} catch (ConfigurateException e) {
Class<?> configClass = defaultConfig.getClass();
if (!configClass.isAnnotationPresent(ConfigSerializable.class)) {
// Not very obvious and can easily happen
throw new ConfigException(configClass.getName()
+ " is not annotated with @ConfigSerializable", e);
}
throw new ConfigException("Failed to load configuration", e);
}
}
@SuppressWarnings("unchecked")
@Override
public void save(AbstractConfigurationLoader<CommentedConfigurationNode> loader) throws ConfigException {
try {
CommentedConfigurationNode node = loader.createNode();
save(configuration, (Class<T>) configuration.getClass(), node);
loader.save(node);
} catch (ConfigurateException e) {
throw new ConfigException("Failed to load configuration", e);
}
}
@Override
public void save() throws ConfigException {
LT loader = loader();
save(loader);
}
protected void save(T config, Class<T> clazz, CommentedConfigurationNode node) throws SerializationException {
objectMapper().get(clazz).save(config, node);
}
}
| 18,438 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/abstraction/ConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.abstraction;
import com.discordsrv.common.exception.ConfigException;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
public interface ConfigManager<T> {
T createConfiguration();
T config();
void load() throws ConfigException;
void reload() throws ConfigException;
void save(AbstractConfigurationLoader<CommentedConfigurationNode> loader) throws ConfigException;
void save() throws ConfigException;
}
| 1,405 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerConfigManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/abstraction/ServerConfigManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.abstraction;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.configurate.manager.MainConfigManager;
import com.discordsrv.common.config.main.MainConfig;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.config.main.channels.base.server.ServerBaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.server.ServerChannelConfig;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import java.nio.file.Path;
public abstract class ServerConfigManager<T extends MainConfig> extends MainConfigManager<T> {
public ServerConfigManager(DiscordSRV discordSRV) {
super(discordSRV);
}
protected ServerConfigManager(Path dataDirectory) {
super(dataDirectory);
}
@Override
public IChannelConfig.Serializer getChannelConfigSerializer(ObjectMapper.Factory mapperFactory) {
return new IChannelConfig.Serializer(mapperFactory, ServerBaseChannelConfig.class, ServerChannelConfig.class);
}
}
| 1,927 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
YamlConfigLoaderProvider.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/loader/YamlConfigLoaderProvider.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.loader;
import org.jetbrains.annotations.ApiStatus;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
import org.spongepowered.configurate.yaml.NodeStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import org.spongepowered.configurate.yaml.internal.snakeyaml.DumperOptions;
import java.lang.reflect.Field;
public interface YamlConfigLoaderProvider extends ConfigLoaderProvider<YamlConfigurationLoader> {
default NodeStyle nodeStyle() {
return NodeStyle.BLOCK;
}
default int indent() {
return 4;
}
@Override
@ApiStatus.NonExtendable
default AbstractConfigurationLoader.Builder<?, YamlConfigurationLoader> createBuilder() {
YamlConfigurationLoader.Builder builder = YamlConfigurationLoader.builder()
.commentsEnabled(true)
.nodeStyle(nodeStyle())
.indent(indent());
try {
Field field = builder.getClass().getDeclaredField("options");
field.setAccessible(true);
DumperOptions dumperOptions = (DumperOptions) field.get(builder);
dumperOptions.setSplitLines(false);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
return builder;
}
}
| 2,186 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ConfigLoaderProvider.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/loader/ConfigLoaderProvider.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.manager.loader;
import org.jetbrains.annotations.ApiStatus;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationOptions;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
import org.spongepowered.configurate.loader.HeaderMode;
import java.nio.file.Path;
public interface ConfigLoaderProvider<LT extends AbstractConfigurationLoader<CommentedConfigurationNode>> {
default HeaderMode headerMode() {
return HeaderMode.PRESET;
}
AbstractConfigurationLoader.Builder<?, LT> createBuilder();
@ApiStatus.NonExtendable
default AbstractConfigurationLoader.Builder<?, LT> createLoader(Path configFile, ConfigurationOptions options) {
return createBuilder()
.path(configFile)
.defaultOptions(options)
.headerMode(headerMode());
}
}
| 1,778 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MinecraftMessageSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/MinecraftMessageSerializer.java | package com.discordsrv.common.config.configurate.serializer;
import com.discordsrv.common.config.helper.MinecraftMessage;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
public class MinecraftMessageSerializer implements TypeSerializer<MinecraftMessage> {
@Override
public MinecraftMessage deserialize(Type type, ConfigurationNode node) throws SerializationException {
return new MinecraftMessage(node.getString());
}
@Override
public void serialize(Type type, @Nullable MinecraftMessage obj, ConfigurationNode node) throws SerializationException {
if (obj == null) {
node.set(null);
return;
}
node.set(obj.rawFormat());
}
}
| 943 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordMessageEmbedSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/DiscordMessageEmbedSerializer.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.serializer;
import com.discordsrv.api.color.Color;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.common.config.configurate.manager.abstraction.ConfigurateConfigManager;
import net.dv8tion.jda.api.entities.Role;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.util.NamingScheme;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
public class DiscordMessageEmbedSerializer implements TypeSerializer<DiscordMessageEmbed.Builder> {
private final NamingScheme namingScheme;
public DiscordMessageEmbedSerializer(NamingScheme namingScheme) {
this.namingScheme = namingScheme;
}
private String map(String option) {
return namingScheme.coerce(option);
}
@Override
public DiscordMessageEmbed.Builder deserialize(Type type, ConfigurationNode node) throws SerializationException {
if (ConfigurateConfigManager.CLEAN_MAPPER.get()) {
return null;
}
if (!node.node(map("Enabled")).getBoolean(node.node(map("Enable")).getBoolean(true))) {
return null;
}
DiscordMessageEmbed.Builder builder = DiscordMessageEmbed.builder();
Color color = node.node(map("Color")).get(Color.class);
builder.setColor(color != null ? color.rgb() : Role.DEFAULT_COLOR_RAW);
ConfigurationNode author = node.node(map("Author"));
builder.setAuthor(
author.node(map("Name")).getString(),
author.node(map("Url")).getString(),
author.node(map("ImageUrl")).getString());
ConfigurationNode title = node.node(map("Title"));
builder.setTitle(
title.node(map("Text")).getString(),
title.node(map("Url")).getString());
builder.setDescription(node.node(map("Description")).getString());
for (DiscordMessageEmbed.Field field : node.node(map("Fields")).getList(DiscordMessageEmbed.Field.class, Collections.emptyList())) {
builder.addField(field);
}
builder.setThumbnailUrl(node.node(map("ThumbnailUrl")).getString());
builder.setImageUrl(node.node(map("ImageUrl")).getString());
// TODO: timestamp
ConfigurationNode footer = node.node(map("Footer"));
builder.setFooter(
footer.node(map("Text")).getString(),
footer.node(map("ImageUrl")).getString(footer.node(map("IconUrl")).getString("")));
return builder;
}
@Override
public void serialize(Type type, DiscordMessageEmbed.@Nullable Builder obj, ConfigurationNode node)
throws SerializationException {
if (obj == null || ConfigurateConfigManager.CLEAN_MAPPER.get()) {
node.set(null);
return;
}
node.node(map("Color")).set(obj.getColor());
ConfigurationNode author = node.node(map("Author"));
author.node(map("Name")).set(obj.getAuthorName());
author.node(map("Url")).set(obj.getAuthorUrl());
author.node(map("ImageUrl")).set(obj.getAuthorImageUrl());
ConfigurationNode title = node.node(map("Title"));
title.node(map("Text")).set(obj.getTitle());
title.node(map("Url")).set(obj.getTitleUrl());
node.node(map("Description")).set(obj.getDescription());
List<DiscordMessageEmbed.Field> fields = obj.getFields();
ConfigurationNode fieldsNode = node.node(map("Fields"));
fieldsNode.setList(DiscordMessageEmbed.Field.class, fields.isEmpty() ? null : obj.getFields());
node.node(map("ThumbnailUrl")).set(obj.getThumbnailUrl());
node.node(map("ImageUrl")).set(obj.getImageUrl());
ConfigurationNode footer = node.node(map("Footer"));
footer.node(map("Text")).set(obj.getFooter());
footer.node(map("ImageUrl")).set(obj.getFooterImageUrl());
}
public static class FieldSerializer implements TypeSerializer<DiscordMessageEmbed.Field> {
private final NamingScheme namingScheme;
public FieldSerializer(NamingScheme namingScheme) {
this.namingScheme = namingScheme;
}
private String map(String option) {
return namingScheme.coerce(option);
}
@Override
public DiscordMessageEmbed.Field deserialize(Type type, ConfigurationNode node) {
// v1 compat
String footerString = node.getString();
if (footerString != null) {
if (footerString.contains(";")) {
String[] parts = footerString.split(";", 3);
if (parts.length < 2) {
return null;
}
boolean inline = parts.length < 3 || Boolean.parseBoolean(parts[2]);
return new DiscordMessageEmbed.Field(parts[0], parts[1], inline);
} else {
boolean inline = Boolean.parseBoolean(footerString);
return new DiscordMessageEmbed.Field("\u200e", "\u200e", inline);
}
}
return new DiscordMessageEmbed.Field(
node.node(map("Title")).getString(),
node.node(map("Value")).getString(),
node.node(map("Inline")).getBoolean()
);
}
@Override
public void serialize(Type type, DiscordMessageEmbed.@Nullable Field obj, ConfigurationNode node)
throws SerializationException {
if (obj == null) {
node.set(null);
return;
}
node.node(map("Title")).set(obj.getTitle());
node.node(map("Value")).set(obj.getValue());
node.node(map("Inline")).set(obj.isInline());
}
}
}
| 6,923 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
PatternSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/PatternSerializer.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.serializer;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.yaml.ScalarStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.lang.reflect.Type;
import java.util.regex.Pattern;
public class PatternSerializer implements TypeSerializer<Pattern> {
@Override
public Pattern deserialize(Type type, ConfigurationNode node) {
String pattern = node != null ? node.getString() : null;
return StringUtils.isNotEmpty(pattern) ? Pattern.compile(pattern) : null;
}
@Override
public void serialize(Type type, @Nullable Pattern obj, ConfigurationNode node) throws SerializationException {
node = node.hint(YamlConfigurationLoader.SCALAR_STYLE, ScalarStyle.DOUBLE_QUOTED);
node.raw(obj != null ? obj.pattern() : null);
}
}
| 1,962 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
SendableDiscordMessageSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/SendableDiscordMessageSerializer.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.serializer;
import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.config.configurate.manager.abstraction.ConfigurateConfigManager;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.util.NamingScheme;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SendableDiscordMessageSerializer implements TypeSerializer<SendableDiscordMessage.Builder> {
private final NamingScheme namingScheme;
public SendableDiscordMessageSerializer(NamingScheme namingScheme) {
this.namingScheme = namingScheme;
}
private String map(String option) {
return namingScheme.coerce(option);
}
@Override
public SendableDiscordMessage.Builder deserialize(Type type, ConfigurationNode node)
throws SerializationException {
String contentOnly = node.getString();
if (contentOnly != null || ConfigurateConfigManager.CLEAN_MAPPER.get()) {
return SendableDiscordMessage.builder()
.setContent(contentOnly);
}
SendableDiscordMessage.Builder builder = SendableDiscordMessage.builder();
ConfigurationNode webhook = node.node(map("Webhook"));
String webhookUsername = webhook.node(map("Username")).getString();
if (webhook.node(map("Enabled")).getBoolean(
webhook.node(map("Enable")).getBoolean(
webhookUsername != null))) {
builder.setWebhookUsername(webhookUsername);
builder.setWebhookAvatarUrl(webhook.node(map("AvatarUrl")).getString());
}
// v1 compat
DiscordMessageEmbed.Builder singleEmbed = node.node(map("Embed")).get(
DiscordMessageEmbed.Builder.class);
List<DiscordMessageEmbed.Builder> embedList = singleEmbed != null
? Collections.singletonList(singleEmbed) : Collections.emptyList();
for (DiscordMessageEmbed.Builder embed : node.node(map("Embeds"))
.getList(DiscordMessageEmbed.Builder.class, embedList)) {
builder.addEmbed(embed.build());
}
builder.setContent(node.node(map("Content")).getString());
return builder;
}
@Override
public void serialize(Type type, SendableDiscordMessage.@Nullable Builder obj, ConfigurationNode node)
throws SerializationException {
if (obj == null || ConfigurateConfigManager.CLEAN_MAPPER.get()) {
node.set(null);
return;
}
String webhookUsername = obj.getWebhookUsername();
if (webhookUsername != null) {
ConfigurationNode webhook = node.node(map("Webhook"));
webhook.node(map("Username")).set(webhookUsername);
webhook.node(map("AvatarUrl")).set(obj.getWebhookAvatarUrl());
}
List<DiscordMessageEmbed.Builder> embedBuilders = new ArrayList<>();
obj.getEmbeds().forEach(embed -> embedBuilders.add(embed.toBuilder()));
if (!embedBuilders.isEmpty()) {
node.node(map("Embeds")).setList(DiscordMessageEmbed.Builder.class, embedBuilders);
}
node.node(map("Content")).set(obj.getContent());
}
}
| 4,433 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ColorSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/ColorSerializer.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.config.configurate.serializer;
import com.discordsrv.api.color.Color;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
public class ColorSerializer implements TypeSerializer<Color> {
@Override
public Color deserialize(Type type, ConfigurationNode node) {
String hexColor = node.getString();
int length;
if (hexColor != null && ((length = hexColor.length()) == 6 || (length == 7 && hexColor.startsWith("#")))) {
if (length == 7) {
hexColor = hexColor.substring(1);
}
try {
return new Color(hexColor);
} catch (NumberFormatException ignored) {}
} else {
int intColor = node.getInt(Integer.MIN_VALUE);
if (intColor != Integer.MIN_VALUE) {
return new Color(intColor);
}
}
return null;
}
@Override
public void serialize(Type type, @Nullable Color obj, ConfigurationNode node) throws SerializationException {
if (obj == null) {
node.set(null);
return;
}
node.set("#" + obj.hex());
}
}
| 2,229 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
EnumSerializer.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/serializer/EnumSerializer.java | package com.discordsrv.common.config.configurate.serializer;
import com.discordsrv.common.logging.Logger;
import io.leangen.geantyref.GenericTypeReflector;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class EnumSerializer implements TypeSerializer<Enum<?>> {
private final Logger logger;
public EnumSerializer(Logger logger) {
this.logger = logger;
}
@SuppressWarnings("unchecked") // Enum generic
@Override
public Enum<?> deserialize(Type type, ConfigurationNode node) throws SerializationException {
Class<? extends Enum<?>> theEnum = (Class<? extends Enum<?>>) GenericTypeReflector.erase(type).asSubclass(Enum.class);
String configValue = node.getString();
if (configValue == null) {
return null;
}
configValue = configValue.toLowerCase(Locale.ROOT);
List<String> values = new ArrayList<>();
for (Enum<?> constant : theEnum.getEnumConstants()) {
String lower = constant.name().toLowerCase(Locale.ROOT);
if (lower.equals(configValue)) {
return constant;
}
values.add(lower);
}
logger.error(
"Option \"" + node.key() + "\" "
+ "has invalid value: \"" + configValue + "\", "
+ "acceptable values: " + String.join(", ", values)
);
return null;
}
@Override
public void serialize(Type type, @Nullable Enum<?> obj, ConfigurationNode node) throws SerializationException {
node.raw(obj != null ? obj.name().toLowerCase(Locale.ROOT) : null);
}
}
| 1,951 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MinecraftMessage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/helper/MinecraftMessage.java | package com.discordsrv.common.config.helper;
import com.discordsrv.api.DiscordSRVApi;
import com.discordsrv.api.component.GameTextBuilder;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.common.component.util.ComponentUtil;
import net.kyori.adventure.text.Component;
public class MinecraftMessage {
private final String rawFormat;
public MinecraftMessage(String rawFormat) {
this.rawFormat = rawFormat;
}
public String rawFormat() {
return rawFormat;
}
public GameTextBuilder textBuilder() {
DiscordSRVApi discordSRV = DiscordSRVApi.get();
if (discordSRV == null) {
throw new IllegalStateException("DiscordSRVApi == null");
}
return discordSRV.componentFactory().textBuilder(rawFormat);
}
public MinecraftComponent make() {
return textBuilder().build();
}
public Component asComponent() {
return ComponentUtil.fromAPI(make());
}
}
| 989 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MessagesConfig.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/messages/MessagesConfig.java | package com.discordsrv.common.config.messages;
import com.discordsrv.api.discord.entity.DiscordUser;
import com.discordsrv.api.placeholder.provider.SinglePlaceholder;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.config.Config;
import com.discordsrv.common.config.configurate.annotation.Constants;
import com.discordsrv.common.config.configurate.annotation.Untranslated;
import com.discordsrv.common.config.helper.MinecraftMessage;
import com.discordsrv.common.future.util.CompletableFutureUtil;
import com.discordsrv.common.player.IOfflinePlayer;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@ConfigSerializable
public class MessagesConfig implements Config {
public static final String FILE_NAME = "messages.yaml";
@Override
public final String getFileName() {
return FILE_NAME;
}
// Helper methods
private void withPlayer(DiscordSRV discordSRV, UUID playerUUID, Consumer<IOfflinePlayer> playerConsumer) {
CompletableFuture<IOfflinePlayer> playerFuture = CompletableFutureUtil.timeout(
discordSRV,
discordSRV.playerProvider().lookupOfflinePlayer(playerUUID),
Duration.ofSeconds(5)
);
playerFuture.whenComplete((player, __) -> playerConsumer.accept(player));
}
private void withUser(DiscordSRV discordSRV, long userId, Consumer<DiscordUser> userConsumer) {
CompletableFuture<DiscordUser> userFuture = CompletableFutureUtil.timeout(
discordSRV,
discordSRV.discordAPI().retrieveUserById(userId),
Duration.ofSeconds(5)
);
userFuture.whenComplete((player, __) -> userConsumer.accept(player));
}
private void withPlayerAndUser(
DiscordSRV discordSRV,
UUID playerUUID,
long userId,
BiConsumer<IOfflinePlayer, DiscordUser> playerAndUserConsumer
) {
CompletableFuture<IOfflinePlayer> playerFuture = CompletableFutureUtil.timeout(
discordSRV,
discordSRV.playerProvider().lookupOfflinePlayer(playerUUID),
Duration.ofSeconds(5)
);
CompletableFuture<DiscordUser> userFuture = CompletableFutureUtil.timeout(
discordSRV,
discordSRV.discordAPI().retrieveUserById(userId),
Duration.ofSeconds(5)
);
playerFuture.whenComplete((player, __) -> userFuture.whenComplete((user, ___) -> playerAndUserConsumer.accept(player, user)));
}
// Methods for responding directly to CommandExecutions
public void playerNotFound(CommandExecution execution) {
execution.send(
minecraft.playerNotFound.asComponent(),
discord.playerNotFound
);
}
public void userNotFound(CommandExecution execution) {
execution.send(
minecraft.userNotFound.asComponent(),
discord.userNotFound
);
}
public void unableToCheckLinkingStatus(CommandExecution execution) {
execution.send(
minecraft.unableToCheckLinkingStatus.asComponent(),
discord.unableToCheckLinkingStatus
);
}
public void playerAlreadyLinked3rd(CommandExecution execution) {
execution.send(
minecraft.playerAlreadyLinked3rd.asComponent(),
discord.playerAlreadyLinked3rd
);
}
public void userAlreadyLinked3rd(CommandExecution execution) {
execution.send(
minecraft.userAlreadyLinked3rd.asComponent(),
discord.userAlreadyLinked3rd
);
}
public void nowLinked3rd(DiscordSRV discordSRV, CommandExecution execution, UUID playerUUID, long userId) {
withPlayerAndUser(discordSRV, playerUUID, userId, (player, user) -> execution.send(
minecraft.nowLinked3rd.textBuilder()
.applyPlaceholderService()
.addContext(user, player)
.addPlaceholder("user_id", userId)
.addPlaceholder("player_uuid", playerUUID)
.build(),
discordSRV.placeholderService().replacePlaceholders(
execution.messages().discord.nowLinked3rd,
user,
player,
new SinglePlaceholder("user_id", userId),
new SinglePlaceholder("player_uuid", playerUUID)
)
));
}
public void discordUserLinkedTo(
DiscordSRV discordSRV,
CommandExecution execution,
UUID playerUUID,
long userId
) {
withPlayerAndUser(discordSRV, playerUUID, userId, (player, user) -> execution.send(
minecraft.discordUserLinkedTo
.textBuilder()
.applyPlaceholderService()
.addContext(user, player)
.addPlaceholder("user_id", userId)
.addPlaceholder("player_uuid", playerUUID)
.build(),
discordSRV.placeholderService().replacePlaceholders(
discord.discordUserLinkedTo,
user,
player,
new SinglePlaceholder("user_id", userId),
new SinglePlaceholder("player_uuid", playerUUID)
)
));
}
public void discordUserUnlinked(
DiscordSRV discordSRV,
CommandExecution execution,
long userId
) {
withUser(discordSRV, userId, (user) -> execution.send(
minecraft.discordUserUnlinked
.textBuilder()
.applyPlaceholderService()
.addContext(user)
.addPlaceholder("user_id", userId)
.build(),
discordSRV.placeholderService().replacePlaceholders(
discord.discordUserUnlinked,
user,
new SinglePlaceholder("user_id", userId)
)
));
}
public void minecraftPlayerLinkedTo(
DiscordSRV discordSRV,
CommandExecution execution,
UUID playerUUID,
long userId
) {
withPlayerAndUser(discordSRV, playerUUID, userId, (player, user) -> execution.send(
minecraft.minecraftPlayerLinkedTo
.textBuilder()
.applyPlaceholderService()
.addContext(player, user)
.addPlaceholder("player_uuid", playerUUID)
.addPlaceholder("user_id", userId)
.build(),
discordSRV.placeholderService().replacePlaceholders(
discord.minecraftPlayerLinkedTo,
player,
user,
new SinglePlaceholder("player_uuid", playerUUID),
new SinglePlaceholder("user_id", userId)
)
));
}
public void minecraftPlayerUnlinked(
DiscordSRV discordSRV,
CommandExecution execution,
UUID playerUUID
) {
withPlayer(discordSRV, playerUUID, (player) -> execution.send(
minecraft.minecraftPlayerUnlinked
.textBuilder()
.applyPlaceholderService()
.addContext(player)
.addPlaceholder("player_uuid", playerUUID)
.build(),
discordSRV.placeholderService().replacePlaceholders(
discord.minecraftPlayerUnlinked,
player,
new SinglePlaceholder("player_uuid", playerUUID)
)
));
}
public void unlinked(CommandExecution execution) {
execution.send(
minecraft.unlinked.asComponent(),
discord.unlinked
);
}
public Minecraft minecraft = new Minecraft();
@ConfigSerializable
public static class Minecraft {
private static final String ERROR_COLOR = "&c";
private static final String SUCCESS_COLOR = "&a";
private static final String NEUTRAL_COLOR = "&b";
private MinecraftMessage make(String rawFormat) {
return new MinecraftMessage(rawFormat);
}
@Comment("Generic")
@Constants(ERROR_COLOR)
public MinecraftMessage noPermission = make("%1Sorry, but you do not have permission to use that command");
@Constants(ERROR_COLOR)
public MinecraftMessage pleaseSpecifyPlayer = make("%1Please specify the Minecraft player");
@Constants(ERROR_COLOR)
public MinecraftMessage pleaseSpecifyUser = make("%1Please specify the Discord user");
@Constants(ERROR_COLOR)
public MinecraftMessage pleaseSpecifyPlayerOrUser = make("%1Please specify the Minecraft player or Discord user");
@Constants(ERROR_COLOR)
public MinecraftMessage playerNotFound = make("%1Minecraft player not found");
@Constants(ERROR_COLOR)
public MinecraftMessage userNotFound = make("%1Discord user not found");
@Constants(ERROR_COLOR)
public MinecraftMessage unableToCheckLinkingStatus = make("%1Unable to check linking status, please try again later");
@Constants({
SUCCESS_COLOR + "[hover:show_text:%user_id%][click:copy_to_clipboard:%user_id%]@%user_name%[click][hover]",
NEUTRAL_COLOR,
SUCCESS_COLOR + "[hover:show_text:%player_uuid%][click:copy_to_clipboard:%player_uuid%]%player_name|text:'<Unknown>'%[click][hover]"
})
public MinecraftMessage discordUserLinkedTo = make("%1 %2is linked to %3");
@Constants({
SUCCESS_COLOR + "[hover:show_text:%user_id%][click:copy_to_clipboard:%user_id%]@%user_name%[click][hover]",
NEUTRAL_COLOR,
ERROR_COLOR
})
public MinecraftMessage discordUserUnlinked = make("%1 %2is %3unlinked");
@Constants({
SUCCESS_COLOR + "[hover:show_text:%player_uuid%][click:copy_to_clipboard:%player_uuid%]%player_name|text:'<Unknown>'%[click][hover]",
NEUTRAL_COLOR,
SUCCESS_COLOR + "[hover:show_text:%user_id%][click:copy_to_clipboard:%user_id%]@%user_name%[click][hover]"
})
public MinecraftMessage minecraftPlayerLinkedTo = make("%1 %2is linked to %3");
@Constants({
SUCCESS_COLOR + "[hover:show_text:%player_uuid%][click:copy_to_clipboard:%player_uuid%]%player_name|text:'<Unknown>'%[click][hover]",
NEUTRAL_COLOR,
ERROR_COLOR
})
public MinecraftMessage minecraftPlayerUnlinked = make("%1 %2is %3unlinked");
@Untranslated(Untranslated.Type.COMMENT)
@Comment("/discord link")
@Constants(ERROR_COLOR)
public MinecraftMessage alreadyLinked1st = make("%1You are already linked");
@Constants(ERROR_COLOR)
public MinecraftMessage pleaseSpecifyPlayerAndUserToLink = make("%1Please specify the Minecraft player and the Discord user to link");
@Constants(ERROR_COLOR)
public MinecraftMessage playerAlreadyLinked3rd = make("%1That player is already linked");
@Constants(ERROR_COLOR)
public MinecraftMessage userAlreadyLinked3rd = make("%1That player is already linked");
@Constants(ERROR_COLOR)
public MinecraftMessage pleaseWaitBeforeRunningThatCommandAgain = make("%1Please wait before running that command again");
@Constants(ERROR_COLOR)
public MinecraftMessage unableToLinkAtThisTime = make("%1Unable to check linking status, please try again later");
@Constants(NEUTRAL_COLOR)
public MinecraftMessage checkingLinkStatus = make("%1Checking linking status...");
@Constants(SUCCESS_COLOR)
public MinecraftMessage nowLinked1st = make("%1You are now linked!");
@Constants({
SUCCESS_COLOR,
NEUTRAL_COLOR,
SUCCESS_COLOR + "[hover:show_text:%player_uuid%][click:copy_to_clipboard:%player_uuid%]%player_name|text:'<Unknown>'%[click][hover]" + NEUTRAL_COLOR,
SUCCESS_COLOR + "[hover:show_text:%user_id%][click:copy_to_clipboard:%user_id%]@%user_name%[click][hover]" + NEUTRAL_COLOR
})
public MinecraftMessage nowLinked3rd = make("%1Link created successfully %2(%3 and %4)");
@Constants({
NEUTRAL_COLOR,
"&f[click:open_url:%minecraftauth_link%][hover:show_text:Click to open]%minecraftauth_link_simple%[click]" + NEUTRAL_COLOR,
"&fMinecraftAuth"
})
public MinecraftMessage minecraftAuthLinking = make("%1Please visit %2 to link your account through %4");
@Untranslated(Untranslated.Type.COMMENT)
@Comment("/discord unlink")
@Constants({SUCCESS_COLOR})
public MinecraftMessage unlinked = make("%1Accounts unlinked");
}
public Discord discord = new Discord();
@ConfigSerializable
public static class Discord {
private static final String SUCCESS_PREFIX = "✅ ";
private static final String INPUT_ERROR_PREFIX = "\uD83D\uDDD2️ ";
private static final String ERROR_PREFIX = "❌ ";
@Comment("Generic")
@Constants(INPUT_ERROR_PREFIX)
public String pleaseSpecifyPlayer = "%1Please specify the Minecraft player";
@Constants(INPUT_ERROR_PREFIX)
public String pleaseSpecifyUser = "%1Please specify the Discord user";
@Constants(INPUT_ERROR_PREFIX)
public String pleaseSpecifyPlayerOrUser = "%1Please specify the Minecraft player or Discord user";
@Constants(ERROR_PREFIX)
public String playerNotFound = "%1Minecraft player not found";
@Constants(ERROR_PREFIX)
public String userNotFound = "%1Discord user not found";
@Constants(ERROR_PREFIX)
public String unableToCheckLinkingStatus = "%1Unable to check linking status, please try again later";
@Constants({
SUCCESS_PREFIX,
"**%user_name%** (<@%user_id%>)",
"**%player_name%** (%player_uuid%)"
})
public String discordUserLinkedTo = "%1%2 is linked to %3";
@Constants({
ERROR_PREFIX,
"**%user_name%** (<@%user_id%>)"
})
public String discordUserUnlinked = "%1%2 is __unlinked__";
@Constants({
SUCCESS_PREFIX,
"**%player_name%** (%player_uuid%)",
"**%user_name%** (<@%user_id%>)"
})
public String minecraftPlayerLinkedTo = "%1%2 is linked to %3";
@Constants({
ERROR_PREFIX,
"**%player_name%** (%player_uuid%)"
})
public String minecraftPlayerUnlinked = "%1%2 is __unlinked__";
@Untranslated(Untranslated.Type.COMMENT)
@Comment("/discord link")
@Constants(ERROR_PREFIX)
public String playerAlreadyLinked3rd = "%1That Minecraft player is already linked";
@Constants(ERROR_PREFIX)
public String userAlreadyLinked3rd = "%1That Discord user is already linked";
@Constants({
SUCCESS_PREFIX,
"**%player_name%** (%player_uuid%)",
"**%user_name%** (<@%user_id%>)"
})
public String nowLinked3rd = "%1Link created successfully\n%2 and %3";
@Untranslated(Untranslated.Type.COMMENT)
@Comment("/discord unlink")
@Constants({SUCCESS_PREFIX})
public String unlinked = "%1Accounts unlinked";
}
}
| 16,292 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DocumentationURLs.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/documentation/DocumentationURLs.java | package com.discordsrv.common.config.documentation;
public final class DocumentationURLs {
private DocumentationURLs() {}
public static final String CREATE_TOKEN = "https://docs.discordsrv.com/installation/initial-setup/#setting-up-the-bot";
public static final String PLACEHOLDERS = "https://docs.discordsrv.com/ascension/placeholders/";
public static final String ELT_FORMAT = "https://github.com/Vankka/EnhancedLegacyText/wiki/Format";
public static final String DISCORD_MARKDOWN = "https://support.discord.com/hc/en-us/articles/210298617";
}
| 569 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordInviteModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/invite/DiscordInviteModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.invite;
import com.discordsrv.api.DiscordSRVApi;
import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent;
import com.discordsrv.api.discord.connection.jda.errorresponse.ErrorCallbackContext;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.placeholder.FormattedText;
import com.discordsrv.api.placeholder.annotation.Placeholder;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.main.DiscordInviteConfig;
import com.discordsrv.common.module.type.AbstractModule;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.channel.attribute.IInviteContainer;
import net.dv8tion.jda.api.events.guild.invite.GuildInviteDeleteEvent;
import net.dv8tion.jda.api.events.guild.update.GuildUpdateVanityCodeEvent;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
public class DiscordInviteModule extends AbstractModule<DiscordSRV> {
private static final String UNKNOWN_INVITE = "https://discord.gg/#Could_not_get_invite,_please_check_your_configuration";
private String invite;
public DiscordInviteModule(DiscordSRV discordSRV) {
super(discordSRV);
discordSRV.placeholderService().addGlobalContext(this);
}
@Override
public @NotNull Collection<DiscordGatewayIntent> requiredIntents() {
DiscordInviteConfig config = discordSRV.config().invite;
if (StringUtils.isNotEmpty(config.inviteUrl)) {
return Collections.emptyList();
}
return Collections.singleton(DiscordGatewayIntent.GUILD_INVITES);
}
@Subscribe
public void onGuildInviteDelete(GuildInviteDeleteEvent event) {
if (invite.equals(event.getUrl())) {
reload(__ -> {});
}
}
@Subscribe
public void onGuildUpdateVanityCode(GuildUpdateVanityCodeEvent event) {
reload(__ -> {});
}
@Override
public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) {
JDA jda = discordSRV.jda();
if (jda == null) {
return;
}
DiscordInviteConfig config = discordSRV.config().invite;
// Manual
String invite = config.inviteUrl;
if (StringUtils.isNotEmpty(invite)) {
this.invite = invite;
return;
}
List<Guild> guilds = jda.getGuilds();
if (guilds.size() != 1) {
return;
}
Guild guild = guilds.get(0);
// Vanity url
if (config.attemptToUseVanityUrl) {
String vanityUrl = guild.getVanityUrl();
if (vanityUrl != null) {
this.invite = vanityUrl;
return;
}
}
// Auto create
if (config.autoCreateInvite) {
Member selfMember = guild.getSelfMember();
if (!selfMember.hasPermission(Permission.CREATE_INSTANT_INVITE)) {
return;
}
IInviteContainer channel = guild.getRulesChannel();
if (channel == null) {
channel = guild.getDefaultChannel();
}
if (channel == null) {
return;
}
channel.createInvite().setMaxAge(0).setUnique(true).queue(
inv -> this.invite = inv.getUrl(),
ErrorCallbackContext.context("Failed to auto create invite")
);
}
}
@Placeholder("discord_invite")
public CharSequence getInvite() {
return new FormattedText(invite != null ? invite : UNKNOWN_INVITE);
}
}
| 4,686 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordSRVDependencyManager.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/dependency/DiscordSRVDependencyManager.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.dependency;
import com.discordsrv.common.DiscordSRV;
import dev.vankka.dependencydownload.ApplicationDependencyManager;
import dev.vankka.dependencydownload.DependencyManager;
import java.io.IOException;
import java.nio.file.Path;
public class DiscordSRVDependencyManager {
private final DiscordSRV discordSRV;
private final ApplicationDependencyManager dependencyManager;
public DiscordSRVDependencyManager(DiscordSRV discordSRV, DependencyLoader initialLoader) {
this.discordSRV = discordSRV;
Path cacheDirectory = DependencyLoader.resolvePath(discordSRV.dataDirectory());
this.dependencyManager = new ApplicationDependencyManager(cacheDirectory);
if (initialLoader != null) {
//noinspection ResultOfMethodCallIgnored
dependencyManager.include(initialLoader.getDependencyManager());
}
}
private DependencyLoader loader(DependencyManager manager) {
return new DependencyLoader(discordSRV, dependencyManager.include(manager));
}
private DependencyLoader loader(String[] paths) throws IOException {
return loader(DependencyLoader.fromPaths(discordSRV.dataDirectory(), paths));
}
public DependencyLoader hikari() throws IOException {
return loader(new String[] {"dependencies/hikari.txt"});
}
public DependencyLoader h2() throws IOException {
return loader(new String[] {"dependencies/h2Driver.txt"});
}
public DependencyLoader mysql() throws IOException {
return loader(new String[] {"dependencies/mysqlDriver.txt"});
}
public DependencyLoader mariadb() throws IOException {
return loader(new String[] {"dependencies/mariadbDriver.txt"});
}
public DependencyLoader mcAuthLib() throws IOException {
return loader(new String[] {"dependencies/mcAuthLib.txt"});
}
}
| 2,727 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DependencyLoader.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/dependency/DependencyLoader.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.dependency;
import com.discordsrv.common.DiscordSRV;
import dev.vankka.dependencydownload.DependencyManager;
import dev.vankka.dependencydownload.classloader.IsolatedClassLoader;
import dev.vankka.dependencydownload.classpath.ClasspathAppender;
import dev.vankka.dependencydownload.repository.Repository;
import dev.vankka.dependencydownload.repository.StandardRepository;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
public class DependencyLoader {
private static final List<Repository> REPOSITORIES = Arrays.asList(
// TODO
new StandardRepository("https://repo1.maven.org/maven2"),
new StandardRepository("https://oss.sonatype.org/content/repositories/snapshots"),
new StandardRepository("https://s01.oss.sonatype.org/content/repositories/snapshots"),
new StandardRepository("https://nexus.scarsz.me/content/groups/public")
);
public static Path resolvePath(Path dataDirectory) {
return dataDirectory.resolve("cache");
}
public static DependencyManager fromPaths(Path dataDirectory, String[] resources) throws IOException {
DependencyManager dependencyManager = new DependencyManager(resolvePath(dataDirectory));
for (String dependencyResource : resources) {
URL resource = DependencyLoader.class.getClassLoader().getResource(dependencyResource);
if (resource == null) {
throw new IllegalArgumentException("Could not find resource with: " + dependencyResource);
}
dependencyManager.loadFromResource(resource);
}
return dependencyManager;
}
private final DependencyManager dependencyManager;
private final Executor executor;
private final ClasspathAppender classpathAppender;
public DependencyLoader(DiscordSRV discordSRV, String[] paths) throws IOException {
this(discordSRV, fromPaths(discordSRV.dataDirectory(), paths));
}
public DependencyLoader(Path dataDirectory, Executor executor, ClasspathAppender classpathAppender, String[] paths) throws IOException {
this(executor, classpathAppender, fromPaths(dataDirectory, paths));
}
public DependencyLoader(DiscordSRV discordSRV, DependencyManager dependencyManager) {
this(discordSRV.scheduler().executor(), discordSRV.bootstrap().classpathAppender(), dependencyManager);
}
public DependencyLoader(Executor executor, ClasspathAppender classpathAppender, DependencyManager dependencyManager) {
this.dependencyManager = dependencyManager;
this.executor = executor;
this.classpathAppender = classpathAppender;
}
public DependencyManager getDependencyManager() {
return dependencyManager;
}
public IsolatedClassLoader loadIntoIsolated() throws IOException {
IsolatedClassLoader classLoader = new IsolatedClassLoader();
download(classLoader).join();
return classLoader;
}
public CompletableFuture<Void> download() {
return download(classpathAppender);
}
private CompletableFuture<Void> download(ClasspathAppender appender) {
return dependencyManager.downloadAll(executor, REPOSITORIES)
.thenCompose(v -> dependencyManager.relocateAll(executor))
.thenCompose(v -> dependencyManager.loadAll(executor, appender));
}
}
| 4,395 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
LuckPermsIntegration.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/integration/LuckPermsIntegration.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.integration;
import com.discordsrv.api.module.type.PermissionModule;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.exception.MessageException;
import com.discordsrv.common.future.util.CompletableFutureUtil;
import com.discordsrv.common.groupsync.GroupSyncModule;
import com.discordsrv.common.groupsync.enums.GroupSyncCause;
import com.discordsrv.common.module.type.PluginIntegration;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.context.ContextSet;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.ImmutableContextSet;
import net.luckperms.api.context.MutableContextSet;
import net.luckperms.api.event.EventSubscription;
import net.luckperms.api.event.LuckPermsEvent;
import net.luckperms.api.event.node.NodeAddEvent;
import net.luckperms.api.event.node.NodeClearEvent;
import net.luckperms.api.event.node.NodeRemoveEvent;
import net.luckperms.api.event.user.track.UserTrackEvent;
import net.luckperms.api.model.PermissionHolder;
import net.luckperms.api.model.data.DataMutateResult;
import net.luckperms.api.model.data.NodeMap;
import net.luckperms.api.model.group.Group;
import net.luckperms.api.model.user.User;
import net.luckperms.api.node.Node;
import net.luckperms.api.node.NodeType;
import net.luckperms.api.node.types.InheritanceNode;
import net.luckperms.api.query.QueryMode;
import net.luckperms.api.query.QueryOptions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class LuckPermsIntegration extends PluginIntegration<DiscordSRV> implements PermissionModule.All {
private LuckPerms luckPerms;
private final List<EventSubscription<?>> subscriptions = new ArrayList<>();
public LuckPermsIntegration(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public @NotNull String getIntegrationName() {
return "LuckPerms";
}
@Override
public boolean isEnabled() {
try {
Class.forName("net.luckperms.api.LuckPerms");
} catch (ClassNotFoundException e) {
return false;
}
return super.isEnabled();
}
@Override
public void enable() {
luckPerms = LuckPermsProvider.get();
subscribe(NodeAddEvent.class, this::onNodeAdd);
subscribe(NodeRemoveEvent.class, this::onNodeRemove);
subscribe(NodeClearEvent.class, this::onNodeClear);
subscribe(UserTrackEvent.class, this::onUserTrack);
}
private <E extends LuckPermsEvent> void subscribe(Class<E> clazz, Consumer<E> method) {
subscriptions.add(luckPerms.getEventBus().subscribe(clazz, method));
}
@Override
public void disable() {
subscriptions.forEach(EventSubscription::close);
subscriptions.clear();
luckPerms = null;
}
private CompletableFuture<User> user(UUID player) {
return luckPerms.getUserManager().loadUser(player);
}
@Override
public boolean supportsOffline() {
return true;
}
@Override
public Set<String> getDefaultServerContext() {
return luckPerms.getContextManager().getStaticContext().getValues(DefaultContextKeys.SERVER_KEY);
}
@Override
public CompletableFuture<Boolean> hasGroup(@NotNull UUID player, @NotNull String groupName, boolean includeInherited, @Nullable Set<String> serverContext) {
return user(player).thenApply(user -> {
MutableContextSet context = luckPerms.getContextManager().getStaticContext().mutableCopy();
if (serverContext != null) {
context.removeAll(DefaultContextKeys.SERVER_KEY);
if (isNotGlobalOnly(serverContext)) {
for (String ctx : serverContext) {
context.add(DefaultContextKeys.SERVER_KEY, ctx);
}
}
}
return (
includeInherited
? user.getInheritedGroups(QueryOptions.builder(QueryMode.CONTEXTUAL).context(context).build())
.stream()
.map(Group::getName)
: user.getNodes(NodeType.INHERITANCE)
.stream()
.filter(node -> context.isSatisfiedBy(node.getContexts()))
.map(InheritanceNode::getGroupName)
).anyMatch(name -> name.equalsIgnoreCase(groupName));
});
}
@Override
public CompletableFuture<Void> addGroup(@NotNull UUID player, @NotNull String groupName, @Nullable Set<String> serverContext) {
return groupMutate(player, groupName, serverContext, NodeMap::add);
}
@Override
public CompletableFuture<Void> removeGroup(@NotNull UUID player, @NotNull String groupName, @Nullable Set<String> serverContext) {
return groupMutate(player, groupName, serverContext, NodeMap::remove);
}
private CompletableFuture<Void> groupMutate(UUID player, String groupName, Set<String> serverContext, BiFunction<NodeMap, Node, DataMutateResult> function) {
Group group = luckPerms.getGroupManager().getGroup(groupName);
if (group == null) {
return CompletableFutureUtil.failed(new MessageException("Group does not exist"));
}
return user(player).thenCompose(user -> {
ContextSet contexts;
if (serverContext != null) {
if (isNotGlobalOnly(serverContext)) {
ImmutableContextSet.Builder builder = ImmutableContextSet.builder();
for (String ctx : serverContext) {
builder.add(DefaultContextKeys.SERVER_KEY, ctx);
}
contexts = builder.build();
} else {
contexts = ImmutableContextSet.empty();
}
} else {
MutableContextSet contextSet = MutableContextSet.create();
for (String value : getDefaultServerContext()) {
contextSet.add(DefaultContextKeys.SERVER_KEY, value);
}
contexts = contextSet;
}
InheritanceNode node = InheritanceNode.builder(group).context(contexts).build();
DataMutateResult result = function.apply(user.data(), node);
if (result != DataMutateResult.SUCCESS) {
return CompletableFutureUtil.failed(new MessageException(result.name()));
}
return luckPerms.getUserManager().saveUser(user);
});
}
private boolean isNotGlobalOnly(Set<String> context) {
return context.size() != 1 || !context.iterator().next().equals("global");
}
@Override
public CompletableFuture<Boolean> hasPermission(@NotNull UUID player, @NotNull String permission) {
return user(player).thenApply(
user -> user.getCachedData().getPermissionData().checkPermission(permission).asBoolean());
}
@Override
public CompletableFuture<String> getPrefix(@NotNull UUID player) {
return user(player).thenApply(user -> user.getCachedData().getMetaData().getPrefix());
}
@Override
public CompletableFuture<String> getSuffix(@NotNull UUID player) {
return user(player).thenApply(user -> user.getCachedData().getMetaData().getSuffix());
}
@Override
public CompletableFuture<String> getMeta(@NotNull UUID player, @NotNull String key) throws UnsupportedOperationException {
return user(player).thenApply(user -> user.getCachedData().getMetaData().getMetaValue(key));
}
private void onNodeAdd(NodeAddEvent event) {
nodeUpdate(event.getTarget(), event.getNode(), false);
}
private void onNodeRemove(NodeRemoveEvent event) {
nodeUpdate(event.getTarget(), event.getNode(), true);
}
private void onNodeClear(NodeClearEvent event) {
PermissionHolder target = event.getTarget();
for (Node node : event.getNodes()) {
nodeUpdate(target, node, true);
}
}
private void onUserTrack(UserTrackEvent event) {
User user = event.getUser();
event.getGroupFrom().ifPresent(group -> groupUpdate(user, group, Collections.emptySet(), true, true));
event.getGroupTo().ifPresent(group -> groupUpdate(user, group, Collections.emptySet(), false, true));
}
private void nodeUpdate(PermissionHolder holder, Node node, boolean remove) {
if (!(holder instanceof User) || node.getType() != NodeType.INHERITANCE) {
return;
}
InheritanceNode inheritanceNode = NodeType.INHERITANCE.cast(node);
String groupName = inheritanceNode.getGroupName();
Set<String> serverContext = inheritanceNode.getContexts().getValues(DefaultContextKeys.SERVER_KEY);
groupUpdate((User) holder, groupName, serverContext, remove, false);
}
private void groupUpdate(User user, String groupName, Set<String> serverContext, boolean remove, boolean track) {
GroupSyncModule module = discordSRV.getModule(GroupSyncModule.class);
if (module == null || !module.isEnabled()) {
return;
}
GroupSyncCause cause = track ? GroupSyncCause.LUCKPERMS_TRACK : GroupSyncCause.LUCKPERMS_NODE_CHANGE;
UUID uuid = user.getUniqueId();
if (remove) {
module.groupRemoved(uuid, groupName, serverContext, cause);
} else {
module.groupAdded(uuid, groupName, serverContext, cause);
}
}
@Override
public List<String> getGroups() {
return luckPerms.getGroupManager().getLoadedGroups().stream()
.map(Group::getName)
.collect(Collectors.toList());
}
}
| 10,814 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
HttpUtil.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/http/util/HttpUtil.java | package com.discordsrv.common.http.util;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.exception.MessageException;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
public final class HttpUtil {
private HttpUtil() {}
public static ResponseBody checkIfResponseSuccessful(Request request, Response response) throws IOException {
ResponseBody responseBody = response.body();
if (responseBody == null || !response.isSuccessful()) {
String responseString = responseBody == null
? "response body is null"
: StringUtils.substring(responseBody.string(), 0, 500);
throw new MessageException("Request to " + request.url().host() + " failed: " + response.code() + ": " + responseString);
}
return responseBody;
}
public static <T> CompletableFuture<T> readJson(DiscordSRV discordSRV, Request request, Class<T> type) {
CompletableFuture<T> future = new CompletableFuture<>();
discordSRV.scheduler().run(() -> {
try (Response response = discordSRV.httpClient().newCall(request).execute()) {
ResponseBody responseBody = checkIfResponseSuccessful(request, response);
T result = discordSRV.json().readValue(responseBody.byteStream(), type);
if (result == null) {
throw new MessageException("Response json cannot be parsed");
}
future.complete(result);
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
return future;
}
}
| 1,829 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Storage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/Storage.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage;
import com.discordsrv.common.linking.LinkStore;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
@Blocking
public interface Storage {
void initialize();
void close();
@Nullable
Long getUserId(@NotNull UUID player);
@Nullable
UUID getPlayerUUID(long userId);
void createLink(@NotNull UUID player, long userId);
void removeLink(@NotNull UUID player, long userId);
/**
* Inserts the given code for the given player, removing any existing code if any, with a {@link LinkStore#LINKING_CODE_EXPIRY_TIME} expiry.
*/
void storeLinkingCode(@NotNull UUID player, String code);
UUID getLinkingCode(String code);
void removeLinkingCode(@NotNull UUID player);
int getLinkedAccountCount();
}
| 1,721 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
StorageType.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/StorageType.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.storage.impl.MemoryStorage;
import com.discordsrv.common.storage.impl.sql.file.H2Storage;
import com.discordsrv.common.storage.impl.sql.hikari.MariaDBStorage;
import com.discordsrv.common.storage.impl.sql.hikari.MySQLStorage;
import java.util.function.Function;
public enum StorageType {
H2(H2Storage::new, "H2", false),
MYSQL(MySQLStorage::new, "MySQL", true),
MARIADB(MariaDBStorage::new, "MariaDB", true),
MEMORY(discordSRV -> new MemoryStorage(), "Memory", false);
private final Function<DiscordSRV, Storage> storageFunction;
private final String prettyName;
private final boolean hikari;
StorageType(Function<DiscordSRV, Storage> storageFunction, String prettyName, boolean hikari) {
this.storageFunction = storageFunction;
this.prettyName = prettyName;
this.hikari = hikari;
}
public Function<DiscordSRV, Storage> storageFunction() {
return storageFunction;
}
public String prettyName() {
return prettyName;
}
public boolean hikari() {
return hikari;
}
}
| 2,017 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
package-info.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/package-info.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage.impl;
| 874 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MemoryStorage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/MemoryStorage.java | package com.discordsrv.common.storage.impl;
import com.discordsrv.common.storage.Storage;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
public class MemoryStorage implements Storage {
public static String IDENTIFIER = UUID.randomUUID().toString();
private final BidiMap<UUID, Long> linkedAccounts = new DualHashBidiMap<>();
private final BidiMap<UUID, String> linkingCodes = new DualHashBidiMap<>();
public MemoryStorage() {}
@Override
public void initialize() {}
@Override
public void close() {
linkedAccounts.clear();
}
@Override
public @Nullable Long getUserId(@NotNull UUID player) {
return linkedAccounts.get(player);
}
@Override
public @Nullable UUID getPlayerUUID(long userId) {
return linkedAccounts.getKey(userId);
}
@Override
public void createLink(@NotNull UUID player, long userId) {
linkedAccounts.put(player, userId);
}
@Override
public void removeLink(@NotNull UUID player, long userId) {
linkedAccounts.remove(player, userId);
}
@Override
public void storeLinkingCode(@NotNull UUID player, String code) {
linkingCodes.put(player, code);
}
@Override
public UUID getLinkingCode(String code) {
return linkingCodes.getKey(code);
}
@Override
public void removeLinkingCode(@NotNull UUID player) {
linkingCodes.remove(player);
}
@Override
public int getLinkedAccountCount() {
return linkedAccounts.size();
}
}
| 1,713 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
SQLStorage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/sql/SQLStorage.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage.impl.sql;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.exception.StorageException;
import com.discordsrv.common.function.CheckedConsumer;
import com.discordsrv.common.function.CheckedFunction;
import com.discordsrv.common.linking.LinkStore;
import com.discordsrv.common.storage.Storage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import java.util.Calendar;
import java.util.UUID;
public abstract class SQLStorage implements Storage {
protected static final String LINKED_ACCOUNTS_TABLE_NAME = "linked_accounts";
protected static final String LINKING_CODES_TABLE_NAME = "linking_codes";
protected final DiscordSRV discordSRV;
public SQLStorage(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
}
public abstract Connection getConnection();
public abstract boolean isAutoCloseConnections();
public abstract void createTables(Connection connection, String tablePrefix) throws SQLException;
private void useConnection(CheckedConsumer<Connection> connectionConsumer) throws StorageException {
useConnection(connection -> {
connectionConsumer.accept(connection);
return null;
});
}
private <T> T useConnection(CheckedFunction<Connection, T> connectionFunction) throws StorageException {
try {
if (isAutoCloseConnections()) {
try (Connection connection = getConnection()) {
return connectionFunction.apply(connection);
}
} else {
return connectionFunction.apply(getConnection());
}
} catch (Throwable e) {
throw new StorageException(e);
}
}
private void exceptEffectedRows(int rows, int expect) {
if (rows != expect) {
throw new StorageException("Excepted to effect " + expect + " rows, actually effected " + rows);
}
}
protected String tablePrefix() {
String tablePrefix = discordSRV.connectionConfig().storage.sqlTablePrefix;
if (!tablePrefix.matches("[\\w_-]*")) {
throw new IllegalStateException("SQL Table prefix may not contain non alphanumeric characters, dashes and underscores!");
}
return tablePrefix;
}
@Override
public void initialize() {
useConnection((CheckedConsumer<Connection>) connection -> createTables(
connection,
tablePrefix()
));
}
@Override
public @Nullable Long getUserId(@NotNull UUID player) {
return useConnection(connection -> {
try (PreparedStatement statement = connection.prepareStatement("select USER_ID from " + tablePrefix() + LINKED_ACCOUNTS_TABLE_NAME + " where PLAYER_UUID = ?;")) {
statement.setString(1, player.toString());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getLong("USER_ID");
}
}
}
return null;
});
}
@Override
public @Nullable UUID getPlayerUUID(long userId) {
return useConnection(connection -> {
try (PreparedStatement statement = connection.prepareStatement("select PLAYER_UUID from " + tablePrefix() + LINKED_ACCOUNTS_TABLE_NAME + " where USER_ID = ?;")) {
statement.setLong(1, userId);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
String value = resultSet.getString("PLAYER_UUID");
if (value == null) {
return null;
}
return UUID.fromString(value);
}
}
}
return null;
});
}
@Override
public void createLink(@NotNull UUID player, long userId) {
useConnection(connection -> {
try (PreparedStatement statement = connection.prepareStatement("insert into " + tablePrefix() + LINKED_ACCOUNTS_TABLE_NAME + " (PLAYER_UUID, USER_ID) values (?, ?);")) {
statement.setString(1, player.toString());
statement.setLong(2, userId);
exceptEffectedRows(statement.executeUpdate(), 1);
}
});
}
@Override
public void removeLink(@NotNull UUID player, long userId) {
useConnection(connection -> {
try (PreparedStatement statement = connection.prepareStatement("delete from " + tablePrefix() + LINKED_ACCOUNTS_TABLE_NAME + " where PLAYER_UUID = ?;")) {
statement.setString(1, player.toString());
exceptEffectedRows(statement.executeUpdate(), 1);
}
});
}
@Override
public int getLinkedAccountCount() {
return useConnection(connection -> {
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery("select count(*) from " + tablePrefix() + LINKED_ACCOUNTS_TABLE_NAME + ";")) {
if (resultSet.next()) {
return resultSet.getInt(1);
}
}
}
return 0;
});
}
private long getTimeMS() {
return Calendar.getInstance().getTimeInMillis();
}
@Override
public UUID getLinkingCode(String code) {
return useConnection(connection -> {
// Clean expired codes
try (PreparedStatement statement = connection.prepareStatement("delete from " + tablePrefix() + LINKING_CODES_TABLE_NAME + " where EXPIRY < ?;")) {
statement.setLong(1, getTimeMS());
statement.executeUpdate();
}
// Get the uuid for the code
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery("select top 1 PLAYERUUID from " + tablePrefix() + LINKING_CODES_TABLE_NAME + ";")) {
if (resultSet.next()) {
return UUID.fromString(resultSet.getString("PLAYERUUID"));
}
}
}
return null;
});
}
@Override
public void removeLinkingCode(@NotNull UUID player) {
useConnection(connection -> {
try (PreparedStatement statement = connection.prepareStatement("delete from " + tablePrefix() + LINKING_CODES_TABLE_NAME + " WHERE PLAYERUUID = ?")) {
statement.setString(1, player.toString());
statement.executeUpdate();
}
});
}
@Override
public void storeLinkingCode(@NotNull UUID player, String code) {
useConnection(connection -> {
// Remove existing code
try (PreparedStatement statement = connection.prepareStatement("delete from " + tablePrefix() + LINKING_CODES_TABLE_NAME + " where PLAYERUUID = ?")) {
statement.setString(1, player.toString());
statement.executeUpdate();
}
// Insert new code
try (PreparedStatement statement = connection.prepareStatement("insert into " + tablePrefix() + LINKING_CODES_TABLE_NAME + " (PLAYERUUID, CODE, EXPIRY)")) {
statement.setString(1, player.toString());
statement.setString(2, code);
statement.setLong(3, getTimeMS() + LinkStore.LINKING_CODE_EXPIRY_TIME.toMillis());
exceptEffectedRows(statement.executeUpdate(), 1);
}
});
}
}
| 8,615 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MariaDBStorage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/sql/hikari/MariaDBStorage.java | package com.discordsrv.common.storage.impl.sql.hikari;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.connection.StorageConfig;
import com.discordsrv.common.exception.StorageException;
import com.zaxxer.hikari.HikariConfig;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class MariaDBStorage extends HikariStorage {
public MariaDBStorage(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public void close() {
super.close();
}
@Override
public void initialize() {
try {
discordSRV.dependencyManager().mariadb().download().join();
super.initialize();
} catch (IOException e) {
throw new StorageException(e);
}
}
@Override
public void createTables(Connection connection, String tablePrefix) throws SQLException {
// Same table creation language
MySQLStorage.createTablesMySQL(connection, tablePrefix);
}
@Override
protected void applyConfiguration(HikariConfig config, StorageConfig storageConfig) {
String address = storageConfig.remote.databaseAddress;
if (!address.contains(":")) {
address += ":3306";
}
config.setDriverClassName("org.mariadb.jdbc.Driver");
config.setJdbcUrl("jdbc:mariadb://" + address + "/" + storageConfig.remote.databaseName);
}
}
| 1,444 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
MySQLStorage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/sql/hikari/MySQLStorage.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage.impl.sql.hikari;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.connection.StorageConfig;
import com.discordsrv.common.exception.StorageException;
import com.zaxxer.hikari.HikariConfig;
import dev.vankka.dependencydownload.classloader.IsolatedClassLoader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
public class MySQLStorage extends HikariStorage {
private IsolatedClassLoader classLoader;
public MySQLStorage(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public void close() {
super.close();
if (classLoader != null) {
try {
classLoader.close();
} catch (IOException e) {
discordSRV.logger().error("Failed to close isolated classloader", e);
}
}
}
public static void createTablesMySQL(Connection connection, String tablePrefix) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.execute(
"create table if not exists " + tablePrefix + LINKED_ACCOUNTS_TABLE_NAME + " "
+ "(ID int not null auto_increment, "
+ "PLAYER_UUID varchar(36), "
+ "USER_ID bigint, "
+ "constraint LINKED_ACCOUNTS_PK primary key (ID)"
+ ")");
}
try (Statement statement = connection.createStatement()) {
statement.execute(
"create table if not exists " + tablePrefix + LINKING_CODES_TABLE_NAME + " "
+ "(PLAYERUUID varchar(36),"
+ "CODE varchar(8),"
+ "EXPIRY bigint,"
+ "constraint LINKING_CODES_PK primary key (PLAYERUUID)"
+ ")");
}
}
@Override
public void createTables(Connection connection, String tablePrefix) throws SQLException {
createTablesMySQL(connection, tablePrefix);
}
@Override
public void initialize() {
try {
initializeWithContext(classLoader = discordSRV.dependencyManager().mysql().loadIntoIsolated());
} catch (IOException e) {
throw new StorageException(e);
}
}
@Override
protected void applyConfiguration(HikariConfig config, StorageConfig storageConfig) {
String address = storageConfig.remote.databaseAddress;
if (!address.contains(":")) {
address += ":3306";
}
config.setDriverClassName("com.mysql.cj.jdbc.NonRegisteringDriver");
config.setJdbcUrl("jdbc:mysql://" + address + "/" + storageConfig.remote.databaseName);
for (Map.Entry<Object, Object> entry : storageConfig.getDriverProperties().entrySet()) {
config.addDataSourceProperty((String) entry.getKey(), entry.getValue());
}
// https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
config.addDataSourceProperty("prepStmtCacheSize", 250);
config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
config.addDataSourceProperty("cachePrepStmts", true);
config.addDataSourceProperty("useServerPrepStmts", true);
config.addDataSourceProperty("cacheServerConfiguration", true);
config.addDataSourceProperty("useLocalSessionState", true);
config.addDataSourceProperty("rewriteBatchedStatements", true);
config.addDataSourceProperty("maintainTimeStats", false);
}
}
| 4,536 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
HikariStorage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/sql/hikari/HikariStorage.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage.impl.sql.hikari;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.connection.StorageConfig;
import com.discordsrv.common.exception.StorageException;
import com.discordsrv.common.storage.impl.sql.SQLStorage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class HikariStorage extends SQLStorage {
private HikariDataSource hikariDataSource;
public HikariStorage(DiscordSRV discordSRV) {
super(discordSRV);
}
protected abstract void applyConfiguration(HikariConfig config, StorageConfig storageConfig);
protected void initializeWithContext(ClassLoader classLoader) {
Thread currentThread = Thread.currentThread();
ClassLoader originalContext = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(classLoader);
initializeInternal();
} finally {
currentThread.setContextClassLoader(originalContext);
}
}
private void initializeInternal() {
StorageConfig storageConfig = discordSRV.connectionConfig().storage;
StorageConfig.Remote remoteConfig = storageConfig.remote;
StorageConfig.Pool poolConfig = remoteConfig.poolOptions;
HikariConfig config = new HikariConfig();
config.setPoolName("discordsrv-pool");
config.setUsername(remoteConfig.username);
config.setPassword(remoteConfig.password);
config.setMinimumIdle(poolConfig.minimumPoolSize);
config.setMaximumPoolSize(poolConfig.maximumPoolSize);
config.setMaxLifetime(poolConfig.maximumLifetime);
config.setKeepaliveTime(poolConfig.keepaliveTime);
applyConfiguration(config, storageConfig);
try {
hikariDataSource = new HikariDataSource(config);
} catch (RuntimeException e) {
// Avoid running into runtime ClassNotFoundException by not using this as the catch
if (e instanceof HikariPool.PoolInitializationException) {
// Already logged by Hikari, so we'll throw an empty exception
throw new StorageException((Throwable) null);
}
throw e;
}
super.initialize();
}
@Override
public void initialize() {
initializeInternal();
}
@Override
public void close() {
if (hikariDataSource != null) {
hikariDataSource.close();
}
}
@Override
public Connection getConnection() {
try {
return hikariDataSource.getConnection();
} catch (SQLException e) {
throw new StorageException(e);
}
}
@Override
public boolean isAutoCloseConnections() {
return true;
}
}
| 3,755 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
H2Storage.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/storage/impl/sql/file/H2Storage.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.storage.impl.sql.file;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.connection.StorageConfig;
import com.discordsrv.common.exception.StorageException;
import com.discordsrv.common.storage.impl.sql.SQLStorage;
import dev.vankka.dependencydownload.classloader.IsolatedClassLoader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class H2Storage extends SQLStorage {
private IsolatedClassLoader classLoader;
private Connection connection;
public H2Storage(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public void initialize() {
try {
classLoader = discordSRV.dependencyManager().h2().loadIntoIsolated();
} catch (IOException e) {
throw new StorageException(e);
}
StorageConfig storageConfig = discordSRV.connectionConfig().storage;
try {
Class<?> clazz = classLoader.loadClass("org.h2.jdbc.JdbcConnection");
Constructor<?> constructor = clazz.getConstructor(
String.class, // url
Properties.class, // info
String.class, // username
Object.class, // password
boolean.class // forbidCreation
);
connection = (Connection) constructor.newInstance(
"jdbc:h2:" + discordSRV.dataDirectory().resolve("h2-database").toAbsolutePath(),
storageConfig.getDriverProperties(),
null,
null,
false
);
} catch (ReflectiveOperationException e) {
throw new StorageException(e);
}
super.initialize();
}
@Override
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException ignored) {}
}
if (classLoader != null) {
try {
classLoader.close();
} catch (IOException e) {
discordSRV.logger().error("Failed to close isolated classloader", e);
}
}
}
@Override
public synchronized Connection getConnection() {
return connection;
}
@Override
public boolean isAutoCloseConnections() {
return false;
}
@Override
public void createTables(Connection connection, String tablePrefix) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.execute(
"create table if not exists " + tablePrefix + LINKED_ACCOUNTS_TABLE_NAME + " "
+ "(ID int not null auto_increment, "
+ "PLAYER_UUID varchar(36), "
+ "USER_ID bigint, "
+ "constraint LINKED_ACCOUNTS_PK primary key (ID)"
+ ")");
}
try (Statement statement = connection.createStatement()) {
statement.execute(
"create table if not exists " + tablePrefix + LINKING_CODES_TABLE_NAME + " "
+ "(PLAYERUUID varchar(36), "
+ "CODE varchar(8), "
+ "EXPIRY bigint, "
+ "constraint LINKING_CODES_PK primary key (PLAYERUUID)"
+ ")");
}
}
}
| 4,437 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/GameCommandModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game;
import com.discordsrv.api.DiscordSRVApi;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.commands.LinkInitCommand;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.commands.DiscordSRVGameCommand;
import com.discordsrv.common.command.game.handler.ICommandHandler;
import com.discordsrv.common.config.main.GameCommandConfig;
import com.discordsrv.common.module.type.AbstractModule;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
public class GameCommandModule extends AbstractModule<DiscordSRV> {
private final Set<GameCommand> commands = new HashSet<>();
private final GameCommand primaryCommand;
private final GameCommand discordAlias;
private final GameCommand linkCommand;
public GameCommandModule(DiscordSRV discordSRV) {
super(discordSRV);
this.primaryCommand = DiscordSRVGameCommand.get(discordSRV, "discordsrv");
this.discordAlias = DiscordSRVGameCommand.get(discordSRV, "discord");
this.linkCommand = LinkInitCommand.getGame(discordSRV);
registerCommand(primaryCommand);
}
@Override
public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) {
GameCommandConfig config = discordSRV.config().gameCommand;
if (config == null) {
return;
}
registerCommand(primaryCommand);
if (config.useDiscordCommand) {
registerCommand(discordAlias);
}
if (config.useLinkAlias) {
registerCommand(linkCommand);
}
}
private void registerCommand(GameCommand command) {
ICommandHandler handler = discordSRV.commandHandler();
if (handler == null) {
return;
}
if (!commands.add(command)) {
return;
}
handler.registerCommand(command);
}
}
| 2,811 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandExecutionHelper.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/GameCommandExecutionHelper.java | package com.discordsrv.common.command.game;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public interface GameCommandExecutionHelper {
CompletableFuture<List<String>> suggestCommands(List<String> parts);
List<String> getAliases(String command);
boolean isSameCommand(String command1, String command2);
}
| 345 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandExecutor.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/abstraction/GameCommandExecutor.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.abstraction;
import com.discordsrv.common.command.game.sender.ICommandSender;
@FunctionalInterface
public interface GameCommandExecutor {
void execute(ICommandSender sender, GameCommandArguments arguments, String label);
}
| 1,103 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandArguments.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/abstraction/GameCommandArguments.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.abstraction;
@FunctionalInterface
public interface GameCommandArguments {
<T> T get(String label, Class<T> type);
default boolean has(String label) {
try {
return get(label, Object.class) != null;
} catch (Throwable ignored) {
return false;
}
}
default String getString(String label) {
return get(label, String.class);
}
default Integer getInt(String label) {
return get(label, Integer.class);
}
}
| 1,368 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/abstraction/GameCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.abstraction;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.function.CheckedFunction;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GameCommand {
private static final GameCommandSuggester BOOLEANS_SUGGESTER = (player, previous, current) -> {
if (current.isEmpty()) {
return Arrays.asList("true", "false");
} else if ("true".startsWith(current)) {
return Collections.singletonList("true");
} else if ("false".startsWith(current)) {
return Collections.singletonList("false");
} else {
return Collections.emptyList();
}
};
public static GameCommand literal(String label) {
return new GameCommand(label, ArgumentType.LITERAL);
}
public static GameCommand booleanArgument(String label) {
return new GameCommand(label, ArgumentType.BOOLEAN).suggester(BOOLEANS_SUGGESTER);
}
public static GameCommand doubleArgument(String label) {
return new GameCommand(label, ArgumentType.DOUBLE);
}
public static GameCommand floatArgument(String label) {
return new GameCommand(label, ArgumentType.FLOAT);
}
public static GameCommand integerArgument(String label) {
return new GameCommand(label, ArgumentType.INTEGER);
}
public static GameCommand longArgument(String label) {
return new GameCommand(label, ArgumentType.LONG);
}
public static GameCommand string(String label) {
return new GameCommand(label, ArgumentType.STRING);
}
public static GameCommand stringWord(String label) {
return new GameCommand(label, ArgumentType.STRING_WORD);
}
public static GameCommand stringGreedy(String label) {
return new GameCommand(label, ArgumentType.STRING_GREEDY);
}
private final ExecutorProxy executorProxy = new ExecutorProxy();
private final SuggesterProxy suggesterProxy = new SuggesterProxy();
// Command info
private GameCommand parent = null;
private final String label;
private final ArgumentType argumentType;
private final List<GameCommand> children;
private GameCommand redirection = null;
// Permission
private String requiredPermission;
private Component noPermissionMessage = null;
// Executor & suggestor
private GameCommandExecutor commandExecutor = null;
private GameCommandSuggester commandSuggester = null;
// Argument type bounds
private double maxValue = Double.MAX_VALUE;
private double minValue = Double.MIN_VALUE;
private GameCommand(String label, ArgumentType argumentType) {
this.label = label;
this.argumentType = argumentType;
this.children = new ArrayList<>();
}
private GameCommand(GameCommand original) {
this.parent = original.parent;
this.label = original.label;
this.argumentType = original.argumentType;
this.children = original.children;
this.redirection = original.redirection;
this.requiredPermission = original.requiredPermission;
this.noPermissionMessage = original.noPermissionMessage;
this.commandExecutor = original.commandExecutor;
this.commandSuggester = original.commandSuggester;
this.maxValue = original.maxValue;
this.minValue = original.minValue;
}
public String getLabel() {
return label;
}
public ArgumentType getArgumentType() {
return argumentType;
}
/**
* Adds a sub command. You can only have multiple literals (with unique labels) or a single non-literal one.
*/
public GameCommand then(GameCommand child) {
if (redirection != null) {
throw new IllegalStateException("Cannot add children to a redirected node");
}
for (GameCommand builder : children) {
if (builder.getArgumentType() == ArgumentType.LITERAL
&& child.getArgumentType() == ArgumentType.LITERAL
&& builder.getLabel().equals(child.getLabel())) {
throw new IllegalArgumentException("Duplicate literal with label \"" + child.label + "\"");
}
if (child.getArgumentType() == ArgumentType.LITERAL && builder.getArgumentType() != ArgumentType.LITERAL) {
throw new IllegalStateException("A non-literal is already present, cannot add literal");
}
if (child.getArgumentType() != ArgumentType.LITERAL) {
throw new IllegalStateException("Cannot add non-literal when another child is already present");
}
}
if (child.getNoPermissionMessage() == null && noPermissionMessage != null) {
child.noPermissionMessage(noPermissionMessage);
}
child.parent = this;
this.children.add(child);
return this;
}
public List<GameCommand> getChildren() {
return children;
}
public GameCommand redirect(GameCommand redirection) {
if (!children.isEmpty()) {
throw new IllegalStateException("Cannot redirect a node with children");
}
if (requiredPermission != null) {
throw new IllegalStateException("Cannot redirect a node with a required permission");
}
this.redirection = redirection;
return this;
}
public GameCommand getRedirection() {
return redirection;
}
public GameCommand requiredPermission(Permission permission) {
return requiredPermission(permission.permission());
}
public GameCommand requiredPermission(String permission) {
if (redirection != null) {
throw new IllegalStateException("Cannot required permissions on a node with a redirection");
}
this.requiredPermission = permission;
return this;
}
public String getRequiredPermission() {
if (redirection != null) {
return redirection.getRequiredPermission();
}
return requiredPermission;
}
public GameCommand noPermissionMessage(Component noPermissionMessage) {
this.noPermissionMessage = noPermissionMessage;
return this;
}
public Component getNoPermissionMessage() {
return noPermissionMessage;
}
public GameCommand executor(GameCommandExecutor executor) {
this.commandExecutor = executor;
return this;
}
public GameCommandExecutor getExecutor() {
return executorProxy;
}
/**
* Cannot be used with {@link #literal(String)}.
*/
public GameCommand suggester(GameCommandSuggester suggester) {
if (argumentType == ArgumentType.LITERAL) {
throw new IllegalArgumentException("Cannot use on argument type literal");
}
this.commandSuggester = suggester;
return this;
}
public GameCommandSuggester getSuggester() {
return suggesterProxy;
}
/**
* Can only be used on number argument types.
*/
public GameCommand minValue(double minValue) {
mustBeNumber();
this.minValue = minValue;
return this;
}
public double getMinValue() {
return minValue;
}
/**
* Can only be used on number argument types.
*/
public GameCommand maxValue(double maxValue) {
mustBeNumber();
this.maxValue = maxValue;
return this;
}
public double getMaxValue() {
return maxValue;
}
private void mustBeNumber() {
if (!argumentType.number()) {
throw new IllegalArgumentException("Cannot be used on this argument type");
}
}
public boolean hasPermission(ICommandSender sender) {
String requiredPermission = getRequiredPermission();
return requiredPermission == null || sender.hasPermission(requiredPermission);
}
public void sendNoPermission(ICommandSender sender) {
sender.sendMessage(noPermissionMessage != null
? noPermissionMessage
: Component.text("No permission", NamedTextColor.RED));
}
public ArgumentResult checkArgument(String argument) {
switch (getArgumentType()) {
case LITERAL: return ArgumentResult.fromBoolean(argument.equals(getLabel()));
case STRING: {
if (argument.startsWith("\"")) {
boolean single = argument.length() == 1;
if (argument.endsWith("\"") && !single) {
return new ArgumentResult(argument.substring(1, argument.length() - 1), MatchResult.MATCHES);
}
return new ArgumentResult(single ? "" : argument.substring(1), single ? MatchResult.END : MatchResult.CONTINUE);
}
if (argument.endsWith("\"")) {
return new ArgumentResult(argument.substring(0, argument.length() - 1), MatchResult.END);
}
return new ArgumentResult(argument, MatchResult.MATCHES);
}
case STRING_GREEDY: return new ArgumentResult(argument, GameCommand.MatchResult.CONTINUE);
default: {
try {
return new ArgumentResult(getArgumentType().function().apply(argument), MatchResult.MATCHES);
} catch (Throwable ignored) {
return ArgumentResult.NO_MATCH;
}
}
}
}
public String getArgumentLabel() {
if (argumentType == ArgumentType.LITERAL) {
return label;
} else {
return "<" + label + ">";
}
}
public Component describe() {
StringBuilder stringBuilder = new StringBuilder();
GameCommand current = this;
while (current != null) {
stringBuilder.insert(0, current.getArgumentLabel() + " ");
current = current.parent;
}
String command = "/" + stringBuilder.substring(0, stringBuilder.length() - 1);
return Component.text(command, NamedTextColor.AQUA);
}
public void sendCommandInstructions(ICommandSender sender) {
if (children.isEmpty()) {
throw new IllegalStateException("No children");
}
TextComponent.Builder builder = Component.text();
builder.append(describe().color(NamedTextColor.GRAY).append(Component.text(" available subcommands:")));
boolean anyAvailable = false;
for (GameCommand child : children) {
if (!child.hasPermission(sender)) {
continue;
}
anyAvailable = true;
builder.append(Component.newline()).append(child.describe());
}
if (!anyAvailable) {
builder.append(Component.newline())
.append(Component.text("No available subcommands", NamedTextColor.RED));
}
sender.sendMessage(builder.build());
}
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException", "MethodDoesntCallSuperMethod"})
@Override
protected GameCommand clone() {
return new GameCommand(this);
}
public static class ArgumentResult {
public static final ArgumentResult EMPTY_MATCH = new ArgumentResult(MatchResult.MATCHES);
public static final ArgumentResult NO_MATCH = new ArgumentResult(MatchResult.NO_MATCH);
public static ArgumentResult fromBoolean(boolean value) {
return value ? EMPTY_MATCH : NO_MATCH;
}
private final Object value;
private final MatchResult result;
private ArgumentResult(MatchResult result) {
this(null, result);
}
public ArgumentResult(Object value, MatchResult result) {
this.value = value;
this.result = result;
}
public Object value() {
return value;
}
public MatchResult result() {
return result;
}
}
public enum MatchResult {
MATCHES,
CONTINUE,
END,
NO_MATCH
}
public enum ArgumentType {
LITERAL(),
BOOLEAN(false, input -> {
boolean value;
if ((value = input.equals("true")) || input.equals("false")) {
return value;
}
throw new IllegalArgumentException();
}),
DOUBLE(true, Double::parseDouble),
FLOAT(true, Float::parseFloat),
INTEGER(true, Integer::parseInt),
LONG(true, Long::parseLong),
STRING_WORD(false, input -> input),
STRING(false, true),
STRING_GREEDY(false, true);
private final boolean number;
private final boolean multi;
private final CheckedFunction<String, Object> function;
ArgumentType() {
this(false, null);
}
ArgumentType(boolean number, CheckedFunction<String, Object> function) {
this(number, false, function);
}
ArgumentType(boolean number, boolean multi) {
this(number, multi, null);
}
ArgumentType(boolean number, boolean multi, CheckedFunction<String, Object> function) {
this.number = number;
this.multi = multi;
this.function = function;
}
public boolean number() {
return number;
}
public boolean multi() {
return multi;
}
public CheckedFunction<String, Object> function() {
return function;
}
}
private class ExecutorProxy implements GameCommandExecutor {
@Override
public void execute(ICommandSender sender, GameCommandArguments arguments, String label) {
if (!hasPermission(sender)) {
sendNoPermission(sender);
return;
}
if (commandExecutor != null) {
commandExecutor.execute(sender, arguments, label);
} else if (!children.isEmpty()) {
sendCommandInstructions(sender);
} else {
throw new IllegalStateException("Command (" + GameCommand.this + ") doesn't have children and has no executor");
}
}
}
private class SuggesterProxy implements GameCommandSuggester {
@Override
public List<String> suggestValues(
ICommandSender sender,
GameCommandArguments previousArguments,
String currentInput
) {
if (!hasPermission(sender)) {
return Collections.emptyList();
}
if (commandSuggester != null) {
return commandSuggester.suggestValues(sender, previousArguments, currentInput);
} else {
return Collections.emptyList();
}
}
}
}
| 16,046 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandSuggester.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/abstraction/GameCommandSuggester.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.abstraction;
import com.discordsrv.common.command.game.sender.ICommandSender;
import java.util.List;
@FunctionalInterface
public interface GameCommandSuggester {
List<String> suggestValues(ICommandSender sender, GameCommandArguments previousArguments, String currentInput);
}
| 1,158 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ICommandHandler.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/handler/ICommandHandler.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.handler;
import com.discordsrv.common.command.game.abstraction.GameCommand;
public interface ICommandHandler {
void registerCommand(GameCommand command);
}
| 1,036 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
BasicCommandHandler.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/handler/BasicCommandHandler.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.handler;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.sender.ICommandSender;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
public class BasicCommandHandler implements ICommandHandler {
private final Map<String, GameCommand> commands = new HashMap<>();
@Override
public void registerCommand(GameCommand command) {
commands.put(command.getLabel(), command);
}
private GameCommand processCommand(
GameCommand command,
List<String> arguments,
Arguments argumentValues,
BiConsumer<GameCommand, Arguments> tooManyArguments,
BiConsumer<GameCommand, Arguments> unclosedQuote,
List<String> literalOptions
) {
GameCommand redirection = command.getRedirection();
if (redirection != null) {
command = redirection;
}
if (!arguments.isEmpty()) {
List<String> currentOptions = new ArrayList<>();
for (GameCommand child : command.getChildren()) {
if (child.getArgumentType() == GameCommand.ArgumentType.LITERAL) {
currentOptions.add(child.getLabel());
}
GameCommand.ArgumentResult result = child.checkArgument(arguments.get(0));
GameCommand.MatchResult matchResult = result.result();
if (matchResult == GameCommand.MatchResult.NO_MATCH) {
continue;
}
arguments.remove(0);
Object value;
if (child.getArgumentType().multi()) {
StringBuilder content = new StringBuilder((String) result.value());
if (matchResult == GameCommand.MatchResult.END) {
// Premature end
if (unclosedQuote != null) {
unclosedQuote.accept(command, argumentValues);
}
return unclosedQuote == null ? command : null;
}
boolean stringStart = matchResult == GameCommand.MatchResult.CONTINUE;
while (stringStart && !arguments.isEmpty()) {
result = child.checkArgument(arguments.remove(0));
Object resultValue = result.value();
content.append(' ').append(resultValue != null ? resultValue : "");
matchResult = result.result();
if (matchResult == GameCommand.MatchResult.END) {
stringStart = false;
}
}
if (stringStart && child.getArgumentType() == GameCommand.ArgumentType.STRING) {
// Unclosed quote
if (unclosedQuote != null) {
unclosedQuote.accept(command, argumentValues);
} else {
argumentValues.put(child.getLabel(), "\"" + content);
}
return unclosedQuote == null ? child : null;
}
value = content.toString();
} else {
value = result.value();
}
argumentValues.put(child.getLabel(), value);
return processCommand(child, arguments, argumentValues, tooManyArguments, unclosedQuote, literalOptions);
}
if (literalOptions != null) {
literalOptions.addAll(currentOptions);
return command;
}
}
if (!arguments.isEmpty() && tooManyArguments != null) {
tooManyArguments.accept(command, argumentValues);
return null;
}
return command;
}
private <T> T useCommand(
String command,
List<String> arguments,
BiConsumer<GameCommand, Arguments> tooManyArguments,
BiConsumer<GameCommand, Arguments> unclosedQuote,
BiFunction<GameCommand, Arguments, T> function,
List<String> literalOptions
) {
command = command.substring(command.lastIndexOf(':') + 1);
GameCommand commandBuilder = commands.get(command);
if (commandBuilder == null) {
return null;
}
Arguments args = new Arguments();
GameCommand subCommand = processCommand(commandBuilder, new ArrayList<>(arguments), args, tooManyArguments, unclosedQuote, literalOptions);
if (subCommand == null) {
return null;
}
return function.apply(subCommand, args);
}
public void execute(ICommandSender sender, String command, List<String> arguments) {
useCommand(
command,
arguments,
(cmd, args) -> {
if (!cmd.hasPermission(sender)) {
cmd.sendNoPermission(sender);
return;
}
error(sender, command, arguments, args, "Incorrect argument for command");
},
(cmd, args) -> {
if (!cmd.hasPermission(sender)) {
cmd.sendNoPermission(sender);
return;
}
error(sender, command, arguments, args, "Unclosed quoted string");
},
(cmd, args) -> {
cmd.getExecutor().execute(sender, args, command);
return null;
},
null);
}
private void error(ICommandSender sender, String command, List<String> arguments, Arguments args, String title) {
// Mimic brigadier behaviour (en-US)
StringBuilder builder = new StringBuilder(command);
for (Object value : args.getValues().values()) {
builder.append(" ").append(value);
}
int length = builder.length();
String pre = length >= 10 ? "..." + builder.substring(length - 9, length) : builder.toString();
sender.sendMessage(
Component.text()
.append(Component.text(title, NamedTextColor.RED))
.append(Component.newline())
.append(Component.text(pre + " ", NamedTextColor.GRAY))
.append(Component.text(String.join(" ", arguments), NamedTextColor.RED, TextDecoration.UNDERLINED))
.append(Component.text("<--[HERE]", NamedTextColor.RED, TextDecoration.ITALIC))
);
}
public List<String> suggest(ICommandSender sender, String command, List<String> arguments) {
List<String> suggestions = new ArrayList<>();
return useCommand(
command,
arguments,
null,
null,
(cmd, args) -> {
suggestions.addAll(
cmd.getSuggester().suggestValues(sender, args, String.valueOf(args.get(cmd.getLabel(), Object.class)))
.stream()
.map(value -> value.substring(value.lastIndexOf(' ') + 1))
.collect(Collectors.toList())
);
return suggestions;
},
suggestions
);
}
private static class Arguments implements GameCommandArguments {
private final Map<String, Object> values = new LinkedHashMap<>();
@SuppressWarnings("unchecked")
@Override
public <T> T get(String label, Class<T> type) {
return (T) values.get(label);
}
public void put(String label, Object value) {
values.put(label, value);
}
public Map<String, Object> getValues() {
return values;
}
@Override
public String toString() {
return "Arguments{" +
"values=" + values +
'}';
}
}
}
| 9,354 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
BrigadierUtil.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/handler/util/BrigadierUtil.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.handler.util;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutor;
import com.discordsrv.common.command.game.abstraction.GameCommandSuggester;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.*;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Helper class to convert DiscordSRV's abstract command tree into a brigadier one.
*/
public final class BrigadierUtil {
private static final Map<GameCommand, CommandNode<?>> CACHE = new ConcurrentHashMap<>();
private BrigadierUtil() {}
public static <S> LiteralCommandNode<S> convertToBrigadier(GameCommand command, Function<S, ICommandSender> commandSenderMapper) {
return (LiteralCommandNode<S>) convert(command, commandSenderMapper);
}
@SuppressWarnings("unchecked")
private static <S> CommandNode<S> convert(GameCommand commandBuilder, Function<S, ICommandSender> commandSenderMapper) {
CommandNode<S> alreadyConverted = (CommandNode<S>) CACHE.get(commandBuilder);
if (alreadyConverted != null) {
return alreadyConverted;
}
GameCommand.ArgumentType type = commandBuilder.getArgumentType();
String label = commandBuilder.getLabel();
GameCommandExecutor executor = commandBuilder.getExecutor();
GameCommandSuggester suggester = commandBuilder.getSuggester();
GameCommand redirection = commandBuilder.getRedirection();
String requiredPermission = commandBuilder.getRequiredPermission();
ArgumentBuilder<S, ?> argumentBuilder;
if (type == GameCommand.ArgumentType.LITERAL) {
argumentBuilder = LiteralArgumentBuilder.literal(label);
} else {
argumentBuilder = RequiredArgumentBuilder.argument(label, convertType(commandBuilder));
}
for (GameCommand child : commandBuilder.getChildren()) {
argumentBuilder.then(convert(child, commandSenderMapper));
}
if (redirection != null) {
CommandNode<S> redirectNode = (CommandNode<S>) CACHE.get(redirection);
if (redirectNode == null) {
redirectNode = convert(redirection, commandSenderMapper);
}
argumentBuilder.redirect(redirectNode);
}
if (requiredPermission != null) {
argumentBuilder.requires(sender -> {
ICommandSender commandSender = commandSenderMapper.apply(sender);
return commandSender.hasPermission(requiredPermission);
});
}
if (executor != null) {
argumentBuilder.executes(context -> {
executor.execute(
commandSenderMapper.apply(context.getSource()),
context::getArgument,
label
);
return Command.SINGLE_SUCCESS;
});
}
if (suggester != null && argumentBuilder instanceof RequiredArgumentBuilder) {
((RequiredArgumentBuilder<S, ?>) argumentBuilder).suggests((context, builder) -> {
try {
List<?> suggestions = suggester.suggestValues(
commandSenderMapper.apply(context.getSource()),
context::getArgument,
builder.getRemaining()
);
suggestions.forEach(suggestion -> builder.suggest(suggestion.toString()));
} catch (Throwable t) {
t.printStackTrace();
}
return CompletableFuture.completedFuture(builder.build());
});
}
CommandNode<S> node = argumentBuilder.build();
CACHE.put(commandBuilder, node);
return node;
}
private static ArgumentType<?> convertType(GameCommand builder) {
GameCommand.ArgumentType argumentType = builder.getArgumentType();
double min = builder.getMinValue();
double max = builder.getMaxValue();
switch (argumentType) {
case LONG: return LongArgumentType.longArg((long) min, (long) max);
case FLOAT: return FloatArgumentType.floatArg((float) min, (float) max);
case DOUBLE: return DoubleArgumentType.doubleArg(min, max);
case STRING: return StringArgumentType.string();
case STRING_WORD: return StringArgumentType.word();
case STRING_GREEDY: return StringArgumentType.greedyString();
case BOOLEAN: return BoolArgumentType.bool();
case INTEGER: return IntegerArgumentType.integer((int) min, (int) max);
}
throw new IllegalStateException();
}
}
| 6,094 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ICommandSender.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/sender/ICommandSender.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.sender;
import com.discordsrv.common.command.game.executor.CommandExecutor;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.audience.ForwardingAudience;
public interface ICommandSender extends ForwardingAudience.Single, CommandExecutor {
default boolean hasPermission(Permission permission) {
return hasPermission(permission.permission());
}
boolean hasPermission(String permission);
}
| 1,315 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
AdventureCommandExecutorProxyTemplate.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/executor/AdventureCommandExecutorProxyTemplate.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.executor;
import dev.vankka.dynamicproxy.processor.Original;
import dev.vankka.dynamicproxy.processor.Proxy;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import org.jetbrains.annotations.NotNull;
import java.util.function.Consumer;
@SuppressWarnings({"UnstableApiUsage", "deprecation"})
@Proxy(value = Audience.class, className = "AdventureCommandExecutorProxy")
public abstract class AdventureCommandExecutorProxyTemplate implements Audience {
@Original
private final Audience audience;
private final Consumer<Component> componentConsumer;
public AdventureCommandExecutorProxyTemplate(Audience audience, Consumer<Component> componentConsumer) {
this.audience = audience;
this.componentConsumer = componentConsumer;
}
private void forwardComponent(ComponentLike component) {
componentConsumer.accept(component.asComponent());
}
@Override
public void sendMessage(@NotNull Identified source, @NotNull ComponentLike message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(source, message, type);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identity source, @NotNull ComponentLike message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(source, message, type);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identified source, @NotNull Component message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(source, message, type);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(source, message, type);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identified source, @NotNull ComponentLike message) {
audience.sendMessage(source, message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Component message) {
audience.sendMessage(message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull ComponentLike message) {
audience.sendMessage(message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identity source, @NotNull Component message) {
audience.sendMessage(source, message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Component message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(message, type);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identified source, @NotNull Component message) {
audience.sendMessage(source, message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull Identity source, @NotNull ComponentLike message) {
audience.sendMessage(source, message);
forwardComponent(message);
}
@Override
public void sendMessage(@NotNull ComponentLike message, @NotNull net.kyori.adventure.audience.MessageType type) {
audience.sendMessage(message, type);
forwardComponent(message);
}
}
| 4,462 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
CommandExecutorProvider.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/executor/CommandExecutorProvider.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.executor;
import net.kyori.adventure.text.Component;
import java.util.function.Consumer;
@FunctionalInterface
public interface CommandExecutorProvider {
CommandExecutor getConsoleExecutor(Consumer<Component> componentConsumer);
}
| 1,111 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
CommandExecutor.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/executor/CommandExecutor.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.executor;
import com.discordsrv.api.discord.entity.DiscordUser;
import com.discordsrv.common.DiscordSRV;
public interface CommandExecutor {
default void runCommandWithLogging(DiscordSRV discordSRV, DiscordUser user, String command) {
discordSRV.logger().writeLogForCurrentDay(
"commandexecution",
"@" + user.getAsTag() + " [ID " + Long.toUnsignedString(user.getId()) + "] executed \"" + command + "\""
);
runCommand(command);
}
void runCommand(String command);
}
| 1,407 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordSRVGameCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/commands/DiscordSRVGameCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.commands;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.commands.*;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutor;
import com.discordsrv.common.command.game.commands.subcommand.BroadcastCommand;
import com.discordsrv.common.command.game.commands.subcommand.reload.ReloadCommand;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.linking.LinkStore;
import com.discordsrv.common.permission.Permission;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DiscordSRVGameCommand implements GameCommandExecutor {
private static final Map<String, GameCommand> INSTANCES = new ConcurrentHashMap<>();
private static DiscordSRVGameCommand COMMAND;
public static GameCommand get(DiscordSRV discordSRV, String alias) {
if (COMMAND == null) {
COMMAND = new DiscordSRVGameCommand(discordSRV);
}
return INSTANCES.computeIfAbsent(alias, key -> {
GameCommand command = GameCommand.literal(alias)
.requiredPermission(Permission.COMMAND_ROOT)
.executor(COMMAND)
.then(BroadcastCommand.discord(discordSRV))
.then(BroadcastCommand.minecraft(discordSRV))
.then(BroadcastCommand.json(discordSRV))
.then(DebugCommand.getGame(discordSRV))
.then(LinkInitCommand.getGame(discordSRV))
.then(LinkedCommand.getGame(discordSRV))
.then(ReloadCommand.get(discordSRV))
.then(ResyncCommand.getGame(discordSRV))
.then(VersionCommand.getGame(discordSRV));
if (discordSRV.linkProvider() instanceof LinkStore) {
command = command.then(UnlinkCommand.getGame(discordSRV));
}
return command;
});
}
private final DiscordSRV discordSRV;
public DiscordSRVGameCommand(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
}
@Override
public void execute(ICommandSender sender, GameCommandArguments arguments, String label) {
MinecraftComponent component = discordSRV.componentFactory()
.textBuilder(discordSRV.config().gameCommand.discordFormat)
.addContext(sender)
.applyPlaceholderService()
.build();
sender.sendMessage(ComponentUtil.fromAPI(component));
}
}
| 3,656 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
BroadcastCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/commands/subcommand/BroadcastCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.commands.subcommand;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel;
import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutor;
import com.discordsrv.common.command.game.abstraction.GameCommandSuggester;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public abstract class BroadcastCommand implements GameCommandExecutor, GameCommandSuggester {
private static GameCommand DISCORD;
private static GameCommand MINECRAFT;
private static GameCommand JSON;
public static GameCommand discord(DiscordSRV discordSRV) {
return make("broadcastd", () -> new Discord(discordSRV), () -> DISCORD, cmd -> DISCORD = cmd);
}
public static GameCommand minecraft(DiscordSRV discordSRV) {
return make("broadcast", () -> new Minecraft(discordSRV), () -> MINECRAFT, cmd -> MINECRAFT = cmd);
}
public static GameCommand json(DiscordSRV discordSRV) {
return make("broadcastraw", () -> new Json(discordSRV), () -> JSON, cmd -> JSON = cmd);
}
private static GameCommand make(
String label,
Supplier<? extends BroadcastCommand> executor,
Supplier<GameCommand> supplier,
Consumer<GameCommand> consumer
) {
if (supplier.get() == null) {
BroadcastCommand command = executor.get();
consumer.accept(
GameCommand.literal(label)
.requiredPermission(Permission.COMMAND_BROADCAST)
.then(
GameCommand.string("channel")
.suggester(command)
.then(
GameCommand.stringGreedy("content")
.suggester((__, ___, ____) -> Collections.emptyList())
.executor(command)
)
)
);
}
return supplier.get();
}
protected final DiscordSRV discordSRV;
private BroadcastCommand(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
}
@Override
public void execute(ICommandSender sender, GameCommandArguments arguments, String label) {
doExecute(sender, arguments);
}
@SuppressWarnings("unchecked") // Wacky generics
private <CC extends BaseChannelConfig & IChannelConfig> void doExecute(ICommandSender sender, GameCommandArguments arguments) {
String channel = arguments.getString("channel");
String content = arguments.getString("content");
Set<DiscordMessageChannel> channels = new HashSet<>();
CompletableFuture<Collection<DiscordGuildMessageChannel>> future = null;
try {
long id = Long.parseUnsignedLong(channel);
DiscordMessageChannel messageChannel = discordSRV.discordAPI().getMessageChannelById(id);
if (messageChannel != null) {
channels.add(messageChannel);
}
} catch (IllegalArgumentException ignored) {
BaseChannelConfig channelConfig = discordSRV.channelConfig().resolve(null, channel);
CC config = channelConfig instanceof IChannelConfig ? (CC) channelConfig : null;
if (config != null) {
future = discordSRV.discordAPI().findOrCreateDestinations(config, true, false);
}
}
if (future != null) {
future.whenComplete((messageChannels, t) -> doBroadcast(sender, content, channel, messageChannels));
} else if (channels.isEmpty()) {
// TODO: please specify target
} else {
doBroadcast(sender, content, channel, channels);
}
}
@Override
public List<String> suggestValues(
ICommandSender sender,
GameCommandArguments previousArguments,
String currentInput
) {
String input = currentInput.toLowerCase(Locale.ROOT);
return discordSRV.channelConfig().getKeys().stream()
.filter(key -> key.toLowerCase(Locale.ROOT).startsWith(input))
.collect(Collectors.toList());
}
private void doBroadcast(ICommandSender sender, String content, String channel, Collection<? extends DiscordMessageChannel> channels) {
if (channels.isEmpty()) {
sender.sendMessage(
Component.text()
.append(Component.text("Channel ", NamedTextColor.RED))
.append(Component.text(channel, NamedTextColor.GRAY))
.append(Component.text(" not found", NamedTextColor.RED))
);
return;
}
SendableDiscordMessage message = getDiscordContent(content);
for (DiscordMessageChannel messageChannel : channels) {
messageChannel.sendMessage(message);
}
sender.sendMessage(Component.text("Broadcasted!", NamedTextColor.GRAY));
}
public SendableDiscordMessage getDiscordContent(String content) {
content = getContent(content);
return SendableDiscordMessage.builder().setContent(content).build();
}
public abstract String getContent(String content);
public static class Discord extends BroadcastCommand {
public Discord(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public SendableDiscordMessage getDiscordContent(String content) {
return SendableDiscordMessage.builder()
// Keep as is, allow newlines though
.setContent(content.replace("\\n", "\n"))
.toFormatter()
.applyPlaceholderService()
.build();
}
// See above
@Override
public String getContent(String content) {
return null;
}
}
public static class Minecraft extends BroadcastCommand {
public Minecraft(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public String getContent(String content) {
MinecraftComponent component = discordSRV.componentFactory()
.textBuilder(content)
.applyPlaceholderService()
.build();
return discordSRV.componentFactory().discordSerializer().serialize(ComponentUtil.fromAPI(component));
}
}
public static class Json extends BroadcastCommand {
public Json(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public String getContent(String content) {
Component component = GsonComponentSerializer.gson().deserialize(content);
return discordSRV.componentFactory().discordSerializer().serialize(component);
}
}
}
| 8,877 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ReloadCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/commands/subcommand/reload/ReloadCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.game.commands.subcommand.reload;
import com.discordsrv.api.DiscordSRVApi;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutor;
import com.discordsrv.common.command.game.abstraction.GameCommandSuggester;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
public class ReloadCommand implements GameCommandExecutor, GameCommandSuggester {
private static GameCommand INSTANCE;
public static GameCommand get(DiscordSRV discordSRV) {
if (INSTANCE == null) {
ReloadCommand cmd = new ReloadCommand(discordSRV);
INSTANCE = GameCommand.literal("reload")
.requiredPermission(Permission.COMMAND_RELOAD)
.executor(cmd)
.then(
GameCommand.stringGreedy("flags")
.executor(cmd).suggester(cmd)
);
}
return INSTANCE;
}
private final DiscordSRV discordSRV;
public ReloadCommand(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
}
@Override
public void execute(ICommandSender sender, GameCommandArguments arguments, String label) {
AtomicBoolean dangerousFlags = new AtomicBoolean(false);
Set<DiscordSRV.ReloadFlag> flags = getFlagsFromArguments(sender, arguments, dangerousFlags);
if (flags == null) {
flags = DiscordSRV.ReloadFlag.DEFAULT_FLAGS;
}
if (dangerousFlags.get()) {
sender.sendMessage(Component.text("You can add -confirm to the end of the command if you wish to proceed anyway", NamedTextColor.DARK_RED));
return;
}
if (flags.isEmpty()) {
sender.sendMessage(Component.text("Please specify at least one valid flag", NamedTextColor.RED));
return;
}
List<DiscordSRVApi.ReloadResult> results = discordSRV.runReload(flags, false);
for (DiscordSRV.ReloadResult result : results) {
String res = result.name();
if (res.equals(ReloadResults.FAILED.name())) {
sender.sendMessage(
Component.text()
.append(Component.text("Reload failed.", NamedTextColor.DARK_RED, TextDecoration.BOLD))
.append(Component.text("Please check the server console/log for more details."))
);
} else if (res.equals(ReloadResults.SECURITY_FAILED.name())) {
sender.sendMessage(Component.text(
"DiscordSRV is disabled due to a security check failure. "
+ "Please check console for more details", NamedTextColor.DARK_RED));
} else if (res.equals(ReloadResults.SUCCESS.name())) {
sender.sendMessage(Component.text("Reload successful", NamedTextColor.GRAY));
} else if (res.equals(ReloadResults.RESTART_REQUIRED.name())) {
sender.sendMessage(Component.text("Some changes require a server restart"));
} else if (res.equals(ReloadResults.STORAGE_CONNECTION_FAILED.name())) {
sender.sendMessage(Component.text("Storage connection failed, please check console for details.", NamedTextColor.RED));
} else if (res.equals(ReloadResults.DISCORD_CONNECTION_FAILED.name())) {
sender.sendMessage(Component.text("Discord connection failed, please check console for details.", NamedTextColor.RED));
} else if (res.equals(ReloadResults.DISCORD_CONNECTION_RELOAD_REQUIRED.name())) {
String command = "discordsrv reload " + DiscordSRVApi.ReloadFlag.DISCORD_CONNECTION.name().toLowerCase(Locale.ROOT) + " -confirm";
Component child;
if (sender instanceof IPlayer) {
child = Component.text("[Click to reload Discord connection]", NamedTextColor.DARK_RED)
.clickEvent(ClickEvent.runCommand("/" + command))
.hoverEvent(HoverEvent.showText(Component.text("/" + command)));
} else {
child = Component.text("Run ", NamedTextColor.DARK_RED)
.append(Component.text(command, NamedTextColor.GRAY))
.append(Component.text(" to reload the Discord connection"));
}
sender.sendMessage(
Component.text()
.append(Component.text("Some changes require a Discord connection reload. ", NamedTextColor.GRAY))
.append(child)
);
}
}
}
private Set<DiscordSRV.ReloadFlag> getFlagsFromArguments(ICommandSender sender, GameCommandArguments arguments, AtomicBoolean dangerousFlags) {
String argument = null;
try {
argument = arguments.get("flags", String.class);
} catch (IllegalArgumentException ignored) {}
if (argument == null) {
return null;
}
List<String> parts = new ArrayList<>(Arrays.asList(argument.split(" ")));
boolean confirm = parts.remove("-confirm");
Set<DiscordSRV.ReloadFlag> flags = new LinkedHashSet<>();
if (discordSRV.status().isStartupError()) {
// If startup error, use all flags
parts.clear();
flags.addAll(DiscordSRVApi.ReloadFlag.ALL);
}
for (String part : parts) {
try {
DiscordSRV.ReloadFlag flag = DiscordSRV.ReloadFlag.valueOf(part.toUpperCase(Locale.ROOT));
if (flag.requiresConfirm(discordSRV) && !confirm) {
dangerousFlags.set(true);
sender.sendMessage(
Component.text("Reloading ", NamedTextColor.RED)
.append(Component.text(part, NamedTextColor.GRAY))
.append(Component.text(" might cause DiscordSRV to end up in a unrecoverable state", NamedTextColor.RED))
);
continue;
}
flags.add(flag);
} catch (IllegalArgumentException ignored) {
sender.sendMessage(Component.text("Flag ", NamedTextColor.RED)
.append(Component.text(part, NamedTextColor.GRAY))
.append(Component.text(" is not known", NamedTextColor.RED)));
}
}
return flags;
}
@Override
public List<String> suggestValues(
ICommandSender sender,
GameCommandArguments previousArguments,
String currentInput
) {
int lastSpace = currentInput.lastIndexOf(' ') + 1;
String last = currentInput.substring(lastSpace);
String beforeLastSpace = currentInput.substring(0, lastSpace);
List<String> options = DiscordSRV.ReloadFlag.ALL.stream()
.map(flag -> flag.name().toLowerCase(Locale.ROOT))
.filter(flag -> flag.startsWith(last))
.collect(Collectors.toList());
for (String part : currentInput.split(" ")) {
options.remove(part);
}
return options.stream().map(flag -> beforeLastSpace + flag).collect(Collectors.toList());
}
}
| 8,905 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ReloadResults.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/game/commands/subcommand/reload/ReloadResults.java | package com.discordsrv.common.command.game.commands.subcommand.reload;
import com.discordsrv.api.DiscordSRVApi;
public enum ReloadResults implements DiscordSRVApi.ReloadResult {
FAILED,
SUCCESS,
SECURITY_FAILED,
STORAGE_CONNECTION_FAILED,
DISCORD_CONNECTION_RELOAD_REQUIRED,
DISCORD_CONNECTION_FAILED
}
| 329 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordCommandModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/discord/DiscordCommandModule.java | package com.discordsrv.common.command.discord;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.discord.interaction.command.CommandRegisterEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.discord.commands.DiscordSRVDiscordCommand;
import com.discordsrv.common.module.type.AbstractModule;
public class DiscordCommandModule extends AbstractModule<DiscordSRV> {
public DiscordCommandModule(DiscordSRV discordSRV) {
super(discordSRV);
}
@Subscribe
public void onCommandRegister(CommandRegisterEvent event) {
event.registerCommands(DiscordSRVDiscordCommand.get(discordSRV));
}
}
| 687 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordSRVDiscordCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/discord/commands/DiscordSRVDiscordCommand.java | package com.discordsrv.common.command.discord.commands;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.commands.*;
import com.discordsrv.common.command.discord.commands.subcommand.ExecuteCommand;
import com.discordsrv.common.config.main.DiscordCommandConfig;
import com.discordsrv.common.linking.LinkStore;
public class DiscordSRVDiscordCommand {
private static final ComponentIdentifier IDENTIFIER = ComponentIdentifier.of("DiscordSRV", "discordsrv");
private static DiscordCommand INSTANCE;
public static DiscordCommand get(DiscordSRV discordSRV) {
if (INSTANCE == null) {
DiscordCommandConfig config = discordSRV.config().discordCommand;
DiscordCommand.ChatInputBuilder builder = DiscordCommand.chatInput(IDENTIFIER, "discordsrv", "DiscordSRV related commands")
.addSubCommand(DebugCommand.getDiscord(discordSRV))
.addSubCommand(VersionCommand.getDiscord(discordSRV))
.addSubCommand(ResyncCommand.getDiscord(discordSRV))
.addSubCommand(LinkedCommand.getDiscord(discordSRV));
if (config.execute.enabled) {
builder = builder.addSubCommand(ExecuteCommand.get(discordSRV));
}
if (discordSRV.linkProvider() instanceof LinkStore) {
builder = builder
.addSubCommand(LinkInitCommand.getDiscord(discordSRV))
.addSubCommand(UnlinkCommand.getDiscord(discordSRV));
}
INSTANCE = builder
.setGuildOnly(false)
.setDefaultPermission(DiscordCommand.DefaultPermission.ADMINISTRATOR)
.build();
}
return INSTANCE;
}
}
| 1,955 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ExecuteCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/discord/commands/subcommand/ExecuteCommand.java | package com.discordsrv.common.command.discord.commands.subcommand;
import com.discordsrv.api.discord.entity.DiscordUser;
import com.discordsrv.api.discord.entity.guild.DiscordGuildMember;
import com.discordsrv.api.discord.entity.interaction.DiscordInteractionHook;
import com.discordsrv.api.discord.entity.interaction.command.CommandOption;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordChatInputInteractionEvent;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordCommandAutoCompleteInteractionEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.game.GameCommandExecutionHelper;
import com.discordsrv.common.config.main.DiscordCommandConfig;
import com.discordsrv.common.config.main.generic.GameCommandExecutionConditionConfig;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import net.dv8tion.jda.api.entities.Message;
import net.kyori.adventure.text.Component;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
public class ExecuteCommand implements Consumer<DiscordChatInputInteractionEvent>, DiscordCommand.AutoCompleteHandler {
private static DiscordCommand INSTANCE;
public static DiscordCommand get(DiscordSRV discordSRV) {
if (INSTANCE == null) {
DiscordCommandConfig.ExecuteConfig config = discordSRV.config().discordCommand.execute;
ExecuteCommand command = new ExecuteCommand(discordSRV);
INSTANCE = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "execute"), "execute", "Run a Minecraft console command")
.addOption(
CommandOption.builder(CommandOption.Type.STRING, "command", "The command to execute")
.setAutoComplete(config.suggest)
.setRequired(true)
.build()
)
.setAutoCompleteHandler(command)
.setEventHandler(command)
.build();
}
return INSTANCE;
}
private final DiscordSRV discordSRV;
private final GameCommandExecutionHelper helper;
private final Logger logger;
public ExecuteCommand(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
this.helper = discordSRV.executeHelper();
this.logger = new NamedLogger(discordSRV, "EXECUTE_COMMAND");
}
public boolean isNotAcceptableCommand(DiscordGuildMember member, DiscordUser user, String command, boolean suggestions) {
DiscordCommandConfig.ExecuteConfig config = discordSRV.config().discordCommand.execute;
for (GameCommandExecutionConditionConfig filter : config.executionConditions) {
if (!filter.isAcceptableCommand(member, user, command, suggestions, helper)) {
return true;
}
}
return false;
}
@Override
public void accept(DiscordChatInputInteractionEvent event) {
DiscordCommandConfig.ExecuteConfig config = discordSRV.config().discordCommand.execute;
boolean ephemeral = config.ephemeral;
if (!config.enabled) {
event.reply(SendableDiscordMessage.builder().setContent("The execute command is disabled").build(), ephemeral);
return;
}
String command = event.getOption("command");
if (command == null) {
return;
}
if (isNotAcceptableCommand(event.getMember(), event.getUser(), command, false)) {
event.reply(SendableDiscordMessage.builder().setContent("You do not have permission to run that command").build(), ephemeral);
return;
}
event.reply(SendableDiscordMessage.builder().setContent("Executing command `" + command + "`").build(), ephemeral)
.whenComplete((ih, t) -> {
if (t != null) {
return;
}
new ExecutionContext(discordSRV, ih, config.outputMode, ephemeral).run(event.getUser(), command);
});
}
@Override
public void autoComplete(DiscordCommandAutoCompleteInteractionEvent event) {
if (helper == null) {
// No suggestions available.
return;
}
DiscordCommandConfig.ExecuteConfig config = discordSRV.config().discordCommand.execute;
if (!config.suggest) {
return;
}
String command = event.getOption("command");
if (command == null) {
return;
}
List<String> parts = new ArrayList<>(Arrays.asList(command.split(" ")));
List<String> suggestions = getSuggestions(parts);
if (suggestions == null) {
return;
}
if (suggestions.isEmpty() || suggestions.contains(command)) {
parts.add("");
List<String> newSuggestions = getSuggestions(parts);
if (newSuggestions == null) {
return;
}
suggestions = new ArrayList<>(newSuggestions);
if (suggestions.isEmpty()) {
suggestions.add(command);
}
}
suggestions.sort((s1, s2) -> {
// Options with semicolons (eg. plugin:command) are at the bottom
int semi1 = s1.indexOf(':');
int semi2 = s2.indexOf(':');
if (semi1 > semi2) {
return 1;
} else if (semi2 > semi1) {
return -1;
}
// Otherwise alphabetically sorted
return s1.toLowerCase(Locale.ROOT).compareTo(s2.toLowerCase(Locale.ROOT));
});
for (String suggestion : suggestions) {
if (event.getChoices().size() >= 25) {
break;
}
if (config.filterSuggestions && isNotAcceptableCommand(event.getMember(), event.getUser(), suggestion, true)) {
continue;
}
event.addChoice(suggestion, suggestion);
}
}
private List<String> getSuggestions(List<String> parts) {
try {
return helper.suggestCommands(new ArrayList<>(parts)).get(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} catch (TimeoutException e) {
return null;
} catch (ExecutionException e) {
logger.error("Failed to suggest commands", e.getCause());
return null;
} catch (Throwable t) {
logger.error("Failed to suggest commands", t);
return null;
}
}
private static class ExecutionContext {
private final DiscordSRV discordSRV;
private final DiscordInteractionHook hook;
private final DiscordCommandConfig.OutputMode outputMode;
private final boolean ephemeral;
private ScheduledFuture<?> future;
private final Queue<Component> queued = new LinkedBlockingQueue<>();
public ExecutionContext(
DiscordSRV discordSRV,
DiscordInteractionHook hook,
DiscordCommandConfig.OutputMode outputMode,
boolean ephemeral
) {
this.discordSRV = discordSRV;
this.hook = hook;
this.outputMode = outputMode;
this.ephemeral = ephemeral;
}
public void run(DiscordUser user, String command) {
discordSRV.console().commandExecutorProvider()
.getConsoleExecutor(this::consumeComponent)
.runCommandWithLogging(discordSRV, user, command);
}
private void consumeComponent(Component component) {
if (outputMode == DiscordCommandConfig.OutputMode.OFF) {
return;
}
synchronized (queued) {
queued.offer(component);
if (future == null) {
future = discordSRV.scheduler().runLater(this::send, Duration.ofMillis(500));
}
}
}
private void send() {
boolean ansi = outputMode == DiscordCommandConfig.OutputMode.ANSI;
boolean plainBlock = outputMode == DiscordCommandConfig.OutputMode.CODEBLOCK;
String prefix = ansi ? "```ansi\n" : (plainBlock ? "```\n" : "");
String suffix = ansi ? "```" : (plainBlock ? "```" : "");
String delimiter = "\n";
StringJoiner joiner = new StringJoiner(delimiter);
Component component;
synchronized (queued) {
while ((component = queued.poll()) != null) {
String discord;
switch (outputMode) {
default:
case MARKDOWN:
discord = discordSRV.componentFactory().discordSerializer().serialize(component);
break;
case ANSI:
discord = discordSRV.componentFactory().ansiSerializer().serialize(component);
break;
case PLAIN:
case CODEBLOCK:
discord = discordSRV.componentFactory().plainSerializer().serialize(component);
break;
}
if (prefix.length() + suffix.length() + discord.length() + joiner.length() + delimiter.length() > Message.MAX_CONTENT_LENGTH) {
hook.sendMessage(SendableDiscordMessage.builder().setContent(prefix + joiner + suffix).build(), ephemeral);
joiner = new StringJoiner(delimiter);
}
joiner.add(discord);
}
future = null;
}
hook.sendMessage(SendableDiscordMessage.builder().setContent(prefix + joiner + suffix).build(), ephemeral);
}
}
}
| 10,349 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
CommandExecution.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/abstraction/CommandExecution.java | package com.discordsrv.common.command.combined.abstraction;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.messages.MessagesConfig;
import net.kyori.adventure.text.Component;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
public interface CommandExecution {
Locale locale();
MessagesConfig messages();
void setEphemeral(boolean ephemeral);
String getArgument(String label);
default void send(Text... texts) {
send(Arrays.asList(texts));
}
default void send(Collection<Text> texts) {
send(texts, Collections.emptyList());
}
void send(Collection<Text> texts, Collection<Text> extra);
default void send(MinecraftComponent minecraft, String discord) {
send(ComponentUtil.fromAPI(minecraft), discord);
}
void send(Component minecraft, String discord);
void runAsync(Runnable runnable);
}
| 1,037 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DiscordCommandExecution.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/abstraction/DiscordCommandExecution.java | package com.discordsrv.common.command.combined.abstraction;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordChatInputInteractionEvent;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordCommandAutoCompleteInteractionEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.messages.MessagesConfig;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
import net.dv8tion.jda.api.interactions.commands.CommandInteractionPayload;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.kyori.adventure.text.Component;
import org.apache.commons.lang3.StringUtils;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class DiscordCommandExecution implements CommandExecution {
private final DiscordSRV discordSRV;
private final GenericInteractionCreateEvent createEvent;
private final CommandInteractionPayload interactionPayload;
private final IReplyCallback replyCallback;
private final AtomicBoolean isEphemeral = new AtomicBoolean(true);
private final AtomicReference<InteractionHook> hook = new AtomicReference<>();
public DiscordCommandExecution(DiscordSRV discordSRV, DiscordChatInputInteractionEvent event) {
this.discordSRV = discordSRV;
this.createEvent = event.asJDA();
this.interactionPayload = event.asJDA();
this.replyCallback = event.asJDA();
}
public DiscordCommandExecution(DiscordSRV discordSRV, DiscordCommandAutoCompleteInteractionEvent event) {
this.discordSRV = discordSRV;
this.createEvent = event.asJDA();
this.interactionPayload = event.asJDA();
this.replyCallback = null;
}
@Override
public Locale locale() {
return createEvent.getUserLocale().toLocale();
}
@Override
public MessagesConfig messages() {
return discordSRV.messagesConfig(locale());
}
@Override
public void setEphemeral(boolean ephemeral) {
isEphemeral.set(ephemeral);
}
@Override
public String getArgument(String label) {
OptionMapping mapping = interactionPayload.getOption(label);
return mapping != null ? mapping.getAsString() : null;
}
@Override
public void send(Collection<Text> texts, Collection<Text> extra) {
StringBuilder builder = new StringBuilder();
EnumMap<Text.Formatting, Boolean> formats = new EnumMap<>(Text.Formatting.class);
for (Text text : texts) {
render(text, builder, formats);
}
verifyStyle(builder, formats, null);
if (!extra.isEmpty()) {
builder.append("\n\n");
for (Text text : extra) {
render(text, builder, formats);
}
verifyStyle(builder, formats, null);
}
sendResponse(builder.toString());
}
@Override
public void send(Component minecraft, String discord) {
sendResponse(discord);
}
private void sendResponse(String content) {
if (replyCallback == null) {
throw new IllegalStateException("May not be used on auto completions");
}
InteractionHook interactionHook = hook.get();
boolean ephemeral = isEphemeral.get();
if (interactionHook != null) {
interactionHook.sendMessage(content).setEphemeral(ephemeral).queue();
} else {
replyCallback.reply(content).setEphemeral(ephemeral).queue();
}
}
private void render(Text text, StringBuilder builder, EnumMap<Text.Formatting, Boolean> formats) {
if (StringUtils.isEmpty(text.content())) return;
verifyStyle(builder, formats, text);
builder.append(text.content());
}
private void verifyStyle(StringBuilder builder, EnumMap<Text.Formatting, Boolean> formats, Text text) {
for (Text.Formatting format : Text.Formatting.values()) {
boolean is = formats.computeIfAbsent(format, key -> false);
boolean thisIs = text != null && text.discordFormatting().contains(format);
if (is != thisIs) {
// should end or start
builder.append(format.discord());
formats.put(format, thisIs);
}
}
}
@Override
public void runAsync(Runnable runnable) {
replyCallback.deferReply(isEphemeral.get()).queue(ih -> {
hook.set(ih);
discordSRV.scheduler().run(runnable);
});
}
public User getUser() {
return createEvent.getUser();
}
}
| 4,894 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
GameCommandExecution.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/abstraction/GameCommandExecution.java | package com.discordsrv.common.command.combined.abstraction;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.config.messages.MessagesConfig;
import com.discordsrv.common.player.IPlayer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import java.util.Collection;
import java.util.Locale;
import java.util.regex.Pattern;
public class GameCommandExecution implements CommandExecution {
private static final TextReplacementConfig URL_REPLACEMENT = TextReplacementConfig.builder()
.match(Pattern.compile("^https?://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"))
.replacement((matchResult, builder) -> {
String url = matchResult.group();
return builder.clickEvent(ClickEvent.openUrl(url));
})
.build();
private final DiscordSRV discordSRV;
private final ICommandSender sender;
private final GameCommandArguments arguments;
private final String label;
public GameCommandExecution(DiscordSRV discordSRV, ICommandSender sender, GameCommandArguments arguments, String label) {
this.discordSRV = discordSRV;
this.sender = sender;
this.arguments = arguments;
this.label = label;
}
@Override
public Locale locale() {
return sender instanceof IPlayer ? ((IPlayer) sender).locale() : null;
}
@Override
public MessagesConfig messages() {
return discordSRV.messagesConfig(locale());
}
@Override
public void setEphemeral(boolean ephemeral) {
// NO-OP
}
@Override
public String getArgument(String label) {
return arguments.getString(label);
}
@Override
public void send(Collection<Text> texts, Collection<Text> extra) {
TextComponent.Builder builder = render(texts);
if (!extra.isEmpty()) {
builder.hoverEvent(HoverEvent.showText(render(extra)));
}
sender.sendMessage(builder.build().replaceText(URL_REPLACEMENT));
}
@Override
public void send(Component minecraft, String discord) {
sender.sendMessage(minecraft);
}
private TextComponent.Builder render(Collection<Text> texts) {
TextComponent.Builder builder = Component.text();
for (Text text : texts) {
builder.append(
Component.text(text.content())
.color(text.gameColor())
.decorations(text.gameFormatting(), true)
);
}
return builder;
}
@Override
public void runAsync(Runnable runnable) {
discordSRV.scheduler().run(runnable);
}
public ICommandSender getSender() {
return sender;
}
public String getLabel() {
return label;
}
}
| 3,135 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
CombinedCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/abstraction/CombinedCommand.java | package com.discordsrv.common.command.combined.abstraction;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordChatInputInteractionEvent;
import com.discordsrv.api.event.events.discord.interaction.command.DiscordCommandAutoCompleteInteractionEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.game.abstraction.GameCommandArguments;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutor;
import com.discordsrv.common.command.game.abstraction.GameCommandSuggester;
import com.discordsrv.common.command.game.sender.ICommandSender;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
public abstract class CombinedCommand
implements
GameCommandExecutor,
GameCommandSuggester,
Consumer<DiscordChatInputInteractionEvent>,
DiscordCommand.AutoCompleteHandler
{
protected final DiscordSRV discordSRV;
public CombinedCommand(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
}
@Override
public void execute(ICommandSender sender, GameCommandArguments arguments, String label) {
execute(new GameCommandExecution(discordSRV, sender, arguments, label));
}
@Override
public void accept(DiscordChatInputInteractionEvent event) {
execute(new DiscordCommandExecution(discordSRV, event));
}
public abstract void execute(CommandExecution execution);
@Override
public List<String> suggestValues(ICommandSender sender, GameCommandArguments previousArguments, String currentInput) {
return suggest(new GameCommandExecution(discordSRV, sender, previousArguments, null), currentInput);
}
@Override
public void autoComplete(DiscordCommandAutoCompleteInteractionEvent event) {
List<String> suggestions = suggest(new DiscordCommandExecution(discordSRV, event), null);
suggestions.forEach(suggestion -> event.addChoice(suggestion, suggestion));
}
public List<String> suggest(CommandExecution execution, @Nullable String input) {
return Collections.emptyList();
}
}
| 2,255 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Text.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/abstraction/Text.java | package com.discordsrv.common.command.combined.abstraction;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import java.util.Arrays;
import java.util.EnumSet;
public class Text {
private final String content;
private TextColor gameColor;
private EnumSet<TextDecoration> gameFormatting;
private EnumSet<Formatting> discordFormatting;
public Text(String content) {
this.content = content;
this.gameFormatting = EnumSet.noneOf(TextDecoration.class);
this.discordFormatting = EnumSet.noneOf(Formatting.class);
}
public String content() {
return content;
}
public Text withGameColor(TextColor color) {
this.gameColor = color;
return this;
}
public TextColor gameColor() {
return gameColor;
}
public Text withFormatting(Formatting... formatting) {
EnumSet<TextDecoration> game = EnumSet.noneOf(TextDecoration.class);
for (Formatting format : formatting) {
game.add(format.game);
}
this.gameFormatting = game;
this.discordFormatting = EnumSet.copyOf(Arrays.asList(formatting));
return this;
}
public Text withGameFormatting(Formatting... formatting) {
EnumSet<TextDecoration> game = EnumSet.noneOf(TextDecoration.class);
for (Formatting format : formatting) {
game.add(format.game);
}
this.gameFormatting = game;
return this;
}
public EnumSet<TextDecoration> gameFormatting() {
return gameFormatting;
}
public Text withDiscordFormatting(Formatting... formatting) {
this.discordFormatting = EnumSet.copyOf(Arrays.asList(formatting));
return this;
}
public EnumSet<Formatting> discordFormatting() {
return discordFormatting;
}
public enum Formatting {
BOLD(TextDecoration.BOLD, "**"),
ITALICS(TextDecoration.ITALIC, "*"),
UNDERLINED(TextDecoration.UNDERLINED, "__"),
STRIKETHROUGH(TextDecoration.STRIKETHROUGH, "~~");
private final TextDecoration game;
private final String discord;
Formatting(TextDecoration game, String discord) {
this.game = game;
this.discord = discord;
}
public String discord() {
return discord;
}
}
}
| 2,404 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ResyncCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/ResyncCommand.java | package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.GameCommandExecution;
import com.discordsrv.common.command.combined.abstraction.Text;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.future.util.CompletableFutureUtil;
import com.discordsrv.common.groupsync.GroupSyncModule;
import com.discordsrv.common.groupsync.enums.GroupSyncCause;
import com.discordsrv.common.groupsync.enums.GroupSyncResult;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ResyncCommand extends CombinedCommand {
private static ResyncCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static ResyncCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new ResyncCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
ResyncCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("resync")
.requiredPermission(Permission.COMMAND_RESYNC)
.executor(command);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
ResyncCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "resync"), "resync", "Perform group resync for online players")
.setEventHandler(command)
.build();
}
return DISCORD;
}
public ResyncCommand(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public void execute(CommandExecution execution) {
GroupSyncModule module = discordSRV.getModule(GroupSyncModule.class);
if (module == null) {
execution.send(new Text("GroupSync module has not initialized correctly.").withGameColor(NamedTextColor.RED));
return;
}
if (module.noPermissionProvider()) {
execution.send(new Text("No permission provider available.").withGameColor(NamedTextColor.RED));
return;
}
if (execution instanceof GameCommandExecution) {
// Acknowledge for in-game runs
execution.send(new Text("Synchronizing online players").withGameColor(NamedTextColor.GRAY));
}
execution.runAsync(() -> {
long startTime = System.currentTimeMillis();
CompletableFutureUtil.combine(resyncOnlinePlayers(module))
.whenComplete((results, t) -> {
EnumMap<GroupSyncResult, AtomicInteger> resultCounts = new EnumMap<>(GroupSyncResult.class);
int total = 0;
for (List<GroupSyncResult> result : results) {
for (GroupSyncResult singleResult : result) {
total++;
resultCounts.computeIfAbsent(singleResult, key -> new AtomicInteger(0)).getAndIncrement();
}
}
String resultHover = resultCounts.entrySet().stream()
.map(entry -> entry.getKey().toString() + ": " + entry.getValue().get())
.collect(Collectors.joining("\n"));
long time = System.currentTimeMillis() - startTime;
execution.send(
Arrays.asList(
new Text("Synchronization completed in ").withGameColor(NamedTextColor.GRAY),
new Text(time + "ms").withGameColor(NamedTextColor.GREEN).withFormatting(Text.Formatting.BOLD),
new Text(" (").withGameColor(NamedTextColor.GRAY),
new Text(total + " result" + (total == 1 ? "" : "s"))
.withGameColor(NamedTextColor.GREEN)
.withDiscordFormatting(Text.Formatting.BOLD),
new Text(")").withGameColor(NamedTextColor.GRAY)
),
total > 0
? Collections.singletonList(new Text(resultHover))
: (execution instanceof GameCommandExecution ? Collections.singletonList(new Text("Nothing done")) : Collections.emptyList())
);
});
});
}
private List<CompletableFuture<List<GroupSyncResult>>> resyncOnlinePlayers(GroupSyncModule module) {
List<CompletableFuture<List<GroupSyncResult>>> futures = new ArrayList<>();
for (IPlayer player : discordSRV.playerProvider().allPlayers()) {
futures.add(module.resync(player.uniqueId(), GroupSyncCause.COMMAND));
}
return futures;
}
}
| 5,773 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
LinkedCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/LinkedCommand.java | package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.discord.entity.interaction.command.CommandOption;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.util.CommandUtil;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import com.discordsrv.common.permission.Permission;
import java.util.UUID;
public class LinkedCommand extends CombinedCommand {
private static LinkedCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static LinkedCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new LinkedCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
LinkedCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("linked")
.then(
GameCommand.stringGreedy("target")
.requiredPermission(Permission.COMMAND_LINKED_OTHER)
.executor(command)
)
.requiredPermission(Permission.COMMAND_LINKED)
.executor(command);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
LinkedCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "linked"), "linked", "Check the linking status of accounts")
.addOption(CommandOption.builder(
CommandOption.Type.USER,
"user",
"The Discord user to check the linking status of"
).setRequired(false).build())
.addOption(CommandOption.builder(
CommandOption.Type.STRING,
"player",
"The Minecraft player username or UUID to check the linking status of"
).setRequired(false).build())
.setEventHandler(command)
.build();
}
return DISCORD;
}
private final Logger logger;
public LinkedCommand(DiscordSRV discordSRV) {
super(discordSRV);
this.logger = new NamedLogger(discordSRV, "LINKED_COMMAND");
}
@Override
public void execute(CommandExecution execution) {
execution.setEphemeral(true);
execution.runAsync(() -> CommandUtil.lookupTarget(discordSRV, logger, execution, true, Permission.COMMAND_LINKED_OTHER)
.whenComplete((result, t) -> {
if (t != null) {
logger.error("Failed to execute linked command", t);
return;
}
if (result.isValid()) {
processResult(result, execution);
}
})
);
}
private void processResult(CommandUtil.TargetLookupResult result, CommandExecution execution) {
if (result.isPlayer()) {
UUID playerUUID = result.getPlayerUUID();
discordSRV.linkProvider().getUserId(playerUUID).whenComplete((optUserId, t) -> {
if (t != null) {
logger.error("Failed to check linking status during linked command", t);
execution.messages().unableToCheckLinkingStatus(execution);
return;
}
if (!optUserId.isPresent()) {
execution.messages().minecraftPlayerUnlinked(discordSRV, execution, playerUUID);
return;
}
long userId = optUserId.get();
execution.messages().minecraftPlayerLinkedTo(discordSRV, execution, playerUUID, userId);
});
} else {
long userId = result.getUserId();
discordSRV.linkProvider().getPlayerUUID(userId).whenComplete((optPlayerUUID, t) -> {
if (t != null) {
logger.error("Failed to check linking status during linked command", t);
execution.send(
execution.messages().minecraft.unableToCheckLinkingStatus.asComponent(),
execution.messages().discord.unableToCheckLinkingStatus
);
return;
}
if (!optPlayerUUID.isPresent()) {
execution.messages().discordUserUnlinked(discordSRV, execution, userId);
return;
}
UUID playerUUID = optPlayerUUID.get();
execution.messages().discordUserLinkedTo(discordSRV, execution, playerUUID, userId);
});
}
}
}
| 5,369 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
UnlinkCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/UnlinkCommand.java | package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.discord.entity.interaction.command.CommandOption;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.Text;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.util.CommandUtil;
import com.discordsrv.common.linking.LinkProvider;
import com.discordsrv.common.linking.LinkStore;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.UUID;
public class UnlinkCommand extends CombinedCommand {
private static UnlinkCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static UnlinkCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new UnlinkCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
UnlinkCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("unlink")
.then(
GameCommand.stringGreedy("target")
.requiredPermission(Permission.COMMAND_UNLINK_OTHER)
.executor(command)
)
.requiredPermission(Permission.COMMAND_UNLINK)
.executor(command);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
UnlinkCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "unlink"), "unlink", "Unlink accounts")
.addOption(CommandOption.builder(
CommandOption.Type.USER,
"user",
"The Discord user to unlink"
).setRequired(false).build())
.addOption(CommandOption.builder(
CommandOption.Type.STRING,
"player",
"The Minecraft player username or UUID to unlink"
).setRequired(false).build())
.setEventHandler(command)
.build();
}
return DISCORD;
}
private final Logger logger;
public UnlinkCommand(DiscordSRV discordSRV) {
super(discordSRV);
this.logger = new NamedLogger(discordSRV, "UNLINK_COMMAND");
}
@Override
public void execute(CommandExecution execution) {
execution.setEphemeral(true);
LinkProvider linkProvider = discordSRV.linkProvider();
if (!(linkProvider instanceof LinkStore)) {
execution.send(new Text("Cannot remove links with this link provider").withGameColor(NamedTextColor.DARK_RED));
return;
}
execution.runAsync(() -> CommandUtil.lookupTarget(discordSRV, logger, execution, true, Permission.COMMAND_UNLINK_OTHER)
.whenComplete((result, t) -> {
if (t != null) {
logger.error("Failed to execute linked command", t);
return;
}
if (result.isValid()) {
processResult(result, execution, (LinkStore) linkProvider);
} else {
execution.send(new Text("Invalid target"));
}
})
);
}
private void processResult(CommandUtil.TargetLookupResult result, CommandExecution execution, LinkStore linkStore) {
if (result.isPlayer()) {
UUID playerUUID = result.getPlayerUUID();
discordSRV.linkProvider().queryUserId(playerUUID)
.whenComplete((user, t) -> {
if (t != null) {
logger.error("Failed to query user", t);
execution.messages().unableToCheckLinkingStatus(execution);
return;
}
if (!user.isPresent()) {
execution.messages().minecraftPlayerUnlinked(discordSRV, execution, playerUUID);
return;
}
handleUnlinkForPair(playerUUID, user.get(), execution, linkStore);
});
} else {
long userId = result.getUserId();
discordSRV.linkProvider().queryPlayerUUID(result.getUserId())
.whenComplete((player, t) -> {
if (t != null) {
logger.error("Failed to query player", t);
execution.messages().unableToCheckLinkingStatus(execution);
return;
}
if (!player.isPresent()) {
execution.messages().discordUserUnlinked(discordSRV, execution, userId);
return;
}
handleUnlinkForPair(player.get(), userId, execution, linkStore);
});
}
}
private void handleUnlinkForPair(UUID player, Long user, CommandExecution execution, LinkStore linkStore) {
linkStore.removeLink(player, user).whenComplete((v, t2) -> {
if (t2 != null) {
logger.error("Failed to remove link", t2);
execution.send(
execution.messages().minecraft.unableToLinkAtThisTime.asComponent(),
execution.messages().discord.unableToCheckLinkingStatus
);
return;
}
execution.messages().unlinked(execution);
});
}
}
| 6,382 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
LinkInitCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/LinkInitCommand.java | package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.discord.entity.interaction.command.CommandOption;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.GameCommandExecution;
import com.discordsrv.common.command.combined.abstraction.Text;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.command.util.CommandUtil;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.messages.MessagesConfig;
import com.discordsrv.common.linking.LinkProvider;
import com.discordsrv.common.linking.LinkStore;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.logging.NamedLogger;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import com.github.benmanes.caffeine.cache.Cache;
import net.kyori.adventure.text.format.NamedTextColor;
import org.apache.commons.lang3.StringUtils;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class LinkInitCommand extends CombinedCommand {
private static LinkInitCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static LinkInitCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new LinkInitCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
LinkInitCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("link")
.then(
GameCommand.stringWord("player")
.then(
GameCommand.stringWord("user")
.requiredPermission(Permission.COMMAND_LINK_OTHER)
.executor(command)
)
)
.requiredPermission(Permission.COMMAND_LINK)
.executor(command);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
LinkInitCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "link"), "link", "Link players")
.addOption(
CommandOption.builder(CommandOption.Type.USER, "user", "The user to link")
.setRequired(true)
.build()
)
.addOption(
CommandOption.builder(CommandOption.Type.STRING, "player", "The player to link")
.setRequired(true)
.build()
)
.setAutoCompleteHandler(command)
.setEventHandler(command)
.build();
}
return DISCORD;
}
private final DiscordSRV discordSRV;
private final Logger logger;
private final Cache<UUID, Boolean> linkCheckRateLimit;
public LinkInitCommand(DiscordSRV discordSRV) {
super(discordSRV);
this.discordSRV = discordSRV;
this.logger = new NamedLogger(discordSRV, "LINK_COMMAND");
this.linkCheckRateLimit = discordSRV.caffeineBuilder()
.expireAfterWrite(LinkStore.LINKING_CODE_RATE_LIMIT)
.build();
}
@Override
public void execute(CommandExecution execution) {
String playerArgument = execution.getArgument("player");
String userArgument = execution.getArgument("user");
if (execution instanceof GameCommandExecution) {
ICommandSender sender = ((GameCommandExecution) execution).getSender();
if (StringUtils.isEmpty(playerArgument)) {
if (sender instanceof IPlayer) {
startLinking((IPlayer) sender, ((GameCommandExecution) execution).getLabel());
} else {
sender.sendMessage(discordSRV.messagesConfig(sender).pleaseSpecifyPlayerAndUserToLink.asComponent());
}
return;
}
if (!sender.hasPermission(Permission.COMMAND_LINK_OTHER)) {
sender.sendMessage(discordSRV.messagesConfig(sender).noPermission.asComponent());
return;
}
}
LinkProvider linkProvider = discordSRV.linkProvider();
if (!(linkProvider instanceof LinkStore)) {
execution.send(new Text("Cannot create links using this link provider").withGameColor(NamedTextColor.DARK_RED));
return;
}
CompletableFuture<UUID> playerUUIDFuture = CommandUtil.lookupPlayer(discordSRV, logger, execution, false, playerArgument, null);
CompletableFuture<Long> userIdFuture = CommandUtil.lookupUser(discordSRV, logger, execution, false, userArgument, null);
playerUUIDFuture.whenComplete((playerUUID, __) -> userIdFuture.whenComplete((userId, ___) -> {
if (playerUUID == null) {
execution.messages().playerNotFound(execution);
return;
}
if (userId == null) {
execution.messages().userNotFound(execution);
return;
}
linkProvider.queryUserId(playerUUID).whenComplete((linkedUser, t) -> {
if (t != null) {
logger.error("Failed to check linking status", t);
execution.messages().unableToCheckLinkingStatus(execution);
return;
}
if (linkedUser.isPresent()) {
execution.messages().playerAlreadyLinked3rd(execution);
return;
}
linkProvider.queryPlayerUUID(userId).whenComplete((linkedPlayer, t2) -> {
if (t2 != null) {
logger.error("Failed to check linking status", t2);
execution.messages().unableToCheckLinkingStatus(execution);
return;
}
if (linkedPlayer.isPresent()) {
execution.messages().userAlreadyLinked3rd(execution);
return;
}
((LinkStore) linkProvider).createLink(playerUUID, userId).whenComplete((v, t3) -> {
if (t3 != null) {
logger.error("Failed to create link", t3);
execution.send(
execution.messages().minecraft.unableToLinkAtThisTime.asComponent(),
execution.messages().discord.unableToCheckLinkingStatus
);
return;
}
execution.messages().nowLinked3rd(discordSRV, execution, playerUUID, userId);
});
});
});
}));
}
private void startLinking(IPlayer player, String label) {
MessagesConfig.Minecraft messages = discordSRV.messagesConfig(player);
LinkProvider linkProvider = discordSRV.linkProvider();
if (linkProvider.getCachedUserId(player.uniqueId()).isPresent()) {
player.sendMessage(messages.alreadyLinked1st.asComponent());
return;
}
if (linkCheckRateLimit.getIfPresent(player.uniqueId()) != null) {
player.sendMessage(messages.pleaseWaitBeforeRunningThatCommandAgain.asComponent());
return;
}
linkCheckRateLimit.put(player.uniqueId(), true);
player.sendMessage(discordSRV.messagesConfig(player).checkingLinkStatus.asComponent());
linkProvider.queryUserId(player.uniqueId(), true).whenComplete((userId, t1) -> {
if (t1 != null) {
logger.error("Failed to check linking status", t1);
player.sendMessage(messages.unableToLinkAtThisTime.asComponent());
return;
}
if (userId.isPresent()) {
player.sendMessage(messages.nowLinked1st.asComponent());
return;
}
linkProvider.getLinkingInstructions(player, label).whenComplete((comp, t2) -> {
if (t2 != null) {
logger.error("Failed to link account", t2);
player.sendMessage(messages.unableToLinkAtThisTime.asComponent());
return;
}
player.sendMessage(ComponentUtil.fromAPI(comp));
});
});
}
}
| 9,283 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
VersionCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/VersionCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.color.Color;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.Text;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.debug.data.VersionInfo;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class VersionCommand extends CombinedCommand {
private static VersionCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static VersionCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new VersionCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
VersionCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("version")
.requiredPermission(Permission.COMMAND_VERSION)
.executor(command);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
VersionCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "version"), "version", "Get the DiscordSRV version")
.setEventHandler(command)
.build();
}
return DISCORD;
}
public VersionCommand(DiscordSRV discordSRV) {
super(discordSRV);
}
@Override
public void execute(CommandExecution execution) {
VersionInfo versionInfo = discordSRV.versionInfo();
List<Text> text = new ArrayList<>();
text.add(
new Text("Running DiscordSRV ")
.withGameColor(TextColor.color(Color.BLURPLE.rgb()))
);
text.add(
new Text("v" + versionInfo.version())
.withGameColor(NamedTextColor.GRAY)
.withDiscordFormatting(Text.Formatting.BOLD)
);
if (versionInfo.isSnapshot()) {
String rev = StringUtils.substring(versionInfo.gitRevision(), 0, 6);
text.add(new Text(" (" + rev + "/" + versionInfo.gitBranch() + ")").withGameColor(NamedTextColor.AQUA));
}
execution.send(text);
}
}
| 3,747 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DebugCommand.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/combined/commands/DebugCommand.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.command.combined.commands;
import com.discordsrv.api.discord.entity.interaction.command.CommandOption;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CombinedCommand;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.Text;
import com.discordsrv.common.command.game.abstraction.GameCommand;
import com.discordsrv.common.debug.DebugReport;
import com.discordsrv.common.paste.Paste;
import com.discordsrv.common.paste.PasteService;
import com.discordsrv.common.paste.service.AESEncryptedPasteService;
import com.discordsrv.common.paste.service.BytebinPasteService;
import com.discordsrv.common.permission.Permission;
import net.kyori.adventure.text.format.NamedTextColor;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Collections;
import java.util.Locale;
public class DebugCommand extends CombinedCommand {
private static DebugCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
private static DebugCommand getInstance(DiscordSRV discordSRV) {
return INSTANCE != null ? INSTANCE : (INSTANCE = new DebugCommand(discordSRV));
}
public static GameCommand getGame(DiscordSRV discordSRV) {
if (GAME == null) {
DebugCommand command = getInstance(discordSRV);
GAME = GameCommand.literal("debug")
.requiredPermission(Permission.COMMAND_DEBUG)
.executor(command)
.then(
GameCommand.stringWord("format")
.suggester((sender, previousArguments, currentInput) ->
"zip".startsWith(currentInput.toLowerCase(Locale.ROOT))
? Collections.singletonList("zip") : Collections.emptyList())
.executor(command)
);
}
return GAME;
}
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
DebugCommand command = getInstance(discordSRV);
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "debug"), "debug", "Create a debug report")
.addOption(
CommandOption.builder(CommandOption.Type.STRING, "format", "The format to generate the debug report")
.addChoice(".zip", "zip")
.setRequired(false)
.build()
)
.setEventHandler(command)
.build();
}
return DISCORD;
}
private static final String URL_FORMAT = DiscordSRV.WEBSITE + "/debug/%s#%s";
private static final Base64.Encoder KEY_ENCODER = Base64.getUrlEncoder().withoutPadding();
private final PasteService pasteService;
public DebugCommand(DiscordSRV discordSRV) {
super(discordSRV);
this.pasteService = new AESEncryptedPasteService(new BytebinPasteService(discordSRV, "https://bytebin.lucko.me") /* TODO: final store tbd */, 128);
}
@Override
public void execute(CommandExecution execution) {
boolean usePaste = !"zip".equals(execution.getArgument("format"));
execution.runAsync(() -> {
DebugReport report = new DebugReport(discordSRV);
report.generate();
Throwable pasteError = usePaste ? paste(execution, report) : null;
if (usePaste && pasteError == null) {
// Success
return;
}
Throwable zipError = zip(execution, report);
if (zipError == null) {
// Success
if (usePaste) {
discordSRV.logger().warning("Failed to upload debug, zip generation succeeded", pasteError);
}
return;
}
if (pasteError != null) {
zipError.addSuppressed(pasteError);
}
discordSRV.logger().error(usePaste ? "Failed to upload & zip debug" : "Failed to zip debug", zipError);
execution.send(
new Text(usePaste
? "Failed to upload debug report to paste & failed to generate zip"
: "Failed to create debug zip"
).withGameColor(NamedTextColor.DARK_RED)
);
});
}
private Throwable paste(CommandExecution execution, DebugReport report) {
try {
Paste paste = report.upload(pasteService);
String key = new String(KEY_ENCODER.encode(paste.decryptionKey()), StandardCharsets.UTF_8);
String url = String.format(URL_FORMAT, paste.id(), key);
execution.send(new Text(url));
return null;
} catch (Throwable e) {
return e;
}
}
private Throwable zip(CommandExecution execution, DebugReport report) {
try {
Path zip = report.zip();
Path relative = discordSRV.dataDirectory().resolve("../..").relativize(zip);
execution.send(
new Text("Debug generated to zip ")
.withGameColor(NamedTextColor.GRAY),
new Text(relative.toString())
.withGameColor(NamedTextColor.GREEN)
.withDiscordFormatting(Text.Formatting.BOLD)
);
return null;
} catch (Throwable e) {
return e;
}
}
}
| 6,818 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
CommandUtil.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/command/util/CommandUtil.java | package com.discordsrv.common.command.util;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.command.combined.abstraction.CommandExecution;
import com.discordsrv.common.command.combined.abstraction.DiscordCommandExecution;
import com.discordsrv.common.command.combined.abstraction.GameCommandExecution;
import com.discordsrv.common.command.game.sender.ICommandSender;
import com.discordsrv.common.config.messages.MessagesConfig;
import com.discordsrv.common.logging.Logger;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import com.discordsrv.common.uuid.util.UUIDUtil;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.utils.MiscUtil;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public final class CommandUtil {
private CommandUtil() {}
public static CompletableFuture<UUID> lookupPlayer(
DiscordSRV discordSRV,
Logger logger,
CommandExecution execution,
boolean selfPermitted,
String target,
@Nullable Permission otherPermission
) {
return lookupTarget(discordSRV, logger, execution, target, selfPermitted, true, false, otherPermission)
.thenApply((result) -> {
if (result != null && result.isValid()) {
return result.getPlayerUUID();
}
return null;
});
}
public static CompletableFuture<Long> lookupUser(
DiscordSRV discordSRV,
Logger logger,
CommandExecution execution,
boolean selfPermitted,
String target,
@Nullable Permission otherPermission
) {
return lookupTarget(discordSRV, logger, execution, target, selfPermitted, false, true, otherPermission)
.thenApply(result -> {
if (result != null && result.isValid()) {
return result.getUserId();
}
return null;
});
}
public static CompletableFuture<TargetLookupResult> lookupTarget(
DiscordSRV discordSRV,
Logger logger,
CommandExecution execution,
boolean selfPermitted,
@Nullable Permission otherPermission
) {
String target = execution.getArgument("target");
if (target == null) {
target = execution.getArgument("user");
}
if (target == null) {
target = execution.getArgument("player");
}
return lookupTarget(discordSRV, logger, execution, target, selfPermitted, true, true, otherPermission);
}
private static CompletableFuture<TargetLookupResult> lookupTarget(
DiscordSRV discordSRV,
Logger logger,
CommandExecution execution,
String target,
boolean selfPermitted,
boolean lookupPlayer,
boolean lookupUser,
@Nullable Permission otherPermission
) {
MessagesConfig messages = discordSRV.messagesConfig(execution.locale());
if (execution instanceof GameCommandExecution) {
ICommandSender sender = ((GameCommandExecution) execution).getSender();
if (target != null) {
if (otherPermission != null && !sender.hasPermission(Permission.COMMAND_LINKED_OTHER)) {
sender.sendMessage(discordSRV.messagesConfig(sender).noPermission.asComponent());
return CompletableFuture.completedFuture(TargetLookupResult.INVALID);
}
} else if (sender instanceof IPlayer && selfPermitted && lookupPlayer) {
target = ((IPlayer) sender).uniqueId().toString();
}
} else if (execution instanceof DiscordCommandExecution) {
if (target == null) {
if (selfPermitted && lookupUser) {
target = Long.toUnsignedString(((DiscordCommandExecution) execution).getUser().getIdLong());
} else {
execution.send(
messages.minecraft.pleaseSpecifyUser.asComponent(),
messages.discord.pleaseSpecifyUser
);
return CompletableFuture.completedFuture(TargetLookupResult.INVALID);
}
}
} else {
throw new IllegalStateException("Unexpected CommandExecution");
}
if (target == null) {
return CompletableFuture.completedFuture(requireTarget(execution, lookupUser, lookupPlayer, messages));
}
if (lookupUser) {
if (target.matches("\\d{17,22}")) {
// Discord user id
long id;
try {
id = MiscUtil.parseLong(target);
} catch (IllegalArgumentException ignored) {
execution.send(
messages.minecraft.userNotFound.asComponent(),
messages.discord.userNotFound
);
return CompletableFuture.completedFuture(TargetLookupResult.INVALID);
}
return CompletableFuture.completedFuture(new TargetLookupResult(true, null, id));
} else if (target.startsWith("@")) {
// Discord username
String username = target.substring(1);
JDA jda = discordSRV.jda();
if (jda != null) {
List<User> users = jda.getUsersByName(username, true);
if (users.size() == 1) {
return CompletableFuture.completedFuture(new TargetLookupResult(true, null, users.get(0).getIdLong()));
}
}
}
}
if (lookupPlayer) {
UUID uuid;
boolean shortUUID;
if ((shortUUID = target.length() == 32) || target.length() == 36) {
// Player UUID
try {
if (shortUUID) {
uuid = UUIDUtil.fromShort(target);
} else {
uuid = UUID.fromString(target);
}
} catch (IllegalArgumentException ignored) {
execution.send(
messages.minecraft.playerNotFound.asComponent(),
messages.discord.playerNotFound
);
return CompletableFuture.completedFuture(TargetLookupResult.INVALID);
}
return CompletableFuture.completedFuture(new TargetLookupResult(true, uuid, 0L));
} else if (target.matches("[a-zA-Z0-9_]{1,16}")) {
// Player name
IPlayer playerByName = discordSRV.playerProvider().player(target);
if (playerByName != null) {
uuid = playerByName.uniqueId();
} else {
return discordSRV.playerProvider().lookupOfflinePlayer(target)
.thenApply(offlinePlayer -> new TargetLookupResult(true, offlinePlayer.uniqueId(), 0L))
.exceptionally(t -> {
logger.error("Failed to lookup offline player by username", t);
return TargetLookupResult.INVALID;
});
}
return CompletableFuture.completedFuture(new TargetLookupResult(true, uuid, 0L));
}
}
return CompletableFuture.completedFuture(requireTarget(execution, lookupUser, lookupPlayer, messages));
}
private static TargetLookupResult requireTarget(CommandExecution execution, boolean lookupUser, boolean lookupPlayer, MessagesConfig messages) {
if (lookupPlayer && lookupUser) {
execution.send(
messages.minecraft.pleaseSpecifyPlayerOrUser.asComponent(),
messages.discord.pleaseSpecifyPlayerOrUser
);
return TargetLookupResult.INVALID;
} else if (lookupPlayer) {
execution.send(
messages.minecraft.pleaseSpecifyPlayer.asComponent(),
messages.discord.pleaseSpecifyPlayer
);
return TargetLookupResult.INVALID;
} else if (lookupUser) {
execution.send(
messages.minecraft.pleaseSpecifyUser.asComponent(),
messages.discord.pleaseSpecifyUser
);
return TargetLookupResult.INVALID;
} else {
throw new IllegalStateException("lookupPlayer & lookupUser are false");
}
}
public static class TargetLookupResult {
public static TargetLookupResult INVALID = new TargetLookupResult(false, null, 0L);
private final boolean valid;
private final UUID playerUUID;
private final long userId;
public TargetLookupResult(boolean valid, UUID playerUUID, long userId) {
this.valid = valid;
this.playerUUID = playerUUID;
this.userId = userId;
}
public boolean isValid() {
return valid;
}
public boolean isPlayer() {
return playerUUID != null;
}
public UUID getPlayerUUID() {
return playerUUID;
}
public long getUserId() {
return userId;
}
}
}
| 9,709 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
AwardMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/AwardMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.bus.EventPriority;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.message.forward.game.AwardMessageForwardedEvent;
import com.discordsrv.api.event.events.message.receive.game.AwardMessageReceiveEvent;
import com.discordsrv.api.player.DiscordSRVPlayer;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.server.ServerBaseChannelConfig;
import com.discordsrv.common.config.main.channels.server.AwardMessageConfig;
import com.github.benmanes.caffeine.cache.Cache;
import net.kyori.adventure.text.Component;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class AwardMessageModule extends AbstractGameMessageModule<AwardMessageConfig, AwardMessageReceiveEvent> {
private final Cache<UUID, AtomicInteger> advancementCount;
public AwardMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "AWARD_MESSAGES");
this.advancementCount = discordSRV.caffeineBuilder()
.expireAfterWrite(5, TimeUnit.SECONDS)
.build();
}
@SuppressWarnings("DataFlowIssue") // Not possible
private boolean checkIfShouldPermit(DiscordSRVPlayer player) {
// Prevent spamming if a lot of advancements are granted at once (the advancement command)
int count = advancementCount.get(player.uniqueId(), key -> new AtomicInteger(0)).incrementAndGet();
boolean permit = count < 5;
if (!permit && (count % 5 == 0)) {
logger().debug("Skipping advancement/achievement processing for player " + player.username()
+ ", currently at " + count + " advancements/achievements within 5 seconds");
}
return permit;
}
@Subscribe(priority = EventPriority.LAST)
public void onAwardMessageReceive(AwardMessageReceiveEvent event) {
if (checkCancellation(event) || checkProcessor(event)) {
return;
}
if (checkIfShouldPermit(event.getPlayer())) {
process(event, event.getPlayer(), event.getGameChannel());
}
event.markAsProcessed();
}
@Override
public AwardMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return ((ServerBaseChannelConfig) channelConfig).awardMessages;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {
discordSRV.eventBus().publish(new AwardMessageForwardedEvent(cluster));
}
@Override
public void setPlaceholders(AwardMessageConfig config, AwardMessageReceiveEvent event, SendableDiscordMessage.Formatter formatter) {
MinecraftComponent nameComponent = event.getName();
Component name = nameComponent != null ? ComponentUtil.fromAPI(nameComponent) : null;
MinecraftComponent titleComponent = event.getTitle();
Component title = titleComponent != null ? ComponentUtil.fromAPI(titleComponent) : null;
formatter
.addPlaceholder("award_name", name)
.addPlaceholder("award_title", title);
}
}
| 4,390 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
StopMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/StopMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.events.message.receive.game.AbstractGameMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.main.channels.StopMessageConfig;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.player.IPlayer;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class StopMessageModule extends AbstractGameMessageModule<StopMessageConfig, AbstractGameMessageReceiveEvent> {
public StopMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "START_MESSAGE");
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public StopMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return channelConfig.stopMessage;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {}
@Override
public Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> sendMessageToChannels(
StopMessageConfig config,
IPlayer player,
SendableDiscordMessage.Builder format,
Collection<DiscordGuildMessageChannel> channels,
AbstractGameMessageReceiveEvent event,
Object... context
) {
if (!config.enabled) {
return Collections.emptyMap();
}
return super.sendMessageToChannels(config, player, format, channels, event, context);
}
@Override
public void setPlaceholders(StopMessageConfig config, AbstractGameMessageReceiveEvent event, SendableDiscordMessage.Formatter formatter) {}
@Override
public void disable() {
try {
process(null, null, null).get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
logger().error("Failed to queue stop message to be sent within 5 seconds.");
} catch (InterruptedException | ExecutionException ignored) {}
}
}
| 3,365 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
DeathMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/DeathMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.bus.EventPriority;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.message.forward.game.DeathMessageForwardedEvent;
import com.discordsrv.api.event.events.message.receive.game.DeathMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.server.ServerBaseChannelConfig;
import com.discordsrv.common.config.main.channels.server.DeathMessageConfig;
public class DeathMessageModule extends AbstractGameMessageModule<DeathMessageConfig, DeathMessageReceiveEvent> {
public DeathMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "DEATH_MESSAGES");
}
@Subscribe(priority = EventPriority.LAST)
public void onDeathMessageReceive(DeathMessageReceiveEvent event) {
if (checkCancellation(event) || checkProcessor(event)) {
return;
}
process(event, event.getPlayer(), event.getGameChannel());
event.markAsProcessed();
}
@Override
public DeathMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return ((ServerBaseChannelConfig) channelConfig).deathMessages;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {
discordSRV.eventBus().publish(new DeathMessageForwardedEvent(cluster));
}
@Override
public void setPlaceholders(
DeathMessageConfig config,
DeathMessageReceiveEvent event,
SendableDiscordMessage.Formatter formatter
) {
MinecraftComponent messageComponent = event.getMessage();
formatter.addPlaceholder("message", ComponentUtil.fromAPI(messageComponent));
}
}
| 2,950 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
LeaveMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/LeaveMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.bus.EventPriority;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.message.forward.game.LeaveMessageForwardedEvent;
import com.discordsrv.api.event.events.message.receive.game.LeaveMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.LeaveMessageConfig;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class LeaveMessageModule extends AbstractGameMessageModule<LeaveMessageConfig, LeaveMessageReceiveEvent> {
public LeaveMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "LEAVE_MESSAGES");
}
@Subscribe(priority = EventPriority.LAST)
public void onLeaveMessageReceive(LeaveMessageReceiveEvent event) {
if (checkCancellation(event) || checkProcessor(event)) {
return;
}
process(event, event.getPlayer(), event.getGameChannel());
event.markAsProcessed();
}
@Override
protected CompletableFuture<Void> forwardToChannel(
@Nullable LeaveMessageReceiveEvent event,
@Nullable IPlayer player,
@NotNull BaseChannelConfig config
) {
if (config.leaveMessages.enableSilentPermission && player != null && player.hasPermission(Permission.SILENT_QUIT)) {
logger().info(player.username() + " is leaving silently, leave message will not be sent");
return CompletableFuture.completedFuture(null);
}
return super.forwardToChannel(event, player, config);
}
@Override
public LeaveMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return channelConfig.leaveMessages;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {
discordSRV.eventBus().publish(new LeaveMessageForwardedEvent(cluster));
}
@Override
public void setPlaceholders(
LeaveMessageConfig config,
LeaveMessageReceiveEvent event,
SendableDiscordMessage.Formatter formatter
) {
MinecraftComponent messageComponent = event.getMessage();
Component message = messageComponent != null ? ComponentUtil.fromAPI(messageComponent) : null;
formatter.addPlaceholder("message", message);
}
}
| 3,755 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
AbstractGameMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/AbstractGameMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.channel.GameChannel;
import com.discordsrv.api.discord.connection.jda.errorresponse.ErrorCallbackContext;
import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.events.message.receive.game.AbstractGameMessageReceiveEvent;
import com.discordsrv.api.player.DiscordSRVPlayer;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.IChannelConfig;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageClusterImpl;
import com.discordsrv.common.future.util.CompletableFutureUtil;
import com.discordsrv.common.logging.NamedLogger;
import com.discordsrv.common.module.type.AbstractModule;
import com.discordsrv.common.player.IPlayer;
import com.discordsrv.common.testing.TestHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public abstract class AbstractGameMessageModule<T extends IMessageConfig, E extends AbstractGameMessageReceiveEvent> extends AbstractModule<DiscordSRV> {
public AbstractGameMessageModule(DiscordSRV discordSRV, String loggerName) {
super(discordSRV, new NamedLogger(discordSRV, loggerName));
}
@Override
public boolean isEnabled() {
for (BaseChannelConfig channelConfig : discordSRV.channelConfig().getAllChannels()) {
if (mapConfig(channelConfig).enabled()) {
return true;
}
}
return false;
}
public T mapConfig(E event, BaseChannelConfig channelConfig) {
return mapConfig(channelConfig);
}
public abstract T mapConfig(BaseChannelConfig channelConfig);
public abstract void postClusterToEventBus(ReceivedDiscordMessageCluster cluster);
public final CompletableFuture<?> process(
@Nullable E event,
@Nullable DiscordSRVPlayer player,
@Nullable GameChannel channel
) {
if (player != null && !(player instanceof IPlayer)) {
throw new IllegalArgumentException("Provided player was not created by DiscordSRV, instead was " + player.getClass().getName());
}
IPlayer srvPlayer = (IPlayer) player;
if (channel == null) {
// Send to all channels due to lack of specified channel
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (BaseChannelConfig channelConfig : discordSRV.channelConfig().getAllChannels()) {
futures.add(forwardToChannel(event, srvPlayer, channelConfig));
}
return CompletableFutureUtil.combine(futures);
}
BaseChannelConfig channelConfig = discordSRV.channelConfig().get(channel);
return forwardToChannel(event, srvPlayer, channelConfig);
}
@SuppressWarnings("unchecked") // Wacky generis
protected <CC extends BaseChannelConfig & IChannelConfig> CompletableFuture<Void> forwardToChannel(
@Nullable E event,
@Nullable IPlayer player,
@NotNull BaseChannelConfig config
) {
T moduleConfig = mapConfig(event, config);
if (!moduleConfig.enabled()) {
return null;
}
CC channelConfig = config instanceof IChannelConfig ? (CC) config : null;
if (channelConfig == null) {
return null;
}
return discordSRV.discordAPI().findOrCreateDestinations(channelConfig, true, true).thenCompose(messageChannels -> {
SendableDiscordMessage.Builder format = moduleConfig.format();
if (format == null || format.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> messageFutures;
messageFutures = sendMessageToChannels(
moduleConfig, player, format, messageChannels, event,
// Context
config, player
);
return CompletableFuture.allOf(messageFutures.keySet().toArray(new CompletableFuture[0]))
.whenComplete((vo, t2) -> {
Set<ReceivedDiscordMessage> messages = new LinkedHashSet<>();
for (Map.Entry<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> entry : messageFutures.entrySet()) {
CompletableFuture<ReceivedDiscordMessage> future = entry.getKey();
if (future.isCompletedExceptionally()) {
future.exceptionally(t -> {
if (t instanceof CompletionException) {
t = t.getCause();
}
ErrorCallbackContext.context("Failed to deliver a message to " + entry.getValue()).accept(t);
TestHelper.fail(t);
return null;
});
// Ignore ones that failed
continue;
}
// They are all done, so joining will return the result instantly
messages.add(future.join());
}
if (messages.isEmpty()) {
// Nothing was delivered
return;
}
postClusterToEventBus(new ReceivedDiscordMessageClusterImpl(messages));
})
.exceptionally(t -> {
if (t instanceof CompletionException) {
return null;
}
discordSRV.logger().error("Failed to publish to event bus", t);
TestHelper.fail(t);
return null;
});
}).exceptionally(t -> {
discordSRV.logger().error("Error in sending message", t);
TestHelper.fail(t);
return null;
});
}
public Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> sendMessageToChannels(
T config,
IPlayer player,
SendableDiscordMessage.Builder format,
Collection<DiscordGuildMessageChannel> channels,
E event,
Object... context
) {
SendableDiscordMessage.Formatter formatter = format.toFormatter()
.addContext(context)
.applyPlaceholderService();
setPlaceholders(config, event, formatter);
SendableDiscordMessage discordMessage = formatter
.build();
if (discordMessage.isEmpty()) {
return Collections.emptyMap();
}
Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> futures = new LinkedHashMap<>();
for (DiscordGuildMessageChannel channel : channels) {
futures.put(channel.sendMessage(discordMessage), channel);
}
return futures;
}
public abstract void setPlaceholders(T config, E event, SendableDiscordMessage.Formatter formatter);
}
| 8,661 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
JoinMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/JoinMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.bus.EventPriority;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.message.forward.game.JoinMessageForwardedEvent;
import com.discordsrv.api.event.events.message.receive.game.JoinMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.generic.IMessageConfig;
import com.discordsrv.common.permission.Permission;
import com.discordsrv.common.player.IPlayer;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class JoinMessageModule extends AbstractGameMessageModule<IMessageConfig, JoinMessageReceiveEvent> {
public JoinMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "JOIN_MESSAGES");
}
@Subscribe(priority = EventPriority.LAST)
public void onJoinMessageReceive(JoinMessageReceiveEvent event) {
if (checkCancellation(event) || checkProcessor(event)) {
return;
}
process(event, event.getPlayer(), event.getGameChannel());
event.markAsProcessed();
}
@Override
protected CompletableFuture<Void> forwardToChannel(
@Nullable JoinMessageReceiveEvent event,
@Nullable IPlayer player,
@NotNull BaseChannelConfig config
) {
if (config.joinMessages().enableSilentPermission && player != null && player.hasPermission(Permission.SILENT_JOIN)) {
logger().info(player.username() + " is joining silently, join message will not be sent");
return CompletableFuture.completedFuture(null);
}
return super.forwardToChannel(event, player, config);
}
@Override
public IMessageConfig mapConfig(JoinMessageReceiveEvent event, BaseChannelConfig channelConfig) {
return channelConfig.joinMessages().getForEvent(event);
}
@Override
public IMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return channelConfig.joinMessages();
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {
discordSRV.eventBus().publish(new JoinMessageForwardedEvent(cluster));
}
@Override
public void setPlaceholders(
IMessageConfig config,
JoinMessageReceiveEvent event,
SendableDiscordMessage.Formatter formatter
) {
MinecraftComponent messageComponent = event.getMessage();
Component message = messageComponent != null ? ComponentUtil.fromAPI(messageComponent) : null;
formatter.addPlaceholder("message", message);
}
}
| 3,915 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
ServerSwitchMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/ServerSwitchMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.component.MinecraftComponent;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.bus.EventPriority;
import com.discordsrv.api.event.bus.Subscribe;
import com.discordsrv.api.event.events.message.forward.game.ServerSwitchMessageForwardedEvent;
import com.discordsrv.api.event.events.message.receive.game.ServerSwitchMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.component.util.ComponentUtil;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.config.main.channels.base.proxy.ProxyBaseChannelConfig;
import com.discordsrv.common.config.main.channels.proxy.ServerSwitchMessageConfig;
import net.kyori.adventure.text.Component;
public class ServerSwitchMessageModule extends AbstractGameMessageModule<ServerSwitchMessageConfig, ServerSwitchMessageReceiveEvent> {
public ServerSwitchMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "SERVER_SWITCH_MESSAGES");
}
@Subscribe(priority = EventPriority.LAST)
public void onServerSwitchMessageReceive(ServerSwitchMessageReceiveEvent event) {
if (checkCancellation(event) || checkProcessor(event)) {
return;
}
process(event, event.getPlayer(), null);
event.markAsProcessed();
}
@Override
public ServerSwitchMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return ((ProxyBaseChannelConfig) channelConfig).serverSwitchMessages;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {
discordSRV.eventBus().publish(new ServerSwitchMessageForwardedEvent(cluster));
}
@Override
public void setPlaceholders(
ServerSwitchMessageConfig config,
ServerSwitchMessageReceiveEvent event,
SendableDiscordMessage.Formatter formatter
) {
MinecraftComponent messageComponent = event.getMessage();
Component message = messageComponent != null ? ComponentUtil.fromAPI(messageComponent) : null;
formatter.addPlaceholder("message", message);
}
}
| 3,148 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
StartMessageModule.java | /FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/StartMessageModule.java | /*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.common.messageforwarding.game;
import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage;
import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster;
import com.discordsrv.api.discord.entity.message.SendableDiscordMessage;
import com.discordsrv.api.event.events.message.receive.game.AbstractGameMessageReceiveEvent;
import com.discordsrv.common.DiscordSRV;
import com.discordsrv.common.config.main.channels.StartMessageConfig;
import com.discordsrv.common.config.main.channels.base.BaseChannelConfig;
import com.discordsrv.common.player.IPlayer;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class StartMessageModule extends AbstractGameMessageModule<StartMessageConfig, AbstractGameMessageReceiveEvent> {
public StartMessageModule(DiscordSRV discordSRV) {
super(discordSRV, "START_MESSAGE");
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public StartMessageConfig mapConfig(BaseChannelConfig channelConfig) {
return channelConfig.startMessage;
}
@Override
public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) {}
@Override
public Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> sendMessageToChannels(
StartMessageConfig config,
IPlayer player,
SendableDiscordMessage.Builder format,
Collection<DiscordGuildMessageChannel> channels,
AbstractGameMessageReceiveEvent event,
Object... context
) {
if (!config.enabled) {
return Collections.emptyMap();
}
return super.sendMessageToChannels(config, player, format, channels, event, context);
}
@Override
public void setPlaceholders(StartMessageConfig config, AbstractGameMessageReceiveEvent event, SendableDiscordMessage.Formatter formatter) {}
@Override
public void enable() {
process(null, null, null);
}
}
| 2,998 | Java | .java | DiscordSRV/Ascension | 17 | 3 | 1 | 2021-07-29T01:14:02Z | 2024-05-08T00:28:36Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.