src/app/pages/item_info.rs
344 lines · 12602 bytes
1use std::{
2 collections::LinkedList,
3 process::Command,
4 sync::{Arc, Mutex},
5 thread,
6};
7
8use crate::{
9 app::{app::App, pages::global::*},
10 functions::{download_all_thumbnails, ItemType},
11 structs::{FullVideo, Item, ListItem, Page, Row, RowItem},
12 traits::{KeyInput, LoadItem, SelectItem},
13 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
14};
15use crossterm::event::KeyCode;
16use tui::{
17 backend::Backend,
18 layout::{Constraint, Rect},
19 style::{Color, Style},
20 Frame,
21};
22
23use super::global::GlobalItem;
24
25#[derive(Debug, Clone)]
26pub enum ItemInfoItem {
27 Unknown,
28 Video(VideoItemInfo),
29}
30
31#[derive(Debug, Clone)]
32pub struct VideoItemInfo {
33 video: FullVideo,
34 list: TextList,
35 mode: Mode,
36}
37
38impl SelectItem for ItemInfoItem {
39 fn select(&mut self, app: App) -> (App, bool) {
40 let selected = true;
41
42 (app, selected)
43 }
44
45 fn selectable(&self) -> bool {
46 true
47 }
48}
49
50impl KeyInput for ItemInfoItem {
51 fn key_input(&mut self, key: KeyCode, mut app: App) -> (bool, App) {
52 match self {
53 ItemInfoItem::Video(videoinfo) => match key {
54 KeyCode::Up => videoinfo.list.up(),
55 KeyCode::Down => videoinfo.list.down(),
56 KeyCode::PageUp => videoinfo.list.selected = 0,
57 KeyCode::PageDown => videoinfo.list.selected = videoinfo.list.items.len() - 1,
58 KeyCode::Enter => {
59 if videoinfo.list.selected < 5 {
60 *app.message.lock().unwrap() = Some(String::from("Launched application"));
61 }
62 match videoinfo.list.selected {
63 0 => {
64 let command = vec![
65 String::from("mpv"),
66 String::from("--no-terminal"),
67 match videoinfo.mode {
68 Mode::Youtube => {
69 format!("https://youtu.be/{}", videoinfo.video.video_id)
70 }
71 Mode::Invidious => {
72 format!(
73 "{}/embed/{}",
74 app.client.server, videoinfo.video.video_id
75 )
76 }
77 },
78 ];
79
80 run_command(command, app.message.clone());
81 }
82 1 => {
83 let command = vec![
84 String::from("konsole"),
85 String::from("-e"),
86 String::from("mpv"),
87 String::from("--no-video"),
88 match videoinfo.mode {
89 Mode::Youtube => {
90 format!("https://youtu.be/{}", videoinfo.video.video_id)
91 }
92 Mode::Invidious => {
93 format!(
94 "{}/embed/{}",
95 app.client.server, videoinfo.video.video_id
96 )
97 }
98 },
99 ];
100
101 run_command(command, app.message.clone());
102 }
103 2 => {
104 let command = vec![
105 String::from("konsole"),
106 String::from("-e"),
107 String::from("yt-dlp"),
108 match videoinfo.mode {
109 Mode::Youtube => {
110 format!("https://youtu.be/{}", videoinfo.video.video_id)
111 }
112 Mode::Invidious => {
113 format!(
114 "{}/embed/{}",
115 app.client.server, videoinfo.video.video_id
116 )
117 }
118 },
119 String::from("-o"),
120 String::from("~/Downloads/%(title)s.%(ext)s"),
121 ];
122 run_command(command, app.message.clone());
123 }
124 3 => {
125 let command = vec![
126 String::from("konsole"),
127 String::from("-e"),
128 String::from("yt-dlp"),
129 match videoinfo.mode {
130 Mode::Youtube => {
131 format!("https://youtu.be/{}", videoinfo.video.video_id)
132 }
133 Mode::Invidious => {
134 format!(
135 "{}/embed/{}",
136 app.client.server, videoinfo.video.video_id
137 )
138 }
139 },
140 String::from("-o"),
141 String::from("~/Downloads/%(title)s.%(ext)s"),
142 String::from("-x"),
143 ];
144 run_command(command, app.message.clone());
145 }
146 4 => {
147 let mut dir = home::home_dir().unwrap();
148
149 dir.push(".cache");
150 dir.push("youtube-tui");
151 dir.push("thumbnails");
152 dir.push("videos");
153 dir.push(format!("{}.png", videoinfo.video.video_id));
154 let command = vec![
155 String::from("mpv"),
156 String::from("--no-terminal"),
157 (*dir.as_path().to_string_lossy()).to_string(),
158 ];
159
160 run_command(command, app.message.clone());
161 }
162 5 => {
163 *app.message.lock().unwrap() = Some(String::from(
164 "Too lazy to implement that what do you expect?",
165 ));
166 }
167 6 => {
168 videoinfo.mode.toggle();
169 }
170
171 _ => {}
172 }
173 }
174 _ => {}
175 },
176 _ => {}
177 }
178
179 (true, app)
180 }
181}
182
183impl LoadItem for ItemInfoItem {
184 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
185 let mut this = self.clone();
186
187 if let ItemInfoItem::Unknown = this {
188 match &app.page {
189 Page::ItemDisplay(display_item) => match display_item {
190 DisplayItem::Video(id) => {
191 let mut list = TextList::default();
192 let video: FullVideo = app.client.video(id, None)?.into();
193 let _ = download_all_thumbnails(LinkedList::from([(
194 video.video_thumbnail.clone(),
195 video.video_id.clone(),
196 ItemType::Video,
197 )]));
198 list.items(vec![
199 String::from("Watch video"),
200 String::from("Play audio"),
201 String::from("Download video"),
202 String::from("Download audio"),
203 String::from("View thumbnail"),
204 String::from("Visit channel"),
205 String::from("Mode placeholder"),
206 ]);
207 this = ItemInfoItem::Video(VideoItemInfo {
208 video,
209 list,
210 mode: Mode::Youtube,
211 });
212 }
213 },
214
215 _ => {}
216 }
217 }
218 Ok(Box::new(this))
219 }
220}
221
222impl ItemInfoItem {
223 pub fn render_item<B: Backend>(
224 &mut self,
225 frame: &mut Frame<B>,
226 rect: Rect,
227 selected: bool,
228 hover: bool,
229 ) {
230 match self {
231 ItemInfoItem::Video(videoinfo) => {
232 let index = videoinfo.list.items.len() - 1;
233 videoinfo.list.items[index] = format!("Mode: {}", videoinfo.mode);
234 drop(index);
235
236 let split = HorizontalSplit::default()
237 .percentages(vec![40, 60])
238 .border_style(Style::default().fg(if selected {
239 Color::LightBlue
240 } else if hover {
241 Color::LightRed
242 } else {
243 Color::Reset
244 }));
245
246 let chunks = split.inner(rect);
247 let mut list = videoinfo.list.clone();
248
249 list.area(chunks[1]);
250 if selected {
251 list.selected_style(Style::default().fg(Color::LightRed));
252 } else {
253 list.selected_style(Style::default().fg(Color::LightYellow));
254 }
255
256 frame.render_widget(split, rect);
257
258 let item_display = ItemDisplay {
259 item: ListItem::FullVideo(videoinfo.video.clone()),
260 };
261
262 frame.render_widget(item_display, chunks[0]);
263
264 frame.render_widget(list, chunks[1]);
265 }
266
267 ItemInfoItem::Unknown => {
268 let split = HorizontalSplit::default()
269 .percentages(vec![40, 60])
270 .border_style(Style::default().fg(if selected {
271 Color::LightBlue
272 } else if hover {
273 Color::LightRed
274 } else {
275 Color::Reset
276 }));
277 frame.render_widget(split, rect);
278 }
279 }
280 }
281}
282
283#[derive(Debug, Clone, PartialEq)]
284pub enum DisplayItem {
285 Video(String),
286}
287
288pub struct ItemInfo;
289
290impl ItemInfo {
291 pub fn message() -> String {
292 String::from("Loading item info...")
293 }
294
295 pub fn default() -> Vec<Row> {
296 vec![
297 Row {
298 items: vec![RowItem {
299 item: Item::Global(GlobalItem::SearchBar(String::new())),
300 constraint: Constraint::Percentage(100),
301 }],
302 centered: false,
303 height: Constraint::Length(3),
304 },
305 Row {
306 items: vec![RowItem {
307 item: Item::ItemInfo(ItemInfoItem::Unknown),
308 constraint: Constraint::Percentage(100),
309 }],
310 centered: false,
311 height: Constraint::Min(6),
312 },
313 Row {
314 items: vec![RowItem {
315 item: Item::Global(GlobalItem::MessageBar),
316 constraint: Constraint::Percentage(100),
317 }],
318 centered: false,
319 height: Constraint::Length(3),
320 },
321 ]
322 }
323}
324
325fn run_command(args: Vec<String>, message: Arc<Mutex<Option<String>>>) {
326 thread::spawn(move || {
327 let mut args = args.into_iter();
328 let mut command = Command::new(args.next().unwrap());
329 for arg in args {
330 command.arg(arg);
331 }
332
333 let res = command.spawn();
334 if let Err(e) = res {
335 *message.lock().unwrap() = Some(
336 e.to_string()
337 .lines()
338 .next()
339 .unwrap_or("An error occured")
340 .to_string(),
341 );
342 }
343 });
344}