2017-01-29 15:36:39 +00:00
|
|
|
use std::path::PathBuf;
|
2016-03-16 04:07:04 +00:00
|
|
|
use std::io::Read;
|
2017-01-29 15:36:39 +00:00
|
|
|
use std::fs::File;
|
|
|
|
|
|
|
|
use util::{FileId, mkdir_existing};
|
|
|
|
use authentication::Credentials;
|
|
|
|
|
|
|
|
pub struct Cache {
|
|
|
|
root: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Cache {
|
|
|
|
pub fn new(location: PathBuf) -> Cache {
|
|
|
|
mkdir_existing(&location).unwrap();
|
|
|
|
mkdir_existing(&location.join("files")).unwrap();
|
|
|
|
|
|
|
|
Cache {
|
|
|
|
root: location
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-03-16 04:07:04 +00:00
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
impl Cache {
|
|
|
|
fn credentials_path(&self) -> PathBuf {
|
|
|
|
self.root.join("credentials.json")
|
2016-03-16 04:07:04 +00:00
|
|
|
}
|
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
pub fn credentials(&self) -> Option<Credentials> {
|
|
|
|
let path = self.credentials_path();
|
|
|
|
Credentials::from_file(path)
|
2016-03-16 04:07:04 +00:00
|
|
|
}
|
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
pub fn save_credentials(&self, cred: &Credentials) {
|
|
|
|
let path = self.credentials_path();
|
|
|
|
cred.save_to_file(&path);
|
2016-03-16 04:07:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
impl Cache {
|
|
|
|
fn file_path(&self, file: FileId) -> PathBuf {
|
|
|
|
let name = file.to_base16();
|
|
|
|
self.root.join("files").join(&name[0..2]).join(&name[2..])
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn file(&self, file: FileId) -> Option<File> {
|
|
|
|
File::open(self.file_path(file)).ok()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn save_file(&self, file: FileId, contents: &mut Read) {
|
|
|
|
let path = self.file_path(file);
|
|
|
|
|
|
|
|
mkdir_existing(path.parent().unwrap()).unwrap();
|
2016-03-16 04:07:04 +00:00
|
|
|
|
2017-01-29 15:36:39 +00:00
|
|
|
let mut cache_file = File::create(path).unwrap();
|
|
|
|
::std::io::copy(contents, &mut cache_file).unwrap();
|
|
|
|
}
|
|
|
|
}
|