src/global/structs/localstore.rs
106 lines · 3121 bytes
10 symbols in this file
1// currently 3 copies of the same item is stored in ram
2// - in localstore
3// - in watch history
4// - in the actual state
5//
6// this needs to change
7use std::{
8 collections::{HashMap, HashSet},
9 fs::{self, OpenOptions},
10 io::Write,
11 sync::OnceLock,
12};
13
14use crate::global::{functions::paths, structs::Item};
15
16static mut LOCALSTORE: OnceLock<LocalStore> = OnceLock::new();
17
18pub struct LocalRecord {
19 item: Item,
20 is_new: bool,
21}
22
23/// cached access and write files to ~/.local/share
24#[derive(Default)]
25pub struct LocalStore {
26 info: HashMap<String, LocalRecord>,
27 downloaded_images: HashSet<String>,
28}
29
30impl LocalStore {
31 pub fn add_image(id: String) {
32 unsafe { LOCALSTORE.get_mut() }
33 .unwrap()
34 .downloaded_images
35 .insert(id);
36 }
37
38 pub fn init() {
39 unsafe {
40 let _ = LOCALSTORE.set(Self::default());
41 }
42 }
43
44 pub fn rm_cache(id: &str) -> bool {
45 let res = unsafe { LOCALSTORE.get_mut() }.unwrap().info.remove(id);
46 unsafe { LOCALSTORE.get_mut() }
47 .unwrap()
48 .downloaded_images
49 .remove(id);
50 let data = paths::data_dir();
51 let info_path = data.join("info");
52 let thumbnail_path = data.join("thumbnails");
53 let _ = fs::remove_file(info_path.join(id).with_extension("json"));
54 let _ = fs::remove_file(thumbnail_path.join(id));
55
56 res.is_some()
57 }
58
59 pub fn get_info(id: &str) -> Option<Item> {
60 let localstore = unsafe { LOCALSTORE.get_mut() }.unwrap();
61
62 match localstore.info.get(id) {
63 Some(LocalRecord { item, .. }) => Some(item.clone()),
64 None => {
65 let path = paths::data_dir()
66 .join(format!("info/{id}.json"));
67
68 if path.exists() {
69 serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?
70 } else {
71 None
72 }
73 }
74 }
75 }
76
77 pub fn set_info(id: String, item: Item, is_new: bool) {
78 let localstore = unsafe { LOCALSTORE.get_mut() }.unwrap();
79 localstore.info.insert(id, LocalRecord { item, is_new });
80 }
81
82 pub fn save_only(ids: &HashSet<String>) {
83 let info_path = paths::data_dir().join("info");
84
85 for (id, LocalRecord { item, is_new }) in unsafe { LOCALSTORE.get() }.unwrap().info.iter() {
86 let info = info_path.join(id).with_extension("json");
87 if *is_new && ids.contains(id) {
88 let mut file = match OpenOptions::new()
89 .write(true)
90 .create(true)
91 .truncate(true)
92 .open(info)
93 {
94 Ok(f) => f,
95 Err(_) => continue,
96 };
97 let item_string = serde_json::to_string(&item).unwrap();
98 let _ = file.write_all(item_string.as_bytes());
99 }
100 }
101 }
102
103 pub fn list_downloaded_images() -> &'static HashSet<String> {
104 &unsafe { LOCALSTORE.get() }.unwrap().downloaded_images
105 }
106}