src/global/traits/collection.rs

243 lines · 7500 bytes

  1use home::home_dir;
  2use serde::{de::DeserializeOwned, Serialize};
  3use std::{
  4    error::Error,
  5    fs::{self, OpenOptions},
  6    io::Write,
  7};
  8
  9pub trait CollectionItem {
 10    fn id(&self) -> Option<&str>;
 11    fn children_ids(&self) -> Vec<&str>;
 12}
 13
 14pub trait Collection<T>
 15where
 16    Self: Default + Clone + Serialize + DeserializeOwned,
 17    T: Serialize + DeserializeOwned + CollectionItem,
 18{
 19    const INDEX_PATH: &'static str;
 20
 21    fn items(&self) -> &Vec<T>;
 22    fn items_mut(&mut self) -> &mut Vec<T>;
 23
 24    fn from_items(items: Vec<T>) -> Self;
 25
 26    fn trim(&mut self, length: usize) {
 27        let items = self.items_mut();
 28        if items.len() > length {
 29            items.drain(0..items.len() - length);
 30        }
 31    }
 32
 33    /// saves the current state of watch history into a file
 34    fn save(&self) -> Result<(), Box<dyn Error>> {
 35        let save_string = serde_json::to_string_pretty(
 36            &self
 37                .items()
 38                .iter()
 39                .map(|item| item.id().unwrap_or_default())
 40                .filter(|id| !id.is_empty())
 41                .collect::<Vec<&str>>(),
 42        )?;
 43        let path = home_dir().unwrap().join(Self::INDEX_PATH);
 44
 45        let mut file = OpenOptions::new()
 46            .write(true)
 47            .create(true)
 48            .truncate(true)
 49            .open(path)?;
 50
 51        file.write_all(save_string.as_bytes())?;
 52
 53        Ok(())
 54    }
 55
 56    /// add an item to watch history
 57    fn push(&mut self, item: T) -> Result<(), Box<dyn Error>> {
 58        let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
 59
 60        // removes duplicates and place them on top (if exists)
 61        let id = item.id().unwrap_or("invalid-dump");
 62        if let Some(index) = self
 63            .items_mut()
 64            .iter_mut()
 65            .position(|item_in_iter| item_in_iter.id().unwrap_or_default() == id)
 66        {
 67            self.items_mut().remove(index);
 68        }
 69        let mut file = OpenOptions::new()
 70            .write(true)
 71            .create(true)
 72            .truncate(true)
 73            .open(info.join(format!("{id}.json")))?;
 74        let item_string = serde_json::to_string(&item)?;
 75        file.write_all(item_string.as_bytes())?;
 76
 77        self.items_mut().push(item);
 78
 79        Ok(())
 80    }
 81
 82    /// loads watch history from file
 83    fn load() -> Self {
 84        let path = home_dir().unwrap().join(Self::INDEX_PATH);
 85        let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
 86            let file_string = fs::read_to_string(&path)?;
 87            let deserialized = serde_json::from_str(&file_string)?;
 88            Ok(deserialized)
 89        })();
 90
 91        // if res is err, then the file either doesn't exist of has be altered incorrectly, in
 92        // which case returns Self::default()
 93        let items = if let Ok(deserialized) = res {
 94            let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
 95            deserialized
 96                .into_iter()
 97                .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
 98                .filter_map(|file_content| serde_json::from_str(&file_content).ok())
 99                .collect()
100        } else {
101            // if the file does exist, back it up
102            // if it doesn't exist, it will throw an error but we dont care
103            let mut new_path = path.clone();
104            new_path.pop();
105            new_path.push(format!(
106                "{}.{}.old",
107                Self::INDEX_PATH,
108                chrono::offset::Local::now()
109            ));
110            let _ = fs::rename(&path, &new_path);
111
112            Vec::new()
113        };
114
115        Self::from_items(items)
116    }
117
118    /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
119    fn exit_move(&self) {
120        let home_dir = home_dir().unwrap();
121        let store_thumbnails_path = home_dir.join(".local/share/youtube-tui/thumbnails/");
122        let store_info_path = home_dir.join(".local/share/youtube-tui/info/");
123        let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
124        let cache_info_path = home_dir.join(".cache/youtube-tui/info");
125
126        self.items().iter().for_each(|item| {
127            let id = item.id().unwrap_or("invalid-dump");
128            let _ = fs::rename(
129                cache_thumbnails_path.join(id),
130                store_thumbnails_path.join(id),
131            );
132
133            let _ = fs::rename(
134                cache_info_path.join(format!("{id}.json")),
135                store_info_path.join(format!("{id}.json")),
136            );
137
138            item.children_ids().iter().for_each(|id| {
139                let _ = fs::rename(
140                    cache_thumbnails_path.join(id),
141                    store_thumbnails_path.join(id),
142                );
143            })
144        })
145    }
146
147    /// remove item based on their id
148    fn remove(&mut self, id: &str) -> bool {
149        let items = self.items_mut();
150
151        if let Some(found) = items
152            .iter()
153            .enumerate()
154            .find(|(_index, item)| item.id() == Some(id))
155        {
156            items.remove(found.0);
157            true
158        } else {
159            false
160        }
161    }
162}
163
164pub trait CollectionNoId<T>
165where
166    Self: Default + Clone + Serialize + DeserializeOwned,
167    T: Serialize + DeserializeOwned + PartialEq,
168{
169    const INDEX_PATH: &'static str;
170
171    fn items(&self) -> &Vec<T>;
172    fn items_mut(&mut self) -> &mut Vec<T>;
173
174    fn from_items(items: Vec<T>) -> Self;
175
176    fn trim(&mut self, length: usize) {
177        let items = self.items_mut();
178        if items.len() > length {
179            items.drain(0..items.len() - length);
180        }
181    }
182    /// saves the current state of watch history into a file
183    fn save(&self) -> Result<(), Box<dyn Error>> {
184        let save_string = serde_json::to_string_pretty(&self)?;
185        let path = home_dir().unwrap().join(Self::INDEX_PATH);
186
187        let mut file = OpenOptions::new()
188            .write(true)
189            .create(true)
190            .truncate(true)
191            .open(path)?;
192
193        file.write_all(save_string.as_bytes())?;
194
195        Ok(())
196    }
197
198    /// add an item to watch history
199    fn push(&mut self, item: T) {
200        // removes duplicates and place them on top (if exists)
201        if let Some(index) = self
202            .items_mut()
203            .iter_mut()
204            .position(|item_in_iter| *item_in_iter == item)
205        {
206            self.items_mut().remove(index);
207        }
208
209        self.items_mut().push(item);
210    }
211
212    /// loads watch history from file
213    fn load() -> Self {
214        let path = home_dir().unwrap().join(Self::INDEX_PATH);
215        let res = (|| -> Result<Vec<T>, Box<dyn Error>> {
216            let file_string = fs::read_to_string(&path)?;
217            let deserialized = serde_json::from_str(&file_string)?;
218            Ok(deserialized)
219        })();
220
221        // if res is err, then the file either doesn't exist of has be altered incorrectly, in
222        // which case returns Self::default()
223        let items = res.unwrap_or_default();
224
225        Self::from_items(items)
226    }
227
228    /// remove item based on their id
229    fn remove(&mut self, matcher: &T) -> bool {
230        let items = self.items_mut();
231
232        if let Some(found) = items
233            .iter()
234            .enumerate()
235            .find(|(_index, item)| *item == matcher)
236        {
237            items.remove(found.0);
238            true
239        } else {
240            false
241        }
242    }
243}