src/global/traits/collection.rs

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