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"
89source = "registry+https://github.com/rust-lang/crates.io-index" 89source = "registry+https://github.com/rust-lang/crates.io-index"
90checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 90checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
91 91
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
92[[package]] 105[[package]]
93name = "color_quant" 106name = "color_quant"
94version = "1.1.0" 107version = "1.1.0"
@@ -613,9 +626,9 @@ dependencies = [
613 626
614[[package]] 627[[package]]
615name = "invidious" 628name = "invidious"
616version = "0.1.0" 629version = "0.2.0"
617source = "registry+https://github.com/rust-lang/crates.io-index" 630source = "registry+https://github.com/rust-lang/crates.io-index"
618checksum = "db294b3254d491fa9c4d180fd9c6a0bbbf05f1b0f2cf922851d098ca3c662c9e" 631checksum = "89779909e071231edd52fae0a93b5c0a9b3d0d87f83fa0e4f2a958d8c9d66d0a"
619dependencies = [ 632dependencies = [
620 "reqwest", 633 "reqwest",
621 "serde", 634 "serde",
@@ -1283,6 +1296,16 @@ dependencies = [
1283 "weezl", 1296 "weezl",
1284] 1297]
1285 1298
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
1286[[package]] 1309[[package]]
1287name = "tinyvec" 1310name = "tinyvec"
1288version = "1.5.1" 1311version = "1.5.1"
@@ -1668,6 +1691,7 @@ dependencies = [
1668name = "youtube-tui" 1691name = "youtube-tui"
1669version = "0.1.0" 1692version = "0.1.0"
1670dependencies = [ 1693dependencies = [
1694 "chrono",
1671 "crossterm", 1695 "crossterm",
1672 "futures", 1696 "futures",
1673 "home", 1697 "home",
Cargo.toml +2 −1
@@ -8,7 +8,7 @@ edition = "2021"
8[dependencies] 8[dependencies]
9tui = "0.18" 9tui = "0.18"
10crossterm = "0.23" 10crossterm = "0.23"
11invidious = "0.1.0" 11invidious = "0.2"
12futures = "0.3" 12futures = "0.3"
13hrtime = "0.2" 13hrtime = "0.2"
14home = "0.5" 14home = "0.5"
@@ -16,6 +16,7 @@ reqwest = {version = "0.11", features = ["blocking"]}
16tokio = { version = "1.18", features = ["full"] } 16tokio = { version = "1.18", features = ["full"] }
17viuer = "0.6" 17viuer = "0.6"
18thousands = "0.2" 18thousands = "0.2"
19chrono = "0.4"
19 20
20[profile.dev.package."*"] 21[profile.dev.package."*"]
21opt-level = 3 22opt-level = 3
README.md +15 −3
@@ -1,7 +1,17 @@
1## Changes made in this commit 1## Changes made in this commit
2* Added support for multiple pages 2* Home page button
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) 3* Video/audio playing and downloading - can play from YouTube (recommended) or invidious server (Bro you are killing their bandwidth)
4* Added history support, press backspace to go back in history 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
5 15
6## Basic Movements 16## Basic Movements
7> Arrow keys: Move in the direction of the arrow key. 17> Arrow keys: Move in the direction of the arrow key.
@@ -15,6 +25,8 @@
15> Backspace: Go back in history 25> Backspace: Go back in history
16> 26>
17> End: Clear history 27> End: Clear history
28>
29> Home: Go to homepage
18 30
19## Basic Display 31## Basic Display
20> Green (Or your terminal's default foreground color): All the items 32> 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}};
2 2
3use crate::{ 3use crate::{
4 app::pages::{global::*, item_info::*, main_menu::*}, 4 app::pages::{main_menu::*},
5 traits::{KeyInput, SelectItem}, 5 traits::{KeyInput, SelectItem}, structs::{AppHistory, Item, Page, Row},
6}; 6};
7use crossterm::event::KeyCode; 7use crossterm::{event::KeyCode};
8use invidious::blocking::Client; 8use invidious::blocking::Client;
9use tui::{ 9use tui::{
10 backend::Backend, 10 backend::Backend,
@@ -22,14 +22,14 @@ pub struct App {
22 pub hover: Option<(usize, usize)>, // x, y 22 pub hover: Option<(usize, usize)>, // x, y
23 pub selected: Option<(usize, usize)>, 23 pub selected: Option<(usize, usize)>,
24 pub client: Client, 24 pub client: Client,
25 pub message: Option<String>, 25 pub message: Arc<Mutex<Option<String>>>,
26 pub load: bool, 26 pub load: bool,
27 pub render: bool, 27 pub render: bool,
28 pub history: Vec<AppHistory>, 28 pub history: Vec<AppHistory>,
29} 29}
30 30
31impl App { 31impl Default for App {
32 pub fn new() -> Self { 32 fn default() -> Self {
33 let state = MainMenu::default(); 33 let state = MainMenu::default();
34 let selectable = App::selectable(&state); 34 let selectable = App::selectable(&state);
35 Self { 35 Self {
@@ -39,13 +39,15 @@ impl App {
39 client: Client::new(String::from("https://vid.puffyan.us")), 39 client: Client::new(String::from("https://vid.puffyan.us")),
40 selected: None, 40 selected: None,
41 hover: None, 41 hover: None,
42 message: None, 42 message: Arc::new(Mutex::new(None)),
43 load: true, 43 load: true,
44 render: true, 44 render: true,
45 history: Vec::new(), 45 history: Vec::new(),
46 } 46 }
47 } 47 }
48}
48 49
50impl App {
49 pub fn selectable(state: &Vec<Row>) -> Vec<Vec<(usize, usize)>> { 51 pub fn selectable(state: &Vec<Row>) -> Vec<Vec<(usize, usize)>> {
50 let mut selectable = Vec::new(); 52 let mut selectable = Vec::new();
51 53
@@ -294,7 +296,7 @@ impl App {
294 296
295 match item { 297 match item {
296 Item::Global(i) => { 298 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());
298 } 300 }
299 Item::MainMenu(i) => { 301 Item::MainMenu(i) => {
300 i.render_item(frame, chunk, selected, hover, &self.page); 302 i.render_item(frame, chunk, selected, hover, &self.page);
@@ -307,10 +309,10 @@ impl App {
307 } 309 }
308 } 310 }
309 311
310 pub fn pop(&mut self) { 312 pub fn pop(&mut self) -> bool{
311 if self.history.len() == 0 { 313 if self.history.len() == 0 {
312 self.message = Some(String::from("This is the beginning of history")); 314 *self.message.lock().unwrap() = Some(String::from("This is the beginning of history"));
313 return; 315 return false;
314 } 316 }
315 317
316 let app_history = self.history.pop().unwrap(); 318 let app_history = self.history.pop().unwrap();
@@ -324,69 +326,14 @@ impl App {
324 page: app_history.page, 326 page: app_history.page,
325 client: app_history.client, 327 client: app_history.client,
326 load: app_history.load, 328 load: app_history.load,
327 render : app_history.render, 329 render: app_history.render,
328 history: self.history.clone(), 330 history: self.history.clone(),
329 }; 331 };
330 }
331}
332
333#[derive(Debug, PartialEq, Clone)]
334pub enum Page {
335 MainMenu(MainMenuSelector),
336 ItemDisplay(DisplayItem),
337}
338 332
339impl Page { 333 true
340 pub fn default() -> Self {
341 Self::MainMenu(MainMenuSelector::default())
342 } 334 }
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}
377 335
378impl From<App> for AppHistory { 336 pub fn home(&mut self) {
379 fn from(original: App) -> Self { 337 *self = App::default();
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 }
391 } 338 }
392} 339}\ No newline at end of file
src/app/pages/global.rs +26 −61
@@ -1,5 +1,6 @@
1use std::fmt;
2
1use crossterm::event::KeyCode; 3use crossterm::event::KeyCode;
2use invidious::structs::hidden::{PopularItem, TrendingVideo};
3use tui::{style::{Color, Style}, widgets::{Borders, Paragraph, BorderType, Block}, layout::{Alignment, Rect}, Frame, backend::Backend}; 4use tui::{style::{Color, Style}, widgets::{Borders, Paragraph, BorderType, Block}, layout::{Alignment, Rect}, Frame, backend::Backend};
4 5
5use crate::{ 6use crate::{
@@ -13,6 +14,30 @@ pub enum GlobalItem {
13 MessageBar, 14 MessageBar,
14} 15}
15 16
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
16impl SelectItem for GlobalItem { 41impl SelectItem for GlobalItem {
17 fn select(&mut self, app: App) -> (App, bool) { 42 fn select(&mut self, app: App) -> (App, bool) {
18 let selected = match self { 43 let selected = match self {
@@ -51,66 +76,6 @@ impl KeyInput for GlobalItem {
51 } 76 }
52} 77}
53 78
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
114impl GlobalItem { 79impl GlobalItem {
115 pub fn render_item<B: Backend>( 80 pub fn render_item<B: Backend>(
116 &self, 81 &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
1use crate::{ 8use 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},
3 traits::{KeyInput, LoadItem, SelectItem}, 12 traits::{KeyInput, LoadItem, SelectItem},
4 widgets::{horizontal_split::HorizontalSplit, text_list::TextList}, 13 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
5}; 14};
6use crossterm::event::KeyCode; 15use crossterm::event::KeyCode;
7use invidious::structs::video::Video;
8use tui::{ 16use tui::{
9 backend::Backend, 17 backend::Backend,
10 layout::{Constraint, Rect}, 18 layout::{Constraint, Rect},
@@ -17,13 +25,14 @@ use super::global::GlobalItem;
17#[derive(Debug, Clone)] 25#[derive(Debug, Clone)]
18pub enum ItemInfoItem { 26pub enum ItemInfoItem {
19 Unknown, 27 Unknown,
20 Video(Option<VideoItemInfo>), 28 Video(VideoItemInfo),
21} 29}
22 30
23#[derive(Debug, Clone)] 31#[derive(Debug, Clone)]
24pub struct VideoItemInfo { 32pub struct VideoItemInfo {
25 video: Video, 33 video: FullVideo,
26 list: TextList, 34 list: TextList,
35 mode: Mode,
27} 36}
28 37
29impl SelectItem for ItemInfoItem { 38impl SelectItem for ItemInfoItem {
@@ -39,13 +48,129 @@ impl SelectItem for ItemInfoItem {
39} 48}
40 49
41impl KeyInput for ItemInfoItem { 50impl 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) {
43 match self { 52 match self {
44 ItemInfoItem::Video(Some(video)) => match key { 53 ItemInfoItem::Video(videoinfo) => match key {
45 KeyCode::Up => video.list.up(), 54 KeyCode::Up => videoinfo.list.up(),
46 KeyCode::Down => video.list.down(), 55 KeyCode::Down => videoinfo.list.down(),
47 KeyCode::PageUp => video.list.selected = 0, 56 KeyCode::PageUp => videoinfo.list.selected = 0,
48 KeyCode::PageDown => video.list.selected = video.list.items.len() - 1, 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 }
49 _ => {} 174 _ => {}
50 }, 175 },
51 _ => {} 176 _ => {}
@@ -59,34 +184,37 @@ impl LoadItem for ItemInfoItem {
59 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> { 184 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
60 let mut this = self.clone(); 185 let mut this = self.clone();
61 186
62 if let ItemInfoItem::Unknown = self { 187 if let ItemInfoItem::Unknown = this {
63 match &app.page { 188 match &app.page {
64 Page::ItemDisplay(display_item) => match display_item { 189 Page::ItemDisplay(display_item) => match display_item {
65 DisplayItem::Video(id) => { 190 DisplayItem::Video(id) => {
66 if let ItemInfoItem::Video(videoinfo) = &mut this { 191 let mut list = TextList::default();
67 let mut list = TextList::default(); 192 let video: FullVideo = app.client.video(id, None)?.into();
68 let video = app.client.video(id, None)?; 193 let _ = download_all_thumbnails(LinkedList::from([(
69 list.items(vec![ 194 video.video_thumbnail.clone(),
70 String::from("Watch from YouTube (Recommeneded)"), 195 video.video_id.clone(),
71 String::from("Watch from Invidious"), 196 ItemType::Video,
72 String::from("Play audio only from YouTube (Recommended)"), 197 )]));
73 String::from("Play audio only from Invidious"), 198 list.items(vec![
74 String::from("Download from YouTube (Recommended)"), 199 String::from("Watch video"),
75 String::from("Download from Invidious"), 200 String::from("Play audio"),
76 String::from("Download audio only from YouTube (Recommended)"), 201 String::from("Download video"),
77 String::from("Download audio only from Invidious"), 202 String::from("Download audio"),
78 String::from("Visit channel"), 203 String::from("View thumbnail"),
79 String::from("View thumbnail"), 204 String::from("Visit channel"),
80 ]); 205 String::from("Mode placeholder"),
81 *videoinfo = Some(VideoItemInfo { video, list }); 206 ]);
82 } 207 this = ItemInfoItem::Video(VideoItemInfo {
208 video,
209 list,
210 mode: Mode::Youtube,
211 });
83 } 212 }
84 }, 213 },
85 214
86 _ => {} 215 _ => {}
87 } 216 }
88 } 217 }
89
90 Ok(Box::new(this)) 218 Ok(Box::new(this))
91 } 219 }
92} 220}
@@ -101,6 +229,10 @@ impl ItemInfoItem {
101 ) { 229 ) {
102 match self { 230 match self {
103 ItemInfoItem::Video(videoinfo) => { 231 ItemInfoItem::Video(videoinfo) => {
232 let index = videoinfo.list.items.len() - 1;
233 videoinfo.list.items[index] = format!("Mode: {}", videoinfo.mode);
234 drop(index);
235
104 let split = HorizontalSplit::default() 236 let split = HorizontalSplit::default()
105 .percentages(vec![40, 60]) 237 .percentages(vec![40, 60])
106 .border_style(Style::default().fg(if selected { 238 .border_style(Style::default().fg(if selected {
@@ -112,11 +244,38 @@ impl ItemInfoItem {
112 })); 244 }));
113 245
114 let chunks = split.inner(rect); 246 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 }
115 255
116 frame.render_widget(split, rect); 256 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]);
117 } 265 }
118 266
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 }
120 } 279 }
121 } 280 }
122} 281}
@@ -129,6 +288,10 @@ pub enum DisplayItem {
129pub struct ItemInfo; 288pub struct ItemInfo;
130 289
131impl ItemInfo { 290impl ItemInfo {
291 pub fn message() -> String {
292 String::from("Loading item info...")
293 }
294
132 pub fn default() -> Vec<Row> { 295 pub fn default() -> Vec<Row> {
133 vec![ 296 vec![
134 Row { 297 Row {
@@ -141,7 +304,7 @@ impl ItemInfo {
141 }, 304 },
142 Row { 305 Row {
143 items: vec![RowItem { 306 items: vec![RowItem {
144 item: Item::ItemInfo(ItemInfoItem::Video(None)), 307 item: Item::ItemInfo(ItemInfoItem::Unknown),
145 constraint: Constraint::Percentage(100), 308 constraint: Constraint::Percentage(100),
146 }], 309 }],
147 centered: false, 310 centered: false,
@@ -158,3 +321,24 @@ impl ItemInfo {
158 ] 321 ]
159 } 322 }
160} 323}
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};
2 2
3use crate::{ 3use crate::{
4 app::{ 4 app::{
5 app::{App, Item, Page, Row, RowItem}, 5 pages::{global::*, item_info::*}, app::App,
6 pages::{global::*, item_info::*},
7 }, 6 },
8 functions::download_all_thumbnails, 7 functions::{download_all_thumbnails, ItemType},
9 traits::{KeyInput, LoadItem, SelectItem}, 8 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},
11}; 10};
12use crossterm::event::KeyCode; 11use crossterm::event::KeyCode;
13use tui::{ 12use tui::{
@@ -34,7 +33,6 @@ impl SelectItem for MainMenuItem {
34 } 33 }
35 app.page = Page::MainMenu(*selector); 34 app.page = Page::MainMenu(*selector);
36 app.load = true; 35 app.load = true;
37 app.message = Some(String::from("Loading videos..."));
38 false 36 false
39 } 37 }
40 38
@@ -60,7 +58,6 @@ impl KeyInput for MainMenuItem {
60 KeyCode::Enter => { 58 KeyCode::Enter => {
61 let state = ItemInfo::default(); 59 let state = ItemInfo::default();
62 let mut history = app.history.clone(); 60 let mut history = app.history.clone();
63 let client = app.client.clone();
64 history.push(app.into()); 61 history.push(app.into());
65 62
66 return (false, App { 63 return (false, App {
@@ -68,14 +65,9 @@ impl KeyInput for MainMenuItem {
68 page: Page::ItemDisplay(DisplayItem::Video( 65 page: Page::ItemDisplay(DisplayItem::Video(
69 video_list.iter().nth(list.selected).unwrap().id(), 66 video_list.iter().nth(list.selected).unwrap().id(),
70 )), 67 )),
71 render: false,
72 selectable: App::selectable(&state), 68 selectable: App::selectable(&state),
73 state, 69 state,
74 load: true, 70 ..Default::default()
75 client,
76 message: None,
77 hover: None,
78 selected: None,
79 }); 71 });
80 } 72 }
81 _ => {} 73 _ => {}
@@ -100,10 +92,16 @@ impl LoadItem for MainMenuItem {
100 .trending(None)? 92 .trending(None)?
101 .videos 93 .videos
102 .into_iter() 94 .into_iter()
103 .map(|t| ListItem::Video(t.into())) 95 .map(|t| ListItem::MiniVideo(t.into()))
104 .collect(); 96 .collect();
105 97
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())?;
107 105
108 if let Some((video_list, text_list, _)) = enum_items { 106 if let Some((video_list, text_list, _)) = enum_items {
109 *text_list = TextList::default(); 107 *text_list = TextList::default();
@@ -123,10 +121,16 @@ impl LoadItem for MainMenuItem {
123 .popular(None)? 121 .popular(None)?
124 .items 122 .items
125 .into_iter() 123 .into_iter()
126 .map(|t| ListItem::Video(t.into())) 124 .map(|t| ListItem::MiniVideo(t.into()))
127 .collect(); 125 .collect();
128 126
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())?;
130 134
131 let mut text_list = TextList::default(); 135 let mut text_list = TextList::default();
132 136
@@ -234,7 +238,7 @@ fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
234 original 238 original
235 .iter() 239 .iter()
236 .map(|item| match item { 240 .map(|item| match item {
237 ListItem::Video(video) => video 241 ListItem::MiniVideo(video) => video
238 .title 242 .title
239 .clone() 243 .clone()
240 .chars() 244 .chars()
@@ -263,6 +267,10 @@ impl Default for MainMenuSelector {
263pub struct MainMenu; 267pub struct MainMenu;
264 268
265impl MainMenu { 269impl MainMenu {
270 pub fn message() -> String {
271 String::from("Loading home page...")
272 }
273
266 pub fn default() -> Vec<Row> { 274 pub fn default() -> Vec<Row> {
267 vec![ 275 vec![
268 Row { 276 Row {
src/functions/download_all_thumbnails.rs +8 −18
@@ -3,41 +3,31 @@ use std::{collections::LinkedList, error::Error, io::Cursor, thread};
3use futures::future::join_all; 3use futures::future::join_all;
4use tokio::runtime::Runtime; 4use tokio::runtime::Runtime;
5 5
6use crate::app::pages::global::ListItem;
7
8pub enum ItemType { 6pub enum ItemType {
9 Video, 7 Video,
10 Playlist, 8 Playlist,
11} 9}
12 10
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>> {
14 thread::spawn(move || { 14 thread::spawn(move || {
15 let rt: Runtime = tokio::runtime::Runtime::new().unwrap(); 15 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 }
25 16
26 let _ = rt.block_on(download_items(urls)); 17 let _ = rt.block_on(download_items(list));
27 }); 18 });
28 19
29 Ok(()) 20 Ok(())
30} 21}
31 22
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>> {
33 let mut actions = Vec::new(); 24 let mut actions = Vec::new();
34 let mut path = home::home_dir().expect("Cannot get your home directory"); 25 let mut path = home::home_dir().expect("Cannot get your home directory");
35 path.push(".siriusmart"); 26 path.push(".cache");
36 path.push("youtube-tui"); 27 path.push("youtube-tui");
37 path.push("cache");
38 path.push("thumbnails"); 28 path.push("thumbnails");
39 29
40 for (url, video_id, item_type) in urls { 30 for (url, video_id, item_type) in urls.iter() {
41 path.push(match item_type { 31 path.push(match item_type {
42 ItemType::Video => "videos", 32 ItemType::Video => "videos",
43 ItemType::Playlist => "playlists", 33 ItemType::Playlist => "playlists",
@@ -47,7 +37,7 @@ pub async fn download_items(urls: Vec<(&str, &str, ItemType)>) -> Result<(), Box
47 37
48 if !path.exists() { 38 if !path.exists() {
49 actions.push(fetch_url( 39 actions.push(fetch_url(
50 url, 40 url.as_str(),
51 path.clone().into_os_string().into_string().unwrap(), 41 path.clone().into_os_string().into_string().unwrap(),
52 )); 42 ));
53 } 43 }
src/lib.rs +2 −1
@@ -1,4 +1,5 @@
1pub mod app; 1pub mod app;
2pub mod traits; 2pub mod traits;
3pub mod widgets; 3pub 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::{
9 Terminal, 9 Terminal,
10}; 10};
11use youtube_tui::{ 11use 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},
13 traits::LoadItem, 17 traits::LoadItem,
14}; 18};
15 19
16fn main() -> Result<(), Box<dyn Error>> { 20fn main() -> Result<(), Box<dyn Error>> {
17 init()?; 21 init()?;
18 22
19 let app = App::new(); 23 let app = App::default();
20 24
21 enable_raw_mode()?; 25 enable_raw_mode()?;
22 let mut stdout = io::stdout(); 26 let mut stdout = io::stdout();
@@ -40,17 +44,18 @@ fn main() -> Result<(), Box<dyn Error>> {
40} 44}
41 45
42fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> { 46fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> {
43 app.message = Some(String::from("Loading videos..."));
44 loop { 47 loop {
45
46
47 if app.render { 48 if app.render {
48 ui(&mut terminal, &mut app)?; 49 ui(&mut terminal, &mut app)?;
49 app.message = None;
50 app.render = false;
51 } 50 }
52 51
53 if app.load { 52 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)?;
54 let mut new_state = Vec::new(); 59 let mut new_state = Vec::new();
55 for row in app.state.iter() { 60 for row in app.state.iter() {
56 let mut row_vec = Vec::new(); 61 let mut row_vec = Vec::new();
@@ -68,26 +73,22 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
68 item: Item::MainMenu(item.clone()), 73 item: Item::MainMenu(item.clone()),
69 ..*row_item 74 ..*row_item
70 }); 75 });
71 //app.message = Some(String::from("An error occurred while loading videos")); 76 *app.message.lock().unwrap() = Some(e.to_string());
72 app.message = Some(e.to_string());
73 } 77 }
74 }, 78 },
75 Item::ItemInfo(item) => { 79 Item::ItemInfo(item) => match item.load_item(&app) {
76 match item.load_item(&app) { 80 Ok(new) => {
77 Ok(new) => { 81 row_vec.push(RowItem {
78 row_vec.push(RowItem { 82 item: Item::ItemInfo(*new),
79 item: Item::ItemInfo(*new), 83 ..*row_item
80 ..*row_item 84 });
81 }); 85 }
82 } 86 Err(e) => {
83 Err(e) => { 87 row_vec.push(RowItem {
84 row_vec.push(RowItem { 88 item: Item::ItemInfo(item.clone()),
85 item: Item::ItemInfo(item.clone()), 89 ..*row_item
86 ..*row_item 90 });
87 }); 91 *app.message.lock().unwrap() = Some(e.to_string());
88 //app.message = Some(String::from("An error occurred while loading videos"));
89 app.message = Some(e.to_string());
90 }
91 } 92 }
92 }, 93 },
93 _ => { 94 _ => {
@@ -108,7 +109,8 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
108 app.state = new_state; 109 app.state = new_state;
109 110
110 app.load = false; 111 app.load = false;
111 app.render = true; 112 terminal.clear()?;
113 ui(&mut terminal, &mut app)?;
112 } else { 114 } else {
113 match event::read()? { 115 match event::read()? {
114 event::Event::Key(key) => { 116 event::Event::Key(key) => {
@@ -118,7 +120,9 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
118 return Ok(()); 120 return Ok(());
119 } 121 }
120 KeyCode::Backspace => { 122 KeyCode::Backspace => {
121 app.pop(); 123 if app.pop() {
124 terminal.clear()?;
125 }
122 app.render = true; 126 app.render = true;
123 continue; 127 continue;
124 } 128 }
@@ -126,12 +130,17 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
126 app.history = Vec::new(); 130 app.history = Vec::new();
127 continue; 131 continue;
128 } 132 }
133 KeyCode::Home => {
134 terminal.clear()?;
135 app.home();
136 continue;
137 }
129 _ => {} 138 _ => {}
130 } 139 }
131 } 140 }
132 141
133 app = app.key_input(key.code); 142 app = app.key_input(key.code);
134 app.render = true; 143 app.render = true;
135 } 144 }
136 event::Event::Resize(_, _) => { 145 event::Event::Resize(_, _) => {
137 app.render = true; 146 app.render = true;
@@ -147,13 +156,16 @@ fn ui<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<(), Box<d
147 app.render(&mut frame); 156 app.render(&mut frame);
148 })?; 157 })?;
149 158
159 *app.message.lock().unwrap() = None;
160 app.render = false;
161
150 Ok(()) 162 Ok(())
151} 163}
152 164
153fn init() -> Result<(), Box<dyn Error>> { 165fn init() -> Result<(), Box<dyn Error>> {
154 let mut dir = home::home_dir().expect("Cannot get your home directory"); 166 let mut dir = home::home_dir().expect("Cannot get your home directory");
155 167
156 dir.push(".siriusmart"); 168 dir.push(".cache");
157 if !dir.exists() { 169 if !dir.exists() {
158 fs::create_dir(&dir)?; 170 fs::create_dir(&dir)?;
159 } 171 }
@@ -163,13 +175,6 @@ fn init() -> Result<(), Box<dyn Error>> {
163 fs::create_dir(&dir)?; 175 fs::create_dir(&dir)?;
164 } 176 }
165 177
166 dir.push("cache");
167
168 if dir.exists() {
169 fs::remove_dir_all(&dir)?;
170 }
171 fs::create_dir(&dir)?;
172
173 dir.push("thumbnails"); 178 dir.push("thumbnails");
174 179
175 if !dir.exists() { 180 if !dir.exists() {
@@ -196,7 +201,7 @@ fn init() -> Result<(), Box<dyn Error>> {
196fn exit() -> Result<(), Box<dyn Error>> { 201fn exit() -> Result<(), Box<dyn Error>> {
197 let mut dir = home::home_dir().expect("Cannot get your home directory"); 202 let mut dir = home::home_dir().expect("Cannot get your home directory");
198 203
199 dir.push(".siriusmart"); 204 dir.push(".cache");
200 dir.push("youtube-tui"); 205 dir.push("youtube-tui");
201 dir.push("cache"); 206 dir.push("cache");
202 207
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;
3use tui::{ 1use tui::{
4 buffer::Buffer, 2 buffer::Buffer,
5 layout::{Margin, Rect}, 3 layout::{Margin, Rect},
@@ -8,6 +6,8 @@ use tui::{
8}; 6};
9use viuer::{print_from_file, Config}; 7use viuer::{print_from_file, Config};
10 8
9use crate::structs::ListItem;
10
11#[derive(Clone)] 11#[derive(Clone)]
12pub struct ItemDisplay { 12pub struct ItemDisplay {
13 pub item: ListItem, 13 pub item: ListItem,
@@ -16,17 +16,16 @@ pub struct ItemDisplay {
16impl Widget for ItemDisplay { 16impl Widget for ItemDisplay {
17 fn render(self, area: Rect, buf: &mut Buffer) { 17 fn render(self, area: Rect, buf: &mut Buffer) {
18 match self.item { 18 match self.item {
19 ListItem::Video(video) => { 19 ListItem::MiniVideo(video) => {
20 let mut path = home::home_dir().expect("Cannot get your home directory"); 20 let mut path = home::home_dir().expect("Cannot get your home directory");
21 path.push(".siriusmart"); 21 path.push(".cache");
22 path.push("youtube-tui"); 22 path.push("youtube-tui");
23 path.push("cache");
24 path.push("thumbnails"); 23 path.push("thumbnails");
25 path.push("videos"); 24 path.push("videos");
26 path.push(format!("{}.png", video.video_id)); 25 path.push(format!("{}.png", video.video_id));
27 let exists = path.exists(); 26 let exists = path.exists();
28 let mut image_transform = area; 27 let mut image_transform = area;
29 if exists{ 28 if exists {
30 if image_transform.width * 9 > image_transform.height * 2 * 16 { 29 if image_transform.width * 9 > image_transform.height * 2 * 16 {
31 image_transform.width = image_transform.height * 2 * 16 / 9; 30 image_transform.width = image_transform.height * 2 * 16 / 9;
32 } else { 31 } else {
@@ -53,10 +52,113 @@ impl Widget for ItemDisplay {
53 let mut to_print = Vec::new(); 52 let mut to_print = Vec::new();
54 to_print.push((String::from("[Video]"), Style::default().fg(Color::Gray))); 53 to_print.push((String::from("[Video]"), Style::default().fg(Color::Gray)));
55 to_print.push((video.title, Style::default().fg(Color::LightBlue))); 54 to_print.push((video.title, Style::default().fg(Color::LightBlue)));
56 to_print.push((format!("Uploaded by {}", video.author), Style::default().fg(Color::LightGreen))); 55 to_print.push((
57 to_print.push((format!("Views: {}", video.view_count.separate_with_commas()), Style::default().fg(Color::LightYellow))); 56 format!("Uploaded by {}", video.author),
58 to_print.push((format!("Published {}", video.published), Style::default().fg(Color::LightMagenta))); 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 };
59 107
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 ));
60 162
61 for (mut item, style) in to_print { 163 for (mut item, style) in to_print {
62 if y > area.height + area.y - 1 { 164 if y > area.height + area.y - 1 {