80 lines
2.1 KiB
Rust
80 lines
2.1 KiB
Rust
use std::
|
|
{
|
|
io,
|
|
fs,
|
|
io::{BufReader, prelude::*},
|
|
net::{TcpListener, TcpStream},
|
|
sync::mpsc,
|
|
thread,
|
|
path::PathBuf,
|
|
};
|
|
use lazy_static::lazy_static;
|
|
|
|
|
|
mod files;
|
|
|
|
lazy_static! {
|
|
static ref ROOT_DIR: PathBuf = fs::canonicalize(PathBuf::from("./root")).unwrap();
|
|
}
|
|
// TODO, remove .unwrap()
|
|
// TODO, make 'code' an enum
|
|
// TODO, safely modify bytes in thread.
|
|
// TODO, Makes paths more consistent.
|
|
// TODO, Avoid copying bytes
|
|
fn main() -> io::Result<()>
|
|
{
|
|
#![warn(clippy::pedantic, clippy::perf)]
|
|
// Default values
|
|
const BIND_ADDRESS: &str = "127.0.0.1:2008";
|
|
const INDEX_FILE: &str = "index.npon";
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
let listener = TcpListener::bind(BIND_ADDRESS).unwrap();
|
|
println!("Listening at {BIND_ADDRESS}");
|
|
|
|
/*
|
|
let mut file_list: Vec<std::path::PathBuf> = vec![ROOT_DIR.join(INDEX_FILE)];
|
|
let (mut bytes, mut new_file_list) = files::read_file(INDEX_FILE, 0);
|
|
file_list.append(&mut new_file_list);
|
|
*/
|
|
// File watch thread
|
|
thread::spawn(
|
|
move || {
|
|
let mut bytes: Vec<u8>;
|
|
let mut file_list: Vec<PathBuf>;
|
|
(bytes, file_list) = files::read_file(INDEX_FILE, 0);
|
|
file_list.push(ROOT_DIR.join(INDEX_FILE));
|
|
println!("Tracking: {:?}", file_list);
|
|
|
|
tx.send(bytes.clone()).unwrap();
|
|
loop
|
|
{
|
|
let code = files::watch_files(&file_list);
|
|
if code == 0
|
|
{
|
|
println!("Re encoding index");
|
|
|
|
(bytes, file_list) = files::read_file(INDEX_FILE, 0);
|
|
file_list.push(ROOT_DIR.join(INDEX_FILE));
|
|
tx.send(bytes.clone()).unwrap();
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
for stream in listener.incoming() {
|
|
let bytes = rx.recv().unwrap();
|
|
let stream = stream.unwrap();
|
|
handle_connection(stream, &bytes);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn handle_connection(mut stream: TcpStream, bytes: &Vec<u8>)
|
|
{
|
|
let buf_reader = BufReader::new(&stream);
|
|
println!("CONNECTION: {buf_reader:#?}");
|
|
stream.write_all(bytes.as_slice()).unwrap();
|
|
}
|