Skip to content

Commit

Permalink
Merge pull request #334 from Raspirus/refactor
Browse files Browse the repository at this point in the history
Refactoring the backend code
  • Loading branch information
Benji377 authored Nov 13, 2023
2 parents e2c233b + a715892 commit 0f83a81
Show file tree
Hide file tree
Showing 18 changed files with 419 additions and 426 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Our release schedule is designed to balance feature development, stability, and
| 1.1.8 | BETA: Moving dependabot to renovate |
| 1.0.0 | First full release with a working product |
| 1.1.0 | Added compressed file scanning functionality |
| 1.1.1 | Fixed updating bugs and improved backend syntax |


Please refer to this change log for details on each version's changes and improvements. We appreciate your feedback and contributions as we continue to enhance our antivirus application to meet your security needs.
39 changes: 28 additions & 11 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,37 @@ install:
@printf "$(TEXT)🚀 Starting installation...$(RESET)"
@sleep 3
@printf "$(TEXT)🌑 >>>> Updating system and removing temps$(RESET)"
sudo apt-get update && apt-get upgrade -y
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get autoremove -y
@printf "$(TEXT)🌒 >>>> Installing curl$(RESET)"
sudo apt-get -y install curl
@printf "$(TEXT)🌓 >>>> Installing Rust for Linux$(RESET)"
curl https://sh.rustup.rs -sSf | sh -s -- -y
export PATH="$HOME/.cargo/bin:$PATH"
-source "$HOME/.cargo/env"
sudo curl https://sh.rustup.rs -sSf | sh -s -- -y
@printf "$(TEXT)🌓 >>>> Adding variables to bashrc$(RESET)"
@if ! grep -q "export PATH=\$$HOME/.cargo/bin:\$$PATH" $(HOME)/.bashrc; then \
echo "export PATH=\$$HOME/.cargo/bin:\$$PATH" >> $(HOME)/.bashrc; \
fi
@if ! grep -q "source \$$HOME/.cargo/env" $(HOME)/.bashrc; then \
echo "source \$$HOME/.cargo/env" >> $(HOME)/.bashrc; \
echo "Appended source to ~/.bashrc"; \
fi
@printf "$(TEXT)🌔 >>>> Installing Nodejs$(RESET)"
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash
sudo apt-get install -y nodejs
sudo apt-get update && sudo apt-get install -y ca-certificates gnupg
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --yes --dearmor -o /etc/apt/keyrings/nodesource.gpg
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_18.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
sudo apt-get update
sudo apt-get install nodejs -y
@printf "$(TEXT)🌕 >>>> Installing Nextjs and EsLint$(RESET)"
npm install next@latest react@latest react-dom@latest eslint-config-next@latest
sudo npm install next@latest react@latest react-dom@latest eslint-config-next@latest
@printf "$(TEXT)🌖 >>>> Installing Tauri deps$(RESET)"
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential wget libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev
@printf "$(TEXT)🌗 >>>> Installing Tauri$(RESET)"
cargo install tauri-cli
source $(HOME)/.cargo/env && cargo install tauri-cli
@printf "$(TEXT)🌘 >>>> Installing npm deps$(RESET)"
npm install
sudo npm install
@printf "$(TEXT)🌘 >>>> Setting up required folders$(RESET)"
mkdir -p out
@printf "$(TEXT)🎉 >>>> Done!$(RESET)"

build: install
Expand All @@ -43,7 +55,12 @@ build: install
cargo tauri build
@printf "$(TEXT)>>>> Done!$(RESET)"

