src/app/pages/search.rs

2737f153106b44565bbbab1d0b08ab3067071283
youtube-tui/src/app/pages/search.rs history · blame · raw

308 lines · 10639 bytes

  1use std::collections::LinkedList;
  2
  3use crossterm::event::KeyCode;
  4use invidious::structs::hidden::SearchItem as InvidiousSearchItem;
  5use tui::{
  6    backend::Backend,
  7    layout::{Constraint, Rect},
  8    style::{Color, Style},
  9    Frame,
 10};
 11
 12use crate::{
 13    app::app::App,
 14    functions::download_all_thumbnails,
 15    structs::{Item, ListItem, MiniVideo, Page, Row, RowItem},
 16    traits::{KeyInput, LoadItem, SelectItem},
 17    widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
 18};
 19
 20use super::{
 21    global::GlobalItem,
 22    item_info::{DisplayItem, ItemInfo},
 23    main_menu::textlist_from_video_list,
 24};
 25
 26#[derive(Debug, Clone)]
 27pub enum SearchItem {
 28    Search {
 29        results: Option<LinkedList<ListItem>>,
 30        text_list: TextList,
 31    },
 32}
 33
 34impl SelectItem for SearchItem {
 35    fn select(&mut self, app: App) -> (App, bool) {
 36        (app, true)
 37    }
 38
 39    fn selectable(&self) -> bool {
 40        true
 41    }
 42}
 43
 44impl KeyInput for SearchItem {
 45    fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
 46        match self {
 47            SearchItem::Search { results, text_list } => match key {
 48                KeyCode::Up => text_list.up(),
 49                KeyCode::Down => text_list.down(),
 50                KeyCode::PageUp => text_list.selected = 0,
 51                KeyCode::PageDown => text_list.selected = text_list.items.len() - 1,
 52                KeyCode::Enter => {
 53                    if let Some(results_unwrapped) = results {
 54                        match results_unwrapped.iter().nth(text_list.selected).unwrap() {
 55                            ListItem::PageTurner(b) => {
 56                                let new_page_no;
 57                                if *b {
 58                                    new_page_no = app.page_no + 1;
 59                                } else {
 60                                    new_page_no = app.page_no - 1;
 61                                }
 62
 63                                *results = None;
 64                                *text_list = TextList::default();
 65
 66                                let state = Search::default();
 67                                let mut history = app.history.clone();
 68                                let search_text = app.search_text.clone();
 69                                let search_settings = app.search_settings.clone();
 70                                history.push(app.into());
 71
 72                                return (
 73                                    false,
 74                                    App {
 75                                        history,
 76                                        page: Page::Search,
 77                                        selectable: App::selectable(&state),
 78                                        state,
 79                                        search_text,
 80                                        search_settings,
 81                                        load: true,
 82                                        page_no: new_page_no,
 83                                        ..Default::default()
 84                                    },
 85                                );
 86                            }
 87
 88                            ListItem::MiniVideo(video) => {
 89                                let state = ItemInfo::default();
 90                                let mut history = app.history.clone();
 91                                history.push(app.into());
 92
 93                                return (
 94                                    false,
 95                                    App {
 96                                        history,
 97                                        page: Page::ItemDisplay(DisplayItem::Video(
 98                                            video.video_id.clone(),
 99                                        )),
100                                        selectable: App::selectable(&state),
101                                        state,
102                                        ..Default::default()
103                                    },
104                                );
105                            }
106
107                            _ => {}
108                        }
109                    }
110                }
111                _ => {}
112            },
113        }
114
115        (true, app)
116    }
117}
118
119impl LoadItem for SearchItem {
120    fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
121        let mut this = self.clone();
122
123        match &mut this {
124            SearchItem::Search { results, text_list } => {
125                // panic!("got here");
126                if app.search_text.len() == 0 {
127                    *app.message.lock().unwrap() =
128                        Some(String::from("Search term cannot be empty"));
129                } else {
130                    let mut args = vec![app.search_text.clone()];
131                    args.extend(app.search_settings.clone().to_vec());
132
133                    let invidious_results = app
134                        .client
135                        .search(Some(&format!(
136                            "page={}&q={}",
137                            app.page_no,
138                            args.join("&").as_str()
139                        )))?
140                        .items;
141
142                    let mut items = LinkedList::new();
143
144                    for item in invidious_results {
145                        match item {
146                            InvidiousSearchItem::Video {
147                                title: _,
148                                videoId: _,
149                                author: _,
150                                authorId: _,
151                                authorUrl: _,
152                                lengthSeconds: _,
153                                videoThumbnails: _,
154                                description: _,
155                                descriptionHtml: _,
156                                viewCount: _,
157                                published: _,
158                                publishedText: _,
159                                liveNow: _,
160                                paid: _,
161                                premium: _,
162                            } => {
163                                items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
164                            }
165
166                            _ => {}
167                        }
168                    }
169
170                    let mut minimum_length = 0;
171
172                    if app.page_no != 1 {
173                        minimum_length += 1;
174                        items.push_front(ListItem::PageTurner(false));
175                    }
176
177                    if items.len() == minimum_length {
178                        *app.message.lock().unwrap() = Some(String::from("No results found"));
179                    } else {
180                        items.push_back(ListItem::PageTurner(true));
181                    }
182
183                    text_list.items = textlist_from_video_list(&items);
184
185                    let mut thumbnails = LinkedList::new();
186
187                    for item in items.iter() {
188                        match item {
189                            ListItem::MiniVideo(video) => {
190                                thumbnails.push_back((
191                                    video.video_thumbnail.clone(),
192                                    video.video_id.clone(),
193                                ));
194                            }
195
196                            _ => {}
197                        }
198                    }
199
200                    let _ = download_all_thumbnails(thumbnails);
201
202                    *results = Some(items);
203                }
204            }
205        }
206
207        Ok(Box::new(this))
208    }
209}
210
211impl SearchItem {
212    pub fn render_item<B: Backend>(
213        &mut self,
214        frame: &mut Frame<B>,
215        rect: Rect,
216        selected: bool,
217        hover: bool,
218        popup_focus: bool,
219    ) {
220
221        match self {
222            SearchItem::Search { results, text_list } => {
223                let split = HorizontalSplit::default()
224                    .percentages(vec![60, 40])
225                    .border_style(Style::default().fg(if selected {
226                        Color::LightBlue
227                    } else if hover {
228                        Color::LightRed
229                    } else {
230                        Color::Reset
231                    }));
232
233                let chunks = split.inner(rect);
234
235                frame.render_widget(split, rect);
236
237                text_list.area(chunks[0]);
238                let mut text_list = text_list.clone();
239
240                if let Some(result) = results {
241                    if let Some(item) = result.iter().nth(text_list.selected) {
242                        if !popup_focus {
243                            frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
244                        }
245                    }
246                }
247
248                if selected {
249                    text_list.selected_style(Style::default().fg(Color::LightRed));
250                } else {
251                    text_list.selected_style(Style::default().fg(Color::LightYellow));
252                }
253
254                frame.render_widget(text_list, chunks[0]);
255            }
256        }
257    }
258}
259
260pub struct Search;
261
262impl Search {
263    pub fn message() -> String {
264        String::from("Loading search results...")
265    }
266
267    pub fn min() -> (u16, u16) {
268        (45, 12)
269    }
270
271    pub fn default() -> Vec<Row> {
272        vec![
273            Row {
274                items: vec![
275                    RowItem {
276                        item: Item::Global(GlobalItem::SearchBar),
277                        constraint: Constraint::Min(16),
278                    },
279                    RowItem {
280                        item: Item::Global(GlobalItem::SearchSettings),
281                        constraint: Constraint::Length(5),
282                    },
283                ],
284                centered: false,
285                height: Constraint::Length(3),
286            },
287            Row {
288                items: vec![RowItem {
289                    item: Item::Search(SearchItem::Search {
290                        results: None,
291                        text_list: TextList::default(),
292                    }),
293                    constraint: Constraint::Percentage(100),
294                }],
295                centered: false,
296                height: Constraint::Min(6),
297            },
298            Row {
299                items: vec![RowItem {
300                    item: Item::Global(GlobalItem::MessageBar),
301                    constraint: Constraint::Percentage(100),
302                }],
303                centered: false,
304                height: Constraint::Length(3),
305            },
306        ]
307    }
308}