Bläddra i källkod

清理冗余文件

john 1 år sedan
förälder
incheckning
e965d1e4aa

+ 4 - 1
README.md

@@ -53,4 +53,7 @@ https://github.com/launchbadge/sqlx
 
 
 - https://github.com/Johnhong9527/tauri-plugin-sql
-- https://gitee.com/seamong/tauri-plugin-sql
+- https://gitee.com/seamong/tauri-plugin-sql
+
+## 1.1.0 更新说明
+移除项目中的所有冗余代码

+ 0 - 1
src-tauri/src/common/mod.rs

@@ -1 +0,0 @@
-// pub mod sqlite;

+ 0 - 174
src-tauri/src/common/sqlite/migration/database_version.rs

@@ -1,174 +0,0 @@
-use crate::self_plugin::tauri_plugin_sqlite::sqlite::{execute, execute_batch, query_with_args};
-use anyhow::{anyhow, Result};
-use serde_json::{json, Value};
-
-// 定义一个异步的数据库版本操作接口
-#[async_trait::async_trait]
-pub trait DatabaseVersionSql {
-    // 获取版本号
-    async fn version(&self) -> u32;
-    // 执行DDL脚本之前的操作
-    async fn before(&self);
-    // 获取DDL脚本
-    async fn ddl(&self) -> Vec<String>;
-    // 执行DDL脚本之后的操作
-    async fn after(&self);
-}
-
-// 获取数据库版本
-pub async fn get_database_version(path: &String) -> Result<u32> {
-    // 检查版本表是否存在
-    if !check_version_table(path).await? {
-        Err(anyhow!("系统错误,没有数据库版本表!"))
-    } else {
-        // 查询数据库版本
-        let versions = query_with_args(
-            path.to_string(),
-            "SELECT version FROM databases_version WHERE name = :name".to_string(),
-            json!({
-                ":name": path.clone()
-            }),
-        ).await?;
-
-        // 如果没有版本记录,返回0
-        if versions.len() == 0 {
-            Ok(0)
-        } else {
-            // 获取版本号
-            let version = versions.get(0).map_or(0, |row| {
-                if let Some(Value::Number(v)) = row.get("version") {
-                    let v: u32 = v.as_u64().unwrap().try_into().unwrap();
-                    v
-                } else {
-                    0
-                }
-            });
-            Ok(version)
-        }
-    }
-}
-
-// 设置数据库版本
-pub async fn set_database_version(path: &String, version: u32) -> Result<bool> {
-    // 检查版本表是否存在
-    if !check_version_table(path).await? {
-        Err(anyhow!("系统错误,没有数据库版本表!"))
-    } else {
-        // 更新数据库版本
-        execute(
-            path.to_string(),
-            "INSERT INTO databases_version (name, version) VALUES (:name, :version) 
-             ON CONFLICT(name) DO UPDATE SET version = :version".to_string(),
-            json!({
-                ":name": path.clone(),
-                ":version": version
-            }),
-        ).await?;
-        Ok(true)
-    }
-}
-
-// 合并数据库版本
-pub async fn merge_database_version<T>(path: &String, list: Vec<T>) -> Result<bool>
-    where
-        T: DatabaseVersionSql,
-{
-    // 获取当前版本
-    let version = get_database_version(path).await?;
-    tracing::debug!("当前数据库版本:{}", version);
-
-    // 循环执行升级脚本
-    for item in list {
-        let item_version = item.version().await;
-
-        // 如果新版本大于当前版本,执行升级
-        if item_version > version {
-            item.before().await;
-            let ddls = item.ddl().await;
-
-            // 执行DDL脚本
-            for ddl_sql in ddls {
-                execute_batch(path.to_string(), ddl_sql).await?;
-            }
-
-            item.after().await;
-            set_database_version(path, item_version).await?;
-        }
-    }
-    Ok(true)
-}
-
-// 普通DDL数据库版本结构体
-#[derive(Debug)]
-pub struct NormalDdlDatabaseVersionSql {
-    version: u32,
-    ddl: Vec<String>,
-}
-
-impl NormalDdlDatabaseVersionSql {
-    // 创建一个新实例
-    fn new(version: u32, ddl: Vec<String>) -> Self {
-        Self { version, ddl }
-    }
-}
-
-// 实现 DatabaseVersionSql 接口
-#[async_trait::async_trait]
-impl DatabaseVersionSql for NormalDdlDatabaseVersionSql {
-    async fn version(&self) -> u32 {
-        self.version
-    }
-    async fn before(&self) {
-        tracing::debug!("nothing!");
-    }
-    async fn ddl(&self) -> Vec<String> {
-        self.ddl.clone()
-    }
-    async fn after(&self) {
-        tracing::debug!("nothing!");
-    }
-}
-
-// 检查版本表是否存在
-async fn check_version_table(path: &String) -> Result<bool> {
-    let sql = String::from(
-        "SELECT count(1) count FROM sqlite_master WHERE type='table' and name = :name ",
-    );
-
-    let rows = query_with_args(
-        path.to_string(),
-        sql,
-        json!({
-            ":name": "databases_version"
-        }),
-    ).await?;
-
-    // 如果表不存在,创建版本表
-    if rows.len() == 0 {
-        execute_batch(
-            path.to_string(),
-            "CREATE TABLE databases_version (name TEXT, version INTEGER, unique(name));"
-                .to_string(),
-        ).await?;
-        Ok(true)
-    } else {
-        let count = rows.get(0).map_or(0, |row| {
-            if let Some(Value::Number(v)) = row.get("count") {
-                let v: u32 = v.as_u64().unwrap().try_into().unwrap();
-                v
-            } else {
-                0
-            }
-        });
-
-        // 如果表不存在,创建版本表
-        if count == 0 {
-            execute_batch(
-                path.to_string(),
-                "CREATE TABLE databases_version (name TEXT, version INTEGER, unique(name));"
-                    .to_string(),
-            ).await?;
-        }
-        Ok(true)
-    }
-}

