Commit 6b52ccce6c

6b52ccce6c08377de82d5288ec4e66ec3f878789

parent: 3cea457e08

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-02-18 21:08 UTC

bookmarks

Layout: unified · split

docs/src/commands.md +8
@@ -47,6 +47,14 @@ run [command]
4747>
4848> But for when tasks are stacked up in the *same* event loop and the order of which they are executed matters, this command can be used to force the already stacked up commands to be ran first.
4949
50## Library
51
52```vim
53bookmark [id]
54unmark [id]
55togglemark [id]
56```
57
5058## Text commands
5159
5260Text commands generates a *text only response* without launching the TUI.
src/config/commands.rs +29 −33
@@ -83,7 +83,7 @@ impl Default for CommandsConfigSerde {
8383// Different pages may contain different `env`s (for example `url` is different in each page)
8484
8585fn launch_command_default() -> String {
86 String::from("loadpage popular ;; flush ;; history clear")
86 String::from("loadpage watchhistory ;; flush ;; history clear")
8787}
8888
8989fn video_default() -> Vec<HashMap<String, String>> {
@@ -111,16 +111,16 @@ fn video_default() -> Vec<HashMap<String, String>> {
111111 String::from("run ${browser} '${url}'"),
112112 )]),
113113 HashMap::from([(
114 String::from("Download video (webm)"),
115 String::from(
116 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}'",
117 ),
114 String::from("Toggle bookmark"),
115 String::from("togglemark ${id}")
118116 )]),
119117 HashMap::from([(
120 String::from("Download audio (opus)"),
121 String::from(
122 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}' -x",
123 ),
118 String::from("Save video"),
119 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -o '${save-path}${id}/%(id)s'")
120 )]),
121 HashMap::from([(
122 String::from("Save audio"),
123 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o '${save-path}${id}/%(id)s'")
124124 )]),
125125 HashMap::from([(
126126 String::from("Mode: ${provider}"),
@@ -132,6 +132,10 @@ fn video_default() -> Vec<HashMap<String, String>> {
132132fn playlist_default() -> Vec<HashMap<String, String>> {
133133 vec![
134134 HashMap::from([(String::from("Switch view"), String::from("%switch-view%"))]),
135 HashMap::from([(
136 String::from("Reload as online mode"),
137 String::from("playlist ${id}"),
138 )]),
135139 HashMap::from([(
136140 String::from("Play all videos"),
137141 String::from("run ${video-player} ${all-videos}"),
@@ -140,10 +144,6 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
140144 String::from("Play all audio"),
141145 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video"),
142146 )]),
143 HashMap::from([(
144 String::from("Shuffle play all audio"),
145 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle"),
146 )]),
147147 HashMap::from([(
148148 String::from("Shuffle play all audio (loop)"),
149149 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
@@ -157,12 +157,12 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
157157 String::from("run ${browser} '${url}'"),
158158 )]),
159159 HashMap::from([(
160 String::from("Download all video (webm)"),
161 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}")
160 String::from("Toggle bookmark"),
161 String::from("togglemark ${id}")
162162 )]),
163163 HashMap::from([(
164 String::from("Download all audio (opus)"),
165 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos} -x")
164 String::from("Save all audio"),
165 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run mkdir '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o '${save-path}${id}/%(id)s'")
166166 )]),
167167 HashMap::from([(
168168 String::from("Mode: ${provider}"),
@@ -200,16 +200,16 @@ fn local_video_default() -> Vec<HashMap<String, String>> {
200200 String::from("run ${browser} '${url}'"),
201201 )]),
202202 HashMap::from([(
203 String::from("Download video (webm)"),
204 String::from(
205 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}'",
206 ),
203 String::from("Toggle bookmark"),
204 String::from("togglemark ${id}")
207205 )]),
208206 HashMap::from([(
209 String::from("Download audio (opus)"),
210 String::from(
211 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}' -x",
212 ),
207 String::from("Save video"),
208 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -o '${save-path}${id}/%(id)s'")
209 )]),
210 HashMap::from([(
211 String::from("Save audio"),
212 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o '${save-path}${id}/%(id)s'")
213213 )]),
214214 HashMap::from([(
215215 String::from("Mode: ${provider}"),
@@ -233,10 +233,6 @@ fn local_playlist_default() -> Vec<HashMap<String, String>> {
233233 String::from("Play all audio"),
234234 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video"),
235235 )]),
236 HashMap::from([(
237 String::from("Shuffle play all audio"),
238 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle"),
239 )]),
240236 HashMap::from([(
241237 String::from("Shuffle play all audio (loop)"),
242238 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
@@ -250,12 +246,12 @@ fn local_playlist_default() -> Vec<HashMap<String, String>> {
250246 String::from("run ${browser} '${url}'"),
251247 )]),
252248 HashMap::from([(
253 String::from("Download all video (webm)"),
254 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}")
249 String::from("Toggle bookmark"),
250 String::from("togglemark ${id}")
255251 )]),
256252 HashMap::from([(
257 String::from("Download all audio (opus)"),
258 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos} -x")
253 String::from("Save all audio"),
254 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}' ;; run mkdir '${save-path}${id}' ;; run ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o '${save-path}${id}/%(id)s'")
259255 )]),
260256 HashMap::from([(
261257 String::from("Mode: ${provider}"),
src/config/main.rs +5 −1
@@ -147,7 +147,11 @@ fn default_env() -> HashMap<String, String> {
147147 (String::from("youtube-downloader"), String::from("yt-dlp")),
148148 (
149149 String::from("download-path"),
150 String::from("'~/Downloads/%(title)s-%(id)s.%(ext)s'"),
150 String::from("~/Downloads/%(title)s-%(id)s.%(ext)s"),
151 ),
152 (
153 String::from("save-path"),
154 String::from("~/.local/share/youtube-tui/saved/"),
151155 ),
152156 ])
153157}
src/exit.rs +1 −1
@@ -2,7 +2,7 @@ use home::home_dir;
22use std::{error::Error, fs};
33use tui_additions::framework::Framework;
44
5use crate::global::structs::WatchHistory;
5use crate::global::{structs::WatchHistory, traits::Collection};
66
77/// function to run when the app ends
88// exit tasks:
src/global/functions/download_all_images.rs +1 −1
@@ -36,7 +36,7 @@ impl From<&Item> for Option<DownloadRequest> {
3636 url: fullchannel.thumbnail_url.clone(),
3737 id: fullchannel.id.clone(),
3838 },
39 Item::Unknown(_) | Item::Page(_) => return None,
39 _ => return None,
4040 })
4141 }
4242}
src/global/functions/from_url.rs +2 −6
@@ -10,15 +10,11 @@ pub fn from_channel_url(identifier: &str) -> Result<String, String> {
1010 // if there isnt 24 characters after `/channel/`, that url must not have
1111 // contained a channel id
1212 if identifier.len() < index + 33 {
13 return Err(format!(
14 "Cannot find channel id from string `{identifier}`"
15 ));
13 return Err(format!("Cannot find channel id from string `{identifier}`"));
1614 }
1715 index + 9
1816 } else {
19 return Err(format!(
20 "Cannot find channel id from string `{identifier}`"
21 ));
17 return Err(format!("Cannot find channel id from string `{identifier}`"));
2218 };
2319
2420 Ok(identifier[index..index + 24].to_string())
src/global/functions/init_move.rs added +28
@@ -0,0 +1,28 @@
1use std::fs;
2
3use home::home_dir;
4
5pub fn init_move() {
6 let home_dir = home_dir().unwrap();
7 let store_dir = home_dir.join(".local/share/youtube-tui/");
8 let cache_dir = home_dir.join(".cache/youtube-tui");
9
10 let store_info_dir = store_dir.join("info/");
11 let cache_info_dir = cache_dir.join("info/");
12 fs::read_dir(store_info_dir).unwrap().for_each(|entry| {
13 let entry = entry.unwrap().path();
14 let _ = fs::rename(&entry, cache_info_dir.join(entry.file_name().unwrap()));
15 });
16
17 let store_thumbnails_dir = store_dir.join("thumbnails/");
18 let cache_thumbnails_dir = cache_dir.join("thumbnails/");
19 fs::read_dir(store_thumbnails_dir)
20 .unwrap()
21 .for_each(|entry| {
22 let entry = entry.unwrap().path();
23 let _ = fs::rename(
24 &entry,
25 cache_thumbnails_dir.join(entry.file_name().unwrap()),
26 );
27 });
28}
src/global/functions/mod.rs +2
@@ -23,3 +23,5 @@ mod envs;
2323pub use envs::*;
2424mod update_provider;
2525pub use update_provider::*;
26mod init_move;
27pub use init_move::*;
src/global/functions/run_command.rs +56 −4
@@ -1,13 +1,17 @@
11use crate::{
22 config::Search,
3 global::structs::{
4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Message, Page, SingleItemPage,
5 Status, Task, Tasks,
3 global::{
4 structs::{
5 ChannelDisplayPage, ChannelDisplayPageType, Item, Library, MainMenuPage, Message, Page,
6 SingleItemPage, Status, Task, Tasks,
7 },
8 traits::Collection,
69 },
710 load_configs,
811};
12use home::home_dir;
913use run_script::ScriptOptions;
10use std::{env, io::Stdout, thread};
14use std::{env, error::Error, fs, io::Stdout, thread};
1115use tui::{backend::CrosstermBackend, Terminal};
1216use tui_additions::framework::Framework;
1317
@@ -59,6 +63,49 @@ pub fn run_single_command(
5963 // match a command splitted by space to a bunch of avaliable commands
6064 match command {
6165 [] => {}
66 ["bookmark", id] => {
67 match (|| -> Result<Item, Box<dyn Error>> {
68 Ok(serde_json::from_str(&fs::read_to_string(
69 home_dir()
70 .unwrap()
71 .join(format!(".cache/youtube-tui/info/{id}.json")),
72 )?)?)
73 })() {
74 Ok(item) => {
75 let library = framework.data.global.get_mut::<Library>().unwrap();
76 let _ = library.push(item, None);
77 let _ = library.save();
78 *framework.data.global.get_mut::<Message>().unwrap() =
79 Message::Success(String::from("Item bookmarked"))
80 }
81 Err(e) => {
82 *framework.data.global.get_mut::<Message>().unwrap() =
83 Message::Error(format!("Unknown item: {e}"))
84 }
85 }
86 }
87 ["unmark", id] => {
88 let library = framework.data.global.get_mut::<Library>().unwrap();
89
90 if library.remove(id) {
91 let _ = library.save();
92 *framework.data.global.get_mut::<Message>().unwrap() =
93 Message::Success(String::from("Bookmark removed"))
94 } else {
95 *framework.data.global.get_mut::<Message>().unwrap() =
96 Message::Error(String::from("No item with that ID found"))
97 }
98 }
99 ["togglemark", id] => {
100 let library = framework.data.global.get_mut::<Library>().unwrap();
101 if library.remove(id) {
102 let _ = library.save();
103 *framework.data.global.get_mut::<Message>().unwrap() =
104 Message::Success(String::from("Bookmark removed"))
105 } else {
106 run_single_command(&["bookmark", id], framework, terminal);
107 }
108 }
62109 ["help"] | ["h"] => {
63110 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
64111 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
@@ -361,6 +408,11 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
361408 \x1b[33mrun [command]\x1b[0m Runs a system command (e.g. `run firefox example.com`)
362409 \x1b[33mcopy [text]\x1b[0m Copies text to clipboard
363410
411\x1b[91mLIBRARY:\x1b[0m
412 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded)
413 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID
414 \x1b[33mtogglemark [id]\x1b[0m Toggle bookmark status
415
364416\x1b[91mALT:\x1b[0m
365417\x1b[37malts links back to the original command\x1b[30m
366418 \x1b[33m[page] (additional options)\x1b[0m `loadpage [page]`
src/global/structs/library.rs added +24
@@ -0,0 +1,24 @@
1use crate::global::traits::Collection;
2
3use super::Item;
4use serde::{Deserialize, Serialize};
5use typemap::Key;
6
7#[derive(Clone, Default, Serialize, Deserialize)]
8pub struct Library(pub Vec<Item>);
9
10impl Key for Library {
11 type Value = Self;
12}
13
14impl Collection for Library {
15 const INDEX_PATH: &'static str = ".local/share/youtube-tui/library.json";
16
17 fn items(&self) -> &Vec<Item> {
18 &self.0
19 }
20
21 fn items_mut(&mut self) -> &mut Vec<Item> {
22 &mut self.0
23 }
24}
src/global/structs/mod.rs +2
@@ -3,6 +3,7 @@ mod errors;
33mod invidiousclient;
44mod item;
55mod keyaction;
6mod library;
67mod message;
78mod page;
89mod state_env;
@@ -14,6 +15,7 @@ pub use errors::*;
1415pub use invidiousclient::*;
1516pub use item::*;
1617pub use keyaction::*;
18pub use library::*;
1719pub use message::*;
1820pub use page::*;
1921pub use state_env::*;
src/global/structs/watchhistory.rs +8 −145
@@ -1,11 +1,7 @@
1use crate::global::traits::Collection;
2
13use super::Item;
2use home::home_dir;
34use serde::{Deserialize, Serialize};
4use std::{
5 error::Error,
6 fs::{self, OpenOptions},
7 io::Write,
8};
95use typemap::Key;
106
117#[derive(Clone, Default, Serialize, Deserialize)]
@@ -15,147 +11,14 @@ impl Key for WatchHistory {
1511 type Value = Self;
1612}
1713
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_pretty(
22 &self
23 .0
24 .iter()
25 .map(|item| item.id().unwrap_or_default())
26 .filter(|id| !id.is_empty())
27 .collect::<Vec<&str>>(),
28 )?;
29 let path = home_dir()
30 .unwrap()
31 .join(".local/share/youtube-tui/watch_history/index.json");
32
33 let mut file = OpenOptions::new()
34 .write(true)
35 .create(true)
36 .truncate(true)
37 .open(path)?;
38
39 file.write_all(save_string.as_bytes())?;
40
41 Ok(())
42 }
43
44 /// add an item to watch history
45 pub fn push(&mut self, item: Item, max_items: usize) -> Result<(), Box<dyn Error>> {
46 let info = home_dir()
47 .unwrap()
48 .join(".local/share/youtube-tui/watch_history/info/");
49
50 // removes duplicates and place them on top (if exists)
51 let id = item.id().unwrap_or("invalid-dump");
52 if let Some(index) = self
53 .0
54 .iter()
55 .position(|item_in_iter| item_in_iter.id().unwrap_or_default() == id)
56 {
57 let _ = fs::remove_file(info.join(format!("{id}.json")));
58 self.0.remove(index);
59 }
60 let mut file = OpenOptions::new()
61 .write(true)
62 .create(true)
63 .truncate(true)
64 .open(info.join(format!("{id}.json")))?;
65 let item_string = serde_json::to_string(&item)?;
66 file.write_all(item_string.as_bytes())?;
67
68 self.0.push(item);
69
70 // if length of history exceeds the maximum history length, removes that oldest item
71 if self.0.len() > max_items {
72 let _ = fs::remove_file(
73 info.join(format!("{}.json", self.0[0].id().unwrap_or("invalid-dump"))),
74 );
75 self.0.remove(0);
76 }
14impl Collection for WatchHistory {
15 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
7716
78 Ok(())
17 fn items(&self) -> &Vec<Item> {
18 &self.0
7919 }
8020
81 /// loads watch history from file
82 pub fn load() -> Self {
83 let path = home_dir()
84 .unwrap()
85 .join(".local/share/youtube-tui/watch_history/index.json");
86 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
87 let file_string = fs::read_to_string(&path)?;
88 let deserialized = serde_json::from_str(&file_string)?;
89 Ok(deserialized)
90 })();
91
92 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
93 // which case returns Self::default()
94 if let Ok(deserialized) = res {
95 let info = home_dir()
96 .unwrap()
97 .join(".local/share/youtube-tui/watch_history/info/");
98 Self(
99 deserialized
100 .into_iter()
101 .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
102 .filter_map(|file_content| serde_json::from_str(&file_content).ok())
103 .collect(),
104 )
105 } else {
106 // if the file does exist, back it up
107 // if it doesn't exist, it will throw an error but we dont care
108 let mut new_path = path.clone();
109 new_path.pop();
110 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
111 let _ = fs::rename(&path, &new_path);
112
113 Self::default()
114 }
115 }
116
117 /// moves all thumbnails from storage to cache when starting
118 pub fn init_move() {
119 let history_thumbnails_path = home_dir()
120 .unwrap()
121 .join(".local/share/youtube-tui/watch_history/thumbnails/");
122 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
123
124 fs::read_dir(history_thumbnails_path)
125 .unwrap()
126 .into_iter()
127 .for_each(|path| {
128 let path = path.unwrap().path();
129 let _ = fs::rename(
130 path.clone(),
131 cache_thumbnails_path.join(path.file_name().unwrap()),
132 );
133 });
134 }
135
136 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
137 pub fn exit_move(&self) {
138 let history_thumbnails_path = home_dir()
139 .unwrap()
140 .join(".local/share/youtube-tui/watch_history/thumbnails/");
141 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
142
143 self.0.iter().for_each(|item| {
144 let id = item.id().unwrap();
145 let _ = fs::rename(
146 cache_thumbnails_path.join(id),
147 history_thumbnails_path.join(id),
148 );
149
150 if let Ok(fullplaylist) = item.fullplaylist() {
151 fullplaylist.videos.iter().for_each(|video| {
152 let id = video.id().unwrap_or("invalid-dump");
153 let _ = fs::rename(
154 cache_thumbnails_path.join(id),
155 history_thumbnails_path.join(id),
156 );
157 })
158 }
159 })
21 fn items_mut(&mut self) -> &mut Vec<Item> {
22 &mut self.0
16023 }
16124}
src/global/traits/collection.rs added +152
@@ -0,0 +1,152 @@
1use home::home_dir;
2use serde::{de::DeserializeOwned, Serialize};
3use std::{
4 error::Error,
5 fs::{self, OpenOptions},
6 io::Write,
7};
8use typemap::Key;
9
10use crate::global::structs::Item;
11
12pub trait Collection
13where
14 Self: Default + Clone + Serialize + DeserializeOwned + Key,
15{
16 const INDEX_PATH: &'static str;
17
18 fn items(&self) -> &Vec<Item>;
19 fn items_mut(&mut self) -> &mut Vec<Item>;
20
21 /// saves the current state of watch history into a file
22 fn save(&self) -> Result<(), Box<dyn Error>> {
23 let save_string = serde_json::to_string_pretty(
24 &self
25 .items()
26 .iter()
27 .map(|item| item.id().unwrap_or_default())
28 .filter(|id| !id.is_empty())
29 .collect::<Vec<&str>>(),
30 )?;
31 let path = home_dir().unwrap().join(Self::INDEX_PATH);
32
33 let mut file = OpenOptions::new()
34 .write(true)
35 .create(true)
36 .truncate(true)
37 .open(path)?;
38
39 file.write_all(save_string.as_bytes())?;
40
41 Ok(())
42 }
43
44 /// add an item to watch history
45 fn push(&mut self, item: Item, max_length: Option<usize>) -> Result<(), Box<dyn Error>> {
46 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
47
48 // removes duplicates and place them on top (if exists)
49 let id = item.id().unwrap_or("invalid-dump");
50 if let Some(index) = self
51 .items_mut()
52 .iter_mut()
53 .position(|item_in_iter| item_in_iter.id().unwrap_or_default() == id)
54 {
55 self.items_mut().remove(index);
56 }
57 let mut file = OpenOptions::new()
58 .write(true)
59 .create(true)
60 .truncate(true)
61 .open(info.join(format!("{id}.json")))?;
62 let item_string = serde_json::to_string(&item)?;
63 file.write_all(item_string.as_bytes())?;
64
65 self.items_mut().push(item);
66
67 // if length of history exceeds the maximum history length, removes that oldest item
68 if self.items().len() > max_length.unwrap_or(usize::MAX) {
69 self.items_mut().remove(0);
70 }
71
72 Ok(())
73 }
74
75 /// loads watch history from file
76 fn load() -> Vec<Item> {
77 let path = home_dir().unwrap().join(Self::INDEX_PATH);
78 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
79 let file_string = fs::read_to_string(&path)?;
80 let deserialized = serde_json::from_str(&file_string)?;
81 Ok(deserialized)
82 })();
83
84 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
85 // which case returns Self::default()
86 if let Ok(deserialized) = res {
87 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
88 deserialized
89 .into_iter()
90 .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
91 .filter_map(|file_content| serde_json::from_str(&file_content).ok())
92 .collect()
93 } else {
94 // if the file does exist, back it up
95 // if it doesn't exist, it will throw an error but we dont care
96 let mut new_path = path.clone();
97 new_path.pop();
98 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
99 let _ = fs::rename(&path, &new_path);
100
101 Vec::new()
102 }
103 }
104
105 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
106 fn exit_move(&self) {
107 let home_dir = home_dir().unwrap();
108 let store_thumbnails_path = home_dir.join(".local/share/youtube-tui/thumbnails/");
109 let store_info_path = home_dir.join(".local/share/youtube-tui/info/");
110 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
111 let cache_info_path = home_dir.join(".cache/youtube-tui/info");
112
113 self.items().iter().for_each(|item| {
114 let id = item.id().unwrap_or("invalid-dump");
115 let _ = fs::rename(
116 cache_thumbnails_path.join(id),
117 store_thumbnails_path.join(id),
118 );
119
120 let _ = fs::rename(
121 cache_info_path.join(format!("{id}.json")),
122 store_info_path.join(format!("{id}.json")),
123 );
124
125 if let Item::FullPlaylist(fullplaylist) = item {
126 fullplaylist.videos.iter().for_each(|video| {
127 let id = video.id().unwrap_or("invalid-dump");
128 let _ = fs::rename(
129 cache_thumbnails_path.join(id),
130 store_thumbnails_path.join(id),
131 );
132 })
133 }
134 })
135 }
136
137 /// remove item based on their id
138 fn remove(&mut self, id: &str) -> bool {
139 let items = self.items_mut();
140
141 if let Some(found) = items
142 .iter()
143 .enumerate()
144 .find(|(_index, item)| item.id() == Some(id))
145 {
146 items.remove(found.0);
147 true
148 } else {
149 false
150 }
151 }
152}
src/global/traits/mod.rs +2
@@ -1,8 +1,10 @@
11//! public traits
22mod asurlstring;
3mod collection;
34mod configtrait;
45mod searchfilteritem;
56
67pub use asurlstring::*;
8pub use collection::*;
79pub use configtrait::*;
810pub use searchfilteritem::*;
src/init.rs +29 −25
@@ -4,9 +4,11 @@ use crate::{
44 CommandsConfigSerde, KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
55 },
66 global::{
7 functions::run_command,
8 structs::{InvidiousClient, Message, Page, StateEnvs, Status, Tasks, WatchHistory},
9 traits::ConfigTrait,
7 functions::{init_move, run_command},
8 structs::{
9 InvidiousClient, Library, Message, Page, StateEnvs, Status, Tasks, WatchHistory,
10 },
11 traits::{Collection, ConfigTrait},
1012 },
1113};
1214use home::home_dir;
@@ -24,30 +26,36 @@ pub fn init(
2426 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
2527 command: Option<&str>,
2628) -> Result<(), Box<dyn Error>> {
27 // creating files
2829 let home_dir = home_dir().unwrap();
29 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
30 let history_thumbnails_path =
31 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/");
32 let history_info_path = home_dir.join(".local/share/youtube-tui/watch_history/info/");
33
34 if !&cache_thumbnails_path.exists() {
35 fs::create_dir_all(&cache_thumbnails_path).unwrap();
36 }
37
38 if !&history_thumbnails_path.exists() {
39 fs::create_dir_all(&history_thumbnails_path).unwrap();
40 }
4130
42 if !&history_info_path.exists() {
43 fs::create_dir_all(&history_info_path).unwrap();
44 }
31 // creating files
32 [
33 ".cache/youtube-tui/thumbnails/",
34 ".cache/youtube-tui/info/",
35 ".local/share/youtube-tui/thumbnails/",
36 ".local/share/youtube-tui/info/",
37 ".local/share/youtube-tui/saved/",
38 ]
39 .into_iter()
40 .for_each(|s| {
41 let dir = home_dir.join(s);
42 if !dir.exists() {
43 fs::create_dir_all(dir).unwrap();
44 }
45 });
4546
46 // watch history init
47 WatchHistory::init_move();
47 init_move();
4848
4949 load_configs(&mut framework.split_clean().0).ok();
5050
51 framework
52 .data
53 .global
54 .insert::<WatchHistory>(WatchHistory(WatchHistory::load()));
55 framework
56 .data
57 .global
58 .insert::<Library>(Library(Library::load()));
5159 framework.data.global.insert::<Message>(Message::None);
5260 framework.data.global.insert::<Status>(Status {
5361 provider: framework.data.global.get::<MainConfig>().unwrap().provider,
@@ -101,10 +109,6 @@ pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>
101109 .data
102110 .global
103111 .insert::<CommandsConfig>(CommandsConfig::from(*CommandsConfigSerde::load()?));
104 framework
105 .data
106 .global
107 .insert::<WatchHistory>(WatchHistory::load());
108112 framework
109113 .data
110114 .global
src/items/itemlist.rs +17 −15
@@ -1,5 +1,6 @@
11use std::error::Error;
22
3use home::home_dir;
34use tui::{
45 layout::{Constraint, Rect},
56 style::Style,
@@ -16,7 +17,7 @@ use crate::{
1617 functions::{download_all_images, set_envs, update_provider},
1718 structs::{
1819 ChannelDisplayPage, ChannelDisplayPageType, FullChannelItem, FullPlaylistItem,
19 FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage, Message,
20 FullVideoItem, InvidiousClient, Item, KeyAction, Library, MainMenuPage, Message,
2021 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, StateEnvs,
2122 Status, Task, Tasks, WatchHistory,
2223 },
@@ -40,7 +41,7 @@ impl ItemList {
4041 status: &Status,
4142 ) -> Vec<(String, String)> {
4243 if self.textlist.items.is_empty() {
43 return vec![];
44 return Vec::new();
4445 }
4546
4647 match &self.items[self.textlist.selected] {
@@ -125,8 +126,14 @@ impl ItemList {
125126
126127 /// handles select (enter)
127128 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
128 let page = framework.data.state.get::<Page>().unwrap();
129 let page_to_load = if *page == Page::MainMenu(MainMenuPage::History) {
129 let page_to_load = if home_dir()
130 .unwrap()
131 .join(format!(
132 ".cache/youtube-tui/info/{}.json",
133 self.items[self.textlist.selected].id().unwrap_or_default()
134 ))
135 .exists()
136 {
130137 match &self.items[self.textlist.selected] {
131138 Item::MiniVideo(MiniVideoItem { id, .. })
132139 | Item::FullVideo(FullVideoItem { id, .. }) => {
@@ -312,20 +319,15 @@ impl FrameworkItem for ItemList {
312319 .collect();
313320 }
314321 Page::MainMenu(MainMenuPage::Subscriptions) => {}
315 Page::MainMenu(MainMenuPage::Library) => {}
322 Page::MainMenu(MainMenuPage::Library) => {
323 let history = framework.data.global.get::<Library>().unwrap();
324 self.items = history.0.clone().into_iter().rev().collect();
325 }
316326 Page::MainMenu(MainMenuPage::History) => {
317327 // the vector needs to be reversed because the latest watch history is pushed to
318328 // the back, meaning it needs to be reversed so that the latests one are on top
319 self.items = framework
320 .data
321 .global
322 .get::<WatchHistory>()
323 .unwrap()
324 .0
325 .clone()
326 .into_iter()
327 .rev()
328 .collect();
329 let history = framework.data.global.get::<WatchHistory>().unwrap();
330 self.items = history.0.clone().into_iter().rev().collect();
329331 }
330332 Page::Search(search) => {
331333 self.items = client
src/items/singleitem.rs +31 −15
@@ -9,6 +9,7 @@ use crate::{
99 InvidiousClient, Item, KeyAction, Message, Page, SingleItemPage, StateEnvs, Status,
1010 Task, Tasks, WatchHistory,
1111 },
12 traits::Collection,
1213 },
1314};
1415use home::home_dir;
@@ -70,21 +71,25 @@ pub struct SinglePlaylistItem {
7071
7172impl SingleVideoItem {
7273 pub fn new(commands: &CommandsConfig) -> Self {
73 Self::new_with_map(commands
74 Self::new_with_map(
75 commands
7476 .video
7577 .clone()
7678 .into_iter()
7779 .map(|(display, command)| (display, command))
78 .collect())
80 .collect(),
81 )
7982 }
8083
8184 pub fn new_local(commands: &CommandsConfig) -> Self {
82 Self::new_with_map(commands
85 Self::new_with_map(
86 commands
8387 .local_video
8488 .clone()
8589 .into_iter()
8690 .map(|(display, command)| (display, command))
87 .collect())
91 .collect(),
92 )
8893 }
8994
9095 pub fn new_with_map(commands: Vec<(String, String)>) -> Self {
@@ -182,21 +187,27 @@ impl SingleVideoItem {
182187
183188impl SinglePlaylistItem {
184189 pub fn new(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
185 Self::new_with_map(commands
190 Self::new_with_map(
191 commands
186192 .playlist
187193 .clone()
188194 .into_iter()
189195 .map(|(display, command)| (display, command))
190 .collect(), playlist_items)
196 .collect(),
197 playlist_items,
198 )
191199 }
192200
193201 pub fn new_local(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
194 Self::new_with_map(commands
202 Self::new_with_map(
203 commands
195204 .local_playlist
196205 .clone()
197206 .into_iter()
198207 .map(|(display, command)| (display, command))
199 .collect(), playlist_items)
208 .collect(),
209 playlist_items,
210 )
200211 }
201212
202213 pub fn new_with_map(commands: Vec<(String, String)>, playlist_items: &[Item]) -> Self {
@@ -659,9 +670,11 @@ impl FrameworkItem for SingleItem {
659670 Some(playlist)
660671 }
661672 SingleItemPage::LocalVideo(id) => {
662 let s = fs::read_to_string(home_dir().unwrap().join(format!(
663 ".local/share/youtube-tui/watch_history/info/{id}.json"
664 )))?;
673 let s = fs::read_to_string(
674 home_dir()
675 .unwrap()
676 .join(format!(".cache/youtube-tui/info/{id}.json")),
677 )?;
665678 self.r#type = SingleItemType::Video(SingleVideoItem::new_local(
666679 framework.data.global.get::<CommandsConfig>().unwrap(),
667680 ));
@@ -670,9 +683,11 @@ impl FrameworkItem for SingleItem {
670683 }
671684
672685 SingleItemPage::LocalPlaylist(id) => {
673 let s = fs::read_to_string(home_dir().unwrap().join(format!(
674 ".local/share/youtube-tui/watch_history/info/{id}.json"
675 )))?;
686 let s = fs::read_to_string(
687 home_dir()
688 .unwrap()
689 .join(format!(".cache/youtube-tui/info/{id}.json")),
690 )?;
676691
677692 let playlist: Item = serde_json::from_str(&s)?;
678693 let videos = &playlist.fullplaylist()?.videos;
@@ -704,13 +719,14 @@ impl FrameworkItem for SingleItem {
704719
705720 // push to watch history
706721 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
707 watch_history.push(item, max_watch_history)?;
722 watch_history.push(item, Some(max_watch_history))?;
708723 watch_history.save()?;
709724 }
710725
711726 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
712727 // need to update provider every time the item loads or else it will display `${provider}`
713728 // instead of the actual provider (e.g. `YouTube`)
729
714730 set_envs(
715731 self.r#type
716732 .inflate_load(