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