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