All source projects

MrUltimateLibrary Source

Standalone source project / 68 files

MrUltimateLibrary is the backbone of all my plugins; it offers features that facilitate plugin creation, maintenance, and updates.

java

MrUltimateLibrary/src/main/java/eu/mrneznamy/mrultimatelibrary/utils/MrLibPluginUpdater.java

JAVA · Read-only source

package eu.mrneznamy.mrultimatelibrary.utils;

import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * Utility class for downloading plugin updates from Modrinth
 * Plugins can register themselves with their Modrinth slug
 */
public class MrLibPluginUpdater {
    
    private static final String MODRINTH_API = "https://api.modrinth.com/v2";
    private static final Map<String, String> REGISTERED_PLUGINS = new HashMap<>();
    
    /**
     * Register a plugin for updates
     * @param pluginName Name of the plugin
     * @param modrinthSlug Modrinth project slug
     */
    public static void registerPlugin(String pluginName, String modrinthSlug) {
        REGISTERED_PLUGINS.put(pluginName, modrinthSlug);
        MrLibConsoleSayer.MrSay_Info("Registered " + pluginName + " for updates (slug: " + modrinthSlug + ")");
    }
    
    /**
     * Get all registered plugins
     */
    public static Map<String, String> getRegisteredPlugins() {
        return new HashMap<>(REGISTERED_PLUGINS);
    }
    
    /**
     * Download and update a specific plugin
     */
    public static boolean updatePlugin(String pluginName) {
        String slug = REGISTERED_PLUGINS.get(pluginName);
        if (slug == null) {
            MrLibConsoleSayer.MrSay_Warning("Plugin '" + pluginName + "' is not registered for updates");
            return false;
        }
        
        try {
            
            String versionUrl = MODRINTH_API + "/project/" + slug + "/version";
            HttpURLConnection conn = (HttpURLConnection) new URL(versionUrl).openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "MrUltimateLibrary/1.0");
            
            if (conn.getResponseCode() != 200) {
                MrLibConsoleSayer.MrSay_Error("Failed to fetch version info for " + pluginName);
                return false;
            }
            
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            
            String json = response.toString();
            String downloadUrl = extractDownloadUrl(json);
            
            if (downloadUrl == null) {
                MrLibConsoleSayer.MrSay_Error("Could not find download URL for " + pluginName);
                return false;
            }
            
            
            File pluginsFolder = new File("plugins");
            File newFile = new File(pluginsFolder, pluginName + "-new.jar");
            
            MrLibConsoleSayer.MrSay_Info("Downloading " + pluginName + "...");
            downloadFile(downloadUrl, newFile);
            
            
            File oldFile = findPluginJar(pluginName);
            if (oldFile != null && oldFile.exists()) {
                File oldMarked = new File(pluginsFolder, oldFile.getName() + ".old");
                oldFile.renameTo(oldMarked);
                MrLibConsoleSayer.MrSay_Info("Marked old version for deletion: " + oldFile.getName());
            }
            
            
            File finalFile = new File(pluginsFolder, pluginName + ".jar");
            newFile.renameTo(finalFile);
            
            MrLibConsoleSayer.MrSay_Success("Downloaded " + pluginName + " successfully!");
            return true;
            
        } catch (Exception e) {
            MrLibConsoleSayer.MrSay_Error("Failed to update " + pluginName + ": " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * Update all registered plugins
     */
    public static int updateAllPlugins() {
        int updated = 0;
        
        
        for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
            String pluginName = plugin.getName();
            if (REGISTERED_PLUGINS.containsKey(pluginName)) {
                if (updatePlugin(pluginName)) {
                    updated++;
                }
            }
        }
        
        
        deleteOldVersions();
        
        return updated;
    }
    
    /**
     * Extract download URL from Modrinth API JSON response
     */
    private static String extractDownloadUrl(String json) {
        try {
            
            int filesIndex = json.indexOf("\"files\"");
            if (filesIndex == -1) return null;
            
            
            int urlIndex = json.indexOf("\"url\"", filesIndex);
            if (urlIndex == -1) return null;
            
            
            int startQuote = json.indexOf("\"", urlIndex + 6);
            int endQuote = json.indexOf("\"", startQuote + 1);
            
            if (startQuote != -1 && endQuote != -1) {
                return json.substring(startQuote + 1, endQuote);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * Download file from URL
     */
    private static void downloadFile(String urlStr, File destination) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "MrUltimateLibrary/1.0");
        
        try (InputStream in = conn.getInputStream();
             FileOutputStream out = new FileOutputStream(destination)) {
            
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
    
    /**
     * Find plugin JAR file in plugins folder
     */
    private static File findPluginJar(String pluginName) {
        File pluginsFolder = new File("plugins");
        File[] files = pluginsFolder.listFiles((dir, name) -> 
            name.toLowerCase().startsWith(pluginName.toLowerCase()) && name.endsWith(".jar")
        );
        
        if (files != null && files.length > 0) {
            return files[0];
        }
        return null;
    }
    
    /**
     * Delete all .old files
     */
    private static void deleteOldVersions() {
        File pluginsFolder = new File("plugins");
        File[] oldFiles = pluginsFolder.listFiles((dir, name) -> name.endsWith(".jar.old"));
        
        if (oldFiles != null) {
            for (File oldFile : oldFiles) {
                if (oldFile.delete()) {
                    MrLibConsoleSayer.MrSay_Info("Deleted old version: " + oldFile.getName());
                }
            }
        }
    }
}
206 linesGNU GENERAL PUBLIC LICENSE · Version 3, 29 June 2007 · UTF-8 · Read only