Skip to content

Commit

Permalink
Clean up clippy warnings, fix uninstallation and update_config not …
Browse files Browse the repository at this point in the history
…writing JSON, use rbxdd version resolver
  • Loading branch information
WaviestBalloon committed Nov 11, 2024
1 parent 86a0cfa commit 59845d8
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 118 deletions.
4 changes: 2 additions & 2 deletions src/args/initialise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ static ACCEPTED_PARAMS: [(&str, &str); 1] = [
];

pub fn main(raw_args: &[(String, String)]) {
if argparse::get_param_value_new(&raw_args, "help").is_some() {
if argparse::get_param_value_new(raw_args, "help").is_some() {
help!("Accepted parameters:\n{}", argparse::generate_help(ACCEPTED_PARAMS.to_vec()));
return;
}
status!("Initialising Applejuice...");
let override_steamos_check = argparse::get_param_value_new(&raw_args, "sosoverride");
let override_steamos_check = argparse::get_param_value_new(raw_args, "sosoverride");

if setup::confirm_applejuice_data_folder_existence() {
warning!("Configuration directory already exists!");
Expand Down
5 changes: 2 additions & 3 deletions src/args/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn download_and_install(version: ExactVersion, threading: bool) {
success!("Done");
drop(indentation);

let mut package_manifest_parsed: Vec<&str> = package_manifest.split("\n").collect();
let mut package_manifest_parsed: Vec<&str> = package_manifest.split('\n').collect();
package_manifest_parsed.remove(package_manifest_parsed.len() - 1); // Remove last element which is an empty string
let binary_type = installation::get_binary_type(package_manifest_parsed);

Expand Down Expand Up @@ -81,7 +81,6 @@ fn download_and_install(version: ExactVersion, threading: bool) {

fs::create_dir(format!("{}/ClientSettings", folder_path)).expect("Failed to create ClientSettings directory");
fs::write(format!("{}/ClientSettings/ClientAppSettings.json", folder_path), json!({
"FLogNetwork": 7, // Level 7 logs prints and thingys, needed for BloxstrapRPC integration
"DFIntTaskSchedulerTargetFps": target_fps, // Uncapping FPS to the monitor's refresh rate
}).to_string()).expect("Failed to create the config file!");
} else {
Expand All @@ -107,7 +106,7 @@ fn download_and_install(version: ExactVersion, threading: bool) {
status!("Deleting cached deployment...");
fs::remove_dir_all(cache_path).expect("Failed to remove deployment from cache for post-install!");
}
if remove_deployment_postinstall == true && are_we_upgrading == true {
if remove_deployment_postinstall == true && are_we_upgrading {
let old_install_location = installations[binary_type]["install_path"].as_str().unwrap_or_default();
status!("Delting old installation at {}", old_install_location);

Expand Down
31 changes: 14 additions & 17 deletions src/args/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,25 @@ pub fn resolve_active_logfile(expected_log_directory: String) -> Option<String>
let log_path = format!("{expected_log_directory}{file}");
success!("Found log file at {}", log_path);

return Some(log_path);
Some(log_path)
} else {
error!("Failed to find log file");
return None;
None
}
}

pub fn main(raw_args: &[(String, String)]) {
if argparse::get_param_value_new(&raw_args, "help").is_some() {
if argparse::get_param_value_new(raw_args, "help").is_some() {
help!("Accepted parameters:\n{}", argparse::generate_help(ACCEPTED_PARAMS.to_vec()));
return;
}

let dir_location = setup::get_applejuice_dir();
let binary_type = argparse::get_param_value_new(&raw_args, "binary");
let protocol_arguments = argparse::get_param_value_new(&raw_args, "args").unwrap_or_default();
let skip_update_check = argparse::get_param_value_new(&raw_args, "skipupdatecheck"); // Optional
let shall_we_bootstrap = argparse::get_param_value_new(&raw_args, "bootstrap"); // Optional
let override_steamos_check = argparse::get_param_value_new(&raw_args, "sosoverride"); // Optional
let binary_type = argparse::get_param_value_new(raw_args, "binary");
let protocol_arguments = argparse::get_param_value_new(raw_args, "args").unwrap_or_default();
let skip_update_check = argparse::get_param_value_new(raw_args, "skipupdatecheck"); // Optional
let shall_we_bootstrap = argparse::get_param_value_new(raw_args, "bootstrap"); // Optional
let override_steamos_check = argparse::get_param_value_new(raw_args, "sosoverride"); // Optional
if binary_type.is_none() {
error!("Missing binary type, either Player or Studio");
help!("Accepted parameters:\n{}", argparse::generate_help(ACCEPTED_PARAMS.to_vec()));
Expand All @@ -67,7 +67,7 @@ pub fn main(raw_args: &[(String, String)]) {
let binary = binary_type.unwrap();
let installations = configuration::get_config("roblox_installations");
let configuration = configuration::get_config("global");
let found_installation: &serde_json::Value = match installations.get(&binary) {
let found_installation: &serde_json::Value = match installations.get(binary) {
Some(installation) => installation,
None => {
if shall_we_bootstrap.is_none() {
Expand All @@ -80,10 +80,7 @@ pub fn main(raw_args: &[(String, String)]) {
create_notification(&format!("{}/assets/crudejuice.png", dir_location), 15000, &format!("Installing Roblox {}...", binary), "");

// TODO: Remove this, as Roblox has now locked all non-prod deployment channels :c
let _channel = match configuration["misc"]["overrides"]["deployment_channel"].as_str() {
Some(channel) => channel,
None => "LIVE",
};
let _channel = configuration["misc"]["overrides"]["deployment_channel"].as_str().unwrap_or("LIVE");

args::install::main(&[("install".to_string(), binary.to_string())]);

Expand All @@ -98,7 +95,7 @@ pub fn main(raw_args: &[(String, String)]) {

if skip_update_check.is_none() {
status!("Checking for updates...");
let latest_version = installation::get_latest_version_hash(binary, &found_installation["channel"].as_str().unwrap_or_default());
let latest_version = installation::get_latest_version_hash(binary, found_installation["channel"].as_str().unwrap_or_default());
let version = found_installation["version_hash"].as_str().unwrap();
let deployment_channel = found_installation["channel"].as_str().unwrap();

Expand Down Expand Up @@ -175,7 +172,7 @@ pub fn main(raw_args: &[(String, String)]) {
let proton_installs = configuration::get_config("proton_installations");
let proton_installation_path = proton_installs[found_installation["preferred_proton"].as_str().unwrap_or_default()].as_str().unwrap_or_default();
help!("Using Proton path from `preferred_proton` match: {}", proton_installation_path);
if fs::metadata(&proton_installation_path).is_err() {
if fs::metadata(proton_installation_path).is_err() {
error!("Proton installation does not exist, check your configuration file");
create_notification("dialog-warning", 30000, "Proton configuration error", "Unable to find the Proton installation to launch Roblox with, please check your configuration file to ensure that `preferred_proton` is set correctly");
process::exit(1);
Expand All @@ -197,15 +194,15 @@ pub fn main(raw_args: &[(String, String)]) {

let prefix_location = install_configuration["prefix"].as_str().unwrap_or_default();
help!("Using prefix: `{}`", prefix_location);
if fs::metadata(&format!("{}/{}", dir_location, prefix_location)).is_err() {
if fs::metadata(format!("{}/{}", dir_location, prefix_location)).is_err() {
error!("Prefix location does not exist, check your configuration file");
create_notification("dialog-warning", 30000, "Prefix configuration error", "Unable to find the prefix location, please check your configuration file to ensure that `prefix` is set correctly");
process::exit(1);
}
let run_verb = install_configuration["use_verb"].as_str().unwrap_or_default();
help!("Using verb: `{}`", run_verb);

let output = process::Command::new(dbg!(format!("{}/proton", proton_installation_path)))
let output = process::Command::new(format!("{}/proton", proton_installation_path))
.env(
"STEAM_COMPAT_DATA_PATH",
format!("{}/{}", dir_location, prefix_location),
Expand Down
25 changes: 7 additions & 18 deletions src/args/purge.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::utils::{setup, terminal::*, argparse, configuration::{get_config, update_config, self}};
use std::{fs::{read_dir, remove_dir_all, remove_file, metadata}, process, env::var};
use serde_json::json;

use crate::utils::{setup, terminal::*, argparse, configuration};
use std::{fs::{read_dir, remove_dir_all}, process};

static ACCEPTED_PARAMS: [(&str, &str); 2] = [
("cache", "Deletes all cached deployments (~/.local/share/applejuice/cache)"),
Expand All @@ -12,7 +14,7 @@ fn check_location(folder: &str) {
process::exit(1);
}

let paths = read_dir(format!("{}/cache", setup::get_applejuice_dir())).unwrap();
let paths = read_dir(format!("{}/{}", setup::get_applejuice_dir(), folder)).unwrap();
if paths.count() == 0 {
error!("{folder} directory is empty!");
process::exit(1);
Expand All @@ -21,7 +23,7 @@ fn check_location(folder: &str) {

pub fn main(args: Vec<Vec<(String, String)>>) {
let binding = argparse::get_param_value(args, "purge");
let parsed_args = binding.split(" ").collect::<Vec<&str>>();
let parsed_args = binding.split(' ').collect::<Vec<&str>>();

if parsed_args[0] == "blank" {
error!("No command line arguments provided to purge!");
Expand Down Expand Up @@ -111,24 +113,11 @@ pub fn main(args: Vec<Vec<(String, String)>>) {
process::exit(1);
}
}

status!("Removing shortcuts to deployments...");
removing.iter().for_each(|version| {
let config = get_config(version);
let binary_type = config.get("binary_type").unwrap().as_str().unwrap();
let clean_version_hash = version.replace("version-", "");
let desktop_shortcut_path = format!("{}/.local/share/applications/roblox-{}-{}.desktop", var("HOME").expect("$HOME not set"), binary_type.to_lowercase(), clean_version_hash);
if metadata(desktop_shortcut_path.clone()).is_ok() {
remove_file(desktop_shortcut_path).unwrap();
}
});

configuration::update_desktop_database();

status!("Removing installation entires from configuration file...");
removing.iter().for_each(|version| {
update_config(serde_json::Value::Null, version);
});
configuration::update_config(json!({ }), "roblox_installations");

setup::create_dir("roblox");
success!("Created Roblox directory");
Expand Down
18 changes: 9 additions & 9 deletions src/utils/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,17 @@ pub fn update_config(json: serde_json::Value, config_type: &str) {
let config_file = fs::read_to_string(config_path.clone()).unwrap();
let mut config_json: serde_json::Value = serde_json::from_str(&config_file).unwrap();

// do not overwrite everything inside of config_type, just append onto it
let mut config_type_json = config_json[config_type].clone();
for (key, value) in json.as_object().unwrap() {
config_type_json[key] = value.clone();
if json.is_null() || json.as_object().unwrap().is_empty() {
config_json[config_type] = json;
} else {
// do not overwrite everything inside of config_type, just append onto it
let mut config_type_json = config_json[config_type].clone();
for (key, value) in json.as_object().unwrap() {
config_type_json[key] = value.clone();
}
config_json[config_type] = config_type_json.clone();
}
config_json[config_type] = config_type_json;


//config_json[config_type] = json;

//serde_json::from_str::<Config>(&config_file)
fs::write(config_path, serde_json::to_string_pretty(&config_json).unwrap()).unwrap();
}

Expand Down
56 changes: 12 additions & 44 deletions src/utils/installation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@ use std::process::exit;
use std::{process, fs, path, io, thread, thread::available_parallelism};
use crate::utils::terminal::*;
use crate::setup;
use rbxdd::{appsettings, bindings};
use serde::Deserialize;
use serde_json::from_str;
use reqwest::blocking::get;
use rbxdd::rbxcdn::Binary;
use rbxdd::{appsettings, bindings, rbxcdn};

const LATEST_VERSION_PLAYER_CHANNEL: &str = "https://clientsettings.roblox.com/v2/client-version/WindowsPlayer/channel/";
const LATEST_VERSION_STUDIO_CHANNEL: &str = "https://clientsettings.roblox.com/v2/client-version/WindowsStudio64/channel/";
const LIVE_DEPLOYMENT_CDN: &str = "https://setup.rbxcdn.com/";
const CHANNEL_DEPLOYMENT_CDN: &str = "https://roblox-setup.cachefly.net/channel/";

Expand Down Expand Up @@ -57,24 +53,6 @@ impl<'a> Version<'a> {
}
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Response {
client_version_upload: String
}

/* Response error handling for fetch_latest_version fn */
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResponseErrorMeat {
code: i32,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResponseError {
errors: Vec<ResponseErrorMeat>
}

pub fn get_latest_version_hash(binary: &str, channel: &str) -> String {
fetch_latest_version(LatestVersion {
channel: Cow::Borrowed(channel),
Expand All @@ -85,33 +63,23 @@ pub fn get_latest_version_hash(binary: &str, channel: &str) -> String {
pub fn fetch_latest_version(version: LatestVersion) -> ExactVersion {
let LatestVersion {channel, binary} = version;

let version = match &*binary.to_lowercase() {
"player" => format!("{}{}", LATEST_VERSION_PLAYER_CHANNEL, channel),
"studio" => format!("{}{}", LATEST_VERSION_STUDIO_CHANNEL, channel),
let required_binary: Binary = match &*binary.to_lowercase() {
"player" => Binary::Player,
"studio" => Binary::Studio,
_ => {
error!("Unknown binary type {:?}", binary);
exit(1);
}
};

let output = get(version)
.expect("Failed to get the latest available version hash.")
.text()
.unwrap();

let Response {client_version_upload: hash} = match from_str(&output) {
Ok(json_parsed) => json_parsed,
Err(error) => {
let ResponseError {errors} = from_str(&output).expect(&format!("Failed to parse error response from server.\nResponse: {}\nError: {}", output, error));
match errors[0].code {
1 => { error!("Could not find version details for channel {}, make sure you have spelt the deployment channel name correctly.", channel); },
5 => { error!("The deployment channel {} is restricted by Roblox!", channel); },
_ => { error!("Unknown error response when attempting to resolve channel {}!\nResponse: {}\nError: {}", channel, output, error); }
}

let hash = match rbxcdn::get_latest_version(required_binary, None) {
Ok(hash) => hash,
Err(err) => {
error!("Failed to get latest version: {}", err);
exit(1);
}
};

success!("Resolved hash to {}", hash);
ExactVersion {channel, hash: Cow::Owned(hash)}
}
Expand Down Expand Up @@ -161,7 +129,7 @@ pub fn download_deployment(binary: &str, version_hash: String, channel: &str) ->

let client = reqwest::blocking::Client::new();
progress_bar::init_progress_bar_with_eta(bindings.len());
for (_index, (package, _path)) in bindings.iter().enumerate() {
for (package, _path) in bindings.iter() {
progress_bar::print_progress_bar_info("•", format!("Downloading {package}... ({version_hash}-{package})").as_str(), progress_bar::Color::Blue, progress_bar::Style::Bold);

let mut response = client.get(format!("{}{}-{}", deployment_channel, version_hash, package)).send().unwrap();
Expand Down Expand Up @@ -189,7 +157,7 @@ pub fn extract_deployment_zips(binary: &str, temp_path: String, extraction_path:
progress_bar::init_progress_bar_with_eta(bindings.len());

if disallow_multithreading {
for (_index, (package, path)) in bindings.iter().enumerate() {
for (package, path) in bindings.iter() {
progress_bar::print_progress_bar_info("•", format!("Extracting {package}...").as_str(), progress_bar::Color::Blue, progress_bar::Style::Bold);

if setup::confirm_existence(&format!("{}/{}", extraction_path, path)) && !path.is_empty() {
Expand Down
21 changes: 10 additions & 11 deletions src/utils/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ enum BloxstrapCommand {
}

fn convert_into_assetdelivery_url(asset_id: i64) -> String {
return format!("https://assetdelivery.roblox.com/v1/asset/?id={}", asset_id);
format!("https://assetdelivery.roblox.com/v1/asset/?id={}", asset_id)
}

macro_rules! construct_default_rpc {
Expand Down Expand Up @@ -123,7 +123,7 @@ pub fn init_rpc(binary_type: String, already_known_log_file: Option<String>) {
.assets(
activity::Assets::new()
.large_image("crudejuice")
.large_text("Bitdancer Approved"),
.large_text("Meower Approved"),
)
.timestamps(
activity::Timestamps::new()
Expand All @@ -139,19 +139,18 @@ pub fn init_rpc(binary_type: String, already_known_log_file: Option<String>) {
success!("RPC instance started");

Ok(client)
}).or_else(|errmsg| {
}).map_err(|errmsg| {
warning!("Failed to start RPC instance");
Err(errmsg)
errmsg
});

if let Ok(mut rpc_handler) = client { // If the RPC Client had successfully initialised
thread::spawn(move || {
let log_path;
if already_known_log_file.is_some() {
log_path = already_known_log_file;
let log_path= if already_known_log_file.is_some() {
already_known_log_file
} else {
log_path = launch::resolve_active_logfile(format!("{}/prefixdata/pfx/drive_c/users/steamuser/AppData/Local/Roblox/logs/", setup::get_applejuice_dir()));
}
launch::resolve_active_logfile(format!("{}/prefixdata/pfx/drive_c/users/steamuser/AppData/Local/Roblox/logs/", setup::get_applejuice_dir()))
};

if let Some(log_path) = log_path {
let mut file = fs::File::open(log_path.clone()).unwrap();
Expand Down Expand Up @@ -180,7 +179,7 @@ pub fn init_rpc(binary_type: String, already_known_log_file: Option<String>) {
let mut was_rpc_updated = false;

if line_usable.contains("[BloxstrapRPC] ") {
if detected_bloxstrap == false {
if !detected_bloxstrap {
create_notification(&format!("{}/assets/crudejuice.png", setup::get_applejuice_dir()), 5000, "BloxstrapRPC enabled", "This game has support for the BloxstrapRPC protocol! We have switched to using it for your rich presence.");
detected_bloxstrap = true;
}
Expand Down Expand Up @@ -250,7 +249,7 @@ pub fn init_rpc(binary_type: String, already_known_log_file: Option<String>) {
was_rpc_updated = true;
}

if was_rpc_updated == true { // Debug related
if was_rpc_updated { // Debug related
match rpc_handler.recv() {
Ok(output) => {
let output_string = format!("{:?}", output);
Expand Down
Loading

0 comments on commit 59845d8

Please sign in to comment.