user.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. use crate::categories::CatStats;
  2. use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
  3. use radix_trie::Trie;
  4. use shellexpand::tilde;
  5. use std::collections::HashSet;
  6. use std::path::PathBuf;
  7. use std::time::Duration;
  8. /// Configuration for single user
  9. pub struct User {
  10. /// Categories statistics for the user
  11. pub catmap: CatStats,
  12. /// Available accounts for the user
  13. pub accounts: HashSet<String>,
  14. /// database with config
  15. db: PickleDb,
  16. }
  17. #[cfg(not(feature = "docker"))]
  18. pub const DEFAULT_DB_PATH: &str = "~/.config/receqif/";
  19. #[cfg(feature = "docker")]
  20. pub const DEFAULT_DB_PATH: &str = "/etc/receqif/";
  21. impl Drop for User {
  22. fn drop(&mut self) {
  23. self.save_data();
  24. }
  25. }
  26. impl User {
  27. pub fn new(uid: i64, dbfile: &Option<String>) -> Self {
  28. let ten_sec = Duration::from_secs(10);
  29. let path: String = match dbfile {
  30. Some(path) => path.to_string(),
  31. None => DEFAULT_DB_PATH.to_owned() + &uid.to_string() + ".db",
  32. };
  33. let confpath: &str = &tilde(&path);
  34. let confpath = PathBuf::from(confpath);
  35. let dbase = PickleDb::load(
  36. &confpath,
  37. PickleDbDumpPolicy::PeriodicDump(ten_sec),
  38. SerializationMethod::Json,
  39. );
  40. let db = match dbase {
  41. Ok(db) => db,
  42. Err(_) => PickleDb::new(
  43. &confpath,
  44. PickleDbDumpPolicy::PeriodicDump(ten_sec),
  45. SerializationMethod::Json,
  46. ),
  47. };
  48. let catmap: CatStats = match db.get("catmap") {
  49. Some(v) => v,
  50. None => Trie::new(),
  51. };
  52. let accounts = match db.get::<Vec<String>>("accounts") {
  53. Some(a) => HashSet::from_iter(a),
  54. None => HashSet::new(),
  55. };
  56. User {
  57. catmap,
  58. accounts,
  59. db,
  60. }
  61. }
  62. pub fn accounts(&mut self, acc: Vec<String>) {
  63. self.accounts = HashSet::from_iter(acc);
  64. }
  65. pub fn save_data(&mut self) {
  66. log::debug!("Saving user data");
  67. self.db.set("catmap", &self.catmap).unwrap();
  68. self.db.dump().unwrap();
  69. }
  70. }