Skip to content

Commit

Permalink
Merge pull request #84 from Sreyas-Sreelal/code-clean
Browse files Browse the repository at this point in the history
Removal of unsafe block and some code refactoring
  • Loading branch information
AmyrAhmady committed Jan 22, 2024
2 parents 554e678 + 656d707 commit d561f5f
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 113 deletions.
31 changes: 14 additions & 17 deletions src-tauri/src/discord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,25 @@ use discord_rich_presence::{
activity::{self, Timestamps},
DiscordIpc, DiscordIpcClient,
};
use std::error::Error;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use sysinfo::System;
use tauri::async_runtime::block_on;

static mut SHOULD_SEND_UPDATE_TO_DISCORD: bool = true;
static SHOULD_SEND_UPDATE_TO_DISCORD: Mutex<bool> = Mutex::new(true);

pub fn toggle_drpc(toggle: bool) -> () {
unsafe {
SHOULD_SEND_UPDATE_TO_DISCORD = toggle;
pub fn toggle_drpc(toggle: bool) -> Result<(), Box<dyn Error>> {
let mut discord_update = SHOULD_SEND_UPDATE_TO_DISCORD.lock()?;
*discord_update = toggle;

if SHOULD_SEND_UPDATE_TO_DISCORD {
initialize_drpc();
}
if *discord_update {
initialize_drpc();
}
Ok(())
}

pub fn initialize_drpc() -> () {
pub fn initialize_drpc() {
std::thread::spawn(move || {
#[allow(unused_assignments)]
let mut connected = false;
Expand Down Expand Up @@ -48,14 +50,9 @@ pub fn initialize_drpc() -> () {
let mut in_game = false;

loop {
unsafe {
if !SHOULD_SEND_UPDATE_TO_DISCORD {
match client.close() {
Ok(_) => {}
Err(_) => {}
};
break;
}
if !*SHOULD_SEND_UPDATE_TO_DISCORD.lock().unwrap() {
let _ = client.close();
break;
}

if !connected {
Expand Down Expand Up @@ -128,7 +125,7 @@ pub fn initialize_drpc() -> () {
}
let nick_name_detail = format!("Playing as {}", name);
let full_server_address = format!("{}:{}", ip, port);
hostname = if hostname.len() > 0 {
hostname = if !hostname.is_empty() {
hostname
} else {
"Unable to get server name".to_string()
Expand Down
24 changes: 11 additions & 13 deletions src-tauri/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,13 @@ pub fn decode_buffer(buf: Vec<u8>) -> (String, String) {
let actual_encoding = if chardet_encoding == "ascii" && charset_normalizer_encoding == "ascii" {
// Default to UTF-8 if both chardet and charset normalizer detect ASCII
Encoding::for_label("UTF_8".as_bytes()).unwrap_or(UTF_8)
} else if chardet_encoding == "koi8-r" && charset_normalizer_encoding == "koi8-r" {
// Use windows-1251 if both chardet and charset normalizer detect KOI8-R
Encoding::for_label("windows-1251".as_bytes()).unwrap_or(UTF_8)
} else if (chardetng_encoding == "gbk"
&& (chardet_encoding == "windows-1255" || charset_normalizer_encoding == "ibm866"))
|| chardet_encoding == "x-mac-cyrillic"
|| charset_normalizer_encoding == "macintosh"
|| (chardet_encoding == "koi8-r" && charset_normalizer_encoding == "koi8-r")
{
// Use windows-1251 for various combinations
// Use windows-1251 if both chardet and charset normalizer detect KOI8-R and for various other combinations
Encoding::for_label("windows-1251".as_bytes()).unwrap_or(UTF_8)
} else if (chardetng_encoding == "windows-1252" && chardet_encoding == "windows-1251")
|| (chardet_encoding == "iso-8859-1"
Expand Down Expand Up @@ -96,7 +94,7 @@ pub fn copy_files(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Result<(), S
if ty.is_dir() {
let dir_path = dest.as_ref().join(entry.file_name());
let dir_path_str = dir_path.to_str().unwrap();
let dir_creation_results = fs::create_dir(dir_path.to_owned());
let dir_creation_results = fs::create_dir(&dir_path);
match dir_creation_results {
Ok(_) => {}
Err(e) => {
Expand All @@ -105,7 +103,7 @@ pub fn copy_files(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Result<(), S
println!("Directory {} already exists", dir_path_str)
}
} else {
info!("[helpers.rs] copy_files: {}", e.to_string());
info!("[helpers.rs] copy_files: {}", e);
return Err(e.to_string());
}
}
Expand All @@ -114,8 +112,8 @@ pub fn copy_files(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Result<(), S
match copy_files(entry.path(), dest.as_ref().join(entry.file_name())) {
Ok(_) => {}
Err(e) => {
info!("[helpers.rs] copy_files: {}", e.to_string());
return Err(e.to_string());
info!("[helpers.rs] copy_files: {}", e);
return Err(e);
}
}
} else {
Expand All @@ -124,23 +122,23 @@ pub fn copy_files(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Result<(), S
match copy_results {
Ok(_) => {}
Err(e) => {
info!("[helpers.rs] copy_files: {}", e.to_string());
info!("[helpers.rs] copy_files: {}", e);
return Err(e.to_string());
}
}
}
}
Err(e) => {
info!("[helpers.rs] copy_files: {}", e.to_string());
info!("[helpers.rs] copy_files: {}", e);
return Err(e.to_string());
}
}
}
return Ok(());
Ok(())
}
Err(e) => {
info!("[helpers.rs] copy_files: {}", e.to_string());
return Err(e.to_string());
info!("[helpers.rs] copy_files: {}", e);
Err(e.to_string())
}
}
}
11 changes: 7 additions & 4 deletions src-tauri/src/injector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub async fn run_samp(
.arg("-p")
.arg(format!("{}", port));

if password.len() > 0 {
if !password.is_empty() {
ready_for_exec = ready_for_exec.arg("-z").arg(password);
}

Expand All @@ -98,7 +98,10 @@ pub async fn run_samp(
return Err("need_admin".to_string());
}

return Err(format!("Spawning process failed (error code: {})", raw_os_err).to_owned());
Err(format!(
"Spawning process failed (error code: {})",
raw_os_err
))
}
}
}
Expand All @@ -119,7 +122,7 @@ pub fn inject_dll(child: u32, dll_path: &str, times: u32) -> Result<(), String>

if times == 10 {
info!("[injector.rs] Dll injection failed: {}", e.to_string());
Err(format!("Injecting dll failed: {}", e.to_string()).to_owned())
Err(format!("Injecting dll failed: {}", e.to_string()))
} else {
inject_dll(child, dll_path, times + 1)
}
Expand All @@ -128,7 +131,7 @@ pub fn inject_dll(child: u32, dll_path: &str, times: u32) -> Result<(), String>
}
Err(e) => {
info!("[injector.rs] Process creation failed: {}", e.to_string());
Err(format!("Finding GTASA process failed: {}", e.to_string()).to_owned())
Err(format!("Finding GTASA process failed: {}", e.to_string()))
}
}
}
5 changes: 2 additions & 3 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ mod rpcs;
mod samp;

use log::LevelFilter;
use runas;
use tauri::Manager;
use tauri::PhysicalSize;

Expand All @@ -28,12 +27,12 @@ async fn inject(

#[tauri::command]
fn get_gtasa_path_from_samp() -> String {
samp::get_gtasa_path().to_string()
samp::get_gtasa_path()
}

#[tauri::command]
fn get_nickname_from_samp() -> String {
samp::get_nickname().to_string()
samp::get_nickname()
}

#[tauri::command]
Expand Down
56 changes: 12 additions & 44 deletions src-tauri/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct Query {
socket: UdpSocket,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Default)]
pub struct InfoPacket {
pub password: bool,
pub players: u16,
Expand All @@ -25,51 +25,19 @@ pub struct InfoPacket {
pub language: String,
}

impl Default for InfoPacket {
fn default() -> Self {
Self {
password: false,
players: 0,
max_players: 0,
hostname: String::new(),
gamemode: String::new(),
language: String::new(),
}
}
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct Player {
pub name: String,
pub score: i32,
}

impl Default for Player {
fn default() -> Self {
Self {
name: String::new(),
score: 0,
}
}
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct ExtraInfoPacket {
pub discord_link: String,
pub light_banner_url: String,
pub dark_banner_url: String,
}

impl Default for ExtraInfoPacket {
fn default() -> Self {
Self {
discord_link: String::new(),
light_banner_url: String::new(),
dark_banner_url: String::new(),
}
}
}

impl Query {
pub async fn new(addr: &str, port: i32) -> Result<Self, std::io::Error> {
let regex = Regex::new(r"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$").unwrap();
Expand Down Expand Up @@ -138,16 +106,15 @@ impl Query {

pub async fn recv(&self) -> Result<String, std::io::Error> {
let mut buf = [0; 1500];
let amt;
match timeout_at(
let amt = match timeout_at(
Instant::now() + Duration::from_secs(2),
self.socket.recv(&mut buf),
)
.await?
{
Ok(n) => amt = n,
Ok(n) => n,
Err(e) => return Err(e),
}
};

if amt == 0 {
return Ok(String::from("no_data"));
Expand All @@ -171,11 +138,12 @@ impl Query {
}

fn build_info_packet(&self, mut packet: Cursor<Vec<u8>>) -> Result<String, std::io::Error> {
let mut data = InfoPacket::default();

data.password = packet.read_i8().unwrap() != 0;
data.players = packet.read_u16::<LittleEndian>().unwrap();
data.max_players = packet.read_u16::<LittleEndian>().unwrap();
let mut data = InfoPacket {
password: packet.read_i8().unwrap() != 0,
players: packet.read_u16::<LittleEndian>().unwrap(),
max_players: packet.read_u16::<LittleEndian>().unwrap(),
..Default::default()
};

let hostname_len = packet.read_u32::<LittleEndian>().unwrap();
let mut hostname_buf = vec![0u8; hostname_len as usize];
Expand Down
Loading

0 comments on commit d561f5f

Please sign in to comment.