Skip to content

Commit

Permalink
improve: remove TranslationLoader
Browse files Browse the repository at this point in the history
  • Loading branch information
Siroshun09 committed Nov 19, 2023
1 parent 8c55422 commit 5154e41
Show file tree
Hide file tree
Showing 7 changed files with 231 additions and 295 deletions.
40 changes: 4 additions & 36 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,6 @@
<version>5.4</version>
<scope>provided</scope>
</dependency>
<!-- TranslationLoader https://github.com/Siroshun09/TranslationLoader -->
<dependency>
<groupId>com.github.siroshun09.translationloader</groupId>
<artifactId>translationloader</artifactId>
<version>2.0.2</version>
<scope>compile</scope>
</dependency>
</dependencies>

<pluginRepositories>
Expand All @@ -90,6 +83,8 @@
</resource>
</resources>

<finalName>${project.name}-${project.version}</finalName>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand All @@ -108,35 +103,8 @@
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<finalName>${project.name}-${project.version}</finalName>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
</excludes>
</filter>
</filters>
<shadedArtifactAttached>true</shadedArtifactAttached>
<minimizeJar>true</minimizeJar>
<relocations>
<relocation>
<pattern>com.github.siroshun09</pattern>
<shadedPattern>${project.groupId}.lib</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</build>
Expand Down
111 changes: 74 additions & 37 deletions src/main/java/net/okocraft/serverconnector/ServerConnectorPlugin.java
Original file line number Diff line number Diff line change
@@ -1,36 +1,44 @@
package net.okocraft.serverconnector;

import com.github.siroshun09.translationloader.directory.TranslationDirectory;
import com.google.inject.Inject;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyReloadEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.translation.Translator;
import net.okocraft.serverconnector.command.SlashServerCommand;
import net.okocraft.serverconnector.config.ServerConnectorConfig;
import net.okocraft.serverconnector.lang.Messages;
import net.okocraft.serverconnector.listener.FirstJoinListener;
import net.okocraft.serverconnector.listener.PlayerListener;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

