src/app/pages/search.rs

6f8b64c4fa1b89868a2dbaa1bbd9fda20ecd0768
youtube-tui/src/app/pages/search.rs history · blame · raw

337 lines · 11860 bytes

  1use std::{collections::LinkedList, error::Error};
  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, MiniPlayList, MiniVideo, Page, Row, RowItem},
 16    traits::{KeyInput, 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                            ListItem::MiniPlayList(playlist) => {
108                                let state = ItemInfo::default();
109                                let mut history = app.history.clone();
110                                history.push(app.into());
111
112                                return (
113                                    false,
114                                    App {
115                                        history,
116                                        page: Page::ItemDisplay(DisplayItem::PlayList(
117                                            playlist.playlist_id.clone(),
118                                        )),
119                                        selectable: App::selectable(&state),
120                                        state,
121                                        ..Default::default()
122                                    },
123                                );
124                            }
125
126                            _ => {}
127                        }
128                    }
129                }
130                _ => {}
131            },
132        }
133
134        (true, app)
135    }
136}
137
138impl SearchItem {
139    pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
140        let mut this = self.clone();
141
142        match &mut this {
143            SearchItem::Search { results, text_list } => {
144                // panic!("got here");
145
146                let mut args = vec![app.search_text.clone()];
147                args.extend(app.search_settings.clone().to_vec());
148
149                let invidious_results = app
150                    .client
151                    .search(Some(&format!(
152                        "page={}&q={}",
153                        app.page_no,
154                        args.join("&").as_str()
155                    )))?
156                    .items;
157
158                let mut items = LinkedList::new();
159
160                for item in invidious_results {
161                    match item {
162                        InvidiousSearchItem::Video {
163                            title: _,
164                            videoId: _,
165                            author: _,
166                            authorId: _,
167                            authorUrl: _,
168                            lengthSeconds: _,
169                            videoThumbnails: _,
170                            description: _,
171                            descriptionHtml: _,
172                            viewCount: _,
173                            published: _,
174                            publishedText: _,
175                            liveNow: _,
176                            paid: _,
177                            premium: _,
178                        } => {
179                            items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
180                        }
181
182                        InvidiousSearchItem::Playlist {
183                            title: _,
184                            playlistId: _,
185                            author: _,
186                            authorId: _,
187                            authorUrl: _,
188                            videoCount: _,
189                            videos: _,
190                        } => {
191                            items.push_back(ListItem::MiniPlayList(MiniPlayList::from(item)));
192                        }
193
194                        _ => {}
195                    }
196                }
197
198                let mut minimum_length = 0;
199
200                if app.page_no != 1 {
201                    minimum_length += 1;
202                    items.push_front(ListItem::PageTurner(false));
203                }
204
205                if items.len() == minimum_length {
206                    *app.message.lock().unwrap() = Some(String::from("No results found"));
207                } else {
208                    items.push_back(ListItem::PageTurner(true));
209                }
210
211                text_list.items = textlist_from_video_list(&items);
212
213                let mut thumbnails = LinkedList::new();
214
215                for item in items.iter() {
216                    match item {
217                        ListItem::MiniVideo(video) => {
218                            thumbnails
219                                .push_back((video.video_thumbnail.clone(), video.video_id.clone()));
220                        }
221
222                        ListItem::MiniPlayList(playlist) => {
223                            if let Some(thumbnail) = &playlist.thumbnail {
224                                thumbnails
225                                    .push_back((thumbnail.clone(), playlist.playlist_id.clone()));
226                            }
227                        }
228
229                        _ => {}
230                    }
231                }
232
233                let _ = download_all_thumbnails(thumbnails);
234
235                *results = Some(items);
236            }
237        }
238
239        Ok(Box::new(this))
240    }
241
242    pub fn render_item<B: Backend>(
243        &mut self,
244        frame: &mut Frame<B>,
245        rect: Rect,
246        selected: bool,
247        hover: bool,
248        popup_focus: bool,
249    ) {
250        match self {
251            SearchItem::Search { results, text_list } => {
252                let split = HorizontalSplit::default()
253                    .percentages(vec![60, 40])
254                    .border_style(Style::default().fg(if selected {
255                        Color::LightBlue
256                    } else if hover {
257                        Color::LightRed
258                    } else {
259                        Color::Reset
260                    }));
261
262                let chunks = split.inner(rect);
263
264                frame.render_widget(split, rect);
265
266                text_list.area(chunks[0]);
267                let mut text_list = text_list.clone();
268
269                if let Some(result) = results {
270                    if let Some(item) = result.iter().nth(text_list.selected) {
271                        if !popup_focus {
272                            frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
273                        }
274                    }
275                }
276
277                if selected {
278                    text_list.selected_style(Style::default().fg(Color::LightRed));
279                } else {
280                    text_list.selected_style(Style::default().fg(Color::LightYellow));
281                }
282
283                frame.render_widget(text_list, chunks[0]);
284            }
285        }
286    }
287}
288
289pub struct Search;
290
291impl Search {
292    pub fn message() -> String {
293        String::from("Loading search results...")
294    }
295
296    pub fn min() -> (u16, u16) {
297        (45, 12)
298    }
299
300    pub fn default() -> Vec<Row> {
301        vec![
302            Row {
303                items: vec![
304                    RowItem {
305                        item: Item::Global(GlobalItem::SearchBar),
306                        constraint: Constraint::Min(16),
307                    },
308                    RowItem {
309                        item: Item::Global(GlobalItem::SearchSettings),
310                        constraint: Constraint::Length(5),
311                    },
312                ],
313                centered: false,
314                height: Constraint::Length(3),
315            },
316            Row {
317                items: vec![RowItem {
318                    item: Item::Search(SearchItem::Search {
319                        results: None,
320                        text_list: TextList::default(),
321                    }),
322                    constraint: Constraint::Percentage(100),
323                }],
324                centered: false,
325                height: Constraint::Min(6),
326            },
327            Row {
328                items: vec![RowItem {
329                    item: Item::Global(GlobalItem::MessageBar),
330                    constraint: Constraint::Percentage(100),
331                }],
332                centered: false,
333                height: Constraint::Length(3),
334            },
335        ]
336    }
337}