Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
// WARNING: These APIs will be deprecated soon due to removing FS API access from frontend.
// It's added to ensure the legacy implementation from frontend still functions before removal.
use super::asset_scope::allow_picked_file;
use super::grants::{record_picks, DENIED_PREFIX};
use super::helpers::{
resolve_app_path_within_jan_data_folder, resolve_app_read_path, resolve_path,
};
use super::models::{DialogOpenOptions, FileStat};
use rfd::AsyncFileDialog;
use std::fs;
use std::path::PathBuf;
use tauri::Runtime;
#[tauri::command]
pub fn rm<R: Runtime>(app_handle: tauri::AppHandle<R>, args: Vec<String>) -> Result<(), String> {
if args.is_empty() || args[0].is_empty() {
return Err("rm error: Invalid argument".to_string());
}
let (canonical_data, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])
.map_err(|_| format!("rm error: path {} is not under jan data folder", args[0]))?;
if !path.starts_with(&canonical_data) {
return Err(format!(
"rm error: path {} is not under jan data folder {}",
path.display(),
canonical_data.display()
));
}
if path.is_file() {
fs::remove_file(&path).map_err(|e| e.to_string())?;
} else if path.is_dir() {
fs::remove_dir_all(&path).map_err(|e| e.to_string())?;
} else {
return Err("rm error: Path does not exist".to_string());
}
Ok(())
}
#[tauri::command]
pub fn mkdir<R: Runtime>(app_handle: tauri::AppHandle<R>, args: Vec<String>) -> Result<(), String> {
if args.is_empty() || args[0].is_empty() {
return Err("mkdir error: Invalid argument".to_string());
}
let (_, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])?;
fs::create_dir_all(&path).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn mv<R: Runtime>(app_handle: tauri::AppHandle<R>, args: Vec<String>) -> Result<(), String> {
if args.len() < 2 || args[0].is_empty() || args[1].is_empty() {
return Err("mv error: Invalid argument - source and destination required".to_string());
}
let (_, source) = resolve_app_path_within_jan_data_folder(app_handle.clone(), &args[0])?;
let (_, destination) = resolve_app_path_within_jan_data_folder(app_handle, &args[1])?;
if !source.exists() {
return Err("mv error: Source path does not exist".to_string());
}
fs::rename(&source, &destination).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn join_path<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: Vec<String>,
) -> Result<String, String> {
if args.is_empty() {
return Err("join_path error: Invalid argument".to_string());
}
let path = resolve_path(app_handle, &args[0]);
let joined_path = args[1..].iter().fold(path, |acc, part| acc.join(part));
Ok(joined_path.to_string_lossy().to_string())
}
#[tauri::command]
pub fn exists_sync<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: Vec<String>,
) -> Result<bool, String> {
if args.is_empty() || args[0].is_empty() {
return Err("exist_sync error: Invalid argument".to_string());
}
match resolve_app_read_path(app_handle, &args[0]) {
Ok(path) => Ok(path.exists()),
// A path the app may not read looks the same as a missing one, so this
// command cannot be used to probe the disk.
Err(e) if e.starts_with(DENIED_PREFIX) => Ok(false),
Err(e) => Err(e),
}
}
#[tauri::command]
pub fn file_stat<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: String,
) -> Result<FileStat, String> {
if args.is_empty() {
return Err("file_stat error: Invalid argument".to_string());
}
let path = resolve_app_read_path(app_handle, &args)?;
let metadata = fs::metadata(&path).map_err(|e| e.to_string())?;
let is_directory = metadata.is_dir();
let size = if is_directory { 0 } else { metadata.len() };
let file_stat = FileStat { is_directory, size };
Ok(file_stat)
}
#[tauri::command]
pub fn read_file_sync<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: Vec<String>,
) -> Result<String, String> {
if args.is_empty() || args[0].is_empty() {
return Err("read_file_sync error: Invalid argument".to_string());
}
let path = resolve_app_read_path(app_handle, &args[0])?;
fs::read_to_string(&path).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn write_file_sync<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: Vec<String>,
) -> Result<(), String> {
if args.len() < 2 || args[0].is_empty() || args[1].is_empty() {
return Err("write_file_sync error: Invalid argument".to_string());
}
let (_, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])?;
let content = &args[1];
fs::write(&path, content).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn readdir_sync<R: Runtime>(
app_handle: tauri::AppHandle<R>,
args: Vec<String>,
) -> Result<Vec<String>, String> {
if args.is_empty() || args[0].is_empty() {
return Err("read_dir_sync error: Invalid argument".to_string());
}
let path = resolve_app_read_path(app_handle, &args[0])?;
let entries = fs::read_dir(&path).map_err(|e| e.to_string())?;
let paths: Vec<String> = entries
.filter_map(|entry| entry.ok())
.map(|entry| entry.path().to_string_lossy().to_string())
.collect();
Ok(paths)
}
#[tauri::command]
pub fn write_yaml(
app: tauri::AppHandle<impl Runtime>,
data: serde_json::Value,
save_path: &str,
) -> Result<(), String> {
// TODO: have an internal function to check scope
let (_jan_data_folder, save_path) = resolve_app_path_within_jan_data_folder(app, save_path)?;
let file = fs::File::create(&save_path).map_err(|e| e.to_string())?;
let mut writer = std::io::BufWriter::new(file);
serde_yaml::to_writer(&mut writer, &data).map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub fn read_yaml<R: Runtime>(
app: tauri::AppHandle<R>,
path: &str,
) -> Result<serde_json::Value, String> {
let (_jan_data_folder, path) = resolve_app_path_within_jan_data_folder(app, path)?;
let file = fs::File::open(&path).map_err(|e| e.to_string())?;
let reader = std::io::BufReader::new(file);
let data: serde_json::Value = serde_yaml::from_reader(reader).map_err(|e| e.to_string())?;
Ok(data)
}
/// Unpacking a backend archive is hundreds of megabytes of gzip and file IO. A
/// synchronous command would run it on the main thread and freeze the window
/// (and, on WebKitGTK, all rendering) for its whole duration, so the work is
/// handed to the blocking pool instead.
#[tauri::command]
pub async fn decompress<R: Runtime>(
app: tauri::AppHandle<R>,
path: String,
output_dir: String,
) -> Result<(), String> {
let path_buf = std::path::PathBuf::from(&path);
let (_jan_data_folder, output_dir_buf) =
resolve_app_path_within_jan_data_folder(app, &output_dir)?;
tauri::async_runtime::spawn_blocking(move || unpack_archive(&path_buf, &output_dir_buf))
.await
.map_err(|e| format!("Decompression task failed: {}", e))?
}
pub(crate) fn unpack_archive(
path_buf: &std::path::Path,
output_dir_buf: &std::path::Path,
) -> Result<(), String> {
// Ensure output directory exists
fs::create_dir_all(output_dir_buf).map_err(|e| {
format!(
"Failed to create output directory {}: {}",
output_dir_buf.to_string_lossy(),
e
)
})?;
// Use short path on Windows to handle paths with spaces
#[cfg(windows)]
let file = {
if let Some(short_path) = jan_utils::path::get_short_path(path_buf) {
fs::File::open(&short_path).map_err(|e| e.to_string())?
} else {
fs::File::open(path_buf).map_err(|e| e.to_string())?
}
};
#[cfg(not(windows))]
let file = fs::File::open(path_buf).map_err(|e| e.to_string())?;
let name = path_buf.to_string_lossy();
if name.ends_with(".tar.gz") {
let tar = flate2::read::GzDecoder::new(file);
let mut archive = tar::Archive::new(tar);
archive.unpack(output_dir_buf).map_err(|e| e.to_string())?;
} else if name.ends_with(".zip") {
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
for i in 0..zip.len() {
let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
let outpath = output_dir_buf.join(
entry
.enclosed_name()
.ok_or_else(|| "Invalid zip entry path".to_string())?,
);
if entry.is_dir() {
std::fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
} else {
if let Some(parent) = outpath.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let mut outfile = std::fs::File::create(&outpath).map_err(|e| e.to_string())?;
std::io::copy(&mut entry, &mut outfile).map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Some(mode) = entry.unix_mode() {
let _ = std::fs::set_permissions(
&outpath,
std::fs::Permissions::from_mode(mode),
);
}
}
}
}
} else {
return Err("Unsupported file format. Only .tar.gz and .zip are supported.".to_string());
}
Ok(())
}
// rfd native file dialog. Picked files (not folders) are granted to the asset
// protocol, whose static scope is empty: the chat pickers read them back
// through `convertFileSrc`.
#[tauri::command]
pub async fn open_dialog<R: Runtime>(
app_handle: tauri::AppHandle<R>,
options: Option<DialogOpenOptions>,
) -> Result<Option<serde_json::Value>, String> {
let mut dialog = AsyncFileDialog::new();
if let Some(opts) = options {
// Set default path
if let Some(path) = opts.default_path {
dialog = dialog.set_directory(&path);
}
// Set filters
if let Some(filters) = opts.filters {
for filter in filters {
let extensions: Vec<&str> = filter.extensions.iter().map(|s| s.as_str()).collect();
dialog = dialog.add_filter(&filter.name, &extensions);
}
}
// Handle directory vs file selection
if opts.directory == Some(true) {
let result = dialog.pick_folder().await;
return Ok(result.map(|folder| {
record_picks(&app_handle, &[folder.path().to_path_buf()]);
serde_json::Value::String(folder.path().to_string_lossy().to_string())
}));
}
// Handle multiple file selection
if opts.multiple == Some(true) {
let result = dialog.pick_files().await;
return Ok(result.map(|files| {
let picked: Vec<PathBuf> = files.iter().map(|f| f.path().to_path_buf()).collect();
record_picks(&app_handle, &picked);
let paths: Vec<String> = picked
.iter()
.map(|p| {
allow_picked_file(&app_handle, p);
p.to_string_lossy().to_string()
})
.collect();
serde_json::to_value(paths).unwrap()
}));
}
}
// Default: single file selection
let result = dialog.pick_file().await;
Ok(result.map(|file| {
record_picks(&app_handle, &[file.path().to_path_buf()]);
allow_picked_file(&app_handle, file.path());
serde_json::Value::String(file.path().to_string_lossy().to_string())
}))
}
#[tauri::command]
pub async fn save_dialog(options: Option<DialogOpenOptions>) -> Result<Option<String>, String> {
let mut dialog = AsyncFileDialog::new();
if let Some(opts) = options {
// Set default path
if let Some(path) = opts.default_path {
dialog = dialog.set_directory(&path);
}
// Set filters
if let Some(filters) = opts.filters {
for filter in filters {
let extensions: Vec<&str> = filter.extensions.iter().map(|s| s.as_str()).collect();
dialog = dialog.add_filter(&filter.name, &extensions);
}
}
}
let result = dialog.save_file().await;
Ok(result.map(|file| file.path().to_string_lossy().to_string()))
}