public final class ServerConnectorPlugin {

private final ProxyServer proxy;
private final ServerConnectorConfig config = new ServerConnectorConfig();
private final TranslationDirectory translationDirectory;
private final Map<Locale, Messages> localizedMessagesMap = new HashMap<>();
private final Path dataDirectory;
private final List<SlashServerCommand> registeredSlashServerCommands = new ArrayList<>();

Expand All @@ -40,29 +48,16 @@ public final class ServerConnectorPlugin {
public ServerConnectorPlugin(@NotNull ProxyServer proxy, @DataDirectory Path dataDirectory) {
this.proxy = proxy;
this.dataDirectory = dataDirectory;

this.translationDirectory =
TranslationDirectory.newBuilder()
.setDirectory(dataDirectory.resolve("languages"))
.setKey(Key.key("serverconnector", "language"))
.setDefaultLocale(Locale.ENGLISH)
.onDirectoryCreated(this::saveDefaultLanguages)
.build();

}

@Subscribe(order = PostOrder.FIRST)
public void onEnable(ProxyInitializeEvent ignored) {
try {
Files.createDirectories(this.dataDirectory);
this.loadConfig();
} catch (IOException e) {
throw new IllegalStateException("Failed to load config.yml", e);
}

try {
translationDirectory.load();
} catch (IOException e) {
throw new IllegalStateException("Failed to load languages", e);
this.loadMessages();
} catch (IOException | UncheckedIOException e) {
throw new IllegalStateException("Failed to load config.yml or languages", e);
}

enablePlayerListener();
Expand All @@ -78,17 +73,15 @@ public void onDisable(ProxyShutdownEvent ignored) {

getProxy().getEventManager().unregisterListeners(this);

registeredSlashServerCommands.forEach(SlashServerCommand::unregister);

translationDirectory.unload();
this.registeredSlashServerCommands.forEach(SlashServerCommand::unregister);
this.registeredSlashServerCommands.clear();
this.localizedMessagesMap.clear();
}

@Subscribe
public void onReload(ProxyReloadEvent ignored) {
if (!registeredSlashServerCommands.isEmpty()) {
registeredSlashServerCommands.forEach(SlashServerCommand::unregister);
enableSlashServer();
}
this.registeredSlashServerCommands.forEach(SlashServerCommand::unregister);
enableSlashServer();
}

public @NotNull ProxyServer getProxy() {
Expand All @@ -99,6 +92,24 @@ public void onReload(ProxyReloadEvent ignored) {
return config;
}

public @NotNull Messages getLocalizedMessages(@Nullable CommandSource sender) {
if (sender instanceof Player) {
return this.getLocalizedMessages(((Player) sender).getEffectiveLocale());
} else {
return this.getLocalizedMessages((Locale) null);
}
}

public @NotNull Messages getLocalizedMessages(@Nullable Locale locale) {
var messages = this.localizedMessagesMap.get(locale);

if (messages == null && locale != null) {
messages = this.localizedMessagesMap.get(new Locale(locale.getLanguage()));
}

return messages != null ? messages : this.localizedMessagesMap.get(null);
}

private void loadConfig() throws IOException {
var filepath = this.dataDirectory.resolve("config.yml");

Expand Down Expand Up @@ -131,6 +142,42 @@ private void loadConfig() throws IOException {
this.config.fallbackServer = node.getNode("server-to-send-when-kicked").getString();
}

private void loadMessages() throws IOException {
Path directory = this.dataDirectory.resolve("languages");
Files.createDirectories(directory);
this.localizedMessagesMap.put(null, new Messages(ConfigurationNode.root()));
this.saveResource("en.yml", directory.resolve("en.yml"));
this.saveResource("ja_JP.yml", directory.resolve("ja_JP.yml"));
try (Stream<Path> list = Files.list(directory)) {
list.forEach(this::loadMessageFile);
}
}

private void loadMessageFile(Path filepath) {
String filename = filepath.getFileName().toString();
if (!filename.endsWith(".yml")) {
return;
}

Locale locale = Translator.parseLocale(filename.substring(0, filename.length() - 4));

if (locale == null) {
return;
}

ConfigurationNode source;

try {
source = YAMLConfigurationLoader.builder().setPath(filepath).build().load();
} catch (IOException e) {
throw new UncheckedIOException(e);
}

var messageMap = new Messages(source);
this.localizedMessagesMap.put(locale, messageMap);
this.localizedMessagesMap.put(new Locale(locale.getLanguage()), messageMap);
}

private void saveResource(String resourceName, Path filepath) throws IOException {
if (!Files.isRegularFile(filepath)) {
try (InputStream input = this.getClass().getClassLoader().getResourceAsStream(resourceName)) {
Expand Down Expand Up @@ -158,14 +205,4 @@ private void enableFirstJoinDetector() {
this.firstJoinListener = new FirstJoinListener(this);
}
}

private void saveDefaultLanguages(@NotNull Path directory) throws IOException {
var defaultFileName = "en.yml";
var defaultFile = directory.resolve(defaultFileName);
this.saveResource(defaultFileName, defaultFile);

var japaneseFileName = "ja_JP.yml";
var japaneseFile = directory.resolve(japaneseFileName);
this.saveResource(japaneseFileName, japaneseFile);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import net.kyori.adventure.text.Component;
import net.okocraft.serverconnector.ServerConnectorPlugin;
import net.okocraft.serverconnector.lang.Messages;

import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -45,9 +45,10 @@ public void unregister() {
@Override
public void execute(Invocation invocation) {
var sender = invocation.source();
var messages = this.plugin.getLocalizedMessages(sender);

if (!sender.hasPermission(this.permission)) {
sender.sendMessage(Messages.SLASH_SERVER_NO_PERMISSION.apply(this.permission));
sender.sendMessage(messages.slashServerNoPermission);
return;
}

Expand All @@ -56,40 +57,39 @@ public void execute(Invocation invocation) {

if (0 < args.length) {
if (!sender.hasPermission(GLOBAL_OTHER_PLAYER_PERMISSION) && !sender.hasPermission(otherPermission)) {
sender.sendMessage(Messages.SLASH_SERVER_NO_PERMISSION.apply(otherPermission));
sender.sendMessage(messages.slashServerNoPermission);
return;
}

target = this.plugin.getProxy().getPlayer(args[0]).orElse(null);

if (target == null) {
sender.sendMessage(Messages.SLASH_SERVER_PLAYER_NOT_FOUND.apply(args[0]));
sender.sendMessage(messages.slashServerPlayerNotFound(args[0]));
return;
}
} else {
if (sender instanceof Player) {
target = (Player) sender;
} else {
sender.sendMessage(Messages.SLASH_SERVER_ONLY_PLAYER);
sender.sendMessage(Component.text("/" + this.serverInfo.getName() + " <player>"));
return;
}
}

var currentServer = target.getCurrentServer().map(ServerConnection::getServerInfo);

if (serverInfo.equals(currentServer.orElse(null))) {
sender.sendMessage(Messages.SLASH_SERVER_ALREADY_CONNECTED);
if (this.serverInfo.equals(currentServer.orElse(null))) {
sender.sendMessage(messages.slashServerAlreadyConnected);
return;
}

target.createConnectionRequest(server).fireAndForget();
target.sendMessage(messages.slashServerConnecting(this.serverInfo.getName()));

if (sender != target) {
target.sendMessage(Messages.SLASH_SERVER_CONNECTING.apply(serverInfo.getName()));
sender.sendMessage(Messages.SLASH_SERVER_CONNECTING_OTHER.apply(target, serverInfo.getName()));
} else {
sender.sendMessage(Messages.SLASH_SERVER_CONNECTING.apply(serverInfo.getName()));
sender.sendMessage(messages.slashServerConnectingOther(target, this.serverInfo.getName()));
}

target.createConnectionRequest(this.server).fireAndForget();
}

@Override
Expand All @@ -98,9 +98,9 @@ public List<String> suggest(Invocation invocation) {
var args = invocation.arguments();

if (args.length <= 1 && (sender.hasPermission(GLOBAL_OTHER_PLAYER_PERMISSION) || sender.hasPermission(otherPermission))) {
return plugin.getProxy().getAllPlayers().stream()
return this.plugin.getProxy().getAllPlayers().stream()
.filter(Predicate.not(sender::equals))
.filter(Predicate.not(player -> serverInfo.equals(player.getCurrentServer().map(ServerConnection::getServerInfo).orElse(null))))
.filter(Predicate.not(player -> this.serverInfo.equals(player.getCurrentServer().map(ServerConnection::getServerInfo).orElse(null))))
.map(Player::getUsername)
.filter(name -> args.length == 0 || name.regionMatches(true, 0, args[0], 0, args[0].length()))
.collect(Collectors.toList());
Expand Down
Loading

0 comments on commit 5154e41

Please sign in to comment.