feat: Implement backend commands for plugin data management and enhance frontend synchronization with updated plugin interfaces

This commit is contained in:
Rbanh committed 2025-03-30 19:31:00 -04:00
1 parent 78f22f65f4
commit 83be780243
35 files changed
+5261 -2208

No files matched your search

+191
View File
@@ -0,0 +1,191 @@
use std::env;
use std::error::Error;
use std::path::Path;
use std::time::Duration;
use tokio::time::sleep;
use cached::proc_macro::cached;
use reqwest;
use reqwest::header::{
HeaderMap, HeaderValue, USER_AGENT, AUTHORIZATION, ACCEPT, ACCEPT_LANGUAGE, CONNECTION, RETRY_AFTER,
};
use reqwest::StatusCode;
/// HTTP Client for making requests to external services
pub struct HttpClient {
client: reqwest::Client,
github_token: Option<String>,
}
/// Cache HTTP GET requests to avoid hitting rate limits
#[cached(
time = 3600, // Cache for 1 hour
size = 100, // Maximum number of cached responses
key = "String",
convert = r#"{ url.clone() }"#,
result = true
)]
async fn cached_http_get(url: String, client: reqwest::Client, token: Option<String>) -> Result<String, Box<dyn Error + Send + Sync>> {
const MAX_RETRIES: u32 = 3;
const BASE_RETRY_DELAY_MS: u64 = 1000;
let mut headers = HeaderMap::new();
// Set common headers for all requests
headers.insert(USER_AGENT, HeaderValue::from_static("PlugSnatcherApp/0.1.0"));
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
headers.insert(ACCEPT_LANGUAGE, HeaderValue::from_static("en-US,en;q=0.5"));
headers.insert(CONNECTION, HeaderValue::from_static("keep-alive"));
// Add authorization header if token is provided
if let Some(token_value) = token {
if url.contains("github.com") {
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("token {}", token_value)).unwrap_or_else(|_| HeaderValue::from_static("")),
);
}
}
let mut retry_count = 0;
let mut retry_delay = BASE_RETRY_DELAY_MS;
loop {
let response = client
.get(&url)
.headers(headers.clone())
.send()
.await;
match response {
Ok(resp) => {
// Handle rate limiting
if resp.status() == StatusCode::TOO_MANY_REQUESTS {
if retry_count >= MAX_RETRIES {
return Err(format!("Rate limit exceeded for {}", url).into());
}
// Check for Retry-After header or use exponential backoff
let retry_after = resp.headers()
.get(RETRY_AFTER)
.and_then(|val| val.to_str().ok())
.and_then(|val| val.parse::<u64>().ok())
.map(|secs| secs * 1000) // Convert header seconds to ms
.unwrap_or_else(|| {
// If no Retry-After header, just use the current exponential delay
retry_delay
});
// Exponential backoff calculation for the *next* potential retry
retry_delay *= 2;
println!("Rate limited for {}. Retrying after {} ms...", url, retry_after);
sleep(Duration::from_millis(retry_after)).await;
retry_count += 1;
continue;
}
// Handle other responses
if resp.status().is_success() {
return Ok(resp.text().await?);
} else {
return Err(format!(
"Request to {} failed with status code: {}",
url,
resp.status()
).into());
}
},
Err(err) => {
if retry_count >= MAX_RETRIES {
return Err(Box::new(err));
}
sleep(Duration::from_millis(retry_delay)).await;
retry_delay *= 2;
retry_count += 1;
}
}
}
}
/// Helper function to parse Modrinth's rate limit format
fn parse_modrinth_ratelimit(error_body: &str) -> Option<u64> {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(error_body) {
if let Some(retry_after) = json.get("retry_after") {
if let Some(seconds) = retry_after.as_u64() {
return Some(seconds * 1000);
}
}
}
None
}
impl HttpClient {
/// Create a new HTTP client
pub fn new() -> Self {
let client = reqwest::ClientBuilder::new()
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(5))
.pool_idle_timeout(Duration::from_secs(90))
.build()
.unwrap_or_else(|_| reqwest::Client::new());
// Try to get GitHub token from environment variable
let github_token = match env::var("GITHUB_API_TOKEN") {
Ok(token) if !token.is_empty() => Some(token),
_ => None,
};
HttpClient {
client,
github_token,
}
}
/// Perform an HTTP GET request
pub async fn get(&self, url: &str) -> Result<String, Box<dyn Error + Send + Sync>> {
cached_http_get(url.to_string(), self.client.clone(), self.github_token.clone()).await
}
/// Download a file from a URL to the specified destination
pub async fn download(&self, url: &str, destination: &Path) -> Result<(), Box<dyn Error + Send + Sync>> {
// Create a client with a larger timeout for downloads
let client = reqwest::ClientBuilder::new()
.timeout(Duration::from_secs(180)) // Longer timeout for downloads
.build()?;
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("PlugSnatcherApp/0.1.0"));
// Add GitHub token if URL is GitHub and we have a token
if url.contains("github.com") && self.github_token.is_some() {
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("token {}", self.github_token.as_ref().unwrap()))
.unwrap_or_else(|_| HeaderValue::from_static("")),
);
}
// Get response
let response = client.get(url).headers(headers).send().await?;
// Check if request was successful
if !response.status().is_success() {
return Err(format!("Failed to download: Status {}", response.status()).into());
}
// Get response bytes
let bytes = response.bytes().await?;
// Create parent directories if needed
if let Some(parent) = destination.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)?;
}
}
// Write to file
std::fs::write(destination, bytes)?;
Ok(())
}
}
+3
View File
@@ -0,0 +1,3 @@
mod client;
pub use client::HttpClient;
+8
View File
@@ -0,0 +1,8 @@
pub mod http;
pub mod plugin_scanner;
pub mod update_manager;
// Re-export important services
pub use http::HttpClient;
pub use plugin_scanner::{scan_server_directory, perform_scan, extract_plugin_metadata, calculate_file_hash, is_file_locked};
pub use update_manager::{check_for_plugin_updates, check_single_plugin_update, backup_plugin, replace_plugin, normalize_version, compare_plugin_versions};
@@ -0,0 +1,58 @@
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
use sha2::{Sha256, Digest};
/// Calculate SHA-256 hash of a file for identification and verification
pub fn calculate_file_hash(file_path: &str) -> Result<String, String> {
// Open the file
let mut file = match File::open(file_path) {
Ok(file) => file,
Err(e) => return Err(format!("Failed to open file for hashing: {}", e)),
};
// Read the file content
let mut buffer = Vec::new();
if let Err(e) = file.read_to_end(&mut buffer) {
return Err(format!("Failed to read file for hashing: {}", e));
}
// Calculate the SHA-256 hash
let mut hasher = Sha256::new();
hasher.update(&buffer);
let result = hasher.finalize();
// Convert the hash to a hex string
let hash_string = format!("{:x}", result);
Ok(hash_string)
}
/// Check if a file is currently locked by another process
pub fn is_file_locked(file_path: &str) -> bool {
// Try to open the file with write permissions to check if locked
match fs::OpenOptions::new()
.write(true)
.open(file_path)
{
Ok(_) => false, // File can be opened for writing, so it's not locked
Err(_) => {
// If we can't open for writing, try to check if it exists
// This helps determine if the error is due to file being locked
// or just not existing
Path::new(file_path).exists()
}
}
}
/// Read YAML content from a ZIP archive
pub fn read_yaml_from_archive(archive: &mut zip::ZipArchive<fs::File>, file_name: &str) -> Result<String, String> {
match archive.by_name(file_name) {
Ok(mut file) => {
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|e| format!("Failed to read {}: {}", file_name, e))?;
Ok(contents)
},
Err(e) => Err(format!("Failed to find {}: {}", file_name, e))
}
}
@@ -0,0 +1,219 @@
use std::fs;
use std::path::Path;
use yaml_rust::{YamlLoader, Yaml};
use zip::ZipArchive;
use crate::models::plugin::PluginMeta;
use super::file_utils::{calculate_file_hash, read_yaml_from_archive};
/// Extract metadata from a plugin JAR file
pub fn extract_plugin_metadata(jar_path: &Path) -> Result<PluginMeta, String> {
// Get the file size
let metadata = match fs::metadata(jar_path) {
Ok(meta) => meta,
Err(e) => return Err(format!("Failed to get file metadata: {}", e)),
};
let file_size = metadata.len();
// Open the JAR file
let file = match fs::File::open(jar_path) {
Ok(file) => file,
Err(e) => return Err(format!("Failed to open JAR file: {}", e)),
};
// Create a ZIP archive reader
let mut archive = match ZipArchive::new(file) {
Ok(archive) => archive,
Err(e) => return Err(format!("Failed to read JAR as ZIP archive: {}", e)),
};
// Try to read plugin.yml
let yaml_content = match read_yaml_from_archive(&mut archive, "plugin.yml") {
Ok(content) => content,
Err(_) => {
// If plugin.yml is not found, try bungee.yml for BungeeCord plugins
match read_yaml_from_archive(&mut archive, "bungee.yml") {
Ok(content) => content,
Err(_) => {
// If neither is found, use fallback metadata
return fallback_plugin_meta(jar_path, file_size);
}
}
}
};
// Parse the YAML content
let docs = match YamlLoader::load_from_str(&yaml_content) {
Ok(docs) => docs,
Err(e) => return Err(format!("Failed to parse plugin.yml: {}", e)),
};
// If there's no document in the YAML, use fallback
if docs.is_empty() {
return fallback_plugin_meta(jar_path, file_size);
}
let doc = &docs[0];
// Extract plugin information
let name = yaml_str_with_fallback(doc, "name", jar_path);
let version = yaml_str_with_fallback(doc, "version", jar_path);
let description = yaml_str_opt(doc, "description");
let website = yaml_str_opt(doc, "website");
let api_version = yaml_str_opt(doc, "api-version");
let main_class = yaml_str_opt(doc, "main");
// Extract author/authors
let authors = match &doc["author"] {
Yaml::String(author) => vec![author.clone()],
_ => match &doc["authors"] {
Yaml::Array(authors) => authors
.iter()
.filter_map(|a| match a {
Yaml::String(s) => Some(s.clone()),
_ => None,
})
.collect(),
Yaml::String(author) => vec![author.clone()],
_ => Vec::new(),
},
};
// Extract dependencies
let depend = yaml_str_array(doc, "depend");
let soft_depend = yaml_str_array(doc, "softdepend");
let load_before = yaml_str_array(doc, "loadbefore");
// Extract commands and permissions
let commands = match &doc["commands"] {
Yaml::Hash(_) => {
Some(serde_json::Value::String("Commands data present".to_string()))
},
_ => None
};
let permissions = match &doc["permissions"] {
Yaml::Hash(_) => {
Some(serde_json::Value::String("Permissions data present".to_string()))
},
_ => None
};
// Calculate the file hash
let file_hash = calculate_file_hash(jar_path.to_str().unwrap_or("unknown.jar")).unwrap_or_else(|_| "unknown".to_string());
Ok(PluginMeta {
name,
version,
description,
authors,
api_version,
main_class,
depend,
soft_depend,
load_before,
commands,
permissions,
file_path: jar_path.to_string_lossy().to_string(),
file_size,
file_hash,
website,
})
}
/// Create plugin metadata with fallback values
fn fallback_plugin_meta(jar_path: &Path, file_size: u64) -> Result<PluginMeta, String> {
let filename = jar_path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown.jar");
// Extract name and version from filename (e.g., "WorldEdit-7.2.8.jar" → name: "WorldEdit", version: "7.2.8")
let mut parts: Vec<&str> = filename.trim_end_matches(".jar").split('-').collect();
let version = if parts.len() > 1 {
parts.pop().unwrap_or("1.0.0").to_string()
} else {
"1.0.0".to_string()
};
let name = parts.join("-");
// Calculate hash
let file_hash = calculate_file_hash(jar_path.to_str().unwrap_or("unknown.jar")).unwrap_or_else(|_| "unknown".to_string());
Ok(PluginMeta {
name,
version,
description: None,
authors: Vec::new(),
website: None,
api_version: None,
main_class: None,
depend: None,
soft_depend: None,
load_before: None,
commands: None,
permissions: None,
file_path: jar_path.to_string_lossy().to_string(),
file_size,
file_hash,
})
}
/// Helper function to extract a string with fallback
fn yaml_str_with_fallback(yaml: &Yaml, key: &str, jar_path: &Path) -> String {
match yaml[key] {
Yaml::String(ref s) => s.clone(),
_ => {
// Fallback to the JAR filename without extension
let filename = jar_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.trim_end_matches(".jar");
if key == "name" {
let name_parts: Vec<&str> = filename.split('-').collect();
name_parts[0].to_string()
} else if key == "version" {
let version_parts: Vec<&str> = filename.split('-').collect();
if version_parts.len() > 1 {
version_parts[1].to_string()
} else {
"1.0.0".to_string()
}
} else {
"".to_string()
}
}
}
}
/// Helper function to extract an optional string
fn yaml_str_opt(yaml: &Yaml, key: &str) -> Option<String> {
match &yaml[key] {
Yaml::String(s) => Some(s.clone()),
_ => None,
}
}
/// Helper function to extract an array of strings
fn yaml_str_array(yaml: &Yaml, key: &str) -> Option<Vec<String>> {
match &yaml[key] {
Yaml::Array(arr) => {
let string_arr: Vec<String> = arr
.iter()
.filter_map(|item| match item {
Yaml::String(s) => Some(s.clone()),
_ => None,
})
.collect();
if string_arr.is_empty() {
None
} else {
Some(string_arr)
}
},
_ => None,
}
}
@@ -0,0 +1,7 @@
mod scanner;
mod metadata_extractor;
mod file_utils;
pub use scanner::{scan_server_directory, perform_scan, get_plugin_data_path};
pub use metadata_extractor::extract_plugin_metadata;
pub use file_utils::{calculate_file_hash, is_file_locked};
@@ -0,0 +1,409 @@
use std::fs;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Manager, Emitter};
use walkdir::WalkDir;
use regex::Regex;
use std::ffi::OsStr;
use std::io::Read;
use crate::models::server::{ServerType, ServerInfo, ScanResult, ScanProgress};
use crate::models::plugin::{Plugin, PluginMeta};
use super::metadata_extractor::extract_plugin_metadata;
/// Scan a server directory and emit progress events
pub async fn scan_server_directory(app_handle: AppHandle, path: String) -> Result<(), String> {
// Get the main window
let window = app_handle.get_webview_window("main").ok_or("Main window not found")?;
println!("Starting scan for server directory: {}", path);
// Start the scan
match window.emit("scan_started", {}) {
Ok(_) => println!("Emitted scan_started event successfully"),
Err(e) => {
let err_msg = format!("Failed to emit scan_started event: {}", e);
println!("{}", err_msg);
return Err(err_msg);
}
}
// Perform the actual scan in a separate function
match perform_scan(&app_handle, &path).await {
Ok(result) => {
println!("Scan completed successfully. Found {} plugins", result.plugins.len());
// Save the scan result to disk
match save_plugin_data(app_handle.clone(), result.plugins.clone(), path.clone()).await {
Ok(_) => println!("Saved plugin data to disk successfully"),
Err(e) => println!("Failed to save plugin data: {}", e)
}
// Emit scan completion event with the result
println!("Emitting scan_completed event with {} plugins", result.plugins.len());
match window.emit("scan_completed", result.clone()) {
Ok(_) => {
println!("Emitted scan_completed event successfully");
Ok(())
},
Err(e) => {
let err_msg = format!("Failed to emit scan_completed event: {}", e);
println!("{}", err_msg);
Err(err_msg)
}
}
},
Err(e) => {
println!("Scan failed with error: {}", e);
// Emit scan error event
match window.emit("scan_error", e.clone()) {
Ok(_) => println!("Emitted scan_error event successfully"),
Err(err) => println!("Failed to emit scan_error event: {}", err)
}
Err(e)
}
}
}
/// Perform a scan of the server directory
pub async fn perform_scan(app_handle: &AppHandle, path: &str) -> Result<ScanResult, String> {
// Normalize the path and check if it exists
let server_path = Path::new(path);
if !server_path.exists() {
return Err(format!("Server directory not found: {}", path));
}
// Detect server type
let server_type = detect_server_type(server_path);
// Find Minecraft version
let minecraft_version = detect_minecraft_version(server_path, &server_type);
// Find plugins directory
let plugins_dir = get_plugins_directory(server_path, &server_type);
let plugins_path = Path::new(&plugins_dir);
// Check if plugins directory exists
if !plugins_path.exists() {
return Err(format!("Plugins directory not found: {}", plugins_dir));
}
// Get all JAR files in plugins directory
let mut plugin_files = Vec::new();
for entry in WalkDir::new(plugins_path)
.max_depth(1) // Only scan the top level
.into_iter()
.filter_map(|e| e.ok())
{
let path = entry.path();
if path.is_file() && path.extension() == Some(OsStr::new("jar")) {
plugin_files.push(path.to_path_buf());
}
}
// Create server info object
let server_info = ServerInfo {
server_type,
minecraft_version,
plugins_directory: plugins_dir,
plugins_count: plugin_files.len(),
};
// Emit total plugin count
app_handle.emit("scan_progress", ScanProgress {
processed: 0,
total: plugin_files.len(),
current_file: "Starting scan...".to_string(),
}).map_err(|e| e.to_string())?;
// Process each plugin
let mut plugins = Vec::new();
for (index, jar_path) in plugin_files.iter().enumerate() {
// Emit progress update
let file_name = jar_path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown.jar");
app_handle.emit("scan_progress", ScanProgress {
processed: index,
total: plugin_files.len(),
current_file: file_name.to_string(),
}).map_err(|e| e.to_string())?;
// Extract plugin metadata
match extract_plugin_metadata(jar_path) {
Ok(meta) => {
// Convert PluginMeta to Plugin
let plugin = Plugin {
name: meta.name,
version: meta.version,
latest_version: None, // Will be populated during update check
description: meta.description,
authors: meta.authors,
website: meta.website,
has_update: false, // Will be populated during update check
api_version: meta.api_version,
main_class: meta.main_class,
depend: meta.depend,
soft_depend: meta.soft_depend,
load_before: meta.load_before,
commands: meta.commands,
permissions: meta.permissions,
file_path: meta.file_path,
file_hash: meta.file_hash,
changelog: None, // Will be populated during update check
repository_source: None, // Will be populated during update check
repository_id: None, // Will be populated during update check
repository_url: None, // Will be populated during update check
};
plugins.push(plugin);
},
Err(e) => {
// Log the error but continue processing other plugins
eprintln!("Error extracting metadata from {}: {}", file_name, e);
}
}
}
// Emit final progress
app_handle.emit("scan_progress", ScanProgress {
processed: plugin_files.len(),
total: plugin_files.len(),
current_file: "Scan complete".to_string(),
}).map_err(|e| e.to_string())?;
// Return the result
Ok(ScanResult {
server_info,
plugins,
})
}
/// Detect the type of Minecraft server
fn detect_server_type(server_path: &Path) -> ServerType {
// Check for server JAR file
if let Some(jar_path) = find_server_jar(server_path) {
let jar_filename = jar_path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
// Convert filename to lowercase for easier matching
let filename_lower = jar_filename.to_lowercase();
// Check for known server types
if filename_lower.contains("paper") {
return ServerType::Paper;
} else if filename_lower.contains("spigot") {
return ServerType::Spigot;
} else if filename_lower.contains("bukkit") || filename_lower.contains("craftbukkit") {
return ServerType::Bukkit;
} else if filename_lower.contains("forge") {
return ServerType::Forge;
} else if filename_lower.contains("fabric") {
return ServerType::Fabric;
} else if filename_lower.contains("velocity") {
return ServerType::Velocity;
} else if filename_lower.contains("bungeecord") {
return ServerType::BungeeCord;
} else if filename_lower.contains("waterfall") {
return ServerType::Waterfall;
}
// If server.properties exists, it's likely a vanilla or modified vanilla server
if server_path.join("server.properties").exists() {
// Check if there's a plugins directory
if server_path.join("plugins").exists() {
// Assume Spigot if we can't tell more specifically but plugins exist
return ServerType::Spigot;
}
return ServerType::Vanilla;
}
}
// If we can't determine, check for directory structure hints
if server_path.join("plugins").exists() {
if server_path.join("cache").exists() && server_path.join("modules").exists() {
return ServerType::Velocity;
} else if server_path.join("libraries").exists() && server_path.join("mods").exists() {
return ServerType::Forge;
} else {
return ServerType::Spigot; // Default assumption for server with plugins
}
}
ServerType::Unknown
}
/// Find the server JAR file in the server directory
fn find_server_jar(server_path: &Path) -> Option<PathBuf> {
// Define pattern for server JAR files
let server_jar_pattern = Regex::new(r"^(paper|spigot|craftbukkit|minecraft|fabric|forge|velocity|bungeecord|waterfall).*\.jar$").unwrap();
// Look for JAR files in the directory
let entries = match fs::read_dir(server_path) {
Ok(entries) => entries,
Err(_) => return None,
};
// Check each entry
for entry in entries {
if let Ok(entry) = entry {
if let Some(filename) = entry.file_name().to_str() {
// Check if it matches server JAR pattern
if filename.to_lowercase().ends_with(".jar") {
if server_jar_pattern.is_match(&filename.to_lowercase()) {
return Some(entry.path());
}
// Also check for common naming patterns
if filename.contains("server") || filename == "server.jar" {
return Some(entry.path());
}
}
}
}
}
None
}
/// Detect the Minecraft version from server files
fn detect_minecraft_version(server_path: &Path, server_type: &ServerType) -> Option<String> {
// Try to find server JAR
if let Some(jar_path) = find_server_jar(server_path) {
// Try to extract version from JAR filename
if let Some(filename) = jar_path.file_name().and_then(|n| n.to_str()) {
// Look for version pattern like 1.19.2 in filename
let version_pattern = Regex::new(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)").unwrap();
if let Some(captures) = version_pattern.captures(filename) {
if let Some(version_match) = captures.get(0) {
return Some(version_match.as_str().to_string());
}
}
}
// If version not found in filename, try to read it from the JAR
return read_version_from_jar(&jar_path);
}
// Try server.properties for vanilla/bukkit/spigot servers
if matches!(server_type, ServerType::Vanilla | ServerType::Bukkit | ServerType::Spigot | ServerType::Paper) {
let properties_path = server_path.join("server.properties");
if properties_path.exists() {
// Read properties file
if let Ok(content) = fs::read_to_string(properties_path) {
// Look for the level-type property
for line in content.lines() {
if line.starts_with("level-name=") {
// Try to find version.json in the level directory
let level_name = line.trim_start_matches("level-name=").trim();
let version_json_path = server_path.join(level_name).join("version.json");
if version_json_path.exists() {
if let Ok(version_content) = fs::read_to_string(version_json_path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&version_content) {
if let Some(name) = json.get("name").and_then(|n| n.as_str()) {
return Some(name.to_string());
}
}
}
}
}
}
}
}
}
None
}
/// Read version information from a JAR file
fn read_version_from_jar(jar_path: &Path) -> Option<String> {
// Open the JAR file
let file = match fs::File::open(jar_path) {
Ok(file) => file,
Err(_) => return None,
};
// Create a ZIP archive reader
let mut archive = match zip::ZipArchive::new(file) {
Ok(archive) => archive,
Err(_) => return None,
};
// Try to find version.json or similar file
for i in 0..archive.len() {
let mut file = match archive.by_index(i) {
Ok(file) => file,
Err(_) => continue,
};
let name = file.name();
// Check various version files
if name.ends_with("version.json") || name.contains("version") && name.ends_with(".json") {
let mut contents = String::new();
if let Err(_) = file.read_to_string(&mut contents) {
continue;
}
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&contents) {
// Try different possible keys for version
for key in ["name", "version", "minecraft_version", "id"] {
if let Some(version) = json.get(key).and_then(|v| v.as_str()) {
return Some(version.to_string());
}
}
}
}
}
None
}
/// Get the plugins directory for the server
fn get_plugins_directory(server_path: &Path, server_type: &ServerType) -> String {
match server_type {
ServerType::Velocity | ServerType::BungeeCord | ServerType::Waterfall => {
server_path.join("plugins").to_string_lossy().to_string()
},
_ => server_path.join("plugins").to_string_lossy().to_string(),
}
}
/// Save plugin data to disk for persistence
async fn save_plugin_data(app_handle: AppHandle, plugins: Vec<Plugin>, server_path: String) -> Result<(), String> {
// Get plugin data path
let data_dir = get_plugin_data_path(&app_handle, &server_path)?;
// Create directory if it doesn't exist
if !data_dir.exists() {
fs::create_dir_all(&data_dir)
.map_err(|e| format!("Failed to create data directory: {}", e))?;
}
// Save plugins data
let data_path = data_dir.join("plugins.json");
let json_data = serde_json::to_string_pretty(&plugins)
.map_err(|e| format!("Failed to serialize plugin data: {}", e))?;
fs::write(&data_path, json_data)
.map_err(|e| format!("Failed to write plugin data: {}", e))?;
Ok(())
}
/// Get plugin data directory path
pub fn get_plugin_data_path(app_handle: &AppHandle, server_path: &str) -> Result<PathBuf, String> {
let app_data_dir = app_handle.path().app_data_dir()
.map_err(|e| format!("Failed to get app data directory: {}", e))?;
// Hash the server path to create a unique identifier
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(server_path.as_bytes());
let server_hash = format!("{:x}", hasher.finalize());
// Create a directory for this server
Ok(app_data_dir.join("servers").join(server_hash))
}
@@ -0,0 +1,7 @@
mod update_checker;
mod version_utils;
mod plugin_updater;
pub use update_checker::{check_for_plugin_updates, check_single_plugin_update};
pub use version_utils::{normalize_version, compare_plugin_versions};
pub use plugin_updater::{backup_plugin, replace_plugin};
@@ -0,0 +1,109 @@
use std::path::{Path, PathBuf};
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use tauri::AppHandle;
use crate::models::repository::RepositorySource;
use crate::models::server::ServerInfo;
use crate::services::plugin_scanner::is_file_locked;
/// Backup a plugin before replacing it
pub async fn backup_plugin(plugin_file_path: String) -> Result<String, String> {
// Get the current timestamp for the backup filename
let now = SystemTime::now().duration_since(UNIX_EPOCH)
.map_err(|e| format!("Failed to get timestamp: {}", e))?
.as_secs();
// Create backup file path
let path = Path::new(&plugin_file_path);
let file_name = path.file_name()
.ok_or_else(|| "Invalid plugin file path".to_string())?
.to_str()
.ok_or_else(|| "Invalid file name encoding".to_string())?;
// Create backup directory if it doesn't exist
let backup_dir = path.parent()
.unwrap_or_else(|| Path::new("."))
.join("backups");
if !backup_dir.exists() {
fs::create_dir_all(&backup_dir)
.map_err(|e| format!("Failed to create backup directory: {}", e))?;
}
// Create backup file path with timestamp
let backup_path = backup_dir.join(format!("{}.{}.bak", file_name, now));
let backup_path_str = backup_path.to_string_lossy().to_string();
// Check if file is locked
if is_file_locked(&plugin_file_path) {
return Err(format!("File is locked: {}", plugin_file_path));
}
// Copy the file
fs::copy(&plugin_file_path, &backup_path)
.map_err(|e| format!("Failed to create backup: {}", e))?;
Ok(backup_path_str)
}
/// Replace a plugin with a new version
pub async fn replace_plugin(
plugin_id: String,
version: String,
repository: RepositorySource,
current_file_path: String,
server_info: Option<ServerInfo>
) -> Result<String, String> {
// Check if file is locked
if is_file_locked(&current_file_path) {
return Err(format!("Plugin file is currently locked: {}", current_file_path));
}
// Create a temporary file path
let download_path = create_temp_download_path(&current_file_path)?;
// Download the new plugin version
let server_type = server_info.as_ref().map(|info| &info.server_type);
crate::lib_download_plugin_from_repository(
&plugin_id,
&version,
repository,
&download_path.to_string_lossy(),
server_type
).await?;
// Backup the original file
backup_plugin(current_file_path.clone()).await?;
// Replace the original file with the downloaded one
fs::rename(download_path, &current_file_path)
.map_err(|e| format!("Failed to replace plugin: {}", e))?;
Ok(current_file_path)
}
/// Create a temporary file path for plugin download
fn create_temp_download_path(current_file_path: &str) -> Result<PathBuf, String> {
let path = Path::new(current_file_path);
let file_stem = path.file_stem()
.ok_or_else(|| "Invalid plugin file path".to_string())?
.to_str()
.ok_or_else(|| "Invalid file name encoding".to_string())?;
let file_ext = path.extension()
.unwrap_or_else(|| std::ffi::OsStr::new("jar"))
.to_str()
.unwrap_or("jar");
let parent = path.parent()
.unwrap_or_else(|| Path::new("."));
// Generate temp file name with timestamp
let now = SystemTime::now().duration_since(UNIX_EPOCH)
.map_err(|e| format!("Failed to get timestamp: {}", e))?
.as_secs();
let temp_name = format!("{}.new.{}.{}", file_stem, now, file_ext);
Ok(parent.join(temp_name))
}
@@ -0,0 +1,60 @@
use semver::{Version, VersionReq};
use regex::Regex;
/// Normalize a version string to be semver compatible
pub fn normalize_version(version_str: &str) -> String {
// If already starts with a digit, assume semantic version format
if version_str.chars().next().map_or(false, |c| c.is_ascii_digit()) {
// Clean up any common prefixes like 'v'
let cleaned = version_str.trim_start_matches(|c| c == 'v' || c == 'V');
return cleaned.to_string();
}
// Return as-is for now
version_str.to_string()
}
/// Compare two plugin versions to determine if an update is available
pub fn compare_plugin_versions(installed_str: &str, repo_str: &str) -> bool {
// Normalize version strings
let installed_version = normalize_version(installed_str);
let repo_version = normalize_version(repo_str);
// Try to parse as semver
match (Version::parse(&installed_version), Version::parse(&repo_version)) {
(Ok(installed), Ok(repo)) => {
// Simple semver comparison
repo > installed
},
_ => {
// Fallback to simple string comparison for non-semver versions
repo_version != installed_version
}
}
}
/// Extract version pattern from a string
pub fn extract_version_pattern(input: &str) -> Option<String> {
// Look for version pattern like 1.19.2 in string
let version_pattern = Regex::new(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)").unwrap();
if let Some(captures) = version_pattern.captures(input) {
if let Some(version_match) = captures.get(0) {
return Some(version_match.as_str().to_string());
}
}
None
}
/// Check if a plugin version is compatible with a specific Minecraft version
pub fn is_version_compatible(plugin_version: &str, minecraft_version: &str) -> bool {
// Try to parse the Minecraft version
if let Ok(mc_version) = Version::parse(minecraft_version) {
// Try to parse as a version requirement
if let Ok(req) = VersionReq::parse(plugin_version) {
return req.matches(&mc_version);
}
}
// If version formats are incompatible, make best guess
plugin_version.contains(minecraft_version)
}