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