files.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. use hex;
  2. use serde::{Deserialize, Serialize};
  3. use sha2::{Digest as OtherDigest, Sha256}; // 确保导入 `Digest`
  4. use std::fs;
  5. use std::path::{Path, PathBuf};
  6. use std::time::UNIX_EPOCH;
  7. use tauri::command;
  8. extern crate trash;
  9. #[derive(Debug, Deserialize, Serialize)]
  10. pub enum FileSizeCategory {
  11. Huge, // 4GB+
  12. VeryLarge, // 1GB to 4GB-
  13. Large, // 128MB to 1GB-
  14. Medium, // 1MB to 128MB-
  15. Small, // 16KB to 1MB-
  16. Tiny, // 1B to 16KB-
  17. Empty, // Empty files or directories
  18. }
  19. #[derive(Debug, Deserialize, Serialize)]
  20. pub struct FileInfo {
  21. pub path: Option<String>,
  22. pub checkbox_all: Option<bool>,
  23. pub add_type: Option<String>,
  24. pub pass_type: Option<String>,
  25. // pub checked_size_values: Option<Vec<String>>, // 假设值类型为 String,具体类型视情况调整
  26. pub checked_size_values: Option<Vec<FileSizeCategory>>, // 使用正确的类型
  27. pub checkbox_size_all: Option<bool>,
  28. pub checked_type_values: Option<Vec<String>>, // 同上
  29. pub time: Option<String>,
  30. pub id: Option<u32>,
  31. pub progress: Option<f32>,
  32. pub types: Option<Vec<String>>,
  33. }
  34. #[command]
  35. pub fn get_all_directory(file_info: FileInfo) -> Vec<PathBuf> {
  36. let mut files = Vec::new();
  37. if let Some(ref path) = file_info.path {
  38. println!("Processing directory: {}", path);
  39. let directory = Path::new(path);
  40. read_files_in_directory(
  41. directory,
  42. &mut files,
  43. &file_info.checked_size_values,
  44. &file_info.types,
  45. );
  46. files
  47. } else {
  48. files
  49. }
  50. }
  51. #[command]
  52. pub fn get_file_type(file_path: &str) -> Option<&str> {
  53. let path = Path::new(file_path);
  54. path.extension().and_then(|ext| ext.to_str())
  55. }
  56. #[command]
  57. pub fn get_file_type_by_path(file_path: String) -> String {
  58. if let Some(file_type) = get_file_type(&file_path) {
  59. file_type.to_string()
  60. } else {
  61. "Unknown file type".to_string()
  62. }
  63. }
  64. fn read_files_in_directory(
  65. dir: &Path,
  66. files: &mut Vec<PathBuf>,
  67. filters: &Option<Vec<FileSizeCategory>>,
  68. types: &Option<Vec<String>>,
  69. ) {
  70. if dir.is_dir() {
  71. // 尝试读取目录,忽略错误
  72. if let Ok(entries) = fs::read_dir(dir) {
  73. for entry in entries {
  74. if let Ok(entry) = entry {
  75. let path = entry.path();
  76. if path.is_dir() {
  77. // 递归调用,忽略错误
  78. read_files_in_directory(&path, files, filters, types);
  79. } else {
  80. // 尝试获取文件元数据,忽略错误
  81. if let Ok(metadata) = fs::metadata(&path) {
  82. let size = metadata.len();
  83. let size_matches = filters.is_none()
  84. || file_size_matches(size, filters.as_ref().unwrap());
  85. let type_matches = types.is_none()
  86. || file_type_matches(&path, types.as_ref().unwrap());
  87. if size_matches && type_matches {
  88. files.push(path);
  89. }
  90. }
  91. }
  92. }
  93. }
  94. }
  95. }
  96. }
  97. fn file_size_matches(size: u64, categories: &Vec<FileSizeCategory>) -> bool {
  98. use FileSizeCategory::*;
  99. categories.iter().any(|category| match category {
  100. Huge => size >= 4_294_967_296,
  101. VeryLarge => (1_073_741_824..4_294_967_296).contains(&size),
  102. Large => (134_217_728..1_073_741_824).contains(&size),
  103. Medium => (1_048_576..134_217_728).contains(&size),
  104. Small => (16_384..1_048_576).contains(&size),
  105. Tiny => (1..16_384).contains(&size),
  106. Empty => size == 0,
  107. })
  108. }
  109. fn file_type_matches(path: &Path, types: &Vec<String>) -> bool {
  110. if let Some(ext) = path.extension() {
  111. if let Some(ext_str) = ext.to_str() {
  112. return types.iter().any(|type_str| type_str == ext_str);
  113. }
  114. }
  115. false
  116. }
  117. #[command]
  118. pub fn calculate_file_hash(file_path: String) -> String {
  119. let file_bytes = fs::read(file_path).expect("Failed to read file");
  120. // 初始化 SHA256 哈希上下文
  121. let mut hasher = Sha256::new();
  122. hasher.update(&file_bytes);
  123. // 完成哈希计算
  124. let result = hasher.finalize();
  125. // 将结果转换为十六进制字符串
  126. hex::encode(result)
  127. }
  128. #[derive(Debug, Serialize, Deserialize)]
  129. pub struct FileInfos {
  130. file_path: PathBuf,
  131. file_name: Option<String>,
  132. file_type: Option<String>,
  133. file_size: u64,
  134. modified_time: Option<u64>, // 时间戳形式
  135. creation_time: Option<u64>,
  136. }
  137. #[command]
  138. pub fn get_file_info(file_path: String) -> FileInfos {
  139. let path = Path::new(&file_path);
  140. // 使用 match 来处理可能的错误
  141. let metadata = match fs::metadata(&path) {
  142. Ok(meta) => meta,
  143. Err(_) => {
  144. return FileInfos {
  145. // 在这里处理错误,可能是返回默认的 FileInfos
  146. file_path: path.to_path_buf(),
  147. file_name: None,
  148. file_type: None,
  149. file_size: 0,
  150. modified_time: None,
  151. creation_time: None,
  152. };
  153. }
  154. };
  155. // 获取文件修改时间
  156. let modified_time = metadata
  157. .modified()
  158. .ok()
  159. .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
  160. .map(|d| d.as_secs());
  161. // 获取文件创建时间
  162. let accessed_time = metadata
  163. .accessed()
  164. .ok()
  165. .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
  166. .map(|d| d.as_secs());
  167. // 构造 FileInfo 结构
  168. FileInfos {
  169. file_path: path.to_path_buf(),
  170. file_name: path
  171. .file_name()
  172. .and_then(|name| name.to_str())
  173. .map(|name| name.to_string()),
  174. file_type: get_file_type(&file_path).map(|t| t.to_string()), // 确保 get_file_type 也不返回 Result 或 Option
  175. file_size: metadata.len(),
  176. modified_time,
  177. creation_time: accessed_time,
  178. }
  179. }
  180. #[derive(Debug, Serialize, Deserialize)]
  181. pub struct RequestMvFile {
  182. code: Option<u64>,
  183. msg: Option<String>,
  184. data: Option<String>,
  185. }
  186. #[command]
  187. pub fn mv_file_to_trash(file_path: String) -> RequestMvFile {
  188. let data = file_path.clone();
  189. if let Err(e) = trash::delete(file_path) {
  190. RequestMvFile {
  191. code: Some(500),
  192. msg: Some(format!("Error moving file to trash: {}", e)),
  193. data: Some(format!("{}", data)),
  194. }
  195. } else {
  196. println!("File successfully moved to trash.");
  197. RequestMvFile {
  198. code: Some(200),
  199. msg: Some("File successfully moved to trash.".to_string()),
  200. data: Some(format!("{}", data)),
  201. }
  202. }
  203. }
  204. #[derive(Debug, Deserialize, Serialize)]
  205. enum AppError {
  206. DataDirNotFound,
  207. Other(String),
  208. }
  209. impl std::fmt::Display for AppError {
  210. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  211. match *self {
  212. AppError::DataDirNotFound => write!(f, "Application data directory not found"),
  213. AppError::Other(ref err) => write!(f, "Error: {}", err),
  214. }
  215. }
  216. }
  217. #[command]
  218. pub fn get_app_data_dir() -> String {
  219. std::env::var("MY_APP_DATA_DIR")
  220. .unwrap_or_else(|_| "Environment variable for app data directory not set".to_string())
  221. }