src/global/structs/localstore.rs

109 lines · 3266 bytes

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