Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Infobar #177

Merged
merged 4 commits into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src-tauri/src/files_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ extern crate notify;
extern crate open;
extern crate trash;
use crate::file_lib;
use crate::storage;
#[cfg(not(target_os = "macos"))]
use normpath::PathExt;
use notify::{raw_watcher, RawEvent, RecursiveMode, Watcher};
use serde_json::Value;
use std::sync::mpsc::channel;

#[cfg(windows)]
Expand Down Expand Up @@ -199,6 +201,18 @@ pub fn is_dir(path: &Path) -> Result<bool, String> {
}
#[tauri::command]
pub async fn read_directory(dir: &Path) -> Result<FolderInformation, String> {
let preference = storage::read_data("preference".to_string());
let preference = match preference {
Ok(result) => result,
Err(_) => return Err("Error reading preference".into()),
};
let preference: Result<Value, serde_json::Error> = serde_json::from_str(&preference.data);
let preference = match preference {
Ok(result) => result,
Err(_) => return Err("Error parsing preference".into()),
};
let hide_system_files = &preference["hideSystemFiles"];
let hide_system_files = hide_system_files.as_bool().unwrap();
let paths = fs::read_dir(dir).map_err(|err| err.to_string())?;
let mut number_of_files: u16 = 0;
let mut files = Vec::new();
Expand All @@ -211,7 +225,12 @@ pub async fn read_directory(dir: &Path) -> Result<FolderInformation, String> {
skipped_files.push(file_name);
continue;
} else {
files.push(file_info.unwrap())
let file_info = file_info.unwrap();
if hide_system_files && file_info.is_system {
skipped_files.push(file_name);
continue;
}
files.push(file_info)
};
}
Ok(FolderInformation {
Expand Down Expand Up @@ -545,3 +564,16 @@ pub async fn extract_icon(file_path: String) -> Result<String, String> {
pub async fn extract_icon(_file_path: String) -> Result<String, String> {
Err("Not supported".to_string())
}

#[tauri::command]
pub async fn calculate_files_total_size(files: Vec<String>) -> u64 {
let mut total_size: u64 = 0;
for file in files {
let metadata = fs::metadata(file.clone()).unwrap();
if metadata.is_dir() {
total_size += get_dir_size(file).await;
}
total_size += metadata.len();
}
total_size
}
1 change: 1 addition & 0 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ fn main() {
files_api::get_dir_size,
files_api::get_file_properties,
files_api::extract_icon,
files_api::calculate_files_total_size,
drives::get_drives,
storage::write_data,
storage::read_data,
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use tauri::api::path::local_data_dir;

#[derive(serde::Serialize)]
pub struct StorageData {
data: String,
status: bool,
pub data: String,
pub status: bool,
}

#[tauri::command]
Expand Down
42 changes: 31 additions & 11 deletions src/Api/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import FileMetaData from '../Typings/fileMetaData';

/** Invoke Rust command to handle files */
class FileAPI {
readonly fileName: string;
readonly fileName: string | string[];
readonly parentDir: string;
/**
* Construct FileAPI Class
* @param {string} fileName - Your file path
* @param {string} parentDir - Parent directory of the file
*/
constructor(fileName: string, parentDir?: string) {
if (parentDir) {
constructor(fileName: string | string[], parentDir?: string) {
if (parentDir && typeof fileName === 'string') {
this.parentDir = parentDir;
this.fileName = joinPath(parentDir, fileName);
} else this.fileName = fileName;
Expand All @@ -23,14 +23,20 @@ class FileAPI {
* @returns {Promise<any>}
*/
readFile(): Promise<string> {
return new Promise((resolve) => {
fs.readTextFile(this.fileName).then((fileContent) => resolve(fileContent));
return new Promise((resolve, reject) => {
if (typeof this.fileName === 'string') {
fs.readTextFile(this.fileName).then((fileContent) => resolve(fileContent));
} else {
reject('File name is not a string');
}
});
}

async readBuffer(): Promise<Buffer> {
const Buffer = require('buffer/').Buffer;
return Buffer.from(await fs.readBinaryFile(this.fileName));
if (typeof this.fileName === 'string') {
return Buffer.from(await fs.readBinaryFile(this.fileName));
}
}
/**
* Open file on default app
Expand All @@ -44,7 +50,7 @@ class FileAPI {
* @returns {string}
*/
readAsset(): string {
return tauri.convertFileSrc(this.fileName);
return typeof this.fileName === 'string' ? tauri.convertFileSrc(this.fileName) : '';
}
/**
* Read file and return as JSON
Expand All @@ -67,10 +73,12 @@ class FileAPI {
* @returns {Promise<void>}
*/
async createFile(): Promise<void> {
await invoke('create_dir_recursive', {
dirPath: dirname(this.fileName),
});
return await invoke('create_file', { filePath: this.fileName });
if (typeof this.fileName === 'string') {
await invoke('create_dir_recursive', {
dirPath: dirname(this.fileName),
});
return await invoke('create_file', { filePath: this.fileName });
}
}
/**
* Read properties of a file
Expand All @@ -90,9 +98,21 @@ class FileAPI {
});
}

/**
* Extract icon of executable file
* @returns {Promise<string>}
*/
async extractIcon(): Promise<string> {
return await invoke('extract_icon', { filePath: this.fileName });
}

/**
* Calculate total size of given file paths
* @returns {number} - Size in bytes
*/
async calculateFilesSize(): Promise<number> {
return await invoke('calculate_files_total_size', { files: this.fileName });
}
}

export default FileAPI;
21 changes: 6 additions & 15 deletions src/Components/Files/File Operation/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,23 @@ import PromptError from '../../Prompt/error';
* @param {boolean} writeLog - does the operation need to be written
* @returns {Promise<void>}
*/
const NewFile = async (
fileName: string,
parentDir?: string,
writeLog = true
): Promise<void> => {
const NewFile = async (fileName: string, parentDir?: string, writeLog = true): Promise<void> => {
if (!parentDir) parentDir = await focusingPath();
const newFile = new FileAPI(fileName, parentDir);

if (await newFile.exists()) {
PromptError(
'Error creating file',
`Failed to create file ${newFile.fileName}: File already existed`
);
PromptError('Error creating file', `Failed to create file ${newFile.fileName}: File already existed`);
} else {
try {
await newFile.createFile();
} catch (err) {
PromptError(
'Error creating file',
`Failed to create file ${newFile.fileName}: Something went wrong (${err})`
);
PromptError('Error creating file', `Failed to create file ${newFile.fileName}: Something went wrong (${err})`);
}

if (writeLog) {
console.log(writeLog);
OperationLog('newfile', null, newFile.fileName);
if (typeof newFile.fileName === 'string') {
OperationLog('newfile', null, newFile.fileName);
}
}
}
};
Expand Down
Loading