cache.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use std::path::PathBuf;
  2. use std::io::Read;
  3. use std::fs::File;
  4. use util::{FileId, mkdir_existing};
  5. use authentication::Credentials;
  6. #[derive(Clone)]
  7. pub struct Cache {
  8. root: PathBuf,
  9. use_audio_cache: bool,
  10. }
  11. impl Cache {
  12. pub fn new(location: PathBuf, use_audio_cache: bool) -> Cache {
  13. mkdir_existing(&location).unwrap();
  14. mkdir_existing(&location.join("files")).unwrap();
  15. Cache {
  16. root: location,
  17. use_audio_cache: use_audio_cache
  18. }
  19. }
  20. }
  21. impl Cache {
  22. fn credentials_path(&self) -> PathBuf {
  23. self.root.join("credentials.json")
  24. }
  25. pub fn credentials(&self) -> Option<Credentials> {
  26. let path = self.credentials_path();
  27. Credentials::from_file(path)
  28. }
  29. pub fn save_credentials(&self, cred: &Credentials) {
  30. let path = self.credentials_path();
  31. cred.save_to_file(&path);
  32. }
  33. }
  34. impl Cache {
  35. fn file_path(&self, file: FileId) -> PathBuf {
  36. let name = file.to_base16();
  37. self.root.join("files").join(&name[0..2]).join(&name[2..])
  38. }
  39. pub fn file(&self, file: FileId) -> Option<File> {
  40. File::open(self.file_path(file)).ok()
  41. }
  42. pub fn save_file(&self, file: FileId, contents: &mut Read) {
  43. if self.use_audio_cache {
  44. let path = self.file_path(file);
  45. mkdir_existing(path.parent().unwrap()).unwrap();
  46. let mut cache_file = File::create(path).unwrap();
  47. ::std::io::copy(contents, &mut cache_file).unwrap();
  48. }
  49. }
  50. }