src/global/structs/watchhistory.rs
119 lines · 3811 bytes
1use super::Item;
2use home::home_dir;
3use serde::{Deserialize, Serialize};
4use std::{
5 error::Error,
6 fs::{self, OpenOptions},
7 io::Write,
8};
9use typemap::Key;
10
11#[derive(Clone, Default, Serialize, Deserialize)]
12pub struct WatchHistory(pub Vec<Item>);
13
14impl Key for WatchHistory {
15 type Value = Self;
16}
17
18impl WatchHistory {
19 /// saves the current state of watch history into a file
20 pub fn save(&self) -> Result<(), Box<dyn Error>> {
21 let save_string = serde_json::to_string(self)?;
22 let path = home_dir()
23 .unwrap()
24 .join(".local/share/youtube-tui/watch_history.json");
25
26 let mut file = OpenOptions::new()
27 .write(true)
28 .create(true)
29 .truncate(true)
30 .open(&path)?;
31
32 file.write_all(save_string.as_bytes())?;
33
34 Ok(())
35 }
36
37 /// add an item to watch history
38 pub fn push(&mut self, item: Item, max_items: usize) {
39 // removes duplicates and place them on top (if exists)
40 if let Some(index) = self
41 .0
42 .iter()
43 .position(|item_in_iter| item_in_iter.id() == item.id())
44 {
45 self.0.remove(index);
46 }
47 self.0.push(item);
48
49 // if length of history exceeds the maximum history length, removes that oldest item
50 if self.0.len() > max_items {
51 self.0.remove(0);
52 }
53 }
54
55 /// loads watch history from file
56 pub fn load() -> Self {
57 let path = home_dir()
58 .unwrap()
59 .join(".local/share/youtube-tui/watch_history.json");
60 let res = (|| -> Result<Self, Box<dyn Error>> {
61 let file_string = fs::read_to_string(&path)?;
62 let deserialized = serde_json::from_str(&file_string)?;
63 Ok(deserialized)
64 })();
65
66 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
67 // which case returns Self::default()
68 if let Ok(deserialized) = res {
69 deserialized
70 } else {
71 // if the file does exist, back it up
72 // if it doesn't exist, it will throw an error but we dont care
73 let mut new_path = path.clone();
74 new_path.pop();
75 new_path.push(format!(
76 "watch_history-{}.json",
77 chrono::offset::Local::now(),
78 ));
79 let _ = fs::rename(&path, &new_path);
80
81 Self::default()
82 }
83 }
84
85 /// moves all thumbnails from storage to cache when starting
86 pub fn init_move() {
87 let history_thumbnails_path = home_dir()
88 .unwrap()
89 .join(".local/share/youtube-tui/watch_history/thumbnails/");
90 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
91
92 fs::read_dir(history_thumbnails_path)
93 .unwrap()
94 .into_iter()
95 .for_each(|path| {
96 let path = path.unwrap().path();
97 let _ = fs::rename(
98 path.clone(),
99 cache_thumbnails_path.join(path.file_name().unwrap()),
100 );
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 pub fn exit_move(&self) {
106 let history_thumbnails_path = home_dir()
107 .unwrap()
108 .join(".local/share/youtube-tui/watch_history/thumbnails/");
109 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
110
111 self.0.iter().for_each(|item| {
112 let id = item.id().unwrap();
113 let _ = fs::rename(
114 cache_thumbnails_path.join(id),
115 history_thumbnails_path.join(id),
116 );
117 })
118 }
119}