Skip to content

Commit

Permalink
home dir cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
mariotaku committed Nov 22, 2023
1 parent 2ca4d25 commit e0304a8
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 38 deletions.
18 changes: 18 additions & 0 deletions src-tauri/src/ssh_dir/mod.rs → src-tauri/src/app_dirs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,21 @@ pub trait GetSshDir {
pub trait SetSshDir {
fn set_ssh_dir(&self, dir: PathBuf);
}

pub trait GetConfDir {
fn get_conf_dir(&self) -> Option<PathBuf>;
fn ensure_conf_dir(&self) -> Result<PathBuf, Error> {
let Some(dir) = self.get_conf_dir() else {
return Err(Error::bad_config());
};
if !dir.exists() {
create_dir_all(&dir)?;
}
return Ok(dir);
}
}

pub trait SetConfDir {
fn set_conf_dir(&self, dir: PathBuf);

}
2 changes: 1 addition & 1 deletion src-tauri/src/conn_pool/connection.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::{Debug, Formatter};
use std::io::Read;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::path::Path;
use std::sync::Mutex;
use std::time::Duration;

Expand Down
33 changes: 12 additions & 21 deletions src-tauri/src/device_manager/io.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
use std::{env, fs};
use std::fs;
use std::fs::{create_dir_all, File};
use std::io::{BufReader, BufWriter, ErrorKind};
use std::path::PathBuf;
use std::path::{Path, PathBuf};

use serde_json::Value;

use crate::device_manager::Device;
use crate::error::Error;

pub(crate) async fn read() -> Result<Vec<Device>, Error> {
pub(crate) async fn read(conf_dir: Option<&Path>) -> Result<Vec<Device>, Error> {
let conf_dir = conf_dir.map(|conf_dir| conf_dir.to_path_buf());
return tokio::task::spawn_blocking(move || -> Result<Vec<Device>, Error> {
let path = devices_file_path()?;
let path = devices_file_path(conf_dir.as_deref())?;
let file = match File::open(path.as_path()) {
Ok(file) => file,
Err(e) => {
Expand All @@ -32,9 +33,10 @@ pub(crate) async fn read() -> Result<Vec<Device>, Error> {
.expect("critical failure in app::io::read task");
}

pub(crate) async fn write(devices: Vec<Device>) -> Result<(), Error> {
pub(crate) async fn write(devices: Vec<Device>, conf_dir: Option<&Path>) -> Result<(), Error> {
let conf_dir = conf_dir.map(|conf_dir| conf_dir.to_path_buf());
return tokio::task::spawn_blocking(move || -> Result<(), Error> {
let path = devices_file_path()?;
let path = devices_file_path(conf_dir.as_deref())?;
let file = match File::create(path.as_path()) {
Ok(file) => file,
Err(e) => {
Expand All @@ -61,15 +63,10 @@ pub(crate) async fn write(devices: Vec<Device>) -> Result<(), Error> {
.expect("critical failure in app::io::write task");
}

#[cfg(target_family = "windows")]
fn devices_file_path() -> Result<PathBuf, Error> {
let home = env::var("APPDATA")
.or_else(|_| env::var("USERPROFILE"))
.map_err(|_| Error::bad_config())?;
return Ok(PathBuf::from(home)
.join(".webos")
.join("ose")
.join("novacom-devices.json"));
fn devices_file_path(conf_dir: Option<&Path>) -> Result<PathBuf, Error> {
return conf_dir
.map(|conf_dir| conf_dir.join("novacom-devices.json"))
.ok_or_else(|| Error::bad_config());
}

#[cfg(not(unix))]
Expand All @@ -80,12 +77,6 @@ fn fix_devices_json_perm(path: PathBuf) -> Result<(), Error> {
return Ok(());
}

#[cfg(not(target_family = "windows"))]
fn devices_file_path() -> Result<PathBuf, Error> {
let home = home_dir().ok_or_else(|| Error::bad_config())?;
return Ok(home.join(".webos").join("ose").join("novacom-devices.json"));
}

#[cfg(unix)]
fn fix_devices_json_perm(path: PathBuf) -> Result<(), Error> {
use std::os::unix::fs::PermissionsExt;
Expand Down
32 changes: 23 additions & 9 deletions src-tauri/src/device_manager/manager.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
use std::fs;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};

use libssh_rs::SshKey;
use tokio::fs::{remove_file, File};
use tokio::io::AsyncWriteExt;

use crate::app_dirs::{GetConfDir, GetSshDir, SetConfDir, SetSshDir};
use crate::device_manager::io::{read, write};
use crate::device_manager::{Device, DeviceManager, PrivateKey};
use crate::error::Error;
use crate::ssh_dir::{GetSshDir, SetSshDir};

impl DeviceManager {
pub async fn list(&self) -> Result<Vec<Device>, Error> {
let devices = read().await?;
let devices = read(self.get_conf_dir().as_deref()).await?;
*self.devices.lock().unwrap() = devices.clone();
return Ok(devices);
}

pub async fn set_default(&self, name: &str) -> Result<Option<Device>, Error> {
let mut devices = read().await?;
let conf_dir = self.get_conf_dir();
let mut devices = read(conf_dir.as_deref()).await?;
let mut result: Option<Device> = None;
for device in &mut devices {
if device.name == name {
Expand All @@ -30,11 +30,12 @@ impl DeviceManager {
}
}
log::trace!("{:?}", devices);
write(devices).await?;
write(devices, conf_dir.as_deref()).await?;
return Ok(result);
}

pub async fn add(&self, device: &Device) -> Result<Device, Error> {
let conf_dir = self.get_conf_dir();
let mut device = device.clone();
if let Some(key) = &device.private_key {
match key {
Expand All @@ -59,14 +60,15 @@ impl DeviceManager {
}
}
log::info!("Save device {}", device.name);
let mut devices = read().await?;
let mut devices = read(conf_dir.as_deref()).await?;
devices.push(device.clone());
write(devices.clone()).await?;
write(devices.clone(), conf_dir.as_deref()).await?;
return Ok(device);
}

pub async fn remove(&self, name: &str, remove_key: bool) -> Result<(), Error> {
let devices = read().await?;
let conf_dir = self.get_conf_dir();
let devices = read(conf_dir.as_deref()).await?;
let (will_delete, mut will_keep): (Vec<Device>, Vec<Device>) =
devices.into_iter().partition(|d| d.name == name);
let mut need_new_default = false;
Expand All @@ -90,7 +92,7 @@ impl DeviceManager {
if need_new_default && !will_keep.is_empty() {
will_keep.first_mut().unwrap().default = Some(true);
}
write(will_keep).await?;
write(will_keep, conf_dir.as_deref()).await?;
return Ok(());
}

Expand Down Expand Up @@ -139,3 +141,15 @@ impl SetSshDir for DeviceManager {
*self.ssh_dir.lock().unwrap() = Some(dir);
}
}

impl GetConfDir for DeviceManager {
fn get_conf_dir(&self) -> Option<PathBuf> {
return self.conf_dir.lock().unwrap().clone();
}
}

impl SetConfDir for DeviceManager {
fn set_conf_dir(&self, dir: PathBuf) {
*self.conf_dir.lock().unwrap() = Some(dir);
}
}
1 change: 1 addition & 0 deletions src-tauri/src/device_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub struct DeviceSessionToken {
#[derive(Default)]
pub struct DeviceManager {
ssh_dir: Mutex<Option<PathBuf>>,
conf_dir: Mutex<Option<PathBuf>>,
devices: Mutex<Vec<Device>>,
}

Expand Down
26 changes: 24 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
extern crate core;

use std::env;
use std::path::PathBuf;

use log::LevelFilter;
use native_dialog::{MessageDialog, MessageType};
use tauri::api::path::home_dir;
use tauri::{AppHandle, Manager, RunEvent, Runtime};

use crate::app_dirs::{GetConfDir, GetSshDir, SetConfDir, SetSshDir};
use crate::device_manager::DeviceManager;
use crate::session_manager::SessionManager;
use crate::shell_manager::ShellManager;
use crate::spawn_manager::SpawnManager;
use crate::ssh_dir::{GetSshDir, SetSshDir};

mod app_dirs;
mod conn_pool;
mod device_manager;
mod error;
Expand All @@ -22,7 +24,6 @@ mod remote_files;
mod session_manager;
mod shell_manager;
mod spawn_manager;
mod ssh_dir;

//#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
Expand Down Expand Up @@ -63,6 +64,9 @@ pub fn run() {
app.state::<SessionManager>().set_ssh_dir(ssh_dir.clone());
app.state::<ShellManager>().set_ssh_dir(ssh_dir.clone());
}
if let Some(conf_dir) = app.get_conf_dir() {
app.state::<DeviceManager>().set_conf_dir(conf_dir.clone());
}
}
_ => {}
});
Expand Down Expand Up @@ -97,3 +101,21 @@ impl<R: Runtime> GetSshDir for AppHandle<R> {
.map(|d| d.join(".ssh"));
}
}

impl<R: Runtime> GetConfDir for AppHandle<R> {
fn get_conf_dir(&self) -> Option<PathBuf> {
let home: Option<PathBuf>;
#[cfg(target_family = "windows")]
{
home = env::var("APPDATA")
.or_else(|_| env::var("USERPROFILE"))
.map(|d| PathBuf::from(d))
.ok();
}
#[cfg(not(target_family = "windows"))]
{
home = home_dir();
}
return home.map(|d| d.join(".webos").join("ose"));
}
}
2 changes: 1 addition & 1 deletion src-tauri/src/plugins/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tauri::{AppHandle, State};

use crate::device_manager::{Device, DeviceManager};
use crate::error::Error;
use crate::ssh_dir::GetSshDir;
use crate::app_dirs::GetSshDir;

#[tauri::command]
async fn list(manager: State<'_, DeviceManager>) -> Result<Vec<Device>, Error> {
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/session_manager/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::conn_pool::{DeviceConnectionPool, ManagedDeviceConnection};
use crate::device_manager::Device;
use crate::error::Error;
use crate::session_manager::{Proc, SessionManager};
use crate::ssh_dir::{GetSshDir, SetSshDir};
use crate::app_dirs::{GetSshDir, SetSshDir};

impl SessionManager {
pub fn session(&self, device: Device) -> Result<ManagedDeviceConnection, Error> {
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/shell_manager/manager.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::path::PathBuf;
use std::sync::Arc;

use crate::app_dirs::{GetSshDir, SetSshDir};
use crate::device_manager::Device;
use crate::error::Error;
use crate::shell_manager::{Shell, ShellInfo, ShellManager, ShellToken};
use crate::ssh_dir::{GetSshDir, SetSshDir};

impl ShellManager {
pub fn open(&self, device: Device, rows: u16, cols: u16, dumb: bool) -> Arc<Shell> {
Expand Down
3 changes: 1 addition & 2 deletions src-tauri/src/shell_manager/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender;
use std::time::Instant;

use serde::Serialize;
Expand All @@ -10,7 +10,6 @@ use vt100::Parser;
use crate::device_manager::Device;
use crate::error::Error;
use crate::shell_manager::shell::ShellsMap;
use crate::ssh_dir::GetSshDir;

pub(crate) mod manager;
pub(crate) mod shell;
Expand Down

0 comments on commit e0304a8

Please sign in to comment.