+ 0 - 4
src-tauri/src/common/sqlite/migration/mod.rs

@@ -1,4 +0,0 @@
-mod database_version;
-
-
-

+ 0 - 167
src-tauri/src/common/sqlite/mod.rs

@@ -1,167 +0,0 @@
-pub mod migration; // 定义数据库迁移模块
-mod rusqlite_utils; // 定义一些辅助工具模块
-
-use anyhow::{anyhow, Result}; // 引入错误处理库
-use rusqlite::{types::Value as SqliteValue, Connection, OpenFlags, ToSql}; // 引入rusqlite库
-use serde_json::Value as JsonValue; // 引入JSON库
-use std::collections::HashMap; // 引入HashMap数据结构
-use std::sync::{Arc, Mutex, RwLock}; // 引入并发处理库
-
-// 定义一个全局的数据库连接缓存,使用RwLock进行读写锁定
-lazy_static::lazy_static! {
-    pub(crate) static ref CONNECTIONS: RwLock<HashMap<String, Arc<Mutex<Connection>>>> =
-        RwLock::new(HashMap::new());
-}
-
-// 打开数据库连接
-pub async fn open(path: &str) -> Result<Arc<Mutex<Connection>>> {
-    open_with_flags(path, OpenFlags::default()).await
-}
-
-// 打开带有标志的数据库连接
-pub async fn open_with_flags(path: &str, flags: OpenFlags) -> Result<Arc<Mutex<Connection>>> {
-    // 判断是否已经打开
-    let exist = CONNECTIONS.read().unwrap().contains_key(path);
-
-    if exist {
-        if let Some(arc_conn) = CONNECTIONS.read().unwrap().get(path) {
-            return Ok(arc_conn.clone());
-        } else {
-            Err(anyhow!("获取失败"))
-        }
-    } else {
-        // 构造数据库路径
-        let mut storage_path = crate::utils::system_tools_home_path()?.join("sqlite");
-        storage_path.push(path.to_string());
-
-        let prefix = storage_path.parent().unwrap_or(storage_path.as_path());
-        std::fs::create_dir_all(prefix).map_err(|err| anyhow::anyhow!(err))?;
-
-        // 打开数据库连接
-        let arc_conn = Arc::new(Mutex::new(Connection::open_with_flags(
-            &storage_path,
-            flags,
-        )?));
-
-        // 将连接缓存
-        let mut cache = CONNECTIONS.write().unwrap();
-        cache.insert(path.parse()?, arc_conn.clone());
-
-        Ok(arc_conn)
-    }
-}
-
-// 执行SQL语句
-pub async fn execute_sql(path: &String, sql: &String) -> Result<usize> {
-    let arc_conn = open(path).await?;
-
-    let conn = arc_conn
-        .lock()
-        .map_err(|err| anyhow!("lock数据库连接失败:{}", err))?;
-
-    let res = conn.execute(sql.as_str(), [])?;
-    Ok(res)
-}
-
-// 关闭数据库连接
-pub async fn close(path: &String) -> Result<bool> {
-    let arc_conn = open(path).await?;
-
-    let conn = arc_conn
-        .lock()
-        .map_err(|err| anyhow!("lock数据库连接失败:{}", err))?;
-
-    drop(conn);
-    // 移除缓存
-    let mut cache = CONNECTIONS
-        .write()
-        .map_err(|err| anyhow!("获取锁失败:{}", err))?;
-
-    cache.remove(path);
-    Ok(true)
-}
-
-// 批量执行SQL语句
-pub async fn execute_batch(path: &String, sql: &String) -> Result<bool> {
-    let arc_conn = open(path).await?;
-
-    let connection = arc_conn
-        .lock()
-        .map_err(|err| anyhow!("lock数据库连接失败:{}", err))?;
-
-    let res = connection.execute_batch(sql.as_str())?;
-    Ok(true)
-}
-
-// 执行带参数的SQL语句
-pub async fn execute(path: &String, sql: &String, args: &JsonValue) -> Result<usize> {
-    let arc_conn = open(path).await?;
-
-    let conn = arc_conn
-        .lock()
-        .map_err(|err| anyhow!("lock数据库连接失败:{}", err))?;
-
-    // 将参数转换为SQLite的值
-    let mut args_sqlite_values = HashMap::<String, SqliteValue>::new();
-    let mut named_args: Vec<(&str, &dyn ToSql)> = vec![];
-
-    if let JsonValue::Object(json_value) = args {
-        for (k, v) in json_value {
-            args_sqlite_values.insert(k.clone(), rusqlite_utils::value_to_rusqlite_value(v)?);
-        }
-    }
-
-    for (k, v) in &args_sqlite_values {
-        named_args.push((k, v as &dyn ToSql));
-    }
-
-    let res = conn.execute(sql.as_str(), &*named_args)?;
-    return Ok(res);
-}
-
-// 执行带参数的查询语句
-pub async fn query_with_args(
-    path: &String,
-    sql: &String,
-    args: &JsonValue,
-) -> Result<Vec<HashMap<String, JsonValue>>> {
-    let arc_conn = open(path).await?;
-
-    let conn = arc_conn
-        .lock()
-        .map_err(|err| anyhow!("lock数据库连接失败:{}", err))?;
-
-    let mut stmt = conn.prepare(sql.as_str())?;
-
-    let mut names: Vec<String> = Vec::new();
-    for name in stmt.column_names() {
-        names.push(name.to_string());
-    }
-
-    let mut args_sqlite_values = HashMap::<String, SqliteValue>::new();
-    let mut named_args: Vec<(&str, &dyn ToSql)> = vec![];
-
-    if let JsonValue::Object(json_value) = args {
-        for (k, v) in json_value {
-            args_sqlite_values.insert(k.clone(), rusqlite_utils::value_to_rusqlite_value(v)?);
-        }
-    }
-
-    for (k, v) in &args_sqlite_values {
-        named_args.push((k, v as &dyn ToSql));
-    }
-
-    let schema_iter = stmt.query_map(&*named_args, |row| {
-        rusqlite_utils::rusqlite_row_to_map(row, &names)
-            .map_err(|_e| rusqlite::Error::ExecuteReturnedResults)
-    })?;
-
-    let mut result = Vec::<HashMap<String, JsonValue>>::new();
-
-    for table_result in schema_iter {
-        if let Ok(row_value) = table_result {
-            result.push(row_value);
-        }
-    }
-    Ok(result)
-}

