Search in sources :

Example 1 with InteractionVisualizer

use of com.loohp.interactionvisualizer.InteractionVisualizer in project InteractionVisualizer by LOOHP.

the class LanguageUtils method loadTranslations.

@SuppressWarnings("unchecked")
public static void loadTranslations(String language) {
    Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[InteractionVisualizer] Loading languages...");
    Bukkit.getScheduler().runTaskAsynchronously(InteractionVisualizer.plugin, () -> {
        while (lock.get()) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
        }
        lock.set(true);
        try {
            File langFolder = new File(InteractionVisualizer.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 + "[InteractionVisualizer] Unable to fetch version_manifest from " + VERSION_MANIFEST_URL);
                } else {
                    String mcVersion = InteractionVisualizer.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 + "[InteractionVisualizer] Unable to find " + mcVersion + " from version_manifest");
                    } else {
                        JSONObject versionData = HTTPRequestUtils.getJSONResponse(urlObj.toString());
                        if (versionData == null) {
                            Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractionVisualizer] 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 + "[InteractionVisualizer] 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 + "[InteractionVisualizer] 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 + "[InteractionVisualizer] Unable to download " + key + " from " + fileUrl);
                                            }
                                            data.put(lang, values);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                JsonUtils.saveToFilePretty(data, hashFile);
            } catch (Exception e) {
                Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractionVisualizer] 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 + "[InteractionVisualizer] Unable to load " + file.getName());
                    e.printStackTrace();
                }
            }
            if (translations.isEmpty()) {
                throw new RuntimeException();
            }
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[InteractionVisualizer] Loaded all " + translations.size() + " languages!");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[InteractionVisualizer] Unable to setup languages");
            e.printStackTrace();
        }
        lock.set(false);
    });
}
Also used : ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) TranslatableComponent(net.kyori.adventure.text.TranslatableComponent) JSONArray(org.json.simple.JSONArray) NBTEditor(io.github.bananapuncher714.nbteditor.NBTEditor) ArrayList(java.util.ArrayList) ByteArrayInputStream(java.io.ByteArrayInputStream) Component(net.kyori.adventure.text.Component) Map(java.util.Map) PotionMeta(org.bukkit.inventory.meta.PotionMeta) Method(java.lang.reflect.Method) Material(org.bukkit.Material) ChatColor(net.md_5.bungee.api.ChatColor) Bukkit(org.bukkit.Bukkit) PrintWriter(java.io.PrintWriter) InteractionVisualizer(com.loohp.interactionvisualizer.InteractionVisualizer) JSONParser(org.json.simple.parser.JSONParser) Set(java.util.Set) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ItemStack(org.bukkit.inventory.ItemStack) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) JSONObject(org.json.simple.JSONObject) TextReplacementConfig(net.kyori.adventure.text.TextReplacementConfig) BufferedReader(java.io.BufferedReader) XMaterial(com.cryptomorin.xseries.XMaterial) Collections(java.util.Collections) InputStreamReader(java.io.InputStreamReader) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

XMaterial (com.cryptomorin.xseries.XMaterial)1 InteractionVisualizer (com.loohp.interactionvisualizer.InteractionVisualizer)1 NBTEditor (io.github.bananapuncher714.nbteditor.NBTEditor)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 PrintWriter (java.io.PrintWriter)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 TimeUnit (java.util.concurrent.TimeUnit)1