test: install
test:
@printf "$(TEXT)>>>> Executing cargo tests$(RESET)"
cd /src-tauri/ && \
cd src-tauri/ && \
cargo test
@printf "$(TEXT)>>>> Done!$(RESET)"
check:
@printf "$(TEXT)>>>> Checking codebase$(RESET)"
cargo clippy --all-features
@printf "$(TEXT)>>>> Done!$(RESET)"
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ Got questions about Raspirus? We're here to help!
- Join our thriving community on the [Discord server](https://discord.gg/Vx7fW9PA8B) to engage with fellow users.
- If you've encountered a bug, browse the GitHub issues to see if it's already reported.


## Support the Project
If you find value in this project, consider sponsoring it through [GitHub Sponsors](https://github.com/sponsors/Raspirus) to contribute to its continued development and maintenance. Your support is greatly appreciated!

## Star History

<a href="https://star-history.com/#Raspirus/Raspirus&Date">
Expand Down
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "raspirus",
"version": "1.1.0",
"version": "1.1.1",
"private": true,
"scripts": {
"dev": "next dev",
Expand All @@ -21,19 +21,19 @@
"bootstrap": "^5.2.3",
"date-fns": "^2.29.3",
"eslint": "8.53.0",
"eslint-config-next": "14.0.2",
"eslint-config-next": "^14.0.2",
"flag-icons": "^6.6.6",
"i18next": "^23.2.1",
"moment": "^2.29.4",
"next": "14.0.2",
"next": "^14.0.2",
"next-i18next": "^15.0.0",
"next-language-detector": "^1.0.2",
"node-schedule": "^2.1.1",
"prop-types": "^15.7.2",
"react": "18.2.0",
"react": "^18.2.0",
"react-bootstrap": "^2.7.2",
"react-circular-progressbar": "^2.1.0",
"react-dom": "18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^13.0.0",
"react-time-picker": "^6.0.4",
"rxjs": "^7.3.0",
Expand Down
2 changes: 1 addition & 1 deletion pages/[locale]/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ export default function Settings() {
ReactSwal.close(); // Close the SweetAlert
console.log(message);
setCount(Number(message));
setDate(moment().format("DD/MM/YYYY hh:mm:ss"));
setDate(moment().format("DD/MM/YYYY HH:mm:ss")); // Format it to be 24h instead of 12h
Swal.fire(t('update_db_completed'), t('update_db_completed_val'), "success");
})
.catch((error) => {
Expand Down
2 changes: 1 addition & 1 deletion snapcraft.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: raspirus
base: core18
version: 1.1.0
version: 1.1.1
summary: A resource- and human-friendly malware scanner
description: Raspirus is your cost-free, versatile malware scanner. Tailored signature detection, comprehensive file scans, and privacy prioritized for swift, reliable protection.
grade: stable
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "raspirus"
version = "1.1.0"
version = "1.1.1"
description = "A simple hash-based virus-scanner"
authors = ["Demetz Benjamin, Hell Björn Felix"]
license = "GPLv3"
Expand Down
69 changes: 39 additions & 30 deletions src-tauri/src/backend/config_file.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::Path;
use directories_next::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
// Amount of hashes in the database
pub hashes_in_db: u32,
Expand All @@ -23,14 +23,17 @@ pub struct Config {
// If we should scan direcories instead of files (You can only choose one on the current file picker dialog)
pub scan_dir: bool,
// List of hashes that should be ignored during scans
pub ignored_hashes: Vec<String>
pub ignored_hashes: Vec<String>,
// config path
#[serde(skip)]
program_path: String,
}

/// The config file simply holds settings of the application that should perists during reboots
/// The entire config is saved to a JSON file and loaded or created on the first start
impl Config {
pub fn new() -> Self {
Config {
pub fn new() -> Result<Self, String> {
let mut cfg = Config {
hashes_in_db: 0,
last_db_update: "Never".to_string(),
logging_is_active: false,
Expand All @@ -39,45 +42,51 @@ impl Config {
db_update_time: "22:00:00".to_string(),
db_location: "".to_string(),
scan_dir: true,
ignored_hashes: Vec::new()
}
ignored_hashes: Vec::new(),
program_path: String::new(),
};
cfg.set_path()?;
Ok(cfg)
}


/// Finds the suitable path for the current system, creates a subfolder for the app and returns
/// the path as a normal String
pub fn set_path(&self) -> Result<String, io::Error> {
let project_dirs =
ProjectDirs::from("com", "Raspirus", "Data").expect("Failed to get project directories.");
fn set_path(&mut self) -> Result<(), String> {
let project_dirs = ProjectDirs::from("com", "Raspirus", "Data")
.expect("Failed to get project directories.");
let program_dir = project_dirs.data_dir();
fs::create_dir_all(&program_dir).expect("Failed to create program directory.");
fs::create_dir_all(program_dir).expect("Failed to create program directory.");
let conf_file_path = program_dir.join("raspirus.config.json");
let conf_file_str = conf_file_path.to_str().expect("Failed to get config path");
Ok(conf_file_str.to_string())
self.program_path = conf_file_path
.to_str()
.expect("Failed to get config path")
.to_owned();
Ok(())
}

/// Will safe the current configuration to the file
/// Will save the current configuration to the file
/// WARNING! If the fields are blank, it will clear the current config
pub fn save(&self) -> Result<(), io::Error> {
let path = self.set_path().expect("Couldn't get path to Data directories");
let file = File::create(path)?;
serde_json::to_writer_pretty(file, self)?;
Ok(())
pub fn save(&mut self) -> Result<(), String> {
self.set_path()?;
let file = File::create(self.program_path.clone()).expect("Failed creating path");
serde_json::to_writer_pretty(file, self).map_err(|err| err.to_string())
}

/// Loads the current config and returns it, or creates a new one if there is non yet
pub fn load(&self) -> Result<Self, io::Error> {
let path = self.set_path()?;

pub fn load(&mut self) -> Result<Self, String> {
// Checks if the config file exists, else quickly creates it
if !Path::new(&path).exists() {
if !Path::new(&self.program_path).exists() {
self.save()?;
};

let mut file = File::open(path).expect("Couldn't open file");
let mut file = File::open(self.program_path.clone()).expect("Couldn't open file");
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = serde_json::from_str(&contents)?;
Ok(config)
file.read_to_string(&mut contents)
.expect("Failed reading config to string");
let mut config_from_str: Config = serde_json::from_str(&contents)
.map_err(|err| err.to_string())
.expect("Failed deserializing config");
config_from_str.set_path()?;
Ok(config_from_str)
}
}
38 changes: 11 additions & 27 deletions src-tauri/src/backend/db_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,12 @@ impl DBOps {
info!("Database not up-to-date!");
info!("Downloading {} file(s)", web_files.len());
self.download_files(web_files);
} else {
if let Some(window) = &self.tauri_window {
if window
.emit_all(
"progress",
TauriEvent {
message: "100".to_string(),
},
)
.is_err()
{
error!("Couldn't send progress update to frontend");
}
} else {
warn!("tauri_window is None, won't send progress to frontend");
} else if let Some(window) = &self.tauri_window {
if window.emit_all("progress", TauriEvent { message: "100".to_string(), },).is_err() {
error!("Couldn't send progress update to frontend");
}
} else {
warn!("tauri_window is None, won't send progress to frontend");
}
info!("Total hashes in DB: {}", self.count_hashes().unwrap_or(0));
Ok(self.count_hashes().unwrap_or(0))
Expand All @@ -128,7 +118,7 @@ impl DBOps {
/// db_ops.download_files(vec![1, 2, 3]);
/// ```
pub fn download_files(&mut self, files: Vec<i32>) {
if files.len() == 0 {
if files.is_empty() {
return;
}

Expand All @@ -142,7 +132,7 @@ impl DBOps {
Ok(hashes) => match hashes {
Some(hashes) => {

if let Err(_) = Self::calculate_progress(self, last_percentage, i.try_into().expect("Issue with scanned size"), self.total_files) {
if Self::calculate_progress(self, last_percentage, i.try_into().expect("Issue with scanned size"), self.total_files).is_err() {
warn!("Progress calculation is broken");
}

Expand Down Expand Up @@ -179,10 +169,7 @@ impl DBOps {
/// assert!(file.is_some());
/// ```
pub fn download_file(file_nr: i32) -> Result<Option<Vec<(String, String)>>, reqwest::Error> {
let url = format!(
"https://virusshare.com/hashfiles/VirusShare_{}.md5",
format!("{:0>5}", file_nr)
);
let url = format!("https://virusshare.com/hashfiles/VirusShare_{:0>5}.md5", file_nr);
info!("Downloading {url}");
let big_tic = time::Instant::now();
let file = reqwest::blocking::get(&url)?;
Expand All @@ -203,7 +190,7 @@ impl DBOps {
}
let mut hashes: Vec<(String, String)> = Vec::new();
for l in lines {
if !l.starts_with("#") {
if !l.starts_with('#') {
hashes.push((l.to_owned(), format!("{}", file_nr.clone())));
}
}
Expand Down Expand Up @@ -312,7 +299,7 @@ impl DBOps {
/// ```
pub fn _remove_hash(&self, hash_str: &str) -> Result<(), rusqlite::Error> {
self.db_conn
.execute("DELETE FROM signatures WHERE hash = ?", &[hash_str])?;
.execute("DELETE FROM signatures WHERE hash = ?", [hash_str])?;
Ok(())
}

Expand Down Expand Up @@ -387,10 +374,7 @@ impl DBOps {
/// assert!(db_ops.file_exists(123).unwrap_or(false));
/// ```
pub fn file_exists(file_nr: i32) -> Result<bool, reqwest::Error> {
let url = format!(
"https://virusshare.com/hashfiles/VirusShare_{}.md5",
format!("{:0>5}", file_nr)
);
let url = format!("https://virusshare.com/hashfiles/VirusShare_{:0>5}.md5", file_nr);
let client = reqwest::blocking::Client::new();
info!("Checking if file {file_nr} exists...");
let code = client.get(url).send()?;
Expand Down
Loading

0 comments on commit 0f83a81

Please sign in to comment.