use of com.loohp.interactivechat.InteractiveChat in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class InteractiveChatDiscordSrvAddon method onEnable.
@Override
public void onEnable() {
plugin = this;
interactivechat = InteractiveChat.plugin;
discordsrv = DiscordSRV.getPlugin();
if (!getDataFolder().exists()) {
getDataFolder().mkdirs();
}
AssetsDownloader.loadLibraries(getDataFolder());
try {
Config.loadConfig(CONFIG_ID, new File(getDataFolder(), "config.yml"), getClass().getClassLoader().getResourceAsStream("config.yml"), getClass().getClassLoader().getResourceAsStream("config.yml"), true);
} catch (IOException e) {
e.printStackTrace();
getServer().getPluginManager().disablePlugin(this);
return;
}
reloadConfig();
metrics = new Metrics(this, BSTATS_PLUGIN_ID);
Charts.setup(metrics);
DiscordSRV.api.subscribe(new DiscordReadyEvents());
DiscordSRV.api.subscribe(new OutboundToDiscordEvents());
DiscordSRV.api.subscribe(new InboundToGameEvents());
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new InboundToGameEvents(), this);
getServer().getPluginManager().registerEvents(new OutboundToDiscordEvents(), this);
getServer().getPluginManager().registerEvents(new ICPlayerEvents(), this);
getServer().getPluginManager().registerEvents(new Debug(), this);
getServer().getPluginManager().registerEvents(new Updater(), this);
getCommand("interactivechatdiscordsrv").setExecutor(new Commands());
File resourcepacks = new File(getDataFolder(), "resourcepacks");
if (!resourcepacks.exists()) {
File resources = new File(getDataFolder(), "resources");
if (resources.exists() && resources.isDirectory()) {
try {
Files.move(resources.toPath(), resourcepacks.toPath(), StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
getServer().getConsoleSender().sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] Unable to move folder, are any files opened?");
e.printStackTrace();
getServer().getPluginManager().disablePlugin(this);
return;
}
} else {
resourcepacks.mkdirs();
}
}
if (!compatible()) {
for (int i = 0; i < 10; i++) {
getServer().getConsoleSender().sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] VERSION NOT COMPATIBLE WITH INSTALLED INTERACTIVECHAT VERSION, PLEASE UPDATE BOTH TO LATEST!!!!");
}
getServer().getPluginManager().disablePlugin(this);
return;
} else {
getServer().getConsoleSender().sendMessage(ChatColor.GREEN + "[ICDiscordSrvAddon] InteractiveChat DiscordSRV Addon has been Enabled!");
}
reloadTextures(false, false);
modelRenderer = new ModelRenderer(str -> new ThreadFactoryBuilder().setNameFormat(str).build(), () -> InteractiveChatDiscordSrvAddon.plugin.cacheTimeout, image -> ImageGeneration.getEnchantedImage(image), image -> ImageGeneration.getRawEnchantedImage(image), () -> 8, () -> Runtime.getRuntime().availableProcessors());
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("InteractiveChatDiscordSRVAddon Async Media Reading Thread #%d").build();
mediaReadingService = Executors.newFixedThreadPool(4, factory);
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
for (ICPlayer player : ICPlayerFactory.getOnlineICPlayers()) {
cachePlayerSkin(player);
}
AssetsDownloader.loadExtras();
}, 600, 6000);
}
use of com.loohp.interactivechat.InteractiveChat in project InteractiveChat by LOOHP.
the class OutChatPacket method processPacket.
private static void processPacket(Player receiver, PacketContainer packet, UUID messageUUID, boolean isFiltered) {
PacketContainer originalPacket = packet.deepClone();
try {
Component component = null;
ChatComponentType type = null;
int field = -1;
search: for (ChatComponentType t : ChatComponentType.byPriority()) {
for (int i = 0; i < packet.getModifier().size(); i++) {
if (!CustomArrayUtils.allNull(packet.getModifier().read(i)) && packet.getModifier().getField(i).getType().getName().matches(t.getMatchingRegex())) {
try {
component = t.convertFrom(packet.getModifier().read(i));
} catch (Throwable e) {
System.err.println(t.toString(packet.getModifier().read(i)));
e.printStackTrace();
service.send(packet, receiver, messageUUID);
return;
}
field = i;
type = t;
break search;
}
}
}
if (field < 0 || type == null || component == null) {
service.send(packet, receiver, messageUUID);
return;
}
String legacyText = LegacyComponentSerializer.legacySection().serializeOr(component, "");
try {
if (legacyText.equals("") || InteractiveChat.messageToIgnore.stream().anyMatch(each -> legacyText.matches(each))) {
service.send(packet, receiver, messageUUID);
return;
}
} catch (Exception e) {
service.send(packet, receiver, messageUUID);
return;
}
if (InteractiveChat.version.isOld() && JsonUtils.containsKey(InteractiveChatComponentSerializer.gson().serialize(component), "translate")) {
service.send(packet, receiver, messageUUID);
return;
}
boolean isCommand = false;
boolean isChat = false;
Optional<ICPlayer> sender = Optional.empty();
String rawMessageKey = PlainTextComponentSerializer.plainText().serializeOr(component, "");
InteractiveChat.keyTime.putIfAbsent(rawMessageKey, System.currentTimeMillis());
Long timeKey = InteractiveChat.keyTime.get(rawMessageKey);
long unix = timeKey == null ? System.currentTimeMillis() : timeKey;
ProcessSenderResult commandSender = ProcessCommands.process(component);
if (commandSender.getSender() != null) {
ICPlayer icplayer = ICPlayerFactory.getICPlayer(commandSender.getSender());
if (icplayer != null) {
sender = Optional.of(icplayer);
// noinspection UnusedAssignment
isCommand = true;
}
}
ProcessSenderResult chatSender = null;
if (!sender.isPresent()) {
if (InteractiveChat.useAccurateSenderFinder) {
chatSender = ProcessAccurateSender.process(component);
if (chatSender.getSender() != null) {
ICPlayer icplayer = ICPlayerFactory.getICPlayer(chatSender.getSender());
if (icplayer != null) {
sender = Optional.of(icplayer);
// noinspection UnusedAssignment
isChat = true;
}
}
}
}
if (!sender.isPresent() && !InteractiveChat.useAccurateSenderFinder) {
sender = SenderFinder.getSender(component, rawMessageKey);
}
if (sender.isPresent() && !sender.get().isLocal()) {
if (isFiltered) {
Bukkit.getScheduler().runTaskLaterAsynchronously(InteractiveChat.plugin, () -> {
service.execute(() -> {
processPacket(receiver, packet, messageUUID, false);
}, receiver, messageUUID);
}, (int) Math.ceil((double) InteractiveChat.remoteDelay / 50));
return;
}
}
component = commandSender.getComponent();
if (chatSender != null) {
component = chatSender.getComponent();
}
if (sender.isPresent()) {
InteractiveChat.keyPlayer.put(rawMessageKey, sender.get());
}
component = ComponentModernizing.modernize(component);
component = component.replaceText(TextReplacementConfig.builder().match(Registry.ID_PATTERN).replacement("").build());
UUID preEventSenderUUID = sender.isPresent() ? sender.get().getUniqueId() : null;
PrePacketComponentProcessEvent preEvent = new PrePacketComponentProcessEvent(true, receiver, component, preEventSenderUUID);
Bukkit.getPluginManager().callEvent(preEvent);
if (preEvent.getSender() != null) {
Player newsender = Bukkit.getPlayer(preEvent.getSender());
if (newsender != null) {
sender = Optional.of(ICPlayerFactory.getICPlayer(newsender));
}
}
component = preEvent.getComponent();
if (InteractiveChat.translateHoverableItems && InteractiveChat.itemGUI) {
component = HoverableItemDisplay.process(component, receiver);
}
if (InteractiveChat.usePlayerName) {
component = PlayernameDisplay.process(component, sender, receiver, unix);
}
if (InteractiveChat.allowMention && sender.isPresent()) {
PlayerData data = InteractiveChat.playerDataManager.getPlayerData(receiver);
if (data == null || !data.isMentionDisabled()) {
component = MentionDisplay.process(component, receiver, sender.get(), unix, true);
}
}
component = ComponentReplacing.replace(component, Registry.MENTION_TAG_CONVERTER.getReversePattern().pattern(), true, (result, components) -> {
return LegacyComponentSerializer.legacySection().deserialize(result.group(2));
});
component = CustomPlaceholderDisplay.process(component, sender, receiver, InteractiveChat.placeholderList.values(), unix);
if (InteractiveChat.useItem) {
component = ItemDisplay.process(component, sender, receiver, unix);
}
if (InteractiveChat.useInventory) {
component = InventoryDisplay.process(component, sender, receiver, unix);
}
if (InteractiveChat.useEnder) {
component = EnderchestDisplay.process(component, sender, receiver, unix);
}
if (InteractiveChat.clickableCommands) {
component = CommandsDisplay.process(component);
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16) && InteractiveChat.fontTags) {
if (!sender.isPresent() || (sender.isPresent() && PlayerUtils.hasPermission(sender.get().getUniqueId(), "interactivechat.customfont.translate", true, 250))) {
component = ComponentFont.parseFont(component);
}
}
if (PlayerUtils.getColorSettings(receiver).equals(ColorSettings.OFF)) {
component = ComponentStyling.stripColor(component);
}
PostPacketComponentProcessEvent postEvent = new PostPacketComponentProcessEvent(true, receiver, component, preEventSenderUUID);
Bukkit.getPluginManager().callEvent(postEvent);
component = postEvent.getComponent();
boolean legacyRGB = InteractiveChat.version.isLegacyRGB();
String json = legacyRGB ? InteractiveChatComponentSerializer.legacyGson().serialize(component) : InteractiveChatComponentSerializer.gson().serialize(component);
boolean longerThanMaxLength = InteractiveChat.sendOriginalIfTooLong && json.length() > InteractiveChat.packetStringMaxLength;
try {
packet.getModifier().write(field, type.convertTo(component, legacyRGB));
} catch (Throwable e) {
for (int i = 0; i < chatFieldsSize; i++) {
packet.getModifier().write(i, null);
}
packet.getChatComponents().write(0, WrappedChatComponent.fromJson(json));
}
UUID postEventSenderUUID = sender.isPresent() ? sender.get().getUniqueId() : new UUID(0, 0);
if (packet.getUUIDs().size() > 0) {
packet.getUUIDs().write(0, postEventSenderUUID);
}
PreChatPacketSendEvent sendEvent = new PreChatPacketSendEvent(true, receiver, packet, postEventSenderUUID, originalPacket, InteractiveChat.sendOriginalIfTooLong, longerThanMaxLength);
Bukkit.getPluginManager().callEvent(sendEvent);
Bukkit.getScheduler().runTaskLater(InteractiveChat.plugin, () -> {
InteractiveChat.keyTime.remove(rawMessageKey);
InteractiveChat.keyPlayer.remove(rawMessageKey);
}, 10);
if (sendEvent.isCancelled()) {
if (sendEvent.sendOriginalIfCancelled()) {
if (longerThanMaxLength && InteractiveChat.cancelledMessage) {
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[InteractiveChat] " + ChatColor.RED + "Cancelled a chat packet bounded to " + receiver.getName() + " that is " + json.length() + " characters long (Longer than maximum allowed in a chat packet), sending original unmodified message instead! [THIS IS NOT A BUG]");
}
PacketContainer originalPacketModified = sendEvent.getOriginal();
service.send(originalPacketModified, receiver, messageUUID);
return;
}
if (longerThanMaxLength && InteractiveChat.cancelledMessage) {
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[InteractiveChat] " + ChatColor.RED + "Cancelled a chat packet bounded to " + receiver.getName() + " that is " + json.length() + " characters long (Longer than maximum allowed in a chat packet) [THIS IS NOT A BUG]");
}
service.discard(receiver.getUniqueId(), messageUUID);
return;
}
service.send(packet, receiver, messageUUID);
} catch (Exception e) {
e.printStackTrace();
service.send(originalPacket, receiver, messageUUID);
}
}
use of com.loohp.interactivechat.InteractiveChat in project InteractiveChat by LOOHP.
the class InteractiveChatBungee method onPlayerConnected.
@EventHandler
public void onPlayerConnected(PostLoginEvent event) {
if (!filtersAdded) {
addFilters();
}
ProxiedPlayer player = event.getPlayer();
forwardedMessages.put(player.getUniqueId(), new ConcurrentHashMap<>());
if (player.hasPermission("interactivechat.backendinfo")) {
String proxyVersion = plugin.getDescription().getVersion();
for (BackendInteractiveChatData data : serverInteractiveChatInfo.values()) {
if (data.isOnline() && data.getProtocolVersion() != Registry.PLUGIN_MESSAGING_PROTOCOL_VERSION) {
String msg = ChatColor.RED + "[InteractiveChat] Warning: Backend Server " + data.getServer() + " is not running a version of InteractiveChat which has the same plugin messaging protocol version as the proxy!";
Component text = LegacyComponentSerializer.legacySection().deserialize(msg);
text = text.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(ChatColor.YELLOW + "Proxy Version: " + proxyVersion + " (" + Registry.PLUGIN_MESSAGING_PROTOCOL_VERSION + ")\n" + ChatColor.RED + data.getServer() + " Version: " + data.getVersion() + " (" + data.getProtocolVersion() + ")")));
sendMessage(player, text);
sendMessage(ProxyServer.getInstance().getConsole(), text);
}
}
}
UserConnection userConnection = (UserConnection) player;
ChannelWrapper channelWrapper;
Field channelField = null;
try {
channelField = userConnection.getClass().getDeclaredField("ch");
channelField.setAccessible(true);
channelWrapper = (ChannelWrapper) channelField.get(userConnection);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
if (channelField != null) {
channelField.setAccessible(false);
}
}
ChannelPipeline pipeline = channelWrapper.getHandle().pipeline();
pipeline.addBefore(PipelineUtils.BOSS_HANDLER, "interactivechat_interceptor", new ChannelDuplexHandler() {
@Override
public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) throws Exception {
try {
if (obj instanceof Chat) {
Chat packet = (Chat) obj;
String message = packet.getMessage();
byte position = packet.getPosition();
if ((position == 0 || position == 1) && message != null) {
if (message.contains("<QUxSRUFEWVBST0NFU1NFRA==>")) {
message = message.replace("<QUxSRUFEWVBST0NFU1NFRA==>", "");
if (Registry.ID_PATTERN.matcher(message).find()) {
message = Registry.ID_PATTERN.matcher(message).replaceAll("").trim();
}
packet.setMessage(message);
} else if (hasInteractiveChat(player.getServer())) {
messageForwardingHandler.processMessage(player.getUniqueId(), message, position);
return;
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
super.write(channelHandlerContext, obj, channelPromise);
}
});
}
use of com.loohp.interactivechat.InteractiveChat in project InteractiveChat by LOOHP.
the class InteractiveChatBungee method onEnable.
@Override
public void onEnable() {
plugin = this;
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
try {
Config.loadConfig(CONFIG_ID, new File(getDataFolder(), "bungeeconfig.yml"), getResourceAsStream("config_proxy.yml"), getResourceAsStream("config_proxy.yml"), true);
} catch (IOException e) {
e.printStackTrace();
return;
}
loadConfig();
getProxy().registerChannel("interchat:main");
getProxy().getPluginManager().registerListener(this, this);
getProxy().getPluginManager().registerCommand(this, new CommandsBungee());
if (ProxyServer.getInstance().getPluginManager().getPlugin("ViaVersion") != null) {
viaVersionHook = true;
ProxyServer.getInstance().getLogger().info(ChatColor.AQUA + "[InteractiveChat] InteractiveChatBungee has hooked into ViaVersion!");
}
ProxyServer.getInstance().getLogger().info(ChatColor.GREEN + "[InteractiveChat] Registered Plugin Messaging Channels!");
metrics = new Metrics(plugin, BSTATS_PLUGIN_ID);
Charts.setup(metrics);
playerCooldownManager = new ProxyPlayerCooldownManager(placeholderList.values().stream().flatMap(each -> each.stream()).distinct().collect(Collectors.toList()));
run();
messageForwardingHandler = new ProxyMessageForwardingHandler((info, component) -> {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(info.getPlayer());
Server server = player.getServer();
ProxyServer.getInstance().getScheduler().schedule(plugin, () -> {
try {
if (player != null && server != null) {
PluginMessageSendingBungee.requestMessageProcess(player, server.getInfo(), component, info.getId());
}
} catch (IOException e) {
e.printStackTrace();
}
}, delay + 50, TimeUnit.MILLISECONDS);
}, (info, component) -> {
Chat chatPacket = new Chat(component + "<QUxSRUFEWVBST0NFU1NFRA==>", info.getPosition());
UserConnection userConnection = (UserConnection) ProxyServer.getInstance().getPlayer(info.getPlayer());
ChannelWrapper channelWrapper;
Field channelField = null;
if (userConnection == null) {
return;
}
try {
channelField = userConnection.getClass().getDeclaredField("ch");
channelField.setAccessible(true);
channelWrapper = (ChannelWrapper) channelField.get(userConnection);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
if (channelField != null) {
channelField.setAccessible(false);
}
}
channelWrapper.write(chatPacket);
}, uuid -> {
return ProxyServer.getInstance().getPlayer(uuid) != null;
}, uuid -> {
return hasInteractiveChat(ProxyServer.getInstance().getPlayer(uuid).getServer());
}, () -> (long) delay + 2000);
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("InteractiveChatProxy Async PluginMessage Processing Thread #%d").build();
pluginMessageHandlingExecutor = new ThreadPoolExecutor(8, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(true), factory);
ProxyServer.getInstance().getLogger().info(ChatColor.GREEN + "[InteractiveChat] InteractiveChat (Bungeecord) has been enabled!");
addFilters();
}
use of com.loohp.interactivechat.InteractiveChat in project InteractiveChat by LOOHP.
the class LanguageUtils method loadTranslations.
@SuppressWarnings("unchecked")
public static void loadTranslations(String language) {
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[InteractiveChat] Loading languages...");
Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
while (lock.get()) {
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException ignored) {
}
}
lock.set(true);
try {
File langFolder = new File(InteractiveChat.plugin.getDataFolder(), "lang");
langFolder.mkdirs();
File langFileFolder = new File(langFolder, "languages");
langFileFolder.mkdirs();
File hashFile = new File(langFolder, "hashes.json");
if (!hashFile.exists()) {
PrintWriter pw = new PrintWriter(hashFile, "UTF-8");
pw.print("{");
pw.print("}");
pw.flush();
pw.close();
}
InputStreamReader hashStream = new InputStreamReader(new FileInputStream(hashFile), StandardCharsets.UTF_8);
JSONObject data = (JSONObject) new JSONParser().parse(hashStream);
hashStream.close();
try {
JSONObject manifest = HTTPRequestUtils.getJSONResponse(VERSION_MANIFEST_URL);
if (manifest == null) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to fetch version_manifest from " + VERSION_MANIFEST_URL);
} else {
String mcVersion = InteractiveChat.exactMinecraftVersion;
Object urlObj = ((JSONArray) manifest.get("versions")).stream().filter(each -> ((JSONObject) each).get("id").toString().equalsIgnoreCase(mcVersion)).map(each -> ((JSONObject) each).get("url").toString()).findFirst().orElse(null);
if (urlObj == null) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to find " + mcVersion + " from version_manifest");
} else {
JSONObject versionData = HTTPRequestUtils.getJSONResponse(urlObj.toString());
if (versionData == null) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to fetch version data from " + urlObj);
} else {
String clientUrl = ((JSONObject) ((JSONObject) versionData.get("downloads")).get("client")).get("url").toString();
try (ZipArchiveInputStream zip = new ZipArchiveInputStream(new ByteArrayInputStream(HTTPRequestUtils.download(clientUrl)), StandardCharsets.UTF_8.toString(), false, true, true)) {
while (true) {
ZipArchiveEntry entry = zip.getNextZipEntry();
if (entry == null) {
break;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteChunk = new byte[4096];
int n;
while ((n = zip.read(byteChunk)) > 0) {
baos.write(byteChunk, 0, n);
}
byte[] currentEntry = baos.toByteArray();
String name = entry.getName().toLowerCase();
if (name.matches("^.*assets/minecraft/lang/en_us.(json|lang)$")) {
String enUsFileHash = HashUtils.createSha1String(new ByteArrayInputStream(currentEntry));
String enUsExtension = name.substring(name.indexOf(".") + 1);
if (data.containsKey("en_us")) {
JSONObject values = (JSONObject) data.get("en_us");
File fileToSave = new File(langFileFolder, "en_us" + "." + enUsExtension);
if (!values.get("hash").toString().equals(enUsFileHash) || !fileToSave.exists()) {
values.put("hash", enUsFileHash);
if (fileToSave.exists()) {
fileToSave.delete();
}
FileUtils.copy(new ByteArrayInputStream(currentEntry), fileToSave);
}
} else {
JSONObject values = new JSONObject();
values.put("hash", enUsFileHash);
File fileToSave = new File(langFileFolder, "en_us" + "." + enUsExtension);
if (fileToSave.exists()) {
fileToSave.delete();
}
FileUtils.copy(new ByteArrayInputStream(currentEntry), fileToSave);
data.put("en_us", values);
}
zip.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
String indexUrl = ((JSONObject) versionData.get("assetIndex")).get("url").toString();
JSONObject assets = HTTPRequestUtils.getJSONResponse(indexUrl);
if (assets == null) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to fetch assets data from " + indexUrl);
} else {
JSONObject objects = (JSONObject) assets.get("objects");
for (Object obj : objects.keySet()) {
String key = obj.toString().toLowerCase();
if (key.matches("^minecraft\\/lang\\/" + language + ".(json|lang)$")) {
String lang = key.substring(key.lastIndexOf("/") + 1, key.indexOf("."));
String extension = key.substring(key.indexOf(".") + 1);
String hash = ((JSONObject) objects.get(obj.toString())).get("hash").toString();
String fileUrl = RESOURCES_URL + hash.substring(0, 2) + "/" + hash;
if (data.containsKey(lang)) {
JSONObject values = (JSONObject) data.get(lang);
File fileToSave = new File(langFileFolder, lang + "." + extension);
if (!values.get("hash").toString().equals(hash) || !fileToSave.exists()) {
values.put("hash", hash);
if (fileToSave.exists()) {
fileToSave.delete();
}
if (!HTTPRequestUtils.download(fileToSave, fileUrl)) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to download " + key + " from " + fileUrl);
}
}
} else {
JSONObject values = new JSONObject();
values.put("hash", hash);
File fileToSave = new File(langFileFolder, lang + "." + extension);
if (fileToSave.exists()) {
fileToSave.delete();
}
if (!HTTPRequestUtils.download(fileToSave, fileUrl)) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to download " + key + " from " + fileUrl);
}
data.put(lang, values);
}
}
}
}
}
}
}
JsonUtils.saveToFilePretty(data, hashFile);
} catch (Exception e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to download latest languages files from Mojang");
e.printStackTrace();
}
String langRegex = "(en_us|" + language + ")";
for (File file : langFileFolder.listFiles()) {
try {
if (file.getName().matches("^" + langRegex + ".json$")) {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
JSONObject json = (JSONObject) new JSONParser().parse(reader);
reader.close();
Map<String, String> mapping = new HashMap<>();
for (Object obj : json.keySet()) {
try {
String key = (String) obj;
mapping.put(key, (String) json.get(key));
} catch (Exception e) {
}
}
translations.put(file.getName().substring(0, file.getName().lastIndexOf(".")), mapping);
} else if (file.getName().matches("^" + langRegex + ".lang$")) {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
Map<String, String> mapping = new HashMap<>();
br.lines().forEach(line -> {
if (line.contains("=")) {
mapping.put(line.substring(0, line.indexOf("=")), line.substring(line.indexOf("=") + 1));
}
});
br.close();
translations.put(file.getName().substring(0, file.getName().lastIndexOf(".")), mapping);
}
} catch (Exception e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to load " + file.getName());
e.printStackTrace();
}
}
if (translations.isEmpty()) {
throw new RuntimeException();
}
for (Map<String, Map<String, String>> pluginLanguageMapping : pluginTranslations.values()) {
for (Entry<String, Map<String, String>> entry : pluginLanguageMapping.entrySet()) {
String lang = entry.getKey();
Map<String, String> mapping = entry.getValue();
Map<String, String> existingMapping = translations.get(lang);
if (existingMapping == null) {
translations.put(lang, new HashMap<>(mapping));
} else {
existingMapping.putAll(mapping);
}
}
}
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[InteractiveChat] Loaded all " + translations.size() + " languages!");
} catch (Exception e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractiveChat] Unable to setup languages");
e.printStackTrace();
}
lock.set(false);
});
}
Aggregations