+ 0 - 92
src-tauri/src/common/sqlite/rusqlite_utils.rs

@@ -1,92 +0,0 @@
-use anyhow::{anyhow, Result}; // 引入错误处理库
-use rusqlite::{
-    types::FromSql,              // 用于将 SQLite 数据类型转换为 Rust 类型
-    types::Value as SqliteValue, // SQLite 的值类型
-    types::ValueRef::{Blob, Integer, Null, Real, Text}, // SQLite 值引用类型
-    Connection,
-    Params,
-    Row, // 引入 SQLite 连接、参数、行和 ToSql 类型
-};
-use serde_json::{Number, Value}; // 引入 JSON 处理库
-use std::{collections::HashMap}; // 引入 HashMap 和 Mutex
-
-// 查询单个值
-pub fn query_one_value<P, V>(connection: &Connection, sql: &str, p: P) -> Result<V>
-where
-    P: Params,  // 参数类型
-    V: FromSql, // 从 SQLite 值转换的类型
-{
-    // 准备 SQL 语句
-    let mut stmt = connection.prepare(sql)?;
-
-    // 执行查询并映射结果
-    let result_iter = stmt.query_map(p, |row| Ok(row.get(0)?))?;
-
-    // 遍历查询结果
-    for result in result_iter {
-        if let Ok(i32_temp) = result {
-            // 返回查询到的值
-            return Ok(i32_temp);
-        }
-    }
-    Err(anyhow!("")) // 如果没有结果,返回错误
-}
-
-// 将 rusqlite 的行转换为 JSON 值
-pub fn rusqlite_row_to_value(row: &Row<'_>, cnt: usize) -> Result<Vec<Value>> {
-    let mut cols = Vec::<Value>::new(); // 存储列值
-    for i in 0..cnt {
-        // 获取每一列的值
-        let rusqlite_value = row.get_ref_unwrap(i);
-        // 将 rusqlite 的值转换为 JSON 值
-        let idns_value = match rusqlite_value {
-            Null => Value::Null,                                  // 空值
-            Integer(i64_v) => Value::Number(Number::from(i64_v)), // 整数
-            Real(f64_v) => Value::Number(Number::from_f64(f64_v).map_or(Number::from(0i64), |r| r)), // 浮点数
-            Text(str_v) => Value::String(String::from_utf8(str_v.to_vec()).unwrap()), // 文本
-            Blob(_v) => Value::Null, // 二进制数据(这里处理为 Null)
-        };
-        cols.push(idns_value); // 将转换后的值添加到列集合中
-    }
-
-    return Ok(cols); // 返回列值集合
-}
-
-// 将 rusqlite 的行转换为 HashMap
-pub fn rusqlite_row_to_map(_row: &Row<'_>, names: &Vec<String>) -> Result<HashMap<String, Value>> {
-    let mut row = HashMap::default(); // 创建一个 HashMap 来存储行数据
-    for (i, name) in names.iter().enumerate() {
-        // 获取每一列的值
-        let rusqlite_value = _row.get_ref_unwrap(i);
-        // 将 rusqlite 的值转换为 JSON 值
-        let v = match rusqlite_value {
-            Real(f64_v) => Value::Number(Number::from_f64(f64_v).map_or(Number::from(0i64), |r| r)), // 浮点数
-            Integer(i64_v) => Value::Number(Number::from(i64_v)), // 整数
-            Text(str_v) => Value::String(String::from_utf8(str_v.to_vec()).unwrap()), // 文本
-            Blob(_v) => Value::Null,                              // 二进制数据(这里处理为 Null)
-            _ => Value::Null,                                     // 其他类型处理为 Null
-        };
-        row.insert(name.to_owned(), v); // 将列名和值添加到 HashMap 中
-    }
-    Ok(row) // 返回 HashMap
-}
-
-// 将 JSON 值转换为 rusqlite 的值
-pub fn value_to_rusqlite_value(json_value: &Value) -> Result<SqliteValue> {
-    return Ok(match json_value {
-        Value::Null => SqliteValue::Null, // 空值
-        Value::Number(v) => {
-            if v.is_f64() {
-                SqliteValue::Real(v.as_f64().unwrap() as f64) // 浮点数
-            } else if v.is_i64() {
-                SqliteValue::Integer(v.as_i64().unwrap()) // 有符号整数
-            } else if v.is_u64() {
-                SqliteValue::Integer(v.as_u64().unwrap().try_into().unwrap()) // 无符号整数
-            } else {
-                SqliteValue::Integer(0) // 其他情况默认整数0
-            }
-        }
-        Value::String(string_v) => SqliteValue::Text(string_v.clone()), // 字符串
-        _ => SqliteValue::Null,                                         // 其他类型处理为 Null
-    });
-}

