src/app/pages/item_info.rs
424 lines · 17336 bytes
1use std::{
2 collections::LinkedList,
3 process::Command,
4 sync::{Arc, Mutex},
5 thread,
6};
7
8use crate::{
9 app::{app::App, config::EnvVar, pages::global::*},
10 functions::download_all_thumbnails,
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
63 match videoinfo.list.selected {
64 0 => {
65 app.watch_history.push(
66 videoinfo.video.video_id.clone(),
67 ListItem::FullVideo(videoinfo.video.clone()),
68 &app.config,
69 );
70 let command =
71 match app.config.commands.video_player.clone().as_command_vec(
72 EnvVar {
73 url: Some(match videoinfo.mode {
74 Mode::Youtube => {
75 format!(
76 "https://youtu.be/{}",
77 videoinfo.video.video_id
78 )
79 }
80 Mode::Invidious => {
81 format!(
82 "{}/embed/{}",
83 app.client.server, videoinfo.video.video_id
84 )
85 }
86 }),
87 ..Default::default()
88 },
89 &app.config,
90 ) {
91 Ok(command) => command,
92 Err(_) => {
93 *app.message.lock().unwrap() =
94 Some(String::from("Error in parsing launch command"));
95 return (false, app);
96 }
97 };
98
99 run_command(command, app.message.clone());
100 }
101 1 => {
102 app.watch_history.push(
103 videoinfo.video.video_id.clone(),
104 ListItem::FullVideo(videoinfo.video.clone()),
105 &app.config,
106 );
107 let command =
108 match app.config.commands.audio_player.clone().as_command_vec(
109 EnvVar {
110 url: Some(match videoinfo.mode {
111 Mode::Youtube => {
112 format!(
113 "https://youtu.be/{}",
114 videoinfo.video.video_id
115 )
116 }
117 Mode::Invidious => {
118 format!(
119 "{}/embed/{}",
120 app.client.server, videoinfo.video.video_id
121 )
122 }
123 }),
124 ..Default::default()
125 },
126 &app.config,
127 ) {
128 Ok(command) => command,
129 Err(_) => {
130 *app.message.lock().unwrap() =
131 Some(String::from("Error in parsing launch command"));
132 return (false, app);
133 }
134 };
135
136 run_command(command, app.message.clone());
137 }
138 2 => {
139 app.watch_history.push(
140 videoinfo.video.video_id.clone(),
141 ListItem::FullVideo(videoinfo.video.clone()),
142 &app.config,
143 );
144 let command =
145 match app.config.commands.video_downloader.clone().as_command_vec(
146 EnvVar {
147 url: Some(match videoinfo.mode {
148 Mode::Youtube => {
149 format!(
150 "https://youtu.be/{}",
151 videoinfo.video.video_id
152 )
153 }
154 Mode::Invidious => {
155 format!(
156 "{}/embed/{}",
157 app.client.server, videoinfo.video.video_id
158 )
159 }
160 }),
161 ..Default::default()
162 },
163 &app.config,
164 ) {
165 Ok(command) => command,
166 Err(_) => {
167 *app.message.lock().unwrap() =
168 Some(String::from("Error in parsing launch command"));
169 return (false, app);
170 }
171 };
172
173 run_command(command, app.message.clone());
174 }
175 3 => {
176 app.watch_history.push(
177 videoinfo.video.video_id.clone(),
178 ListItem::FullVideo(videoinfo.video.clone()),
179 &app.config,
180 );
181 let command =
182 match app.config.commands.audio_downloader.clone().as_command_vec(
183 EnvVar {
184 url: Some(match videoinfo.mode {
185 Mode::Youtube => {
186 format!(
187 "https://youtu.be/{}",
188 videoinfo.video.video_id
189 )
190 }
191 Mode::Invidious => {
192 format!(
193 "{}/embed/{}",
194 app.client.server, videoinfo.video.video_id
195 )
196 }
197 }),
198 ..Default::default()
199 },
200 &app.config,
201 ) {
202 Ok(command) => command,
203 Err(_) => {
204 *app.message.lock().unwrap() =
205 Some(String::from("Error in parsing launch command"));
206 return (false, app);
207 }
208 };
209
210 run_command(command, app.message.clone());
211 }
212 4 => {
213 let mut dir = home::home_dir().unwrap();
214
215 dir.push(".cache");
216 dir.push("youtube-tui");
217 dir.push("thumbnails");
218 dir.push(format!("{}.png", videoinfo.video.video_id));
219 // let command = vec![
220 // String::from("mpv"),
221 // String::from("--no-terminal"),
222 // (*dir.as_path().to_string_lossy()).to_string(),
223 // ];
224
225 let command =
226 match app.config.commands.image_viewer.clone().as_command_vec(
227 EnvVar {
228 url: Some((*dir.as_path().to_string_lossy()).to_string()),
229 ..Default::default()
230 },
231 &app.config,
232 ) {
233 Ok(command) => command,
234 Err(_) => {
235 *app.message.lock().unwrap() =
236 Some(String::from("Error in parsing launch command"));
237 return (false, app);
238 }
239 };
240
241 run_command(command, app.message.clone());
242 }
243 5 => {
244 *app.message.lock().unwrap() = Some(String::from(
245 "Too lazy to implement that what do you expect?",
246 ));
247 }
248 6 => {
249 videoinfo.mode.toggle();
250 }
251
252 _ => {}
253 }
254 }
255 _ => {}
256 },
257 _ => {}
258 }
259
260 (true, app)
261 }
262}
263
264impl LoadItem for ItemInfoItem {
265 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
266 let mut this = self.clone();
267
268 if let ItemInfoItem::Unknown = this {
269 match &app.page {
270 Page::ItemDisplay(display_item) => match display_item {
271 DisplayItem::Video(id) => {
272 let mut list = TextList::default();
273 let video: FullVideo = app.client.video(id, None)?.into();
274 let _ = download_all_thumbnails(LinkedList::from([(
275 video.video_thumbnail.clone(),
276 video.video_id.clone(),
277 )]));
278 list.items(vec![
279 String::from("Watch video"),
280 String::from("Play audio"),
281 String::from("Download video"),
282 String::from("Download audio"),
283 String::from("View thumbnail"),
284 String::from("Visit channel"),
285 String::from("Mode placeholder"),
286 ]);
287 this = ItemInfoItem::Video(VideoItemInfo {
288 video,
289 list,
290 mode: Mode::Youtube,
291 });
292 }
293 },
294
295 _ => {}
296 }
297 }
298 Ok(Box::new(this))
299 }
300}
301
302impl ItemInfoItem {
303 pub fn render_item<B: Backend>(
304 &mut self,
305 frame: &mut Frame<B>,
306 rect: Rect,
307 selected: bool,
308 hover: bool,
309 ) {
310 match self {
311 ItemInfoItem::Video(videoinfo) => {
312 let index = videoinfo.list.items.len() - 1;
313 videoinfo.list.items[index] = format!("Mode: {}", videoinfo.mode);
314 drop(index);
315
316 let split = HorizontalSplit::default()
317 .percentages(vec![40, 60])
318 .border_style(Style::default().fg(if selected {
319 Color::LightBlue
320 } else if hover {
321 Color::LightRed
322 } else {
323 Color::Reset
324 }));
325
326 let chunks = split.inner(rect);
327 let mut list = videoinfo.list.clone();
328
329 list.area(chunks[1]);
330 if selected {
331 list.selected_style(Style::default().fg(Color::LightRed));
332 } else {
333 list.selected_style(Style::default().fg(Color::LightYellow));
334 }
335
336 frame.render_widget(split, rect);
337
338 let item_display = ItemDisplay {
339 item: ListItem::FullVideo(videoinfo.video.clone()),
340 };
341
342 frame.render_widget(item_display, chunks[0]);
343
344 frame.render_widget(list, chunks[1]);
345 }
346
347 ItemInfoItem::Unknown => {
348 let split = HorizontalSplit::default()
349 .percentages(vec![40, 60])
350 .border_style(Style::default().fg(if selected {
351 Color::LightBlue
352 } else if hover {
353 Color::LightRed
354 } else {
355 Color::Reset
356 }));
357 frame.render_widget(split, rect);
358 }
359 }
360 }
361}
362
363#[derive(Debug, Clone, PartialEq)]
364pub enum DisplayItem {
365 Video(String),
366}
367
368pub struct ItemInfo;
369
370impl ItemInfo {
371 pub fn message() -> String {
372 String::from("Loading item info...")
373 }
374
375 pub fn default() -> Vec<Row> {
376 vec![
377 Row {
378 items: vec![RowItem {
379 item: Item::Global(GlobalItem::SearchBar(String::new())),
380 constraint: Constraint::Percentage(100),
381 }],
382 centered: false,
383 height: Constraint::Length(3),
384 },
385 Row {
386 items: vec![RowItem {
387 item: Item::ItemInfo(ItemInfoItem::Unknown),
388 constraint: Constraint::Percentage(100),
389 }],
390 centered: false,
391 height: Constraint::Min(6),
392 },
393 Row {
394 items: vec![RowItem {
395 item: Item::Global(GlobalItem::MessageBar),
396 constraint: Constraint::Percentage(100),
397 }],
398 centered: false,
399 height: Constraint::Length(3),
400 },
401 ]
402 }
403}
404
405fn run_command(args: Vec<String>, message: Arc<Mutex<Option<String>>>) {
406 thread::spawn(move || {
407 let mut args = args.into_iter();
408 let mut command = Command::new(args.next().unwrap());
409 for arg in args {
410 command.arg(arg);
411 }
412
413 let res = command.spawn();
414 if let Err(e) = res {
415 *message.lock().unwrap() = Some(
416 e.to_string()
417 .lines()
418 .next()
419 .unwrap_or("An error occured")
420 .to_string(),
421 );
422 }
423 });
424}