src/global/traits/collection.rs

152 lines · 5197 bytes

  1use home::home_dir;
  2use serde::{de::DeserializeOwned, Serialize};
  3use std::{
  4    error::Error,
  5    fs::{self, OpenOptions},
  6    io::Write,
  7};
  8use typemap::Key;
  9
 10use crate::global::structs::Item;
 11
 12pub trait Collection
 13where
 14    Self: Default + Clone + Serialize + DeserializeOwned + Key,
 15{
 16    const INDEX_PATH: &'static str;
 17
 18    fn items(&self) -> &Vec<Item>;
 19    fn items_mut(&mut self) -> &mut Vec<Item>;
 20
 21    /// saves the current state of watch history into a file
 22    fn save(&self) -> Result<(), Box<dyn Error>> {
 23        let save_string = serde_json::to_string_pretty(
 24            &self
 25                .items()
 26                .iter()
 27                .map(|item| item.id().unwrap_or_default())
 28                .filter(|id| !id.is_empty())
 29                .collect::<Vec<&str>>(),
 30        )?;
 31        let path = home_dir().unwrap().join(Self::INDEX_PATH);
 32
 33        let mut file = OpenOptions::new()
 34            .write(true)
 35            .create(true)
 36            .truncate(true)
 37            .open(path)?;
 38
 39        file.write_all(save_string.as_bytes())?;
 40
 41        Ok(())
 42    }
 43
 44    /// add an item to watch history
 45    fn push(&mut self, item: Item, max_length: Option<usize>) -> Result<(), Box<dyn Error>> {
 46        let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
 47
 48        // removes duplicates and place them on top (if exists)
 49        let id = item.id().unwrap_or("invalid-dump");
 50        if let Some(index) = self
 51            .items_mut()
 52            .iter_mut()
 53            .position(|item_in_iter| item_in_iter.id().unwrap_or_default() == id)
 54        {
 55            self.items_mut().remove(index);
 56        }
 57        let mut file = OpenOptions::new()
 58            .write(true)
 59            .create(true)
 60            .truncate(true)
 61            .open(info.join(format!("{id}.json")))?;
 62        let item_string = serde_json::to_string(&item)?;
 63        file.write_all(item_string.as_bytes())?;
 64
 65        self.items_mut().push(item);
 66
 67        // if length of history exceeds the maximum history length, removes that oldest item
 68        if self.items().len() > max_length.unwrap_or(usize::MAX) {
 69            self.items_mut().remove(0);
 70        }
 71
 72        Ok(())
 73    }
 74
 75    /// loads watch history from file
 76    fn load() -> Vec<Item> {
 77        let path = home_dir().unwrap().join(Self::INDEX_PATH);
 78        let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
 79            let file_string = fs::read_to_string(&path)?;
 80            let deserialized = serde_json::from_str(&file_string)?;
 81            Ok(deserialized)
 82        })();
 83
 84        // if res is err, then the file either doesn't exist of has be altered incorrectly, in
 85        // which case returns Self::default()
 86        if let Ok(deserialized) = res {
 87            let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
 88            deserialized
 89                .into_iter()
 90                .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
 91                .filter_map(|file_content| serde_json::from_str(&file_content).ok())
 92                .collect()
 93        } else {
 94            // if the file does exist, back it up
 95            // if it doesn't exist, it will throw an error but we dont care
 96            let mut new_path = path.clone();
 97            new_path.pop();
 98            new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
 99            let _ = fs::rename(&path, &new_path);
100
101            Vec::new()
102        }
103    }
104
105    /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
106    fn exit_move(&self) {
107        let home_dir = home_dir().unwrap();
108        let store_thumbnails_path = home_dir.join(".local/share/youtube-tui/thumbnails/");
109        let store_info_path = home_dir.join(".local/share/youtube-tui/info/");
110        let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
111        let cache_info_path = home_dir.join(".cache/youtube-tui/info");
112
113        self.items().iter().for_each(|item| {
114            let id = item.id().unwrap_or("invalid-dump");
115            let _ = fs::rename(
116                cache_thumbnails_path.join(id),
117                store_thumbnails_path.join(id),
118            );
119
120            let _ = fs::rename(
121                cache_info_path.join(format!("{id}.json")),
122                store_info_path.join(format!("{id}.json")),
123            );
124
125            if let Item::FullPlaylist(fullplaylist) = item {
126                fullplaylist.videos.iter().for_each(|video| {
127                    let id = video.id().unwrap_or("invalid-dump");
128                    let _ = fs::rename(
129                        cache_thumbnails_path.join(id),
130                        store_thumbnails_path.join(id),
131                    );
132                })
133            }
134        })
135    }
136
137    /// remove item based on their id
138    fn remove(&mut self, id: &str) -> bool {
139        let items = self.items_mut();
140
141        if let Some(found) = items
142            .iter()
143            .enumerate()
144            .find(|(_index, item)| item.id() == Some(id))
145        {
146            items.remove(found.0);
147            true
148        } else {
149            false
150        }
151    }
152}