+ 0 - 215
src-tauri/src/event_loop.rs

@@ -1,215 +0,0 @@
-// 这里先放基础类型数据,如果不够的话再按模块拆分
-#[tauri::command(name = "greet")]
-pub fn greet(name: &str) -> String {
-    format!("Hello, {}! You've been greeted from Rust!", name)
-}
-
-#[tauri::command(name = "file_path")]
-pub fn file_path(name: &str, parentid: &str) -> String {
-    println!("1111111");
-    // use std::fs;
-    use uuid::Uuid;
-    // #[macro_use]
-    // extern crate lazy_static;
-    extern crate regex;
-    // use crate::files::file_sqlite3::file_sqlite3::{inset, is_create};
-    // use crate::files::file_struct::File;
-    use std::path::Path;
-    use std::time::SystemTime;
-    // 生成 UUID
-    let _uuid = Uuid::new_v4();
-
-    // let err = is_create("files");
-    // println!("2424  {}", err);
-    // let parent = "".to_string();
-    // let mut parent_id: String = "".to_string();
-    // if parentid.len() > 0 {
-    //    parent_id = parentid.to_string();
-    // }
-
-    let system_time = SystemTime::now();
-    let _timestamp = system_time
-        .duration_since(SystemTime::UNIX_EPOCH)
-        .expect("Failed to get timestamp");
-
-    let filepath = Path::new(name);
-    // 获取路径的最后一个部分(即用户名)
-    let filename: String = filepath.file_name().unwrap().to_str().unwrap().to_string();
-    println!("38383838383 {}, {}", filename, parentid);
-    // let file = File {
-    //     name: filename.to_string(),
-    //     path: name.to_string(),
-    //     history_path: name.to_string(),
-    //     uuid: uuid.to_string(),
-    //     parent_id: parentid.to_string(),
-    //     create_time: timestamp,
-    //     update_time: timestamp,
-    //     file_type: name.to_string(),
-    //     user: name.to_string(),
-    //     rule: name.to_string(),
-    // };
-    // inset(file);
-
-    // 获取当前目录中的文件和目录
-    // let entries = fs::read_dir(name).unwrap();
-    // for entry in entries {
-    //     // 获取目录的详细信息
-    //     let dir = entry.unwrap();
-    //      // 判断是否为目录
-    //     if dir.file_type().unwrap().is_dir() {
-    //         // 输出目录的名称
-    //         // println!("{} is a directory", dir.file_name().to_string_lossy());
-    //         // 如果是目录的话
-    //         let path = format!("{}/{}", name, dir.file_name().to_string_lossy());
-    //         file_path(&path);
-    //     } else {
-    //         // 输出目录的名称
-    //         println!("{}", dir.file_name().to_string_lossy());
-    //     }
-
-    // }
-
-    let res = format!("{}", name);
-    // // println!("Message from Rust: {}", res);
-    res
-    // "files"
-}
-
-use sha2::{Digest, Sha256};
-use std::{fs, io};
-
-#[derive(Debug)]
-struct UseHashInfoStruct {
-    path: String,
-    processed: String,
-    hash: String,
-}
-
-fn get_file_hase(path: &str) -> UseHashInfoStruct {
-    let file_path = path;
-    let mut file = fs::File::open(&path).unwrap();
-    let mut hasher = Sha256::new();
-    let n = io::copy(&mut file, &mut hasher).unwrap();
-    let hash = hasher.finalize();
-    let hash_str = format!("{:x}", hash);
-    // println!("Path: {}", path);
-    // println!("Bytes processed: {}", n);
-    // println!("Hash value: {}", hash_str);
-    let info = UseHashInfoStruct {
-        path: file_path.to_string(),
-        processed: format!("{:x}", n),
-        hash: hash_str,
-    };
-    info
-}
-
-
-
-fn read_file(path: &str) -> io::Result<Vec<u8>> {
-    use std::fs::File;
-    use std::io::{Read};
-    let mut file = File::open(path)?;
-    let mut bytes = Vec::new();
-    file.read_to_end(&mut bytes)?;
-    Ok(bytes)
-}
-
-
-
-fn create_file(path: &str, buf: &str) -> io::Result<()> {
-    use std::fs::File;
-    use std::io::{Write};
-    let mut file = File::create(path)?;
-    // let file_byts = read_file("/Users/sysadmin/Downloads/文件相似度对比_new.pdf")?;
-    file.write_all(buf.as_bytes())?;
-    Ok(())
-}
-
-fn jaccard(str1: &str, str2: &str) -> f64 {
-    let set1: std::collections::HashSet<char> = str1.chars().collect();
-    let set2: std::collections::HashSet<char> = str2.chars().collect();
-    let intersection: std::collections::HashSet<char> = set1.intersection(&set2).map(|c| *c).collect();
-    let union: std::collections::HashSet<char> = set1.union(&set2).map(|c| *c).collect();
-    println!("134:   {}, {}", intersection.len() as f64 , union.len() as f64);
-    return intersection.len() as f64 / union.len() as f64;
-}
-
-#[tauri::command(name = "file_sort")]
-// pub fn file_sort(path: &str) -> String {
-pub fn file_sort(path: &str)  {
-    
-    
-    
-    
-    
-
-    // use strsim::{jaccard};
-    let _hash_info = get_file_hase(&path);
-    // let mut file1 = match fs::File::open("/Users/sysadmin/Downloads/文件相似度对比_old.pdf") {
-    //     Ok(f) => f,
-    //     Err(e) => panic!("{}", e),
-    // };
-    // let mut f1 = File::open("/Users/sysadmin/Downloads/文件相似度对比_old.pdf").unwrap();
-    // let mut f2 = File::open("/Users/sysadmin/Downloads/文件相似度对比_new.pdf").unwrap();
-    // let mut buffer: [u64; 410] = [400; 410];
-
-    // read up to 10 bytes
-    // let n1 = f1.read(&mut buffer[..]).unwrap();
-    // let n2 = f2.read(&mut buffer[..]).unwrap();
-    let bytes = read_file("/Users/sysadmin/Downloads/文件相似度对比_old.pdf").unwrap();
-    let bytes_str = format!("{:?}", bytes);
-    // create_file("/Users/sysadmin/Downloads/文件相似度对比_old.md", &bytes_str);
-    // let bytes2 = read_file("/Users/sysadmin/Downloads/文件相似度对比_new.pdf").unwrap();
-    let bytes2 = read_file("/Users/sysadmin/Downloads/截屏2022-11-30 上午10.00.17 2.png").unwrap();
-    let bytes2_str = format!("{:?}", bytes2);
-    // create_file("/Users/sysadmin/Downloads/文件相似度对比_new.md", &bytes2_str);
-
-
-    // File.
-    // let similarity = jaccard(bytes_str, bytes2_str);
-    // println!("Jaccard similarity: {}", damerau_levenshtein(&bytes_str, &bytes2_str));
-    println!("Jaccard damerau_levenshtein: {}", jaccard(&bytes_str, &bytes2_str));
-    // create_file("/Users/sysadmin/Downloads/文件相似度对比_old.md", &bytes_str);
-
-    // println!("The bytes_文件相似度对比_new: {:?}", bytes);
-    // println!("The bytes: {:?}", &buffer[..n2]);
-
-
-    // let mut buffer = [0; 10];
-    // // read up to 10 bytes
-    // let n = file1.read(&mut buffer[..]).unwrap();
-    // println!("The bytes: {:?}", &buffer[..n]);
-
-
-    // let mut file2 = match fs::File::open("/Users/sysadmin/Downloads/文件相似度对比_old.pdf") {
-    //     Ok(f) => f,
-    //     Err(e) => panic!("{}", e),
-    // };
-
-    // diff_files(&mut file1, &mut file2);
-    // println!("diff_files_     {:?}", diff_files(&mut file1, &mut file2));
-    // println!("diff_files_     {:?}", file1.as_inner());
-    // println!("{:?}", hash_info);
-    // format!("{{ 'path': {},'processed': {},'hash': {} }}`", hash_info.path, hash_info.processed, hash_info.hash)
-
-
-
-
-    /*
-
-    实现
-    function jaccard(str1, str2) {
-  let set1 = new Set(str1.split(''));
-  let set2 = new Set(str2.split(''));
-  let intersection = new Set([...set1].filter(x => set2.has(x)));
-  let union = new Set([...set1, ...set2]);
-  return intersection.size / union.size;
-}
-
-let str1 = "hello";
-let str2 = "world";
-let similarity = jaccard(str1, str2);
-console.log("Jaccard similarity: " + similarity);
-
-*/
-}

