A tool to read animebox backup files and export the data in alternate formats.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

  1. use std::error::Error;
  2. use std::ffi::OsString;
  3. use std::fs::File;
  4. use std::io::BufReader;
  5. use std::path::Path;
  6. use std::process::exit;
  7. use serde::ser::Error as SerdeError;
  8. use serde::{Deserialize, Serialize};
  9. use serde_json::{from_reader, to_writer_pretty};
  10. #[derive(Serialize, Deserialize, Debug)]
  11. #[serde(deny_unknown_fields)]
  12. pub struct State {
  13. pub downloaded: Vec<String>,
  14. }
  15. pub struct StateManager {
  16. state_path: OsString,
  17. pub state: State,
  18. }
  19. fn read_state<P: AsRef<Path>>(path: P) -> Result<State, Box<dyn Error>> {
  20. let file = File::open(path)?;
  21. let reader = BufReader::new(file);
  22. let result: State = from_reader(reader)?;
  23. Ok(result)
  24. }
  25. fn save_state<P: AsRef<Path>>(path: P, state: &State) -> serde_json::Result<()> {
  26. match File::create(path) {
  27. Err(e) => Err(serde_json::Error::custom(e)),
  28. Ok(file) => to_writer_pretty(file, state),
  29. }
  30. }
  31. impl StateManager {
  32. pub fn new(state_path: &Path) -> StateManager {
  33. let mut state = StateManager {
  34. state_path: OsString::from(state_path.as_os_str()),
  35. state: State { downloaded: vec![] },
  36. };
  37. state.load();
  38. state
  39. }
  40. fn load(&mut self) {
  41. match read_state(&self.state_path) {
  42. Err(e) => {
  43. println!("Failed to read state file {:#?}: {}", &self.state_path, e);
  44. exit(1);
  45. }
  46. Ok(state) => self.state = state,
  47. }
  48. }
  49. pub fn save(&mut self, state: State) {
  50. match save_state(&self.state_path, &state) {
  51. Err(e) => {
  52. println!("Unexpected error saving state: {}", e);
  53. }
  54. Ok(_) => (),
  55. }
  56. self.state = state;
  57. }
  58. }