Skip to content

Commit

Permalink
Add event based refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
newtoallofthis123 committed Aug 26, 2024
1 parent 6362748 commit bef7ea2
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 29 deletions.
26 changes: 21 additions & 5 deletions swhkd/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
let invoking_uid = get_uid()?;
let uname = get_uname_from_uid(invoking_uid)?;

let env = refresh_env(&uname, invoking_uid, true).unwrap();
let env = refresh_env(&uname, invoking_uid, true)
.unwrap()
.unwrap_or(environ::Env::construct(&uname, None));
log::trace!("Environment Aquired");
let log_file_name = if let Some(val) = args.log {
val
Expand Down Expand Up @@ -137,7 +139,17 @@ async fn main() -> Result<(), Box<dyn Error>> {
loop {
{
let mut pairs = pairs_clone.lock().unwrap();
pairs.clone_from(&refresh_env(&uname, invoking_uid, false).unwrap().pairs);
match refresh_env(&uname, invoking_uid, false) {
Ok(Some(env)) => {
pairs.clone_from(&env.pairs);
}
Ok(None) => {}
Err(e) => {
log::error!("Error: {}", e);
_ = Command::new("notify-send").arg(format!("ERROR {}", e)).spawn();
exit(1);
}
}
}
sleep(Duration::from_millis(server_cooldown)).await;
}
Expand Down Expand Up @@ -623,7 +635,11 @@ fn get_file_paths(runtime_dir: &str) -> (String, String) {
(pid_file_path, sock_file_path)
}

fn refresh_env(uname: &str, invoking_uid: u32, skip: bool) -> Result<environ::Env, Box<dyn Error>> {
fn refresh_env(
uname: &str,
invoking_uid: u32,
skip: bool,
) -> Result<Option<environ::Env>, Box<dyn Error>> {
let env = environ::Env::construct(uname, None);

let (_pid_path, sock_path) =
Expand All @@ -643,7 +659,7 @@ fn refresh_env(uname: &str, invoking_uid: u32, skip: bool) -> Result<environ::En
let mut buf = String::new();
socket.read_to_string(&mut buf)?;
if buf.is_empty() {
continue;
return Ok(None);
}
log::info!("Server Instance found!");
result.push_str(&buf);
Expand All @@ -662,5 +678,5 @@ fn refresh_env(uname: &str, invoking_uid: u32, skip: bool) -> Result<environ::En
}
}
log::trace!("Environment Refreshed");
Ok(environ::Env::construct(uname, Some(&result)))
Ok(Some(environ::Env::construct(uname, Some(&result))))
}
6 changes: 5 additions & 1 deletion swhkd/src/environ.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{collections::HashMap, error::Error, path::PathBuf, process::Command};

#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Env {
pub pairs: HashMap<String, String>,
pub uname: String,
Expand All @@ -25,6 +25,10 @@ impl Env {
pairs
}

pub fn refresh_env(&mut self, pairs: HashMap<String, String>){
self.pairs = pairs;
}

pub fn construct(uname: &str, env: Option<&str>) -> Self {
let env = match env {
Some(env) => env.to_string(),
Expand Down
41 changes: 18 additions & 23 deletions swhks/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;
use std::error::Error;
use std::fs::Permissions;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::{
fs::{self},
io::Write,
Expand Down Expand Up @@ -39,16 +39,6 @@ fn get_env() -> Result<String, Box<dyn std::error::Error>> {
Ok(stdout)
}

fn parse_env(env: &str) -> HashMap<String, String> {
let mut pairs = HashMap::new();
for line in env.lines() {
let mut parts = line.splitn(2, '=');
if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
pairs.insert(key.to_string(), value.to_string());
}
}
pairs
}
fn main() -> std::io::Result<()> {
let args = Args::parse();
if args.debug {
Expand All @@ -59,30 +49,35 @@ fn main() -> std::io::Result<()> {
.init();
}

let env_raw = match get_env() {
Ok(env) => env,
Err(_) => "".to_string(),
};

let env = parse_env(&env_raw);
let mut prev_hash = calculate_hash(String::new());

let invoking_uid = get_uid().unwrap();
let default_runtime_dir = format!("/run/user/{}", invoking_uid);
let runtime_dir = env.get("XDG_RUNTIME_DIR").unwrap_or(&default_runtime_dir);
let runtime_dir = format!("/run/user/{}", invoking_uid);

let (_pid_file_path, sock_file_path) = get_file_paths(runtime_dir);
let (_pid_file_path, sock_file_path) = get_file_paths(&runtime_dir);

log::info!("Started SWHKS placeholder server");
let _ = daemon(true, false);
//let _ = daemon(true, false);
setup_swhks(invoking_uid, PathBuf::from(runtime_dir));
loop {
if let Ok(mut stream) = UnixStream::connect(&sock_file_path) {
let _ = stream.write_all(env_raw.as_bytes());
if prev_hash != calculate_hash(get_env().unwrap()) {
log::debug!("Env changed, sending to swhkd");
let new_env = get_env().unwrap();
let _ = stream.write_all(new_env.as_bytes());
log::debug!("Sent env to swhkd");
prev_hash = calculate_hash(new_env);
}
};
std::thread::sleep(std::time::Duration::from_millis(512));
}
}

pub fn calculate_hash(t: String) -> u64 {
let mut hasher = DefaultHasher::new();
t.hash(&mut hasher);
hasher.finish()
}

pub fn setup_swhks(invoking_uid: u32, runtime_path: PathBuf) {
// Get the runtime path and create it if needed.
if !Path::new(&runtime_path).exists() {
Expand Down

0 comments on commit bef7ea2

Please sign in to comment.