+ 12 - 26
src-tauri/src/main.rs

@@ -1,51 +1,37 @@
-#![cfg_attr(all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows")]
+#![cfg_attr(
+    all(not(debug_assertions), target_os = "windows"),
+    windows_subsystem = "windows"
+)]
 
 mod menus;
-mod event_loop;
 mod self_plugin;
-mod common;
-mod utils;
 mod servics;
+mod utils;
 
 use crate::menus::default::use_memu;
 use crate::menus::event::m_event;
-use crate::event_loop::{greet, file_path, file_sort};
 use self_plugin::tauri_plugin_file;
 use servics::files_servics;
-use tauri::api::path::app_data_dir;
 
 fn main() {
     tauri::Builder::default()
-        // .plugin(tauri_plugin_sqlite::init())
         .plugin(tauri_plugin_persisted_scope::init())
         .plugin(tauri_plugin_file::init())
         .plugin(files_servics::init())
         .plugin(
             tauri_plugin_sql::Builder::default()
-            .add_migrations("sqlite:files.db", files_servics::migrations::set_files_migrations())
-        .build()
-    )
-
+                .add_migrations(
+                    "sqlite:files.db",
+                    files_servics::migrations::set_files_migrations(),
+                )
+                .build(),
+        )
         .menu(use_memu())
         .on_menu_event(|event| {
             // 处理菜单事件
             m_event(event);
         })
-        .invoke_handler(tauri::generate_handler![greet, file_path, file_sort])
-        .setup(|app| {
-            let app_handle = app.handle();
-            let app_dir = app_data_dir(&app_handle.config());
-
-            // 打印应用程序目录路径
-            println!("打印应用程序目录路径App directory: {:?}", app_dir);
-
-
-            // // 设定数据库文件路径
-            // let db_path = app_dir.join("test.db");
-            // println!("Database file path: {:?}", db_path);
-
-            Ok(())
-        })
+        // .setup(|app| Ok(()))
         .run(tauri::generate_context!())
         .expect("error while running tauri application");
 }

+ 0 - 1
src-tauri/src/self_plugin/mod.rs

@@ -1,2 +1 @@
-// pub mod tauri_plugin_sqlite;
 pub mod tauri_plugin_file;

+ 70 - 14
src-tauri/src/self_plugin/tauri_plugin_file/files.rs

@@ -223,23 +223,79 @@ pub fn mv_file_to_trash(file_path: String) -> RequestMvFile {
     }
 }
 
