Skip to content

Commit

Permalink
kitchen on fire
Browse files Browse the repository at this point in the history
  • Loading branch information
DoggySazHi committed Feb 19, 2024
1 parent 49f7831 commit 47d07ce
Show file tree
Hide file tree
Showing 10 changed files with 398 additions and 255 deletions.
3 changes: 0 additions & 3 deletions src/main/java/net/gensokyoreimagined/motoori/Kosuzu.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,6 @@ public final class Kosuzu extends JavaPlugin {
public final FileConfiguration config = getConfig();
public KosuzuRemembersEverything database;

private boolean papiGeoip = false;
public boolean canUsePAPIGeoIP() { return papiGeoip; }

public static Component HEADER = Component
.text("[", NamedTextColor.GOLD)
.append(Component.text("Kosuzu", NamedTextColor.YELLOW, TextDecoration.BOLD))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,52 +17,74 @@

import org.jetbrains.annotations.Nullable;

public class KosuzuDatabaseModels {
public static class Language {
private final String code;
private final String nativeName;
private final String englishName;

public Language(String code, String nativeName, String englishName) {
this.code = code;
this.nativeName = nativeName;
this.englishName = englishName;
}
import java.util.Objects;
import java.util.UUID;

public String getCode() { return code; }
public String getNativeName() { return nativeName; }
public String getEnglishName() { return englishName; }
}
public class KosuzuDatabaseModels {
public record Language(String code, String nativeName, String englishName) {}

public static class Message {
public static class Translation {
private final String messageJson;
private final String textMessage;
private @Nullable String translatedTextLanguageCode;
private final UUID originalTextMessageId;
private @Nullable String originalTextLanguageCode;
private final String originalTextMessage;
private final String requestedLanguageCode;
private @Nullable String translatedTextMessage;
private final String languageCode;

public Message(String messageJson, String textMessage, @Nullable String translatedTextLanguageCode, @Nullable String translatedTextMessage, String languageCode) {
public Translation(String messageJson, UUID originalTextMessageId, @Nullable String originalTextLanguageCode, String originalTextMessage, @Nullable String translatedTextMessage, String requestedLanguageCode) {
this.messageJson = messageJson;
this.textMessage = textMessage;
this.translatedTextLanguageCode = translatedTextLanguageCode;
this.originalTextMessageId = originalTextMessageId;
this.originalTextLanguageCode = originalTextLanguageCode;
this.originalTextMessage = originalTextMessage;
this.translatedTextMessage = translatedTextMessage;
this.languageCode = languageCode;
this.requestedLanguageCode = requestedLanguageCode;
}

public String getMessageJson() { return messageJson; }

public String getTextMessage() { return textMessage; }
public @Nullable String getOriginalTextLanguageCode() { return originalTextLanguageCode; }
public String getOriginalTextMessage() { return originalTextMessage; }
public String getTranslatedTextLanguageCode() { return requestedLanguageCode; }

public @Nullable String getTranslatedTextMessage() { return translatedTextMessage; }

public void loadTranslatedTextMessage(KosuzuTranslatesEverything translator) {
if (translatedTextLanguageCode != null && translatedTextMessage != null) {
public void loadTranslatedTextMessage(KosuzuTranslatesEverything translator, KosuzuRemembersEverything database) {
if (originalTextLanguageCode != null && translatedTextMessage != null) {
return;
}

var translation = translator.translate(textMessage, languageCode);
translatedTextLanguageCode = translation.detectedSourceLanguage;
var translation = translator.translate(originalTextMessage, requestedLanguageCode);
originalTextLanguageCode = translation.detectedSourceLanguage;
translatedTextMessage = translation.text;
database.addTranslation(originalTextMessageId, translation.text, requestedLanguageCode, translation.detectedSourceLanguage);
}
}

// Only used by the database class for caching
public static class Message {
private final String message;
private final String json;

public Message(String message, String json) {
this.message = message;
this.json = json;
}

public String getMessage() { return message; }
public String getJSON() { return json; }

// We don't need to compare the message, just the JSON

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Message message1 = (Message) o;
return Objects.equals(json, message1.json);
}

@Override
public int hashCode() {
return Objects.hash(json);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public KosuzuHintsEverything(Kosuzu kosuzu) {
return
LANGUAGES
.stream()
.filter(l -> l.getCode().toLowerCase().contains(query) || l.getNativeName().toLowerCase().contains(query) || l.getEnglishName().toLowerCase().contains(query))
.map(KosuzuDatabaseModels.Language::getNativeName)
.filter(l -> l.code().toLowerCase().contains(query) || l.nativeName().toLowerCase().contains(query) || l.englishName().toLowerCase().contains(query))
.map(KosuzuDatabaseModels.Language::nativeName)
.toList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,11 @@
package net.gensokyoreimagined.motoori;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,24 @@

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.json.JSONComponentSerializer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.util.UUID;

public class KosuzuLearnsEverything implements CommandExecutor {

private final KosuzuRemembersEverything database;
private final KosuzuTranslatesEverything translator;

public KosuzuLearnsEverything(Kosuzu kosuzu) {
database = kosuzu.database;
translator = new KosuzuTranslatesEverything(kosuzu);
}

@Override
Expand All @@ -43,6 +49,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command
return true;
}

if (args[0].equalsIgnoreCase("translate")) {
translateMessage(sender, args);
return true;
}

invalidSubcommand(sender);
return true;
}
Expand Down Expand Up @@ -77,11 +88,11 @@ private void changeUserLanguage(@NotNull CommandSender sender, @NotNull String[]
var languages = database.getLanguages();
var matchingLanguage = languages
.stream()
.filter(l -> l.getCode().toLowerCase().contains(language) || l.getNativeName().toLowerCase().contains(language) || l.getEnglishName().toLowerCase().contains(language))
.filter(l -> l.code().toLowerCase().contains(language) || l.nativeName().toLowerCase().contains(language) || l.englishName().toLowerCase().contains(language))
.findFirst();

if (matchingLanguage.isPresent()) {
var code = matchingLanguage.get().getCode();
var code = matchingLanguage.get().code();

database.setUserDefaultLanguage(player.getUniqueId(), code);

Expand All @@ -96,4 +107,65 @@ private void changeUserLanguage(@NotNull CommandSender sender, @NotNull String[]
);
}
}

private void translateMessage(@NotNull CommandSender sender, @NotNull String[] args) {
if (args.length < 2) {
return;
}

var uuid = UUID.fromString("00000000-0000-0000-0000-000000000000");
if (sender instanceof Player bukkitPlayer)
uuid = bukkitPlayer.getUniqueId();

UUID messageUuid;
var userLanguage = database.getUserDefaultLanguage(uuid);

try {
messageUuid = UUID.fromString(args[1]);
} catch (IllegalArgumentException e) {
return;
}

var translation = database.getTranslation(messageUuid, uuid);
translation.loadTranslatedTextMessage(translator, database);
var translatedLanguage = translation.getTranslatedTextLanguageCode();
var translated = translation.getTranslatedTextMessage();
var originalLanguage = translation.getOriginalTextLanguageCode();
var original = translation.getOriginalTextMessage();

if (translated == null || originalLanguage == null || translatedLanguage == null) {
sender.sendMessage(
Kosuzu.HEADER.append(Component.text(database.getTranslation("translate.fail", userLanguage), NamedTextColor.RED))
);

return;
}

var json = translation.getMessageJson();
json = json.replace(original, translated);
var translatedComponent = JSONComponentSerializer.json().deserialize(json);

sender.sendMessage(
Component
.text()
.append(
Component
.text()
.content("[" + originalLanguage + " -> " + translatedLanguage + "] ")
.color(NamedTextColor.GRAY)
)

.append(
translatedComponent
)
.append(
Component
.text()
.content(" (" + original + ")")
.decorate(TextDecoration.ITALIC)
.color(NamedTextColor.GRAY)
)
.build()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Kosuzu Copyright (C) 2024 Gensokyo Reimagined
//
// 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 net.gensokyoreimagined.motoori;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

public class KosuzuParsesEverything {
private final ArrayList<Pattern> regexes = new ArrayList<>();
private final Map<String, Map<UUID, Pattern>> placeholderRegexes = new HashMap<>();

public KosuzuParsesEverything(Kosuzu kosuzu) {
var config = kosuzu.config;
var regexes = config.getStringList("match.include");

for (var regex : regexes) {
if (regex.contains("%username%")) {
placeholderRegexes.put(regex, new HashMap<>());
} else {
this.regexes.add(Pattern.compile(regex));
}
}

kosuzu.getLogger().info("Prepared " + this.regexes.size() + " regexes");
}

/**
* Extracts the text message from a chat component
* Also determines if we should translate the message
* @param component The chat component created from the message
* @param player The player who sent the message
* @return The text message, or null if it could/should not be translated
*/
public @Nullable String getTextMessage(Component component, Player player) {
var text = PlainTextComponentSerializer.plainText().serialize(component);

for (var pattern : regexes) {
var matcher = pattern.matcher(text);
if (matcher.matches()) {
return matcher.group(1);
}
}

for (var placeholder : placeholderRegexes.entrySet()) {
var regex = placeholder.getKey();
var cache = placeholder.getValue();

var pattern = cache.computeIfAbsent(player.getUniqueId(), (key) -> Pattern.compile(regex.replace("%username%", player.getName())));
var matcher = pattern.matcher(text);

if (matcher.matches()) {
return matcher.group(1);
}
}

return null;
}
}
Loading

0 comments on commit 47d07ce

Please sign in to comment.