Skip to content

Commit

Permalink
[2.1.5] No more unsafe code & cool box.
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew121410 committed Nov 14, 2024
1 parent 8724ca6 commit 62f6e44
Show file tree
Hide file tree
Showing 9 changed files with 392 additions and 134 deletions.
13 changes: 7 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "limonium"
version = "2.1.3"
version = "2.1.5"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -9,19 +9,20 @@ edition = "2021"
[dependencies]
openssl = { version = "0.10.68", features = ["vendored"] }
reqwest = { version = "0.12.9", features = ["stream"] }
serde = "1.0.214"
serde_derive = "1.0.214"
serde = "1.0.215"
serde_derive = "1.0.215"
serde_json = "1.0.132"
async-trait = "0.1.83"
tokio = { version = "1.41.0", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1.41.1", features = ["rt-multi-thread", "macros"] }
colored = "2.1.0"
self_update = { version = "0.41.0", features = ["archive-zip", "compression-zip-deflate"] }
uuid = { version = "1.11.0", features = ["v4"] }
chrono = "0.4.38"
clap = "4.5.20"
clap = "4.5.21"
openssh-sftp-client = "0.15.2"
openssh = "0.11.3"
indicatif = "0.17.8"
indicatif = "0.17.9"
regex = "1.11.1"
tempdir = "0.3.7"
futures-util = "0.3.31"
once_cell = "1.20.2"
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ It will download the software and check the hash of the file to make sure it dow

### Softwares

1. [Paper](https://github.com/PaperMC/Paper) -> `./limonium download paper 1.21.1`
2. [Purpur](https://github.com/PurpurMC/Purpur) -> `./limonium download purpur 1.21.1`
3. [Pufferfish](https://github.com/pufferfish-gg/Pufferfish) -> `./limonium download pufferfish 1.21.1`
1. [Paper](https://github.com/PaperMC/Paper) -> `./limonium download paper 1.21.3`
2. [Purpur](https://github.com/PurpurMC/Purpur) -> `./limonium download purpur 1.21.3`
3. [Pufferfish](https://github.com/pufferfish-gg/Pufferfish) -> `./limonium download pufferfish 1.21.3`
4. [Geyser](https://github.com/GeyserMc/Geyser) -> `./limonium download geyser 2.1.0` (default is geyser-standalone)

### Proxies
Expand Down Expand Up @@ -58,15 +58,15 @@ Limonium is not affiliated with any of the projects listed.
*Usage: <software> <version>*

```
./limonium download paper 1.21.1
./limonium download paper 1.21.3
```

```
./limonium download paper 1.21.1 --o Paper.jar
./limonium download paper 1.21.3 --o Paper.jar
```

```
./limonium download paper 1.21.1 --o ./mc-servers/hub/Paper.jar
./limonium download paper 1.21.3 --o ./mc-servers/hub/Paper.jar
```

## Compile Function
Expand All @@ -77,7 +77,7 @@ All the software will be downloaded & compiled in the ./limonium-compile directo

### Softwares

1. [Spigot](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/spigot/browse) -> `./limonium compile spigot server.jar --version 1.21.1` (Not recommended to use)
1. [Spigot](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/spigot/browse) -> `./limonium compile spigot server.jar --version 1.21.3` (Not recommended to use)
2. [PlotSquared](https://github.com/IntellectualSites/PlotSquared) -> `./limonium compile plotsquared PlotSquared.jar`
3. [mcMMO](https://github.com/mcMMO-Dev/mcMMO) -> `./limonium compile mcmmo mcMMO.jar`

Expand All @@ -92,7 +92,7 @@ All the software will be downloaded & compiled in the ./limonium-compile directo
*Usage: <software> <output>*

```
./limonium compile spigot server.jar --version 1.21.1
./limonium compile spigot server.jar --version 1.21.3
```

```
Expand Down
6 changes: 3 additions & 3 deletions src/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};

use crate::download_controllers;
use crate::{clap_utils, download_controllers};
use chrono::{NaiveDate, Utc};
use colored::Colorize;
use indicatif::{HumanDuration, ProgressBar, ProgressStyle};
Expand Down Expand Up @@ -129,7 +129,7 @@ impl Backup {
}
}

let i_override = download_controllers::clap_get_one_or_fallback(&"I".to_string(), &"NONE".to_string());
let i_override = clap_utils::clap_get_one_or_fallback(&"I".to_string(), &"NONE".to_string());
if self.backup_format == BackupFormat::TarZst {
// If we have a compression level, use it
if self.compression_level.is_some() && i_override.eq("NONE") {
Expand Down Expand Up @@ -224,7 +224,7 @@ impl Backup {
}
};

let verbose = download_controllers::clap_get_flag_or_fallback(&"verbose".to_string());
let verbose = clap_utils::clap_get_flag_or_false(&"verbose".to_string());
// Verbose before
if verbose { // Capture the output of the backup command
cmd.stdout(Stdio::piped());
Expand Down
40 changes: 40 additions & 0 deletions src/clap_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use clap::ArgMatches;
use std::sync::{RwLock, RwLockReadGuard};

pub(crate) static SUB_COMMAND_ARG_MATCHES: once_cell::sync::Lazy<RwLock<Option<ArgMatches>>> =
once_cell::sync::Lazy::new(|| RwLock::new(None));

fn get_sub_command_arg_matches() -> Option<ArgMatches> {
let lock: RwLockReadGuard<Option<ArgMatches>> = SUB_COMMAND_ARG_MATCHES.read().unwrap();

lock.clone()
}

pub fn write_sub_command_arg_matches(arg_matches: ArgMatches) {
let mut lock = SUB_COMMAND_ARG_MATCHES.write().unwrap();
*lock = Some(arg_matches);
}

pub fn clap_get_one_or_fallback(flag: &str, fallback: &str) -> String {
// Read the lock
let lock = SUB_COMMAND_ARG_MATCHES.read().unwrap();
// Check if the `ArgMatches` is present and return the flag value or fallback
if let Some(args) = &*lock {
args.get_one::<String>(flag)
.unwrap_or(&fallback.to_string())
.to_string()
} else {
fallback.to_string()
}
}

pub fn clap_get_flag_or_false(flag: &str) -> bool {
// Read the lock
let lock = SUB_COMMAND_ARG_MATCHES.read().unwrap();
// Check if the `ArgMatches` is present and return the flag value or `false`
if let Some(args) = &*lock {
args.get_flag(flag)
} else {
false
}
}
8 changes: 4 additions & 4 deletions src/download_controllers/geysermc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::string::String;
use async_trait::async_trait;
use colored::Colorize;

use crate::{download_controllers, number_utils};
use crate::{clap_utils, download_controllers, number_utils};
use crate::download_controllers::platform;
use crate::hash_utils::Hash;
use crate::objects::DownloadedJar::DownloadedJar;
Expand Down Expand Up @@ -39,7 +39,7 @@ impl platform::IPlatform for GeyserAPI {
let mut versions: Vec<String> = json.versions.unwrap();

// See if we don't include snapshot versions
let dont_include_snapshot_versions: bool = download_controllers::clap_get_flag_or_fallback(&String::from("no-snapshot-version"));
let dont_include_snapshot_versions: bool = clap_utils::clap_get_flag_or_false(&String::from("no-snapshot-version"));
if dont_include_snapshot_versions {
versions.retain(|x| !x.contains("-SNAPSHOT"));
}
Expand All @@ -63,7 +63,7 @@ impl platform::IPlatform for GeyserAPI {
to_return.push_str(&build);
to_return.push_str("/downloads/");

let channel = download_controllers::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_GEYSER_CHANNEL));
let channel = clap_utils::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_GEYSER_CHANNEL));
to_return.push_str(&channel);

return to_return;
Expand Down Expand Up @@ -116,7 +116,7 @@ impl platform::IPlatform for GeyserAPI {

if geyser_build_info_json.downloads.is_some() {
let downloads = geyser_build_info_json.downloads.unwrap();
let channel = download_controllers::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_GEYSER_CHANNEL));
let channel = clap_utils::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_GEYSER_CHANNEL));

// Check if channel exists
if !downloads.contains_key(&channel) {
Expand Down
68 changes: 29 additions & 39 deletions src/download_controllers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
use std::{fs, io};
use std::env::temp_dir;
use std::fs::File;
use std::io::{Cursor, Write};
use std::path::{Path, PathBuf};
use std::{fs, io};

use clap::ArgMatches;
use colored::Colorize;
use futures_util::stream::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use regex::Regex;
use reqwest::{Client, header};
use reqwest::{header, Client};
use uuid::Uuid;

use crate::download_controllers::platform::IPlatform;
use crate::objects::DownloadedJar::DownloadedJar;
use crate::SUB_COMMAND_ARG_MATCHES;

pub mod platform;
pub mod geysermc;
pub mod papermc;
pub mod purpurmc;
pub mod platform;
pub mod pufferfish;
pub mod purpurmc;
pub mod spigotmc;
pub mod geysermc;
mod viaversion;

pub fn get_platform(the_project: &String) -> &dyn IPlatform {
Expand Down Expand Up @@ -56,22 +54,6 @@ pub fn is_valid_platform(the_project: &String) -> bool {
};
}

pub fn clap_get_one_or_fallback(flag: &String, fallback: &String) -> String {
unsafe {
let args: &ArgMatches = SUB_COMMAND_ARG_MATCHES.as_ref().expect("SUB_COMMAND_ARG_MATCHES is not set");
let flag = args.get_one::<String>(flag).unwrap_or(&fallback);
return flag.to_string();
}
}

pub fn clap_get_flag_or_fallback(flag: &String) -> bool {
unsafe {
let args: &ArgMatches = SUB_COMMAND_ARG_MATCHES.as_ref().expect("SUB_COMMAND_ARG_MATCHES is not set");
let flag = args.get_flag(flag);
return flag;
}
}

pub fn random_file_name(fileExtension: &String) -> String {
let mut tmp_jar_name = String::from("limonium-");
tmp_jar_name.push_str(&Uuid::new_v4().to_string());
Expand All @@ -83,10 +65,7 @@ pub async fn download_jar_to_temp_dir(link: &String) -> DownloadedJar {
let tmp_jar_name = random_file_name(&".jar".to_string());

let mut headers = header::HeaderMap::new();
headers.insert(
header::USER_AGENT,
"rust-reqwest/limonium".parse().unwrap(),
);
headers.insert(header::USER_AGENT, "rust-reqwest/limonium".parse().unwrap());

// This seems to break some downloads?
// headers.insert(
Expand All @@ -108,7 +87,11 @@ pub async fn download_jar_to_temp_dir(link: &String) -> DownloadedJar {
if !response.status().is_success() {
println!("{} {}", "Failed to download file from".red(), link);
println!("{} {}", "Status code:".red(), response.status());
println!("{} {}", "Status text:".red(), response.status().canonical_reason().unwrap());
println!(
"{} {}",
"Status text:".red(),
response.status().canonical_reason().unwrap()
);
}

let path = temp_dir().join(&tmp_jar_name);
Expand All @@ -127,10 +110,7 @@ pub async fn download_jar_to_temp_dir_with_progress_bar(link: &String) -> Downlo
let tmp_jar_name = random_file_name(&".jar".to_string());

let mut headers = header::HeaderMap::new();
headers.insert(
header::USER_AGENT,
"rust-reqwest/limonium".parse().unwrap(),
);
headers.insert(header::USER_AGENT, "rust-reqwest/limonium".parse().unwrap());

// This seems to break some downloads?
// headers.insert(
Expand All @@ -155,24 +135,31 @@ pub async fn download_jar_to_temp_dir_with_progress_bar(link: &String) -> Downlo
let pb = ProgressBar::new(content_length);
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] {bar} {bytes}/{total_bytes} ({eta})").unwrap()
.progress_chars("#>-")
.template("{spinner:.green} [{elapsed_precise}] {bar} {bytes}/{total_bytes} ({eta})")
.unwrap()
.progress_chars("#>-"),
);

// Create a new file to write the downloaded data
let path = temp_dir().join(&tmp_jar_name);
let mut file = File::create(path).unwrap();

// Create a stream of the file data
let mut stream = client.get(link).send().await.expect("Failed to get file data?").bytes_stream();
let mut stream = client
.get(link)
.send()
.await
.expect("Failed to get file data?")
.bytes_stream();

// Loop over the stream and write to the file
while let Some(item) = stream.next().await {
// Get the chunk of data
let chunk = item.expect("Failed to get chunk");

// Write the chunk to the file
file.write_all(&chunk).expect("Failed to write_all of chunk?");
file.write_all(&chunk)
.expect("Failed to write_all of chunk?");

// Update the progress bar
pb.inc(chunk.len() as u64);
Expand All @@ -189,7 +176,8 @@ pub async fn download_jar_to_temp_dir_with_progress_bar(link: &String) -> Downlo
}

pub fn copy_jar_from_temp_dir_to_dest(tmp_jar_name: &String, final_path: &String) {
fs::copy(temp_dir().join(&tmp_jar_name), &final_path).expect("Failed copying jar from temp directory to final path");
fs::copy(temp_dir().join(&tmp_jar_name), &final_path)
.expect("Failed copying jar from temp directory to final path");
}

pub(crate) fn find_jar_files(dir: &Path, jar_pattern: &Regex) -> Vec<PathBuf> {
Expand All @@ -201,7 +189,9 @@ pub(crate) fn find_jar_files(dir: &Path, jar_pattern: &Regex) -> Vec<PathBuf> {
let path = entry.path();
if path.is_file() {
if let Some(extension) = path.extension() {
if extension == "jar" && jar_pattern.is_match(path.file_name().unwrap().to_str().unwrap()) {
if extension == "jar"
&& jar_pattern.is_match(path.file_name().unwrap().to_str().unwrap())
{
jar_files.push(path.clone());
}
}
Expand All @@ -213,4 +203,4 @@ pub(crate) fn find_jar_files(dir: &Path, jar_pattern: &Regex) -> Vec<PathBuf> {
}

jar_files
}
}
6 changes: 3 additions & 3 deletions src/download_controllers/papermc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::string::String;
use async_trait::async_trait;
use colored::Colorize;

use crate::{download_controllers, number_utils};
use crate::{clap_utils, download_controllers, number_utils};
use crate::download_controllers::platform;
use crate::hash_utils::Hash;
use crate::objects::DownloadedJar::DownloadedJar;
Expand Down Expand Up @@ -42,7 +42,7 @@ impl platform::IPlatform for PaperAPI {
versions.retain(|x| !x.contains("-pre"));

// See if we don't include snapshot versions
let dont_include_snapshot_versions: bool = download_controllers::clap_get_flag_or_fallback(&String::from("no-snapshot-version"));
let dont_include_snapshot_versions: bool = clap_utils::clap_get_flag_or_false(&String::from("no-snapshot-version"));
if dont_include_snapshot_versions {
versions.retain(|x| !x.contains("-SNAPSHOT"));
}
Expand Down Expand Up @@ -119,7 +119,7 @@ impl platform::IPlatform for PaperAPI {

if paper_build_info_json.downloads.is_some() {
let downloads = paper_build_info_json.downloads.unwrap();
let channel = download_controllers::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_PAPER_CHANNEL));
let channel = clap_utils::clap_get_one_or_fallback(&String::from("channel"), &String::from(DEFAULT_PAPER_CHANNEL));

// Check if channel exists
if !downloads.contains_key(&channel) {
Expand Down
Loading

0 comments on commit 62f6e44

Please sign in to comment.