Commit 641938ba1f

641938ba1f255069a13382c2a2903a32612e3873

parent: 49bf7c8f8b

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-05-19 16:52 UTC

0.1.0

Allows actually watching videos from this program

for more check README.md

Layout: unified · split

Cargo.lock +26 −2
@@ -89,6 +89,19 @@ version = "1.0.0"
8989source = "registry+https://github.com/rust-lang/crates.io-index"
9090checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
9191
92[[package]]
93name = "chrono"
94version = "0.4.19"
95source = "registry+https://github.com/rust-lang/crates.io-index"
96checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73"
97dependencies = [
98 "libc",
99 "num-integer",
100 "num-traits",
101 "time",
102 "winapi",
103]
104
92105[[package]]
93106name = "color_quant"
94107version = "1.1.0"
@@ -613,9 +626,9 @@ dependencies = [
613626
614627[[package]]
615628name = "invidious"
616version = "0.1.0"
629version = "0.2.0"
617630source = "registry+https://github.com/rust-lang/crates.io-index"
618checksum = "db294b3254d491fa9c4d180fd9c6a0bbbf05f1b0f2cf922851d098ca3c662c9e"
631checksum = "89779909e071231edd52fae0a93b5c0a9b3d0d87f83fa0e4f2a958d8c9d66d0a"
619632dependencies = [
620633 "reqwest",
621634 "serde",
@@ -1283,6 +1296,16 @@ dependencies = [
12831296 "weezl",
12841297]
12851298
1299[[package]]
1300name = "time"
1301version = "0.1.43"
1302source = "registry+https://github.com/rust-lang/crates.io-index"
1303checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438"
1304dependencies = [
1305 "libc",
1306 "winapi",
1307]
1308
12861309[[package]]
12871310name = "tinyvec"
12881311version = "1.5.1"
@@ -1668,6 +1691,7 @@ dependencies = [
16681691name = "youtube-tui"
16691692version = "0.1.0"
16701693dependencies = [
1694 "chrono",
16711695 "crossterm",
16721696 "futures",
16731697 "home",
Cargo.toml +2 −1
@@ -8,7 +8,7 @@ edition = "2021"
88[dependencies]
99tui = "0.18"
1010crossterm = "0.23"
11invidious = "0.1.0"
11invidious = "0.2"
1212futures = "0.3"
1313hrtime = "0.2"
1414home = "0.5"
@@ -16,6 +16,7 @@ reqwest = {version = "0.11", features = ["blocking"]}
1616tokio = { version = "1.18", features = ["full"] }
1717viuer = "0.6"
1818thousands = "0.2"
19chrono = "0.4"
1920
2021[profile.dev.package."*"]
2122opt-level = 3
README.md +15 −3
@@ -1,7 +1,17 @@
11## Changes made in this commit
2* Added support for multiple pages
3* Added the "ItemInfo" page, can be opened by pressing enter when on a video in the video list (it is supposed to allow you to play the video, WIP)
4* Added history support, press backspace to go back in history
2* Home page button
3* Video/audio playing and downloading - can play from YouTube (recommended) or invidious server (Bro you are killing their bandwidth)
4* Still lacking a lot of main features, but it is now a functional program (check the popular tab those videos are more relevant)
5
6## Requirements
7(These requirements will be removed in the next commit as it will *hopefully* allows you to choose the software/commands you want to use)
8* yt-dlp (for downloading videos/audio)
9* mpv (for video/audio playing and thumbnail preview)
10* konsole (for opening the terminal when downloading and playing audio)
11
12## What Will (Hopefully) Be in the Next Commit
13* Config files
14* Watch history
515
616## Basic Movements
717> Arrow keys: Move in the direction of the arrow key.
@@ -15,6 +25,8 @@
1525> Backspace: Go back in history
1626>
1727> End: Clear history
28>
29> Home: Go to homepage
1830
1931## Basic Display
2032> Green (Or your terminal's default foreground color): All the items
file.txt added +5
@@ -0,0 +1,5 @@
1ItemDisplay(Video("GjMmsEwIcl0"))
2ItemDisplay(Video("V2kWUJkRvVs"))
3ItemDisplay(Video("_CH8uu3L4D0"))
4ItemDisplay(Video("bLxbHQolYCo"))
5ItemDisplay(Video("8meLVxHw5nM"))
main_menu.svg deleted −154
@@ -1,154 +0,0 @@
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<!-- Created with Inkscape (http://www.inkscape.org/) -->
3
4<svg
5 width="297mm"
6 height="210mm"
7 viewBox="0 0 297 210"
8 version="1.1"
9 id="svg5"
10 inkscape:version="1.1.2 (0a00cf5339, 2022-02-04, custom)"
11 sodipodi:docname="main_menu.svg"
12 xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
13 xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
14 xmlns="http://www.w3.org/2000/svg"
15 xmlns:svg="http://www.w3.org/2000/svg">
16 <sodipodi:namedview
17 id="namedview7"
18 pagecolor="#505050"
19 bordercolor="#ffffff"
20 borderopacity="1"
21 inkscape:pageshadow="0"
22 inkscape:pageopacity="0"
23 inkscape:pagecheckerboard="1"
24 inkscape:document-units="mm"
25 showgrid="false"
26 inkscape:zoom="0.73406285"
27 inkscape:cx="681.82173"
28 inkscape:cy="387.56899"
29 inkscape:window-width="1900"
30 inkscape:window-height="987"
31 inkscape:window-x="10"
32 inkscape:window-y="10"
33 inkscape:window-maximized="1"
34 inkscape:current-layer="layer1" />
35 <defs
36 id="defs2" />
37 <g
38 inkscape:label="Layer 1"
39 inkscape:groupmode="layer"
40 id="layer1">
41 <rect
42 style="fill:#ffffff;fill-opacity:0;stroke:#ff23ff;stroke-width:1.56;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
43 id="rect31"
44 width="300.26987"
45 height="14.975105"
46 x="-1.7101005"
47 y="-0.080341153" />
48 <rect
49 style="fill:#ffffff;fill-opacity:0;stroke:#ff23ff;stroke-width:1.19435;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
50 id="rect31-3"
51 width="174.25894"
52 height="15.125169"
53 x="63.20306"
54 y="24.045645" />
55 <rect
56 style="fill:#ffffff;fill-opacity:0;stroke:#ff23ff;stroke-width:1.56;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
57 id="rect1551"
58 width="103.96526"
59 height="151.43961"
60 x="10.3016"
61 y="45.286053" />
62 <rect
63 style="fill:#ffffff;fill-opacity:0;stroke:#ff23ff;stroke-width:1.56;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
64 id="rect1555"
65 width="168.72832"
66 height="151.09547"
67 x="125.62102"
68 y="46.377522" />
69 <text
70 xml:space="preserve"
71 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
72 x="120.79162"
73 y="11.558399"
74 id="text4301"><tspan
75 sodipodi:role="line"
76 id="tspan4299"
77 style="fill:#ffffff;stroke-width:0.264583"
78 x="120.79162"
79 y="11.558399">search bar</tspan></text>
80 <rect
81 style="fill:#ffffff;fill-opacity:0;stroke:#ff23ff;stroke-width:1.56;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
82 id="rect31-7"
83 width="300.26987"
84 height="14.975105"
85 x="-0.77405721"
86 y="204.64107" />
87 <text
88 xml:space="preserve"
89 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
90 x="121.72767"
91 y="216.27982"
92 id="text4301-0"><tspan
93 sodipodi:role="line"
94 id="tspan4299-9"
95 style="fill:#ffffff;stroke-width:0.264583"
96 x="121.72767"
97 y="216.27982">status</tspan></text>
98 <text
99 xml:space="preserve"
100 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
101 x="64.655159"
102 y="34.833267"
103 id="text4301-6"><tspan
104 sodipodi:role="line"
105 id="tspan4299-7"
106 style="fill:#ffffff;stroke-width:0.264583"
107 x="64.655159"
108 y="34.833267">trending</tspan></text>
109 <text
110 xml:space="preserve"
111 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
112 x="120.71136"
113 y="35.150738"
114 id="text4301-6-5"><tspan
115 sodipodi:role="line"
116 id="tspan4299-7-3"
117 style="fill:#ffffff;stroke-width:0.264583"
118 x="120.71136"
119 y="35.150738">popular</tspan></text>
120 <text
121 xml:space="preserve"
122 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
123 x="185.0119"
124 y="34.616146"
125 id="text4301-6-5-5"><tspan
126 sodipodi:role="line"
127 id="tspan4299-7-3-6"
128 style="fill:#ffffff;stroke-width:0.264583"
129 x="185.0119"
130 y="34.616146">history</tspan></text>
131 <text
132 xml:space="preserve"
133 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
134 x="38.379673"
135 y="129.96365"
136 id="text4301-6-5-5-2"><tspan
137 sodipodi:role="line"
138 id="tspan4299-7-3-6-9"
139 style="fill:#ffffff;stroke-width:0.264583"
140 x="38.379673"
141 y="129.96365">video list</tspan></text>
142 <text
143 xml:space="preserve"
144 style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583"
145 x="189.27042"
146 y="130.80986"
147 id="text4301-6-5-5-2-1"><tspan
148 sodipodi:role="line"
149 id="tspan4299-7-3-6-9-2"
150 style="fill:#ffffff;stroke-width:0.264583"
151 x="189.27042"
152 y="130.80986">details</tspan></text>
153 </g>
154</svg>
src/app/app.rs +19 −72
@@ -1,10 +1,10 @@
1use std::{collections::LinkedList, error::Error};
1use std::{collections::LinkedList, sync::{Arc, Mutex}};
22
33use crate::{
4 app::pages::{global::*, item_info::*, main_menu::*},
5 traits::{KeyInput, SelectItem},
4 app::pages::{main_menu::*},
5 traits::{KeyInput, SelectItem}, structs::{AppHistory, Item, Page, Row},
66};
7use crossterm::event::KeyCode;
7use crossterm::{event::KeyCode};
88use invidious::blocking::Client;
99use tui::{
1010 backend::Backend,
@@ -22,14 +22,14 @@ pub struct App {
2222 pub hover: Option<(usize, usize)>, // x, y
2323 pub selected: Option<(usize, usize)>,
2424 pub client: Client,
25 pub message: Option<String>,
25 pub message: Arc<Mutex<Option<String>>>,
2626 pub load: bool,
2727 pub render: bool,
2828 pub history: Vec<AppHistory>,
2929}
3030
31impl App {
32 pub fn new() -> Self {
31impl Default for App {
32 fn default() -> Self {
3333 let state = MainMenu::default();
3434 let selectable = App::selectable(&state);
3535 Self {
@@ -39,13 +39,15 @@ impl App {
3939 client: Client::new(String::from("https://vid.puffyan.us")),
4040 selected: None,
4141 hover: None,
42 message: None,
42 message: Arc::new(Mutex::new(None)),
4343 load: true,
4444 render: true,
4545 history: Vec::new(),
4646 }
4747 }
48}
4849
50impl App {
4951 pub fn selectable(state: &Vec<Row>) -> Vec<Vec<(usize, usize)>> {
5052 let mut selectable = Vec::new();
5153
@@ -294,7 +296,7 @@ impl App {
294296
295297 match item {
296298 Item::Global(i) => {
297 i.render_item(frame, chunk, selected, hover, &self.message);
299 i.render_item(frame, chunk, selected, hover, &*self.message.lock().unwrap());
298300 }
299301 Item::MainMenu(i) => {
300302 i.render_item(frame, chunk, selected, hover, &self.page);
@@ -307,10 +309,10 @@ impl App {
307309 }
308310 }
309311
310 pub fn pop(&mut self) {
312 pub fn pop(&mut self) -> bool{
311313 if self.history.len() == 0 {
312 self.message = Some(String::from("This is the beginning of history"));
313 return;
314 *self.message.lock().unwrap() = Some(String::from("This is the beginning of history"));
315 return false;
314316 }
315317
316318 let app_history = self.history.pop().unwrap();
@@ -324,69 +326,14 @@ impl App {
324326 page: app_history.page,
325327 client: app_history.client,
326328 load: app_history.load,
327 render : app_history.render,
329 render: app_history.render,
328330 history: self.history.clone(),
329331 };
330 }
331}
332
333#[derive(Debug, PartialEq, Clone)]
334pub enum Page {
335 MainMenu(MainMenuSelector),
336 ItemDisplay(DisplayItem),
337}
338332
339impl Page {
340 pub fn default() -> Self {
341 Self::MainMenu(MainMenuSelector::default())
333 true
342334 }
343}
344
345#[derive(Debug, Clone)]
346pub enum Item {
347 Global(GlobalItem),
348 MainMenu(MainMenuItem),
349 ItemInfo(ItemInfoItem),
350}
351
352#[derive(Debug, Clone)]
353pub struct Row {
354 pub items: Vec<RowItem>,
355 pub centered: bool,
356 pub height: Constraint,
357}
358
359#[derive(Debug, Clone)]
360pub struct RowItem {
361 pub item: Item,
362 pub constraint: Constraint,
363}
364
365#[derive(Debug, Clone)]
366pub struct AppHistory {
367 pub page: Page,
368 pub state: Vec<Row>, // Item
369 pub selectable: Vec<Vec<(usize, usize)>>,
370 pub hover: Option<(usize, usize)>, // x, y
371 pub selected: Option<(usize, usize)>,
372 pub client: Client,
373 pub message: Option<String>,
374 pub load: bool,
375 pub render: bool,
376}
377335
378impl From<App> for AppHistory {
379 fn from(original: App) -> Self {
380 Self {
381 page: original.page,
382 state: original.state,
383 selectable: original.selectable,
384 hover: original.hover,
385 selected: original.selected,
386 client: original.client,
387 message: original.message,
388 load: original.load,
389 render: original.render,
390 }
336 pub fn home(&mut self) {
337 *self = App::default();
391338 }
392}
339}
\ No newline at end of file
src/app/pages/global.rs +26 −61
@@ -1,5 +1,6 @@
1use std::fmt;
2
13use crossterm::event::KeyCode;
2use invidious::structs::hidden::{PopularItem, TrendingVideo};
34use tui::{style::{Color, Style}, widgets::{Borders, Paragraph, BorderType, Block}, layout::{Alignment, Rect}, Frame, backend::Backend};
45
56use crate::{
@@ -13,6 +14,30 @@ pub enum GlobalItem {
1314 MessageBar,
1415}
1516
17#[derive(Debug, Clone, Copy)]
18pub enum Mode {
19 Youtube,
20 Invidious,
21}
22
23impl fmt::Display for Mode {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match self {
26 Mode::Youtube => write!(f, "Youtube"),
27 Mode::Invidious => write!(f, "Invidious"),
28 }
29 }
30}
31
32impl Mode {
33 pub fn toggle(&mut self) {
34 match self {
35 Mode::Youtube => *self = Mode::Invidious,
36 Mode::Invidious => *self = Mode::Youtube,
37 }
38 }
39}
40
1641impl SelectItem for GlobalItem {
1742 fn select(&mut self, app: App) -> (App, bool) {
1843 let selected = match self {
@@ -51,66 +76,6 @@ impl KeyInput for GlobalItem {
5176 }
5277}
5378
54#[derive(Debug, Clone)]
55pub enum ListItem {
56 Video(MiniVideo),
57 PageTurner(bool), // true: +1 | false: -1
58}
59
60impl ListItem {
61 pub fn id(&self) -> String {
62 match self {
63 ListItem::Video(video) => video.video_id.clone(),
64 _ => String::new(),
65 }
66 }
67}
68
69#[derive(Debug, Clone)]
70pub struct MiniVideo {
71 pub title: String,
72 pub video_id: String,
73 pub video_thumbnail: String,
74 pub length: String,
75 pub view_count: u64,
76 pub author: String,
77 pub author_url: String,
78 pub published: String,
79 pub description: String,
80}
81
82impl From<TrendingVideo> for MiniVideo {
83 fn from(original: TrendingVideo) -> Self {
84 MiniVideo {
85 title: original.title,
86 video_id: original.videoId,
87 video_thumbnail: original.videoThumbnails[4].url.clone(),
88 length: hrtime::from_sec(original.lengthSeconds as u64),
89 view_count: original.viewCount,
90 author: original.author,
91 author_url: original.authorUrl,
92 published: original.publishedText,
93 description: original.description,
94 }
95 }
96}
97
98impl From<PopularItem> for MiniVideo {
99 fn from(original: PopularItem) -> Self {
100 MiniVideo {
101 title: original.title,
102 video_id: original.videoId,
103 video_thumbnail: original.videoThumbnails[5].url.clone(),
104 length: hrtime::from_sec(original.lengthSeconds as u64),
105 view_count: original.viewCount,
106 author: original.author,
107 author_url: original.authorUrl,
108 published: original.publishedText,
109 description: String::new(),
110 }
111 }
112}
113
11479impl GlobalItem {
11580 pub fn render_item<B: Backend>(
11681 &self,
src/app/pages/item_info.rs +216 −32
@@ -1,10 +1,18 @@
1use std::{
2 collections::LinkedList,
3 process::Command,
4 sync::{Arc, Mutex},
5 thread,
6};
7
18use crate::{
2 app::app::{App, Item, Page, Row, RowItem},
9 app::{app::App, pages::global::*},
10 functions::{download_all_thumbnails, ItemType},
11 structs::{FullVideo, Item, ListItem, Page, Row, RowItem},
312 traits::{KeyInput, LoadItem, SelectItem},
4 widgets::{horizontal_split::HorizontalSplit, text_list::TextList},
13 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
514};
615use crossterm::event::KeyCode;
7use invidious::structs::video::Video;
816use tui::{
917 backend::Backend,
1018 layout::{Constraint, Rect},
@@ -17,13 +25,14 @@ use super::global::GlobalItem;
1725#[derive(Debug, Clone)]
1826pub enum ItemInfoItem {
1927 Unknown,
20 Video(Option<VideoItemInfo>),
28 Video(VideoItemInfo),
2129}
2230
2331#[derive(Debug, Clone)]
2432pub struct VideoItemInfo {
25 video: Video,
33 video: FullVideo,
2634 list: TextList,
35 mode: Mode,
2736}
2837
2938impl SelectItem for ItemInfoItem {
@@ -39,13 +48,129 @@ impl SelectItem for ItemInfoItem {
3948}
4049
4150impl KeyInput for ItemInfoItem {
42 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
51 fn key_input(&mut self, key: KeyCode, mut app: App) -> (bool, App) {
4352 match self {
44 ItemInfoItem::Video(Some(video)) => match key {
45 KeyCode::Up => video.list.up(),
46 KeyCode::Down => video.list.down(),
47 KeyCode::PageUp => video.list.selected = 0,
48 KeyCode::PageDown => video.list.selected = video.list.items.len() - 1,
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 }
49174 _ => {}
50175 },
51176 _ => {}
@@ -59,34 +184,37 @@ impl LoadItem for ItemInfoItem {
59184 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
60185 let mut this = self.clone();
61186
62 if let ItemInfoItem::Unknown = self {
187 if let ItemInfoItem::Unknown = this {
63188 match &app.page {
64189 Page::ItemDisplay(display_item) => match display_item {
65190 DisplayItem::Video(id) => {
66 if let ItemInfoItem::Video(videoinfo) = &mut this {
67 let mut list = TextList::default();
68 let video = app.client.video(id, None)?;
69 list.items(vec![
70 String::from("Watch from YouTube (Recommeneded)"),
71 String::from("Watch from Invidious"),
72 String::from("Play audio only from YouTube (Recommended)"),
73 String::from("Play audio only from Invidious"),
74 String::from("Download from YouTube (Recommended)"),
75 String::from("Download from Invidious"),
76 String::from("Download audio only from YouTube (Recommended)"),
77 String::from("Download audio only from Invidious"),
78 String::from("Visit channel"),
79 String::from("View thumbnail"),
80 ]);
81 *videoinfo = Some(VideoItemInfo { video, list });
82 }
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 });
83212 }
84213 },
85214
86215 _ => {}
87216 }
88217 }
89
90218 Ok(Box::new(this))
91219 }
92220}
@@ -101,6 +229,10 @@ impl ItemInfoItem {
101229 ) {
102230 match self {
103231 ItemInfoItem::Video(videoinfo) => {
232 let index = videoinfo.list.items.len() - 1;
233 videoinfo.list.items[index] = format!("Mode: {}", videoinfo.mode);
234 drop(index);
235
104236 let split = HorizontalSplit::default()
105237 .percentages(vec![40, 60])
106238 .border_style(Style::default().fg(if selected {
@@ -112,11 +244,38 @@ impl ItemInfoItem {
112244 }));
113245
114246 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 }
115255
116256 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]);
117265 }
118266
119 _ => {}
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 }
120279 }
121280 }
122281}
@@ -129,6 +288,10 @@ pub enum DisplayItem {
129288pub struct ItemInfo;
130289
131290impl ItemInfo {
291 pub fn message() -> String {
292 String::from("Loading item info...")
293 }
294
132295 pub fn default() -> Vec<Row> {
133296 vec![
134297 Row {
@@ -141,7 +304,7 @@ impl ItemInfo {
141304 },
142305 Row {
143306 items: vec![RowItem {
144 item: Item::ItemInfo(ItemInfoItem::Video(None)),
307 item: Item::ItemInfo(ItemInfoItem::Unknown),
145308 constraint: Constraint::Percentage(100),
146309 }],
147310 centered: false,
@@ -158,3 +321,24 @@ impl ItemInfo {
158321 ]
159322 }
160323}
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}
src/app/pages/main_menu.rs +26 −18
@@ -1,13 +1,12 @@
1use std::{collections::LinkedList, error::Error, fs};
1use std::{collections::LinkedList, error::Error};
22
33use crate::{
44 app::{
5 app::{App, Item, Page, Row, RowItem},
6 pages::{global::*, item_info::*},
5 pages::{global::*, item_info::*}, app::App,
76 },
8 functions::download_all_thumbnails,
7 functions::{download_all_thumbnails, ItemType},
98 traits::{KeyInput, LoadItem, SelectItem},
10 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
9 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, structs::{Page, Row, RowItem, Item, ListItem},
1110};
1211use crossterm::event::KeyCode;
1312use tui::{
@@ -34,7 +33,6 @@ impl SelectItem for MainMenuItem {
3433 }
3534 app.page = Page::MainMenu(*selector);
3635 app.load = true;
37 app.message = Some(String::from("Loading videos..."));
3836 false
3937 }
4038
@@ -60,7 +58,6 @@ impl KeyInput for MainMenuItem {
6058 KeyCode::Enter => {
6159 let state = ItemInfo::default();
6260 let mut history = app.history.clone();
63 let client = app.client.clone();
6461 history.push(app.into());
6562
6663 return (false, App {
@@ -68,14 +65,9 @@ impl KeyInput for MainMenuItem {
6865 page: Page::ItemDisplay(DisplayItem::Video(
6966 video_list.iter().nth(list.selected).unwrap().id(),
7067 )),
71 render: false,
7268 selectable: App::selectable(&state),
7369 state,
74 load: true,
75 client,
76 message: None,
77 hover: None,
78 selected: None,
70 ..Default::default()
7971 });
8072 }
8173 _ => {}
@@ -100,10 +92,16 @@ impl LoadItem for MainMenuItem {
10092 .trending(None)?
10193 .videos
10294 .into_iter()
103 .map(|t| ListItem::Video(t.into()))
95 .map(|t| ListItem::MiniVideo(t.into()))
10496 .collect();
10597
106 download_all_thumbnails(list.clone())?;
98 download_all_thumbnails(list.iter().map(|t| (
99 match t {
100 ListItem::MiniVideo(v) => (v.video_thumbnail.clone(), v.video_id.clone(), ItemType::Video),
101 _ => unreachable!(),
102
103 }
104 )).collect())?;
107105
108106 if let Some((video_list, text_list, _)) = enum_items {
109107 *text_list = TextList::default();
@@ -123,10 +121,16 @@ impl LoadItem for MainMenuItem {
123121 .popular(None)?
124122 .items
125123 .into_iter()
126 .map(|t| ListItem::Video(t.into()))
124 .map(|t| ListItem::MiniVideo(t.into()))
127125 .collect();
128126
129 download_all_thumbnails(list.clone())?;
127 download_all_thumbnails(list.iter().map(|t| (
128 match t {
129 ListItem::MiniVideo(v) => (v.video_thumbnail.clone(), v.video_id.clone(), ItemType::Video),
130 _ => unreachable!(),
131
132 }
133 )).collect())?;
130134
131135 let mut text_list = TextList::default();
132136
@@ -234,7 +238,7 @@ fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
234238 original
235239 .iter()
236240 .map(|item| match item {
237 ListItem::Video(video) => video
241 ListItem::MiniVideo(video) => video
238242 .title
239243 .clone()
240244 .chars()
@@ -263,6 +267,10 @@ impl Default for MainMenuSelector {
263267pub struct MainMenu;
264268
265269impl MainMenu {
270 pub fn message() -> String {
271 String::from("Loading home page...")
272 }
273
266274 pub fn default() -> Vec<Row> {
267275 vec![
268276 Row {
src/functions/download_all_thumbnails.rs +8 −18
@@ -3,41 +3,31 @@ use std::{collections::LinkedList, error::Error, io::Cursor, thread};
33use futures::future::join_all;
44use tokio::runtime::Runtime;
55
6use crate::app::pages::global::ListItem;
7
86pub enum ItemType {
97 Video,
108 Playlist,
119}
1210
13pub fn download_all_thumbnails(list: LinkedList<ListItem>) -> Result<(), Box<dyn Error>> {
11pub fn download_all_thumbnails(
12 list: LinkedList<(String, String, ItemType)>,
13) -> Result<(), Box<dyn Error>> {
1414 thread::spawn(move || {
1515 let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
16 let mut urls: Vec<(&str, &str, ItemType)> = Vec::new();
17 for i in list.iter() {
18 match i {
19 ListItem::Video(video) => {
20 urls.push((&video.video_thumbnail, &video.video_id, ItemType::Video));
21 }
22 _ => {}
23 }
24 }
2516
26 let _ = rt.block_on(download_items(urls));
17 let _ = rt.block_on(download_items(list));
2718 });
2819
2920 Ok(())
3021}
3122
32pub async fn download_items(urls: Vec<(&str, &str, ItemType)>) -> Result<(), Box<dyn Error>> {
23pub async fn download_items(urls: LinkedList<(String, String, ItemType)>) -> Result<(), Box<dyn Error>> {
3324 let mut actions = Vec::new();
3425 let mut path = home::home_dir().expect("Cannot get your home directory");
35 path.push(".siriusmart");
26 path.push(".cache");
3627 path.push("youtube-tui");
37 path.push("cache");
3828 path.push("thumbnails");
3929
40 for (url, video_id, item_type) in urls {
30 for (url, video_id, item_type) in urls.iter() {
4131 path.push(match item_type {
4232 ItemType::Video => "videos",
4333 ItemType::Playlist => "playlists",
@@ -47,7 +37,7 @@ pub async fn download_items(urls: Vec<(&str, &str, ItemType)>) -> Result<(), Box
4737
4838 if !path.exists() {
4939 actions.push(fetch_url(
50 url,
40 url.as_str(),
5141 path.clone().into_os_string().into_string().unwrap(),
5242 ));
5343 }
src/lib.rs +2 −1
@@ -1,4 +1,5 @@
11pub mod app;
22pub mod traits;
33pub mod widgets;
4pub mod functions;
\ No newline at end of file
4pub mod functions;
5pub mod structs;
\ No newline at end of file
src/main.rs +42 −37
@@ -9,14 +9,18 @@ use tui::{
99 Terminal,
1010};
1111use youtube_tui::{
12 app::app::{App, Item, Row, RowItem},
12 app::{
13 app::App,
14 pages::{item_info::ItemInfo, main_menu::MainMenu},
15 },
16 structs::{Item, Page, Row, RowItem},
1317 traits::LoadItem,
1418};
1519
1620fn main() -> Result<(), Box<dyn Error>> {
1721 init()?;
1822
19 let app = App::new();
23 let app = App::default();
2024
2125 enable_raw_mode()?;
2226 let mut stdout = io::stdout();
@@ -40,17 +44,18 @@ fn main() -> Result<(), Box<dyn Error>> {
4044}
4145
4246fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> {
43 app.message = Some(String::from("Loading videos..."));
4447 loop {
45
46
4748 if app.render {
4849 ui(&mut terminal, &mut app)?;
49 app.message = None;
50 app.render = false;
5150 }
5251
5352 if app.load {
53 *app.message.lock().unwrap() = Some(match app.page {
54 Page::MainMenu(_) => MainMenu::message(),
55 Page::ItemDisplay(_) => ItemInfo::message(),
56 });
57 terminal.clear()?;
58 ui(&mut terminal, &mut app)?;
5459 let mut new_state = Vec::new();
5560 for row in app.state.iter() {
5661 let mut row_vec = Vec::new();
@@ -68,26 +73,22 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
6873 item: Item::MainMenu(item.clone()),
6974 ..*row_item
7075 });
71 //app.message = Some(String::from("An error occurred while loading videos"));
72 app.message = Some(e.to_string());
76 *app.message.lock().unwrap() = Some(e.to_string());
7377 }
7478 },
75 Item::ItemInfo(item) => {
76 match item.load_item(&app) {
77 Ok(new) => {
78 row_vec.push(RowItem {
79 item: Item::ItemInfo(*new),
80 ..*row_item
81 });
82 }
83 Err(e) => {
84 row_vec.push(RowItem {
85 item: Item::ItemInfo(item.clone()),
86 ..*row_item
87 });
88 //app.message = Some(String::from("An error occurred while loading videos"));
89 app.message = Some(e.to_string());
90 }
79 Item::ItemInfo(item) => match item.load_item(&app) {
80 Ok(new) => {
81 row_vec.push(RowItem {
82 item: Item::ItemInfo(*new),
83 ..*row_item
84 });
85 }
86 Err(e) => {
87 row_vec.push(RowItem {
88 item: Item::ItemInfo(item.clone()),
89 ..*row_item
90 });
91 *app.message.lock().unwrap() = Some(e.to_string());
9192 }
9293 },
9394 _ => {
@@ -108,7 +109,8 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
108109 app.state = new_state;
109110
110111 app.load = false;
111 app.render = true;
112 terminal.clear()?;
113 ui(&mut terminal, &mut app)?;
112114 } else {
113115 match event::read()? {
114116 event::Event::Key(key) => {
@@ -118,7 +120,9 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
118120 return Ok(());
119121 }
120122 KeyCode::Backspace => {
121 app.pop();
123 if app.pop() {
124 terminal.clear()?;
125 }
122126 app.render = true;
123127 continue;
124128 }
@@ -126,12 +130,17 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
126130 app.history = Vec::new();
127131 continue;
128132 }
133 KeyCode::Home => {
134 terminal.clear()?;
135 app.home();
136 continue;
137 }
129138 _ => {}
130139 }
131140 }
132141
133142 app = app.key_input(key.code);
134 app.render = true;
143 app.render = true;
135144 }
136145 event::Event::Resize(_, _) => {
137146 app.render = true;
@@ -147,13 +156,16 @@ fn ui<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<(), Box<d
147156 app.render(&mut frame);
148157 })?;
149158
159 *app.message.lock().unwrap() = None;
160 app.render = false;
161
150162 Ok(())
151163}
152164
153165fn init() -> Result<(), Box<dyn Error>> {
154166 let mut dir = home::home_dir().expect("Cannot get your home directory");
155167
156 dir.push(".siriusmart");
168 dir.push(".cache");
157169 if !dir.exists() {
158170 fs::create_dir(&dir)?;
159171 }
@@ -163,13 +175,6 @@ fn init() -> Result<(), Box<dyn Error>> {
163175 fs::create_dir(&dir)?;
164176 }
165177
166 dir.push("cache");
167
168 if dir.exists() {
169 fs::remove_dir_all(&dir)?;
170 }
171 fs::create_dir(&dir)?;
172
173178 dir.push("thumbnails");
174179
175180 if !dir.exists() {
@@ -196,7 +201,7 @@ fn init() -> Result<(), Box<dyn Error>> {
196201fn exit() -> Result<(), Box<dyn Error>> {
197202 let mut dir = home::home_dir().expect("Cannot get your home directory");
198203
199 dir.push(".siriusmart");
204 dir.push(".cache");
200205 dir.push("youtube-tui");
201206 dir.push("cache");
202207
src/structs/apphistory.rs added +37
@@ -0,0 +1,37 @@
1use std::sync::{Arc, Mutex};
2
3use invidious::blocking::Client;
4
5use crate::{
6 app::app::App,
7 structs::{Page, Row},
8};
9
10#[derive(Debug, Clone)]
11pub struct AppHistory {
12 pub page: Page,
13 pub state: Vec<Row>, // Item
14 pub selectable: Vec<Vec<(usize, usize)>>,
15 pub hover: Option<(usize, usize)>, // x, y
16 pub selected: Option<(usize, usize)>,
17 pub client: Client,
18 pub message: Arc<Mutex<Option<String>>>,
19 pub load: bool,
20 pub render: bool,
21}
22
23impl From<App> for AppHistory {
24 fn from(original: App) -> Self {
25 Self {
26 page: original.page,
27 state: original.state,
28 selectable: original.selectable,
29 hover: original.hover,
30 selected: original.selected,
31 client: original.client,
32 message: original.message,
33 load: original.load,
34 render: original.render,
35 }
36 }
37}
src/structs/fullvideo.rs added +58
@@ -0,0 +1,58 @@
1use chrono::{Utc, NaiveDateTime, DateTime};
2use invidious::structs::video::Video;
3use thousands::Separable;
4
5#[derive(Debug, Clone)]
6pub struct FullVideo {
7 pub title: String,
8 pub video_id: String,
9 pub video_thumbnail: String,
10 pub description: String,
11 pub views: String,
12 pub published: String,
13 pub nsfw: bool,
14 pub genre: String,
15 pub channel: String,
16 pub channel_id: String,
17 pub subcount: String,
18 pub length: String,
19 pub public: bool,
20 pub live: bool,
21 pub upcoming: bool,
22 pub recommendations: Vec<String>,
23}
24
25impl From<Video> for FullVideo {
26 fn from(original: Video) -> Self {
27 Self {
28 title: original.title,
29 video_id: original.videoId,
30 video_thumbnail: original.videoThumbnails[5].url.clone(),
31 description: original.description,
32 views: original.viewCount.separate_with_commas(),
33 published: format!(
34 "{}{}",
35 original.publishedText,
36 if Utc::now().timestamp() - original.published as i64 > 86400 {
37 let datetime: DateTime<Utc> = DateTime::from_utc(
38 NaiveDateTime::from_timestamp(original.published as i64, 0),
39 Utc,
40 );
41 format!(" [{}]", datetime.format("%Y/%m/%d"))
42 } else {
43 String::new()
44 }
45 ),
46 nsfw: original.isFamilyFriendly,
47 genre: original.genre,
48 channel: original.author,
49 channel_id: original.authorId,
50 subcount: original.subCountText,
51 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
52 public: original.isListed,
53 live: original.liveNow,
54 upcoming: original.isUpcoming,
55 recommendations: original.recommendedVideos.into_iter().map(|x| x.videoId).collect(),
56 }
57 }
58}
src/structs/listitem.rs added +21
@@ -0,0 +1,21 @@
1
2use crate::structs::{MiniVideo, FullVideo};
3
4#[derive(Debug, Clone)]
5pub enum ListItem {
6 MiniVideo(MiniVideo),
7 FullVideo(FullVideo),
8 PageTurner(bool), // true: +1 | false: -1
9}
10
11impl ListItem {
12 pub fn id(&self) -> String {
13 match self {
14 ListItem::MiniVideo(video) => video.video_id.clone(),
15 ListItem::FullVideo(video) => video.video_id.clone(),
16 _ => {
17 unreachable!()
18 }
19 }
20 }
21}
src/structs/minivideo.rs added +72
@@ -0,0 +1,72 @@
1use thousands::Separable;
2use chrono::{prelude::*, Utc};
3use invidious::structs::hidden::{PopularItem, TrendingVideo};
4
5#[derive(Debug, Clone)]
6pub struct MiniVideo {
7 pub title: String,
8 pub video_id: String,
9 pub video_thumbnail: String,
10 pub length: String,
11 pub view_count: String,
12 pub author: String,
13 pub author_url: String,
14 pub published: String,
15 pub description: String,
16}
17
18impl From<TrendingVideo> for MiniVideo {
19 fn from(original: TrendingVideo) -> Self {
20 MiniVideo {
21 title: original.title,
22 video_id: original.videoId,
23 video_thumbnail: original.videoThumbnails[4].url.clone(),
24 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
25 view_count: original.viewCount.separate_with_commas(),
26 author: original.author,
27 author_url: original.authorUrl,
28 published: format!(
29 "{}{}",
30 original.publishedText,
31 if Utc::now().timestamp() - original.published as i64 > 86400 {
32 let datetime: DateTime<Utc> = DateTime::from_utc(
33 NaiveDateTime::from_timestamp(original.published as i64, 0),
34 Utc,
35 );
36 format!(" [{}]", datetime.format("%Y/%m/%d"))
37 } else {
38 String::new()
39 }
40 ),
41 description: original.description,
42 }
43 }
44}
45
46impl From<PopularItem> for MiniVideo {
47 fn from(original: PopularItem) -> Self {
48 MiniVideo {
49 title: original.title,
50 video_id: original.videoId,
51 video_thumbnail: original.videoThumbnails[5].url.clone(),
52 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
53 view_count: original.viewCount.separate_with_commas(),
54 author: original.author,
55 author_url: original.authorUrl,
56 published: format!(
57 "{}{}",
58 original.publishedText,
59 if Utc::now().timestamp() - original.published as i64 > 86400 {
60 let datetime: DateTime<Utc> = DateTime::from_utc(
61 NaiveDateTime::from_timestamp(original.published as i64, 0),
62 Utc,
63 );
64 format!("[{}]", datetime.format("%Y/%m/%d"))
65 } else {
66 String::new()
67 }
68 ),
69 description: String::new(),
70 }
71 }
72}
src/structs/mod.rs added +17
@@ -0,0 +1,17 @@
1mod apphistory;
2pub use apphistory::*;
3
4mod page;
5pub use page::*;
6
7mod states;
8pub use states::*;
9
10mod listitem;
11pub use listitem::*;
12
13mod minivideo;
14pub use minivideo::*;
15
16mod fullvideo;
17pub use fullvideo::*;
\ No newline at end of file
src/structs/page.rs added +13
@@ -0,0 +1,13 @@
1use crate::app::pages::{main_menu::MainMenuSelector, item_info::DisplayItem};
2
3#[derive(Debug, PartialEq, Clone)]
4pub enum Page {
5 MainMenu(MainMenuSelector),
6 ItemDisplay(DisplayItem),
7}
8
9impl Default for Page {
10 fn default() -> Self {
11 Self::MainMenu(MainMenuSelector::default())
12 }
13}
\ No newline at end of file
src/structs/states.rs added +23
@@ -0,0 +1,23 @@
1use tui::layout::Constraint;
2
3use crate::app::pages::{global::GlobalItem, main_menu::MainMenuItem, item_info::ItemInfoItem};
4
5#[derive(Debug, Clone)]
6pub enum Item {
7 Global(GlobalItem),
8 MainMenu(MainMenuItem),
9 ItemInfo(ItemInfoItem),
10}
11
12#[derive(Debug, Clone)]
13pub struct Row {
14 pub items: Vec<RowItem>,
15 pub centered: bool,
16 pub height: Constraint,
17}
18
19#[derive(Debug, Clone)]
20pub struct RowItem {
21 pub item: Item,
22 pub constraint: Constraint,
23}
\ No newline at end of file
src/widgets/item_display.rs +111 −9
@@ -1,5 +1,3 @@
1use crate::app::pages::global::ListItem;
2use thousands::Separable;
31use tui::{
42 buffer::Buffer,
53 layout::{Margin, Rect},
@@ -8,6 +6,8 @@ use tui::{
86};
97use viuer::{print_from_file, Config};
108
9use crate::structs::ListItem;
10
1111#[derive(Clone)]
1212pub struct ItemDisplay {
1313 pub item: ListItem,
@@ -16,17 +16,16 @@ pub struct ItemDisplay {
1616impl Widget for ItemDisplay {
1717 fn render(self, area: Rect, buf: &mut Buffer) {
1818 match self.item {
19 ListItem::Video(video) => {
19 ListItem::MiniVideo(video) => {
2020 let mut path = home::home_dir().expect("Cannot get your home directory");
21 path.push(".siriusmart");
21 path.push(".cache");
2222 path.push("youtube-tui");
23 path.push("cache");
2423 path.push("thumbnails");
2524 path.push("videos");
2625 path.push(format!("{}.png", video.video_id));
2726 let exists = path.exists();
2827 let mut image_transform = area;
29 if exists{
28 if exists {
3029 if image_transform.width * 9 > image_transform.height * 2 * 16 {
3130 image_transform.width = image_transform.height * 2 * 16 / 9;
3231 } else {
@@ -53,10 +52,113 @@ impl Widget for ItemDisplay {
5352 let mut to_print = Vec::new();
5453 to_print.push((String::from("[Video]"), Style::default().fg(Color::Gray)));
5554 to_print.push((video.title, Style::default().fg(Color::LightBlue)));
56 to_print.push((format!("Uploaded by {}", video.author), Style::default().fg(Color::LightGreen)));
57 to_print.push((format!("Views: {}", video.view_count.separate_with_commas()), Style::default().fg(Color::LightYellow)));
58 to_print.push((format!("Published {}", video.published), Style::default().fg(Color::LightMagenta)));
55 to_print.push((
56 format!("Uploaded by {}", video.author),
57 Style::default().fg(Color::LightGreen),
58 ));
59 to_print.push((
60 format!("Views: {}", video.view_count),
61 Style::default().fg(Color::LightYellow),
62 ));
63 to_print.push((
64 format!("Length: {}", video.length),
65 Style::default().fg(Color::LightCyan),
66 ));
67 to_print.push((
68 format!("Published {}", video.published),
69 Style::default().fg(Color::LightMagenta),
70 ));
71
72 for (mut item, style) in to_print {
73 if y > area.height + area.y - 1 {
74 return;
75 }
76
77 if item.len() > area.width as usize {
78 item = format!("{}...", &item[..area.width as usize - 3]);
79 }
80 buf.set_string(area.x, y, item, style);
81 y += 1;
82 }
83 }
84 ListItem::FullVideo(video) => {
85 let mut path = home::home_dir().expect("Cannot get your home directory");
86 path.push(".cache");
87 path.push("youtube-tui");
88 path.push("thumbnails");
89 path.push("videos");
90 path.push(format!("{}.png", video.video_id));
91 let exists = path.exists();
92 let mut image_transform = area;
93 if exists {
94 if image_transform.width * 9 > image_transform.height * 2 * 16 {
95 image_transform.width = image_transform.height * 2 * 16 / 9;
96 } else {
97 image_transform.height = image_transform.width * 9 / 32;
98 }
99
100 let conf = Config {
101 width: Some(image_transform.width as u32),
102 height: Some(image_transform.height as u32),
103 x: image_transform.x,
104 y: image_transform.y as i16,
105 ..Default::default()
106 };
59107
108 let _ = print_from_file(path.as_os_str(), &conf);
109 }
110
111 let mut y = if exists {
112 image_transform.y + image_transform.height
113 } else {
114 area.y
115 };
116
117 let mut to_print = Vec::new();
118 let mut tags = Vec::new();
119
120 if video.nsfw {
121 tags.push("Non-Family Friendly");
122 }
123
124 if !video.public {
125 tags.push("Unlisted")
126 }
127
128 if video.upcoming {
129 tags.push("Upcoming")
130 }
131 if video.live {
132 tags.push("Live")
133 }
134
135 tags.push("Video");
136
137 to_print.push((
138 format!("[{}]", tags.join(" ")),
139 Style::default().fg(Color::Gray),
140 ));
141 to_print.push((video.title, Style::default().fg(Color::LightBlue)));
142 to_print.push((
143 format!("Uploaded by {}", video.channel),
144 Style::default().fg(Color::LightGreen),
145 ));
146 to_print.push((
147 format!("Views: {}", video.views),
148 Style::default().fg(Color::LightYellow),
149 ));
150 to_print.push((
151 format!("Length: {}", video.length),
152 Style::default().fg(Color::LightCyan),
153 ));
154 to_print.push((
155 format!("Genre: {}", video.genre),
156 Style::default().fg(Color::LightYellow),
157 ));
158 to_print.push((
159 format!("Published {}", video.published),
160 Style::default().fg(Color::LightMagenta),
161 ));
60162
61163 for (mut item, style) in to_print {
62164 if y > area.height + area.y - 1 {