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.

70 lines
1.8 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. if path.as_ref().exists() {
  21. let file = File::open(path)?;
  22. let reader = BufReader::new(file);
  23. let result: State = from_reader(reader)?;
  24. Ok(result)
  25. } else {
  26. Ok(State { downloaded: vec![] })
  27. }
  28. }
  29. fn save_state<P: AsRef<Path>>(path: P, state: &State) -> serde_json::Result<()> {
  30. match File::create(path) {
  31. Err(e) => Err(serde_json::Error::custom(e)),
  32. Ok(file) => to_writer_pretty(file, state),
  33. }
  34. }
  35. impl StateManager {
  36. pub fn new(state_path: &Path) -> StateManager {
  37. let mut state = StateManager {
  38. state_path: OsString::from(state_path.as_os_str()),
  39. state: State { downloaded: vec![] },
  40. };
  41. state.load();
  42. state
  43. }
  44. fn load(&mut self) {
  45. match read_state(&self.state_path) {
  46. Err(e) => {
  47. println!("Failed to read state file {:#?}: {}", &self.state_path, e);
  48. exit(1);
  49. }
  50. Ok(state) => self.state = state,
  51. }
  52. }
  53. pub fn save(&mut self, state: State) {
  54. match save_state(&self.state_path, &state) {
  55. Err(e) => {
  56. println!("Unexpected error saving state: {}", e);
  57. }
  58. Ok(_) => (),
  59. }
  60. self.state = state;
  61. }
  62. }