2020-04-08 14:26:42 +00:00
|
|
|
use rand::Rng;
|
|
|
|
use serde::{Deserialize, Serialize};
|
2021-01-15 13:04:32 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use tokio::fs;
|
2020-08-26 08:07:22 +00:00
|
|
|
use veloren_network::{Participant, ProtocolAddr, Stream};
|
2020-04-08 14:26:42 +00:00
|
|
|
|
2020-07-09 07:58:21 +00:00
|
|
|
use std::collections::HashMap;
|
2020-04-08 14:26:42 +00:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum LocalCommand {
|
|
|
|
Shutdown,
|
|
|
|
Disconnect,
|
2020-07-09 11:42:38 +00:00
|
|
|
Connect(ProtocolAddr),
|
2020-04-08 14:26:42 +00:00
|
|
|
List,
|
|
|
|
Serve(FileInfo),
|
|
|
|
Get(u32, Option<String>),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub enum Command {
|
|
|
|
List,
|
|
|
|
Get(u32),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
|
|
|
pub struct FileInfo {
|
|
|
|
id: u32,
|
|
|
|
pub path: String,
|
|
|
|
pub size: u64,
|
|
|
|
pub hash: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct RemoteInfo {
|
|
|
|
infos: HashMap<u32, FileInfo>,
|
2020-07-09 07:58:21 +00:00
|
|
|
_participant: Participant,
|
2020-04-08 14:26:42 +00:00
|
|
|
pub cmd_out: Stream,
|
|
|
|
pub file_out: Stream,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FileInfo {
|
|
|
|
pub async fn new(path: &Path) -> Option<Self> {
|
|
|
|
let mt = match fs::metadata(&path).await {
|
|
|
|
Err(e) => {
|
|
|
|
println!(
|
2020-07-05 22:13:53 +00:00
|
|
|
"Cannot get metadata for file: {:?}, does it exist? Error: {:?}",
|
2020-04-08 14:26:42 +00:00
|
|
|
&path, &e
|
|
|
|
);
|
|
|
|
return None;
|
|
|
|
},
|
|
|
|
Ok(mt) => mt,
|
|
|
|
};
|
|
|
|
let size = mt.len();
|
|
|
|
Some(Self {
|
|
|
|
id: rand::thread_rng().gen(),
|
|
|
|
path: path.as_os_str().to_os_string().into_string().unwrap(),
|
|
|
|
size,
|
|
|
|
hash: "<none>".to_owned(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn load(&self) -> Result<Vec<u8>, std::io::Error> { fs::read(self.path()).await }
|
|
|
|
|
|
|
|
pub fn id(&self) -> u32 { self.id }
|
|
|
|
|
|
|
|
pub fn path(&self) -> PathBuf { self.path.parse().unwrap() }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RemoteInfo {
|
2020-07-09 07:58:21 +00:00
|
|
|
pub fn new(cmd_out: Stream, file_out: Stream, participant: Participant) -> Self {
|
2020-04-08 14:26:42 +00:00
|
|
|
Self {
|
|
|
|
infos: HashMap::new(),
|
|
|
|
_participant: participant,
|
|
|
|
cmd_out,
|
|
|
|
file_out,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-13 17:11:55 +00:00
|
|
|
pub fn get_info(&self, id: u32) -> Option<FileInfo> { self.infos.get(&id).cloned() }
|
2020-04-08 14:26:42 +00:00
|
|
|
|
|
|
|
pub fn insert_infos(&mut self, mut fi: Vec<FileInfo>) {
|
|
|
|
for fi in fi.drain(..) {
|
|
|
|
self.infos.insert(fi.id(), fi);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|