src/app/pages/search.rs
388 lines · 14094 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, config::Action},
14 functions::download_all_thumbnails,
15 structs::{
16 Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
17 },
18 traits::{ItemTrait, PageTrait},
19 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
20};
21
22use super::{
23 channel::{Channel, ChannelPage},
24 global::GlobalItem,
25 item_info::{DisplayItem, ItemInfo},
26 main_menu::textlist_from_video_list,
27};
28
29#[derive(Debug, Clone)]
30pub enum SearchItem {
31 Search {
32 results: Option<LinkedList<ListItem>>,
33 text_list: TextList,
34 },
35}
36
37impl ItemTrait for SearchItem {
38 fn select(&mut self, app: App) -> (App, bool) {
39 (app, true)
40 }
41
42 fn selectable(&self) -> bool {
43 true
44 }
45
46 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
47 let action = match app.config.keybindings.0.get(&key) {
48 Some(action) => action,
49 None => return (false, app),
50 };
51 match self {
52
53 SearchItem::Search { results, text_list } => match action {
54 Action::Up => text_list.up(),
55 Action::Down => text_list.down(),
56 Action::FirstItem => text_list.selected = 0,
57 Action::LastItem => text_list.selected = text_list.items.len() - 1,
58 Action::Select => {
59 if let Some(results_unwrapped) = results {
60 match results_unwrapped.iter().nth(text_list.selected).unwrap() {
61 ListItem::PageTurner(b) => {
62 let new_page_no;
63 if *b {
64 new_page_no = app.page_no + 1;
65 } else {
66 new_page_no = app.page_no - 1;
67 }
68
69 *results = None;
70 *text_list = TextList::default();
71
72 let state = Search::default();
73 let mut history = app.history.clone();
74 let search_text = app.search_text.clone();
75 let search_settings = app.search_settings.clone();
76 history.push(app.into());
77
78 return (
79 false,
80 App {
81 history,
82 page: Page::Search,
83 selectable: App::selectable(&state),
84 state,
85 search_text,
86 search_settings,
87 load: true,
88 page_no: new_page_no,
89 ..Default::default()
90 },
91 );
92 }
93
94 ListItem::MiniVideo(video) => {
95 let state = ItemInfo::default();
96 let mut history = app.history.clone();
97 history.push(app.into());
98
99 return (
100 false,
101 App {
102 history,
103 page: Page::ItemDisplay(DisplayItem::Video(
104 video.video_id.clone(),
105 )),
106 selectable: App::selectable(&state),
107 state,
108 ..Default::default()
109 },
110 );
111 }
112
113 ListItem::MiniPlayList(playlist) => {
114 let state = ItemInfo::default();
115 let mut history = app.history.clone();
116 history.push(app.into());
117
118 return (
119 false,
120 App {
121 history,
122 page: Page::ItemDisplay(DisplayItem::PlayList(
123 playlist.playlist_id.clone(),
124 )),
125 selectable: App::selectable(&state),
126 state,
127 ..Default::default()
128 },
129 );
130 }
131
132 ListItem::MiniChannel(channel) => {
133 let state = Channel::default();
134 let mut history = app.history.clone();
135 history.push(app.into());
136
137 return (
138 false,
139 App {
140 history,
141 page: Page::Channel(
142 ChannelPage::Home,
143 channel.author_id.clone(),
144 ),
145 selectable: App::selectable(&state),
146 state,
147 ..Default::default()
148 },
149 );
150 }
151
152 _ => {}
153 }
154 }
155 }
156 _ => {}
157 },
158 }
159
160 (true, app)
161 }
162
163 fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
164 let mut this = self.clone();
165
166 match &mut this {
167 SearchItem::Search { results, text_list } => {
168 // panic!("got here");
169
170 let mut args = vec![app.search_text.clone()];
171 args.extend(app.search_settings.clone().to_vec());
172
173 let invidious_results = app
174 .client
175 .search(Some(&format!(
176 "page={}&q={}",
177 app.page_no,
178 args.join("&").as_str()
179 )))?
180 .items;
181
182 let mut items = LinkedList::new();
183
184 for item in invidious_results {
185 match item {
186 InvidiousSearchItem::Video {
187 title: _,
188 videoId: _,
189 author: _,
190 authorId: _,
191 authorUrl: _,
192 lengthSeconds: _,
193 videoThumbnails: _,
194 description: _,
195 descriptionHtml: _,
196 viewCount: _,
197 published: _,
198 publishedText: _,
199 liveNow: _,
200 paid: _,
201 premium: _,
202 } => {
203 items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
204 }
205
206 InvidiousSearchItem::Playlist {
207 title: _,
208 playlistId: _,
209 author: _,
210 authorId: _,
211 authorUrl: _,
212 videoCount: _,
213 videos: _,
214 } => {
215 items.push_back(ListItem::MiniPlayList(MiniPlayList::from(item)));
216 }
217
218 InvidiousSearchItem::Channel {
219 author: _,
220 authorId: _,
221 authorUrl: _,
222 authorThumbnails: _,
223 subCount: _,
224 videoCount: _,
225 description: _,
226 descriptionHtml: _,
227 } => {
228 items.push_back(ListItem::MiniChannel(MiniChannel::from(item)));
229 }
230
231 _ => {}
232 }
233 }
234
235 let mut minimum_length = 0;
236
237 if app.page_no != 1 {
238 minimum_length += 1;
239 items.push_front(ListItem::PageTurner(false));
240 }
241
242 if items.len() == minimum_length {
243 *app.message.lock().unwrap() = Some(String::from("No results found"));
244 } else {
245 items.push_back(ListItem::PageTurner(true));
246 }
247
248 text_list.items = textlist_from_video_list(&items);
249
250 let mut thumbnails = LinkedList::new();
251
252 for item in items.iter() {
253 match item {
254 ListItem::MiniVideo(video) => {
255 thumbnails
256 .push_back((video.video_thumbnail.clone(), video.video_id.clone()));
257 }
258
259 ListItem::MiniPlayList(playlist) => {
260 if let Some(thumbnail) = &playlist.thumbnail {
261 thumbnails
262 .push_back((thumbnail.clone(), playlist.playlist_id.clone()));
263 }
264 }
265
266 ListItem::MiniChannel(channel) => {
267 thumbnails.push_back((
268 format!("https:{}", channel.thumbnail.clone()),
269 channel.author_id.clone(),
270 ));
271
272 // panic!("{:?}", channel.thumbnail.clone());
273 }
274
275 _ => {}
276 }
277 }
278
279 let _ = download_all_thumbnails(thumbnails);
280
281 *results = Some(items);
282 }
283 }
284
285 Ok(Item::Search(this))
286 }
287
288 fn render_item<B: Backend>(
289 &self,
290 frame: &mut Frame<B>,
291 rect: Rect,
292 app: App,
293 selected: bool,
294 hover: bool,
295 popup_focus: bool,
296 _: bool,
297 ) -> (bool, Option<Item>, App) {
298 let out = (false, None, app);
299 match self {
300 SearchItem::Search { results, text_list } => {
301 let split = HorizontalSplit::default()
302 .percentages(vec![60, 40])
303 .border_style(Style::default().fg(if selected {
304 Color::LightBlue
305 } else if hover {
306 Color::LightRed
307 } else {
308 Color::Reset
309 }));
310
311 let chunks = split.inner(rect);
312
313 frame.render_widget(split, rect);
314
315 let mut text_list = text_list.clone();
316 text_list.area(chunks[0]);
317
318 if let Some(result) = results {
319 if let Some(item) = result.iter().nth(text_list.selected) {
320 if !popup_focus {
321 frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
322 }
323 }
324 }
325
326 if selected {
327 text_list.selected_style(Style::default().fg(Color::LightRed));
328 } else {
329 text_list.selected_style(Style::default().fg(Color::LightYellow));
330 }
331
332 frame.render_widget(text_list, chunks[0]);
333 }
334 }
335
336 out
337 }
338}
339
340pub struct Search;
341
342impl PageTrait for Search {
343 fn message() -> String {
344 String::from("Loading search results...")
345 }
346
347 fn min() -> (u16, u16) {
348 (45, 12)
349 }
350
351 fn default() -> Vec<Row> {
352 vec![
353 Row {
354 items: vec![
355 RowItem {
356 item: Item::Global(GlobalItem::SearchBar),
357 constraint: Constraint::Min(16),
358 },
359 RowItem {
360 item: Item::Global(GlobalItem::SearchSettings),
361 constraint: Constraint::Length(5),
362 },
363 ],
364 centered: false,
365 height: Constraint::Length(3),
366 },
367 Row {
368 items: vec![RowItem {
369 item: Item::Search(SearchItem::Search {
370 results: None,
371 text_list: TextList::default(),
372 }),
373 constraint: Constraint::Percentage(100),
374 }],
375 centered: false,
376 height: Constraint::Min(6),
377 },
378 Row {
379 items: vec![RowItem {
380 item: Item::Global(GlobalItem::MessageBar),
381 constraint: Constraint::Percentage(100),
382 }],
383 centered: false,
384 height: Constraint::Length(3),
385 },
386 ]
387 }
388}