-#[derive(Debug, Deserialize, Serialize)]
-enum AppError {
-    DataDirNotFound,
-    Other(String),
+#[command]
+pub fn get_app_data_dir() -> String {
+    std::env::var("MY_APP_DATA_DIR")
+    .unwrap_or_else(|_| "Environment variable for app data directory not set".to_string())
 }
 
-impl std::fmt::Display for AppError {
-    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
-        match *self {
-            AppError::DataDirNotFound => write!(f, "Application data directory not found"),
-            AppError::Other(ref err) => write!(f, "Error: {}", err),
-        }
+/* #[command]
+fn open_finder(path: String) -> RequestMvFile {
+    let open_result = std::process::Command::new("open")
+        .arg("-R")
+        // .arg("Finder")
+        .arg(path)
+        .spawn();
+
+    match open_result {
+        Ok(_) => RequestMvFile {
+            code: Some(200),
+            msg: Some("success".to_string()),
+            data: Some("success".to_string()),
+        },
+        Err(e) => RequestMvFile {
+            code: Some(500),
+            msg: Some("error".to_string()),
+            data: Some(e.to_string()),
+        },
     }
-}
+} */
 
 #[command]
-pub fn get_app_data_dir() -> String {
-    std::env::var("MY_APP_DATA_DIR")
-    .unwrap_or_else(|_| "Environment variable for app data directory not set".to_string())
+pub fn show_file_in_explorer(file_path: String) -> RequestMvFile {
+    println!("256 {}",file_path);
+    // 获取文件所在的目录
+    #[cfg(target_os = "linux")]
+    let path = std::path::Path::new(&file_path);
+    #[cfg(target_os = "linux")]
+    let parent_dir = match path.parent() {
+        Some(dir) => dir.to_str().unwrap_or(""),
+        None => return RequestMvFile {
+            code: Some(500),
+            msg: Some("No parent directory found.".to_string()),
+            data: Some("No parent directory found.".to_string()),
+        }
+    };
+
+    #[cfg(target_os = "windows")]
+    let command = std::process::Command::new("explorer")
+        .args(&["/select,", &file_path])
+        .spawn();
+
+    #[cfg(target_os = "macos")]
+    let command = std::process::Command::new("open")
+        .args(&["-R", &file_path])
+        .spawn();
+
+    #[cfg(target_os = "linux")]
+    let command = std::process::Command::new("nautilus")
+        .args(&["--browser", "--select", &file_path])
+        .or_else(|_| {
+            std::process::Command::new("xdg-open")
+                .arg(parent_dir)
+                .spawn()
+        });
+
+    match command {
+        Ok(_) => RequestMvFile {
+            code: Some(200),
+            msg: Some("success".to_string()),
+            data: Some("success".to_string()),
+        },
+        Err(e) => RequestMvFile {
+            code: Some(500),
+            msg: Some("error".to_string()),
+            data: Some(e.to_string()),
+        },
+    }
 }

+ 3 - 1
src-tauri/src/self_plugin/tauri_plugin_file/mod.rs

@@ -16,7 +16,9 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
             calculate_file_hash,
             get_file_info,
             mv_file_to_trash,
-            get_app_data_dir
+            get_app_data_dir,
+            // open_finder
+            show_file_in_explorer
             // get_file_info_by_path,
         ])
         .setup(|_app| {

+ 0 - 27
src-tauri/src/self_plugin/tauri_plugin_sqlite/mod.rs

@@ -1,27 +0,0 @@
-pub(crate) mod sqlite;
-//  as tauri_plugin_sqlite;
-
-use tauri::{
-    plugin::{Builder, TauriPlugin}, Runtime,
-};
-
-use self::sqlite::*;
-
-/// Initializes the plugin.
-pub fn init<R: Runtime>() -> TauriPlugin<R> {
-    Builder::new("st-sqlite")
-        .invoke_handler(tauri::generate_handler![
-            open,
-            open_with_flags,
-            query_with_args,
-            close,
-            execute_sql,
-            execute_batch,
-            execute
-        ])
-        .setup(|_app| {
-            // app.manage(SqliteMap::default());
-            Ok(())
-        })
-        .build()
-}

+ 0 - 82
src-tauri/src/self_plugin/tauri_plugin_sqlite/sqlite.rs

@@ -1,82 +0,0 @@
-use rusqlite::OpenFlags;
-use std::collections::HashMap;
-use tauri::command;
-
-use serde::{Serialize, Serializer};
-use serde_json::Value as JsonValue;
-
-use crate::common as st_common;
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
-    #[error(transparent)]
-    Anyhow(#[from] anyhow::Error),
-    #[error(transparent)]
-    Sqlite(#[from] rusqlite::Error),
-    #[error("database {0} not opened")]
-    DatabaseNotOpened(String),
-}
-
-impl Serialize for Error {
-    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
-    where
-        S: Serializer,
-    {
-        serializer.serialize_str(self.to_string().as_ref())
-    }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-// #[derive(Default)]
-// pub struct SqliteMap(Mutex<HashMap<String, Connection>>);
-// #[command]
-// pub async fn open(state: State<'_, SqliteMap>, path: String) -> Result<bool> {
-// }
-
-#[command]
-pub async fn open(path: String) -> Result<bool> {
-    st_common::sqlite::open(&path).await?;
-    Ok(true)
-}
-
-#[command]
-pub async fn open_with_flags(path: String, iflags: i32) -> Result<bool> {
-    let flags = OpenFlags::default();
-
-    st_common::sqlite::open_with_flags(&path, flags).await?;
-    Ok(true)
-}
-
-#[command]
-pub async fn close(path: String) -> Result<bool> {
-    st_common::sqlite::close(&path).await?;
-    Ok(true)
-}
-
-#[command]
-pub async fn execute_sql(path: String, sql: String) -> Result<usize> {
-    let res = st_common::sqlite::execute_sql(&path, &sql).await?;
-    Ok(res)
-}
-
-#[command]
-pub async fn execute_batch(path: String, sql: String) -> Result<bool> {
-    let res = st_common::sqlite::execute_batch(&path, &sql).await?;
-    Ok(res)
-}
-
-#[command]
-pub async fn execute(path: String, sql: String, args: JsonValue) -> Result<usize> {
-    let res = st_common::sqlite::execute(&path, &sql, &args).await?;
-    Ok(res)
-}
-
-#[command]
-pub async fn query_with_args(
-    path: String,
-    sql: String,
-    args: JsonValue,
-) -> Result<Vec<HashMap<String, JsonValue>>> {
-    let res = st_common::sqlite::query_with_args(&path, &sql, &args).await?;
-    Ok(res)
-}

+ 0 - 71
src-tauri/src/servics/files_servics/files_servics.rs

@@ -1,71 +0,0 @@
-// use std::fs::File;
-// use crate::files::file_struct::File;
-use tauri::command;
-// use crate::{common::sqlite};
-// use tauri::api::file::IntoInvokeHandler;
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
-    #[error(transparent)]
-    Io(#[from] std::io::Error),
-}
-
-// 判断是否新建表
-// #[command]
-// pub async fn is_create(table_name: &str) -> bool {
-//     if table_name.len() < 1 {
-//         return false;
-//     }
-//     let connection = sqlite::open("tauri.db").await.unwrap();
-//     // let connection = load("sqlite::files.db").unwrap();
-//     let query: String = format!(
-//         "SELECT tbl_name FROM sqlite_master WHERE tbl_name = '{}'",
-//         table_name
-//     );
-//     let mut is_table: bool = false;
-//     connection
-//         .iterate(query, |pairs| {
-//             for &(_tpl_name, value) in pairs.iter() {
-//                 if value.unwrap() == table_name {
-//                     is_table = true
-//                 }
-//             }
-//             true
-//         })
-//         .unwrap();
-//     // is_table
-//     if !is_table {
-//         return create(table_name);
-//     }
-//     is_table
-// }
-
-// #[command]
-// pub async fn create(table_name: &str) -> bool {
-//     println!("28");
-//     if table_name.len() < 1 {
-//         return false;
-//     }
-//     let connection = sqlite::open("tauri.db").await.unwrap();
-//     // CREATE TABLE users (name TEXT, age INTEGER)
-//     let query: String = format!("CREATE TABLE '{}' ( name TEXT, path TEXT, history_path TEXT, uuid TEXT, parent_id TEXT, create_time INTEGER, update_time INTEGER, file_type TEXT, user TEXT, rule TEXT );", table_name);
-//     // let mut isTable: bool = false;
-//     println!("36");
-//     connection.execute(query).unwrap();
-//     true
-// }
-
-// #[command]
-// pub async fn inset(file: File) -> bool {
-//     // INSERT INTO files (name, path, history_path, uuid, parent_id, create_time, update_time, file_type, user, rule) VALUES ('1', '1', '2', '3', '4', 5, null, null, null, null)
-//     let query: String = format!("INSERT INTO files (name, path, history_path, uuid, parent_id, create_time, update_time, file_type, user, rule) VALUES ('{}', '{}', '{}', '{}', '{}', '{:?}', '{:?}', '{}', '{}', '{}')", file.name, file.path, file.history_path, file.uuid, file.parent_id, file.create_time, file.update_time, file.file_type, file.user, file.rule);
-//     let connection = sqlite::open("tauri.db").await.unwrap();
-//     connection.execute(query).await.unwrap();
-//     true
-// }
-
-#[command]
-pub fn test2(name: &str) -> Result<String, String> {
-    println!("36");
-    Ok(name.to_string())
-}

+ 6 - 3
src-tauri/src/servics/files_servics/migrations.rs

@@ -1,9 +1,12 @@
-use tauri_plugin_sql::{Migration, MigrationKind};
+use tauri_plugin_sql::{
+    Migration, 
+    // MigrationKind
+};
 
 // 这里维护可配置的
 pub fn set_files_migrations() -> Vec<Migration> {
     vec![
-        // Define your migrations here
+       /*  // Define your migrations here
         Migration {
             version: 1,
             description: "create_initial_tables",
@@ -69,7 +72,7 @@ pub fn set_files_migrations() -> Vec<Migration> {
             description: "恢复sourceId的数据",
             sql: "ALTER TABLE search_files ADD sourceId INTEGER;UPDATE search_files SET sourceId = source2Id;ALTER TABLE search_files DROP COLUMN source2Id;",
             kind: MigrationKind::Up,
-        }
+        } */
     ]
 }
 // migrations 增加字段, 删除字段、修改字段、无法修改字段类型

+ 3 - 3
src-tauri/src/servics/files_servics/mod.rs

@@ -1,4 +1,4 @@
-pub(crate) mod files_servics;
+// pub(crate) mod files_servics;
 
 pub mod migrations; // 定义数据库迁移模块
 use tauri::{
@@ -6,7 +6,7 @@ use tauri::{
 };
 
 
-use self::files_servics::*;
+// use self::files_servics::*;
 
 /// Initializes the plugin.
 pub fn init<R: Runtime>() -> TauriPlugin<R> {
@@ -15,7 +15,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
             // is_create,
             // create,
             // inset,
-            test2
+            // test2
         ])
         .setup(|_app| {
             Ok(())

+ 4 - 1
src-tauri/tauri.conf.json

@@ -13,7 +13,10 @@
 
   "tauri": {
     "allowlist": {
-      "all": true
+      "all": true,
+      "shell": {
+        "all": true
+      }
     },
     "bundle": {
       "active": true,

+ 31 - 13
src/pages/DuplicateFile/CalculateListPage.tsx

@@ -16,14 +16,18 @@ import {
   get_fileInfo_by_id,
   searchDuplicateFile,
 } from "@/services";
-import { message as tauriMessage, save as dialogSave } from "@tauri-apps/api/dialog";
-import { appDataDir, join } from '@tauri-apps/api/path';
+import {
+  message as tauriMessage,
+  save as dialogSave,
+} from "@tauri-apps/api/dialog";
+import { appDataDir, join } from "@tauri-apps/api/path";
 import styles from "./CalculateListPage.module.less";
 import { useParams } from "react-router";
 import { insertSearchFilesPasamsType } from "@/types/files";
 import type { GetProp } from "antd";
 import File from "@/plugins/tauri-plugin-file/file";
 import { CopyText } from "@/components/Table/CopyText";
+import { FolderOpenOutlined } from "@ant-design/icons";
 
 export default function CalculateListPage() {
   let { fileId } = useParams();
@@ -99,38 +103,48 @@ export default function CalculateListPage() {
       setRemoveList(checkedValues);
     }
   };
+  const openFileShowInExplorer = async (path: string) => {
+    const res = await File.showFileInExplorer(path);
+  };
 
   const CheckboxContent = (item: insertSearchFilesPasamsType) => (
     <div className={styles.CheckboxContent}>
+      <div>
+        <FolderOpenOutlined onClick={() => openFileShowInExplorer(item.path)} />
+      </div>
       <div className={styles.path}>
-        <CopyText
+        {item.path}
+        {/* <CopyText
           width="300px"
           color="#333"
           ellipsisLine={1}
           name={item.path || ""}
-        ></CopyText>
+        ></CopyText> */}
       </div>
       <div className={styles.modified_time}>
-        <CopyText
+        {/* <CopyText
           width="100px"
           color="#333"
           name={item.modified_time || ""}
-        ></CopyText>
+        ></CopyText> */}
+        {item.modified_time}
       </div>
       <div className={styles.modified_time}>
-        <CopyText
+        {/* <CopyText
           width="100px"
           color="#333"
           name={item.file_size || ""}
-        ></CopyText>
+        ></CopyText> */}
+        {item.file_size}
       </div>
       <div className={styles.modified_time}>
-        <CopyText
+        {/* <CopyText
           width="100px"
           color="#333"
           ellipsisLine={1}
-          name={item.name || ""}
-        ></CopyText>
+          name={ || ""}
+        ></CopyText> */}
+        {item.name}
       </div>
     </div>
   );
@@ -187,8 +201,12 @@ export default function CalculateListPage() {
   }
   async function openDialogSave() {
     // const appDataDir = await File.getAppDataDir();
-    const appDataDirPath = await appDataDir();
-    console.log(190, appDataDirPath);
+    // const appDataDirPath = await appDataDir();
+    // console.log(190, appDataDirPath);
+    const res = await File.showFileInExplorer(
+      "/Users/sysadmin/Downloads/hhyy/src/pages/activity/static/noData.png"
+    );
+    console.log(193, res);
 
     return;
     // dialogSave

+ 5 - 0
src/plugins/tauri-plugin-file/file.ts

@@ -42,6 +42,11 @@ export class File {
   static async getAppDataDir(): Promise<string> {
     return await invoke<string>("plugin:st-files|get_app_data_dir");
   }
+  static async showFileInExplorer(filePath: string): Promise<string> {
+    return await invoke<string>("plugin:st-files|show_file_in_explorer", {
+      filePath
+    });
+  }
 
   // async close(): Promise<boolean> {
   //     return await invoke('plugin:st-sqlite|close', { path: this.path })

+ 0 - 1
src/plugins/tauri-plugin-sqlite/index.ts

@@ -1 +0,0 @@
-export * from './sqlite';

+ 0 - 28
src/plugins/tauri-plugin-sqlite/sqlite.ts

@@ -1,28 +0,0 @@
-import { invoke } from '@tauri-apps/api/tauri'
-
-export class SQLite {
-    path: string
-
-    constructor(path: string) {
-        this.path = path
-    }
-
-    static async open(path: string): Promise<SQLite> {
-        let res = await invoke<string>('plugin:st-sqlite|open', { path });
-        return new SQLite(path);
-    }
-
-    async close(): Promise<boolean> {
-        return await invoke('plugin:st-sqlite|close', { path: this.path })
-    }
-
-    async execute(sql: string, values?: Record<string, any>): Promise<boolean> {
-        return values ? await invoke('plugin:st-sqlite|execute', { path: this.path, sql, args: values }) : await invoke('plugin:st-sqlite|execute_sql', { path: this.path, sql })
-    }
-
-    async queryWithArgs<T>(sql: string, values?: Record<string, any>): Promise<T> {
-        return await invoke('plugin:st-sqlite|query_with_args', { path: this.path, sql, args: values ?? {} })
-    }
-}
-
-export default SQLite;

+ 2 - 2
yarn.lock

@@ -1606,9 +1606,9 @@ supports-color@^5.3.0:
   dependencies:
     has-flag "^3.0.0"
 
-"tauri-plugin-sql-api@https://github.com/Johnhong9527/tauri-plugin-sql.git#v1":
+"tauri-plugin-sql-api@https://gitee.com/seamong/tauri-plugin-sql.git#v1":
   version "0.0.0"
-  resolved "https://github.com/Johnhong9527/tauri-plugin-sql.git#6a4a14c36b1ad49c9f468351706d104a54e0540c"
+  resolved "https://gitee.com/seamong/tauri-plugin-sql.git#6a4a14c36b1ad49c9f468351706d104a54e0540c"
   dependencies:
     "@tauri-apps/api" "1.5.6"