Commit 5e1ba1714e

5e1ba1714e89d3ca38d2e87ac89018c2accc9dd3

parent: 1d6be1e815

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-11-11 19:44 UTC

0.5.0

Layout: unified · split

.gitignore +1 −1
@@ -1,2 +1,2 @@
1/target 1/target
2*.svg\ No newline at end of file 2/docs/book
Cargo.lock −25
@@ -426,7 +426,6 @@ checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0"
426dependencies = [ 426dependencies = [
427 "futures-channel", 427 "futures-channel",
428 "futures-core", 428 "futures-core",
429 "futures-executor",
430 "futures-io", 429 "futures-io",
431 "futures-sink", 430 "futures-sink",
432 "futures-task", 431 "futures-task",
@@ -449,34 +448,12 @@ version = "0.3.25"
449source = "registry+https://github.com/rust-lang/crates.io-index" 448source = "registry+https://github.com/rust-lang/crates.io-index"
450checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" 449checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"
451 450
452[[package]]
453name = "futures-executor"
454version = "0.3.25"
455source = "registry+https://github.com/rust-lang/crates.io-index"
456checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2"
457dependencies = [
458 "futures-core",
459 "futures-task",
460 "futures-util",
461]
462
463[[package]] 451[[package]]
464name = "futures-io" 452name = "futures-io"
465version = "0.3.25" 453version = "0.3.25"
466source = "registry+https://github.com/rust-lang/crates.io-index" 454source = "registry+https://github.com/rust-lang/crates.io-index"
467checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" 455checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb"
468 456
469[[package]]
470name = "futures-macro"
471version = "0.3.25"
472source = "registry+https://github.com/rust-lang/crates.io-index"
473checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d"
474dependencies = [
475 "proc-macro2",
476 "quote",
477 "syn",
478]
479
480[[package]] 457[[package]]
481name = "futures-sink" 458name = "futures-sink"
482version = "0.3.25" 459version = "0.3.25"
@@ -495,10 +472,8 @@ version = "0.3.25"
495source = "registry+https://github.com/rust-lang/crates.io-index" 472source = "registry+https://github.com/rust-lang/crates.io-index"
496checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" 473checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"
497dependencies = [ 474dependencies = [
498 "futures-channel",
499 "futures-core", 475 "futures-core",
500 "futures-io", 476 "futures-io",
501 "futures-macro",
502 "futures-sink", 477 "futures-sink",
503 "futures-task", 478 "futures-task",
504 "memchr", 479 "memchr",
Cargo.toml +18 −14
@@ -1,34 +1,38 @@
1[package] 1[package]
2name = "youtube-tui" 2name = "youtube-tui"
3version = "0.5.0" 3version = "0.5.0"
4edition = "2021"
5authors = ["Siriusmart <siriusmart@tuta.io>"] 4authors = ["Siriusmart <siriusmart@tuta.io>"]
5edition = "2021"
6description = "An aesthetically pleasing YouTube TUI written in Rust" 6description = "An aesthetically pleasing YouTube TUI written in Rust"
7documentation = "https://docs.rs/youtube-tui"
7readme = "README.md" 8readme = "README.md"
9homepage = "https://siriusmart.github.io/youtube-tui"
10repository = "https://github.com/siriusmart/youtube-tui"
8license = "GPL-3.0" 11license = "GPL-3.0"
12license-file = "LICENSE"
9keywords = ["cli", "terminal", "youtube", "tui"] 13keywords = ["cli", "terminal", "youtube", "tui"]
10categories =["command-line-interface", "command-line-utilities"] 14categories =["command-line-interface", "command-line-utilities"]
11repository = "https://github.com/Siriusmart/youtube-tui" 15exclude = ["/docs"]
12 16
13# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 17# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
14 18
15[dependencies] 19[dependencies]
16serde = {version = "1.0", features = ["derive"]} 20serde = {version = "1.0", default-features = false, features = ["derive"]}
17tui = {version = "0.19", features = ["serde"]} 21tui = {version = "0.19", default-features = false, features = ["serde"]}
18crossterm = {version = "0.25", features = ["serde"]} 22crossterm = {version = "0.25", default-features = false, features = ["serde"]}
19viuer = {version = "0.6", features = ["sixel"]} 23viuer = {version = "0.6", default-features = false, features = ["sixel"]}
20home = "0.5" 24home = "0.5"
21chrono = {version = "0.4", default-features = false, features = ["clock"]} 25chrono = {version = "0.4", default-features = false, features = ["clock"]}
22tui-additions = {version = "0.1", default-features = false, features = ["framework", "widgets"]} 26tui-additions = {version = "0.1", default-features = false, features = ["framework", "widgets"]}
23typemap = "0.3" 27typemap = {version = "0.3", default-features = false}
24invidious = {version = "0.4", default-features = false, features = ["reqwest"]} 28invidious = {version = "0.4", default-features = false, features = ["reqwest"]}
25serde_yaml = "0.9" 29serde_yaml = {version = "0.9", default-features = false}
26dyn-clone = "1.0" 30dyn-clone = {version = "1.0", default-features = false}
27tokio = "1.21" 31tokio = {version = "1.21", default-features = false}
28futures = "0.3" 32futures = {version = "0.3", default-features = false}
29reqwest = "0.11" 33reqwest = {version = "0.11", default-features = false}
30serde_json = "1.0" 34serde_json = {version = "1.0", default-features = false}
31execute = "0.2" 35execute = {version = "0.2", default-features = false}
32 36
33# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]} 37# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
34# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]} 38# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]}
README.md +44 −66
@@ -4,93 +4,71 @@
4[![](https://img.shields.io/crates/v/youtube-tui?label=crates.io%20version)](https://crates.io/crates/youtube-tui) 4[![](https://img.shields.io/crates/v/youtube-tui?label=crates.io%20version)](https://crates.io/crates/youtube-tui)
5![](https://shields.io/github/stars/siriusmart/youtube-tui?style=social) 5![](https://shields.io/github/stars/siriusmart/youtube-tui?style=social)
6 6
7# YouTube TUI 7*Read more in the [user manual](https://siriusmart.github.io/youtube-tui) (including installation gude and documentation).*
8 8
9An aesthetically pleasing YouTube TUI written in Rust. 9# Overview
10 10
11> ## Warning 11Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal.
12>
13> The current code on GitHub is a rewritten-from-scratch version of the old code, it is currently *somewhat* usable. All the config files are undocumented and you'll need to *read the code* or wait for the documentation to come out after the code is done.
14>
15> The default config files are in the `example config files/` folder, go ahead and appreciate :D
16>
17> ### Todo before release:
18> - Watch history
19>
20> The previous release on `crates.io` is unaffected, and it should be used instead.
21 12
13![](./docs/src/images/search-showcase.png)
22 14
23## Overview 15It is like an *app launcher*, it launches other programs to do the heavy lifting (for example, `mpv` for playing videos).
24YouTube TUI is a text user interface that provides a clean TUI for browsing YouTube. It can perform YouTube query searches, view and inspect channels, and play the desired content as a regular video or audio-only stream for saving bandwidth.
25 16
26![Screenshot](https://cdn.discordapp.com/attachments/906941311142219816/990684947830419526/Screenshot_20220626_192433.png) 17## Customisable
27 18
28## User manual 19The YouTube TUI can be customised through config files, they are located in `~/.config/youtube-tui` and are in the YAML format.
29 20
30[YouTube TUI user manual](https://siriusmart.github.io/youtube-tui) 21Here's an example of the config file:
31 22
32## Installation 23```yaml
24invidious_instance: https://vid.puffyan.us
25max_watch_history: 50
26allow_unicode: false
27images: Sixels
28refresh_after_modifying_search_filters: true
29provider: YouTube
30env:
31 browser: firefox
32 video-player: mpv
33 youtube-downloader: yt-dlp
34 terminal-emulator: konsole -e
33 35
34### Install from crates.io
35
36```bash
37cargo install youtube-tui
38``` 36```
39 37
40## Usage 38Anything from layouts to colours and keybindings can be customised, more on that later.
41
42* A video player (Defaults to `MPV`)
43* A terminal emulator (Defaults to `konsole`)
44* A YouTube downloader (Defaults to `yt-dlp`, it is recommended that you do not use `yt-dl`, as the download speeds are ludicrously slow)
45
46> None of these dependencies is required, and you can change the defaults in the config file `commands.yml`
47
48### Movement
49
50|Key|What does it do|
51|---|---|
52|Arrow/Vim keys|Move in the corresponding direction|
53|Enter|Select/Launch|
54|Q|Quit the program|
55
56Check the user manual [here](https://siriusmart.github.io/youtube-tui)
57
58> ### Note
59>
60> These keys only work when nothing is selected. When something is selected, your key presses are passed directly to the "object" you've selected. Press escape (Esc) if you want to deselect.
61
62### Config
63
64All config files are located at `~/.config/youtube-tui/`, will write documentation for that later
65 39
66## Known issues 40## Dependency-free
67 41
68### Missing hash key: "selected" 42The YouTube TUI does not work on its own, it is instead like a *TUI frontend* for programs like `mpv` or `yt-dlp`/`youtube-dl`.
69 43
70When viewing the playlists page in a channel, it gives you a `Missing hash key: "selected"`. This is because Invidious was not able to fetch the requested playlists. 44However, the programs to launch can be changed, and therefore the YouTube TUI <u>does not rely on any specific dependencies</u> to run.
71 45
72You should also see an error when visiting [this URL](https://vid.puffyan.us/api/v1/channels/UCAkuTH35kk3W1EL9vq6dj6A/playlists) 46![](./docs/src/images/custom-dependencies-showcase.png)
73 47
74Here's the [opened issue](https://github.com/iv-org/invidious/issues/3154) 48## Powerful
75 49
76## Todo (First priority on top) 50The YouTube TUI allows you to browse YouTube with (almost) all of it's features, functions including:
77 51
78* Go directly to a page by URL 52- View popular/trending videos
79* Vim-like commands in the status bar 53- View information about channels, playlists and videos
80* Save as local playlist/video 54- Use search filters to sort and filter search results
81* Command line launch options 55- Save browsing history
82* Channel search and channel video sort
83* Recommended videos
84 56
85## Credits 57### What it doesn't have
86 58
87* [ytfzf](https://github.com/pystardust/ytfzf) by [pystardust](https://github.com/pystardust) - The TUI I used to watch on YouTube, gave me an idea of how this program is going to work 59- Vim-like commands (first priority)
88* [Terminal Typeracer](https://gitlab.com/ttyperacer/terminal-typeracer) by [Darrien Glasser](https://gitlab.com/DarrienG) - A very clean-looking TUI for typing speed test, gave me an idea of how this program should look like 60- Channel search (will implement)
89* [Invidious](https://invidious.io) - For having a nice API for doing YouTube searches and stuff. (I made a wrapper for the API you can check it [here](https://crates.io/crates/invidious) out if you want to) 61- Channel videos sorting (will implement)
62- Subscriptions (will implement)
63- Recommendations/comments (probably will not implement)
90 64
65## How to contribute
91 66
92... and of course, credits to myself for not having the ability to read the docs for ytfzf and decided to make my own instead. 67You will need a <u>general knowledge</u> of the Rust programming language, and the ability to *understand my spaghetti*.
93 68
94## Anything Missing? 691. Open an issue to make sure nobody else is working on the same feature
702. Write code
713. Open a pull request
724. Get merged?
95 73
96If there is a bug or you got a nice idea of what can be added to this program, feel free to open a GitHub issue. Thx :D 74Or just *fix that typo in README* -_-
docs/.gitignore added +1
@@ -0,0 +1 @@
1book
docs/book.toml added +12
@@ -0,0 +1,12 @@
1[book]
2authors = ["Siriusmart"]
3language = "en"
4multilingual = false
5src = "src"
6title = "YouTube TUI User Manual"
7description = "The user manual, documentation and contribution guide for YouTube TUI"
8
9[output.html]
10default-theme = "ayu"
11git-repository-url = "https://github.com/siriusmart/youtube-tui/tree/master/docs"
12edit-url-template = "https://github.com/siriusmart/youtube-tui/edit/master/docs/{path}"
docs/src/README.md added +66
@@ -0,0 +1,66 @@
1# Overview
2
3Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal.
4
5![](./images/search-showcase.png)
6
7It is like an *app launcher*, it launches other programs to do the heavy lifting (for example, `mpv` for playing videos).
8
9## Customisable
10
11The YouTube TUI can be customised through config files, they are located in `~/.config/youtube-tui` and are in the YAML format.
12
13Here's an example of the config file:
14
15```yaml
16invidious_instance: https://vid.puffyan.us
17max_watch_history: 50
18allow_unicode: false
19images: Sixels
20refresh_after_modifying_search_filters: true
21provider: YouTube
22env:
23 browser: firefox
24 video-player: mpv
25 youtube-downloader: yt-dlp
26 terminal-emulator: konsole -e
27
28```
29
30Anything from layouts to colours and keybindings can be customised, more on that later.
31
32## Dependency-free
33
34The YouTube TUI does not work on its own, it is instead like a *TUI frontend* for programs like `mpv` or `yt-dlp`/`youtube-dl`.
35
36However, the programs to launch can be changed, and therefore the YouTube TUI <u>does not rely on any specific dependencies</u> to run.
37
38![](./images/custom-dependencies-showcase.png)
39
40## Powerful
41
42The YouTube TUI allows you to browse YouTube with (almost) all of it's features, functions including:
43
44- View popular/trending videos
45- View information about channels, playlists and videos
46- Use search filters to sort and filter search results
47- Save browsing history
48
49### What it doesn't have
50
51- Vim-like commands (first priority)
52- Channel search (will implement)
53- Channel videos sorting (will implement)
54- Subscriptions (will implement)
55- Recommendations/comments (probably will not implement)
56
57## How to contribute
58
59You will need a <u>general knowledge</u> of the Rust programming language, and the ability to *understand my spaghetti*.
60
611. Open an issue to make sure nobody else is working on the same feature
622. Write code
633. Open a pull request
644. Get merged?
65
66Or just *fix that typo in README* -_-
docs/src/SUMMARY.md added +27
@@ -0,0 +1,27 @@
1# Summary
2
3- [Overview](README.md)
4- [Installation](installation.md)
5- [Basic usage](basic_usage.md)
6
7# Customisation guide
8
9- [Config files](config/README.md)
10 - [main](config/main.md)
11 - [commands](config/commands.md)
12 - [keybindings](config/keybindings.md)
13 - [pages](config/pages.md)
14 - [appearance](config/appearance.md)
15 - [search](config/search.md)
16
17# Contributing
18
19- [How it works]()
20 - [Framework]()
21 - [Invidious API]()
22 - [Individual items]()
23
24- [Contribution guide]()
25
26- [Changelogs](changelogs.md)
27- [Contributors](contributors.md)
docs/src/basic_usage.md added +58
@@ -0,0 +1,58 @@
1# Basic usage
2
3Here is a basic how-to guide on the TUI.
4
5## Cursor
6
7The *cursor* can be moved using arrow keys, or Vim keybindings (hjkl).
8
9![](./images/cursor-showcasae.png)
10
11The item with the cursor hovering will have a <u>red outline</u>.
12
13> Everything here refers to the *latest default config*, including the keybindings.
14
15|Function|Key(s)|
16|---|---|
17|Select|Enter|
18|Deselect|Esc|
19|Cursor up|Up arrow / `k`|
20|Cursor down|Down arrow / `j`|
21|Cursor left|Left arrow / `h`|
22|Cursor right|Right arrow / `l`|
23|Previous page|Backspace / Alt + Left arrow|
24|First page history|Home|
25|Clear page history|End|
26|Quit|`q`|
27
28## Selection
29
30Selecting an item allows you to move the cursor within that item, to select an item, press `Enter`.
31
32When nothing is selected, you can move the cursor between items, to deselect from an item, hit `Esc`.
33
34## Searching
35
36Type the search query when the search bar and press `Enter`, use arrow keys to move the cursor around.
37
38To apply search filters, select the button with 3 dots (`...`) to the right of the search bar, hit enter to start modifying and enter again to save. Pressing `Esc` should reload the current search page to apply the filters.
39
40![](./images/search-filters-showcase.png)
41
42## Playing videos and playlists
43
44> This part assumes that you use `mpv` as your video player, `konsole` as your terminal emulator, `yt-dlp` as your YouTube video downloader, and `firefox` as your browser.
45>
46> If that is not the case, you can learn how to change that in the *custom commands* section.
47
48Press `Enter` to select a video or playlist from any lists, then move the cursor to the *bottom item* where you can play, download and open the webpage in browser.
49
50### Playlist views
51
52The playlist page allows two different view modes, the first of which is *commands view* - similar to what the video page offers.
53
54The other one is *videos view*, which allows you to look at each videos in the playlist individually.
55
56## Buttons
57
58Buttons have no use on their own, but allows you to navigate between pages.
docs/src/changelogs.md added +33
@@ -0,0 +1,33 @@
1# Changelogs
2
3## v0.5.0
4
5#### Added
6
7- Entire TUI rewritten from scratch, now using the <a href="https://crates.io/crates/tui-additions" target=_blank>`tui-additions`</a> crate
8- Sixels image support
9- Improved config files
10
11## v0.4.4
12
13#### Added
14
15- Added default select item for each page (can be changed in `layouts.yml`)
16
17#### Fixes
18
19- Video list view in playlists not working
20- Channel view scroll causes panic
21- Search options gray backgound + image covering popup
22
23### v0.4.3
24
25#### Added
26
27- Refreshing page
28- Key modifiers for key bindings
29- Image loading can be disabled
30
31#### Fixes
32
33- Fixed cache not being cleared after exit
docs/src/config/README.md added +14
@@ -0,0 +1,14 @@
1# Config files
2
3Config files are located in `~/.config/youtube-tui`, modifying them changes the behavior of the TUI accordingly.
4
5Config files will be generated if not present, backed up and regenerated if there is an issue reading it (most likely caused by changes made by user or updates).
6
7In the following sections we will go through all config files including:
8
9- [`main.yml`](./main.md)
10- [`commands.yml`](./commands.md)
11- [`keybindings.yml`](./keybindings.md)
12- [`pages.yml`](./pages.md)
13- [`appearance.yml`](./appearance.md)
14- `search.yml`
docs/src/config/appearance.md added +72
@@ -0,0 +1,72 @@
1# Appearance config
2
3Appearance config controls the colours and the "looks and feel" of the TUI, it is located in `~/.config/youtube-tui/appearance.yml`.
4
5## Example appearance config
6
7```yaml
8borders: Rounded
9colors:
10 text: Reset
11 text_special: Reset
12 text_secondary: Reset
13 text_error: LightRed
14 outline: Reset
15 outline_selected: LightBlue
16 outline_hover: LightRed
17 outline_secondary: LightYellow
18 message_outline: !Rgb # todo: represent colours with hex values or `rgb(r,g,b)`
19 - 255
20 - 127
21 - 0
22 message_error_outline: LightRed
23 message_success_outline: LightGreen
24 item_info:
25 tag: Gray
26 title: LightBlue
27 description: Gray
28 author: LightGreen
29 viewcount: LightYellow
30 length: LightCyan
31 published: LightMagenta
32 video_count: !Rgb
33 - 131
34 - 141
35 - 255
36 sub_count: !Rgb
37 - 101
38 - 255
39 - 186
40 likes: !Rgb
41 - 200
42 - 255
43 - 129
44 genre: !Rgb
45 - 255
46 - 121
47 - 215
48```
49
50<hr>
51
52Below are the description of each of the fields:
53
54### borders
55
56The style of the borders/outline, if outdated view <a href="https://docs.rs/tui/latest/tui/widgets/enum.BorderType.html" target=_blank>*here*</a>.
57
58*Accept: `Plain`/`Rounded`/`Double`/`Thick`*
59
60### Literally everything else
61
62Any colours, here are the 2 main represenations of colours, for more check out this page <a href="https://docs.rs/tui/latest/tui/style/enum.Color.html" target=_blank>*here*</a>.
63
64#### Terminal colour
65
66This can be modified by the themes of your terminal.
67
68#### RGB
69
70RGB colour values, requires TrueColour support in terminal (for instance Windows CMD cannot display RBG colours).
71
72> Hex colour values to be implemented.
docs/src/config/commands.md added +88
@@ -0,0 +1,88 @@
1# Commands config
2
3The commands config file decides what options (that will run a certain command on select) to be display in the *video* and *playlist* page respectively, it is located in `~/.config/youtube-tui/commands.yml`.
4
5## Example commands config
6
7```yaml
8video:
9- Play video: ${video-player} ${embed-url}
10- Play audio: ${terminal-emulator} ${video-player} ${embed-url} --no-video
11- Open in browser: ${browser} ${url}
12- Download video (webm): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${embed-url}
13- 'Mode: ${provider}': '%switch-provider%'
14
15playlist:
16- Switch view: '%switch-view%'
17- Play all videos: ${video-player} ${all-videos}
18- Play all audio: ${terminal-emulator} ${video-player} ${all-videos} --no-video
19- Shuffle play all audio: ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle
20- Open in browser: ${browser} ${url}
21- Download all video (webm): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}
22- 'Mode: ${provider}': '%switch-provider%'
23```
24
25## Env variables
26
27Notice that a lot of the commands contains the `${label}` pattern, this actually replaces the text with the env variables set in `main.yml`, or is added by the current page (video or playlist) on-the-go.
28
29Replacing all these with known values it might look something like this:
30
31```yaml
32video:
33- Play video: mpv 'https://youtube.com/embed/dQw4w9WgXcQ'
34- Play audio: konsole -e mpv 'https://youtube.com/embed/dQw4w9WgXcQ' --no-video
35- Open in browser: firefox 'https://youtu.be/dQw4w9WgXcQ'
36- Download video (webm): konsole -e yt-dlp -o '~/Downloads/%(title)s-%(id)s.%(ext)s' 'https://youtube.com/embed/dQw4w9WgXcQ'
37- 'Mode: ${provider}': '%switch-provider%'
38
39playlist:
40- Switch view: '%switch-view%'
41- Play all videos: mpv 'https://youtube.com/embed/Z8oiddSsB6I' 'https://youtube.com/embed/yiS0DPekSDQ' 'https://youtube.com/embed/YhM8GYuDFps' # and much more...
42- Play all audio: konsole -e mpv 'https://youtube.com/embed/Z8oiddSsB6I' 'https://youtube.com/embed/yiS0DPekSDQ' 'https://youtube.com/embed/YhM8GYuDFps' --no-video
43- Shuffle play all audio: konsole -e mpv 'https://youtube.com/embed/Z8oiddSsB6I' 'https://youtube.com/embed/yiS0DPekSDQ' 'https://youtube.com/embed/YhM8GYuDFps' --no-video --shuffle
44- Open in browser: firefox 'https://www.youtube.com/playlist?list=PLdgHTasZAjYZlCXN9rTcX9LFOQ-RIrzCs'
45- Download all video (webm): konsole -e yt-dlp -o '~/Downloads/%(title)s-%(id)s.%(ext)s' 'https://youtube.com/embed/Z8oiddSsB6I' 'https://youtube.com/embed/yiS0DPekSDQ' 'https://youtube.com/embed/YhM8GYuDFps'
46- 'Mode: ${provider}': '%switch-provider%'
47```
48
49## Item commands
50
51(will be replaced by global vim-like commands in the next major version)
52
53Notice that there is another pattern in the commands, it is the `%label%` commands. They are special cases that are consumed by the item and is never actually ran as a system command.
54
55For instance `%switch-provider%` toggles the provider between `YouTube` and `Invidious`.
56
57<hr>
58
59Below are the description of each of the fields:
60
61### video
62
63Commands to be displayed in a video page.
64
65*Accept: `string_label: string_command` pairs*
66
67### playlist
68
69Commands to be displayed in a playlist page (commands view).
70
71*Accept: `string_label: string_command` pairs*
72
73## Env reference
74
75Does not include custom env set in `main.yml`.
76
77|Name|Page|Value|
78|---|---|---|
79|`url`|video & playlist|String url to the web page|
80|`embed-url`|video|String url to the embed video (required to play video using mpv from Invidious)|
81|`all-videos`|playlist|String url***s*** separated by space to all embed videos in a playlist|
82|`provider`|video & playlist|To display the current provider, is the only env that can be displayed in the label, and can only be used when `%switch-provider%` is the command|
83
84## Item command reference
85
86|Name|Page|Use|
87|---|---|---|
88|`swtich-provider`|video & playlist|Toggles the provider between `YouTube` and `Invidious`|
docs/src/config/keybindings.md added +55
@@ -0,0 +1,55 @@
1# Keybindings config
2
3The keybindings config binds each key to an action, or multiple keys for the same action. It can be found in `~/.config/youtube-tui/keybindings.yml`.
4
5## Example keybindings config
6
7```yaml
8Up:
9 0: MoveUp
10Down:
11 0: MoveDown
12Right:
13 0: MoveRight
14Left:
15 0: MoveLeft
16 4: Back
17Esc:
18 0: Deselect
19Backspace:
20 0: Back
21Enter:
22 0: Select
23```
24
25## Keys
26
27Keys are the name of the keys that are pressed in the keyboard, all keys are avaliable <a href="https://docs.rs/crossterm/latest/crossterm/event/enum.KeyCode.html" target=_blank>*here*</a>.
28
29## Key modifiers
30
31Key modifiers are the modifier keys that are pressed along with the actual key, for instance in `Ctrl + C` would have the modifier `Ctrl` and the key `C`.
32
33Each modifier has its own code, for instance `Shift` would be `1` and `Ctrl` would be `2`. The final modifier will be the <u>sum</u> of all modifier keys. (`Ctrl + Shift` would be a `3`).
34
35### Keys reference
36
37All possible keys can be found <a href="https://docs.rs/crossterm/latest/crossterm/event/enum.KeyCode.html" target=_blank>*here*</a>.
38
39> Enums are represented using the character `!`, for example the `q` key would be `!Char 'q'`
40>
41> `Shift + Q` however would be `!Char 'Q'` with `0` as modifier code as `Shift` turns `q` into an upper case character.
42
43### Modifiers reference
44
45|Modifier|Code|
46|---|---|
47|None|`0`|
48|`Shift`|`1`|
49|`Ctrl`|`2`|
50|`Alt`|`4`|
51|`Super`/"Windows" key|`8`|
52|`Hyper`|`16`|
53|`Meta`|`32`|
54
55All key modifiers (if any are added) will be in <a href="https://docs.rs/crossterm/latest/crossterm/event/struct.KeyModifiers.html" target=_blank>*the code*</a>.
docs/src/config/main.md added +97
@@ -0,0 +1,97 @@
1# The main config
2
3The main config file is located in `~/.config/youtube-tui/main.yml`.
4
5## Example main.yml
6
7```yaml
8invidious_instance: https://vid.puffyan.us
9max_watch_history: 50
10allow_unicode: false
11message_bar_default: All good :)
12images: Sixels
13refresh_after_modifying_search_filters: true
14image_index: 4
15provider: YouTube
16env:
17 browser: firefox
18 terminal-emulator: konsole -e
19 youtube-downloader: yt-dlp
20 video-player: mpv
21```
22
23<hr>
24
25Below are the description of each of the fields:
26
27### invidious_instance
28
29The Invidious instance you want to use, a full list of Invidious instances can be found here <a href="https://api.invidious.io" target=_blank>*here*</a>.
30
31*Accept: string of a valid url to an Invidious instance*
32
33### max_watch_history
34
35The maximum length that the watch history can hold, a value higher will record more items, but will also result in a larger file size in storage.
36
37*Accept: positive integer below 2<sup>*your CPU architecture*</sup> - 1*
38
39### allow_unicode
40
41Enable unicode in video and playlist names, doing so may cause unwanted behaviors like video name continuing into the info field to the right.
42
43*Accept: `true`/`false`*
44
45### message_bar_default
46
47The default message displayed in the message bar.
48
49*Accept: any string*
50
51### images
52
53How to display thumbnails, if `None` is selected video thumbnails will not be downloaded in the first place.
54
55*Accept: `Sixels`/`HalfBlocks`/`None`*
56
57### refresh_after_modifying_search_filters
58
59Whether to refresh the current search page after search filters are modified
60
61*Accept: `true`/`false`*
62
63### image_index
64
65The index in the array of thumbnail qualities you want to download
66
67Typically these are the avaliable qualities:
68
69|Index|Label|Resolution|
70|---|---|---|
71|0|maxres|1280 x 720|
72|1|maxresdefault|1280 x 720|
73|2|sddefault|640 x 480|
74|3|high|480 x 360|
75|4|medium|320 x 180|
76|5|default|120 x 90|
77|6|start|120 x 90|
78|7|middle|120 x 90|
79|8|end|120 x 90|
80
81Usually you don't want to use the max resolution as it will create a large gap between the page being loaded and before the thumbnails are started to get displayed
82
83*Accept: integer that is a valid index*
84
85### Provider
86
87This changes the `${url}` and `${embed_url}` of videos, allowing you to watch videos from Invidious if it is restricted on YouTube.
88
89(Don't always use Invidious if YouTube is working, because first of all the load time if gonna be much slower, and secondly you will be DDoSing Invidious)
90
91*Accept: `YouTube`/`Invidious`*
92
93### env
94
95Env are variables that can be used in `commands.yml`, this allows you to change multiple commands by modifying just one env variable. And not to be confused with system/terminal environment variables, these are just *"a thing"* that you can use in the TUI.
96
97*Accept: `string_key: string_value` pairs*
docs/src/config/pages.md added +57
@@ -0,0 +1,57 @@
1# Layout config
2
3The layout config determins the position of where each item is placed, mainly their order. The config file can be found in `~/.config/youtube-tui/pages.yml`.
4
5## Example layout config
6
7```yaml
8main_menu:
9 layout:
10 - !NonCenteredRow
11 - SearchBar
12 - SearchFilters
13 - !CenteredRow
14 - Popular
15 - Trending
16 - History
17 - !NonCenteredRow
18 - ItemList
19 - !NonCenteredRow
20 - MessageBar
21 message: Loading main menu...
22
23# and much more ...
24```
25
26## Items
27
28Each item is an individual "thing", these things can be optionally selectable, or hoverable by the cursor.
29
30## Rows
31
32A row is a horizontal row of items, it can be either centered (like the buttons) or non centered (which will align to the left).
33
34> Non centered rows are faster and less crash prone compared to centered rows.
35
36Each item are ordered from left to right.
37
38## Message
39
40The message to display when loading the page.
41
42### Items reference
43
44|Item|Can be used in page|Description|
45|---|---|---|
46|MessageBar|Any|The panel (default in the bottom of every page) that displays message and error messages|
47|SearchBar|Any|A text field that searches that entered query|
48|SearchFilters|Any|A button that brings up a popup for modifying search filters|
49|Trending|Any|Loads the trending page|
50|Popular|Any|Loads the popular page|
51|History|Any|Loads the watch history page|
52|ItemList|Main menu/search|Display multiple videos, channels, or playlists in a list|
53|SingleItemInfo|Single item|Display info of one single item (a single video or playlist)|
54|ChannelDisplay|Channel display|Display information of a channel, depending on the page|
55|ChannelMain|Channel display|Loads the main channel page|
56|ChannelVideos|Channel display|Loads the channel videos page|
57|ChannelPlaylists|Channel display|Loads the channel playlists page|
docs/src/config/search.md added +30
@@ -0,0 +1,30 @@
1# Default search options
2
3The default search query/filters when launching the TUI, this can be found in `~/.config/youtube-tui/search.yml`, but should not be "customised" like how you would to a config file because it's just a configurable default value.
4
5## Example search default value
6
7```yaml
8query: ''
9filters:
10 sort: Relevance
11 date: None
12 duration: None
13 type: All
14```
15
16<hr>
17
18Below are the description of each field
19
20### query
21
22The default query when you launch the TUI.
23
24*Accept: any string*
25
26### Sort
27
28How the search results are sorted.
29
30*Accept: `Relevance`/`Rating`/`Date`/`Views`*
docs/src/contributors.md added +13
@@ -0,0 +1,13 @@
1# Contributors
2
3## <a href="https://github.com/siriusmart" target=_blank>Siriusmart</a>
4
5Creator and main developer of YouTube TUI.
6
7## <a href="https://github.com/zaedus" target=_blank>Zaedus</a>
8
9Made the PKGBUILD and maintainer of the `youtube-tui-git` package on <a href="https://aur.archlinux.org/packages/youtube-tui-git" target=_blank>the AUR</a>.
10
11## <a href="https://github.com/fractal-tess" target=_blank>Fractal Tess</a>
12
13Fixed typos in README.
docs/src/images/cursor-showcasae.png added

Binary file not shown.

docs/src/images/custom-dependencies-showcase.png added

Binary file not shown.

docs/src/images/search-filters-showcase.png added

Binary file not shown.

docs/src/images/search-showcase.png added

Binary file not shown.

docs/src/installation.md added +49
@@ -0,0 +1,49 @@
1# Installation
2
3It's about download (or building) the binary and putting them in an easily accessible location (like `/bin/`).
4
5## Install from Crates.io (recommended)
6
7Crates.io is a repository for programs written in Rust, and the YouTube TUI is avaliable <a href="https://crates.io/crates/youtube-tui" target=_blank>*there*</a>.
8
9To install using this method, you will need `rustc` and `cargo` present. <a href="https://www.rust-lang.org/tools/install" target=_blank>*Here*</a>'s a tutorial on how to get them.
10
11Now, run the following command:
12
13```sh
14cargo install youtube-tui
15```
16
17> To check and update all programs installed from Crates.io, you can use CLI tools like <a href="https://crates.io/crates/cargo-update" target=_blank>*cargo-update*</a>.
18
19## AUR for Arch Linux (recommended)
20
21The YouTube TUI is avaliable in the AUR <a href="https://aur.archlinux.org/packages/youtube-tui-git" target=_blank>*here*</a>.
22
23Use an <a href="https://aur.archlinux.org" target=_blank>AUR</a> helper like <a href="https://aur.archlinux.org/packages/yay" target=_blank>`yay`</a> to install.
24
25```sh
26yay -S youtube-tui # replace `yay` with your AUR helper
27```
28
29## Download a compiled binary
30
31Download the compiled binary for your system from <a href="https://github.com/Siriusmart/youtube-tui/releases" target=_blank>*GitHub releases*</a> and manually place it in *a folder* (e.g. `~/.cargo/bin/` or `/bin/`)
32
33## Build from source
34
35Use the `cargo` command:
36
37```sh
38cargo install --git https://github.com/siriusmart/youtube-tui
39```
40
41### Confirm YouTube TUI has been installed
42
43Run the following command in terminal:
44
45```sh
46youtube-tui
47```
48
49If installed correctly, a TUI should be launched. Press `q` to close the TUI.
src/config/appearance.rs +1 −1
@@ -209,7 +209,7 @@ fn video_count_default() -> Color {
209} 209}
210 210
211fn sub_count_default() -> Color { 211fn sub_count_default() -> Color {
212 Color::LightYellow 212 Color::Rgb(101, 255, 186)
213} 213}
214 214
215fn likes_default() -> Color { 215fn likes_default() -> Color {
src/config/commands.rs +2
@@ -5,6 +5,7 @@ use typemap::Key;
5 5
6use crate::global::traits::ConfigTrait; 6use crate::global::traits::ConfigTrait;
7 7
8/// Stores combinations of label and commands
8#[derive(Clone)] 9#[derive(Clone)]
9pub struct CommandsConfig { 10pub struct CommandsConfig {
10 pub video: Vec<(String, String)>, 11 pub video: Vec<(String, String)>,
@@ -32,6 +33,7 @@ impl From<CommandsConfigSerde> for CommandsConfig {
32 } 33 }
33} 34}
34 35
36/// Hashmaps are better formatted in YAML, impls Into<CommandsConfig>
35// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look 37// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look
36#[derive(Serialize, Deserialize, Clone)] 38#[derive(Serialize, Deserialize, Clone)]
37pub struct CommandsConfigSerde { 39pub struct CommandsConfigSerde {
src/config/keybindings.rs +1 −1
@@ -49,7 +49,7 @@ impl Default for KeyBindingsConfig {
49 (KeyCode::Enter, HashMap::from([(0, KeyAction::Select)])), 49 (KeyCode::Enter, HashMap::from([(0, KeyAction::Select)])),
50 (KeyCode::Esc, HashMap::from([(0, KeyAction::Deselect)])), 50 (KeyCode::Esc, HashMap::from([(0, KeyAction::Deselect)])),
51 (KeyCode::Char('q'), HashMap::from([(0, KeyAction::Exit)])), 51 (KeyCode::Char('q'), HashMap::from([(0, KeyAction::Exit)])),
52 (KeyCode::Char('r'), HashMap::from([(0, KeyAction::Reload)])), 52 (KeyCode::Char('r'), HashMap::from([(2, KeyAction::Reload)])),
53 // history 53 // history
54 (KeyCode::Backspace, HashMap::from([(0, KeyAction::Back)])), 54 (KeyCode::Backspace, HashMap::from([(0, KeyAction::Back)])),
55 (KeyCode::End, HashMap::from([(0, KeyAction::ClearHistory)])), 55 (KeyCode::End, HashMap::from([(0, KeyAction::ClearHistory)])),
src/config/main.rs +10 −9
@@ -8,8 +8,8 @@ use typemap::Key;
8pub struct MainConfig { 8pub struct MainConfig {
9 #[serde(default = "invidious_instance_default")] 9 #[serde(default = "invidious_instance_default")]
10 pub invidious_instance: String, 10 pub invidious_instance: String,
11 #[serde(default = "piped_instance_default")] 11 #[serde(default = "max_watch_history_default")]
12 pub piped_instance: String, 12 pub max_watch_history: usize,
13 #[serde(default = "allow_unicode_default")] 13 #[serde(default = "allow_unicode_default")]
14 pub allow_unicode: bool, 14 pub allow_unicode: bool,
15 #[serde(default = "message_bar_default_default")] 15 #[serde(default = "message_bar_default_default")]
@@ -37,7 +37,7 @@ impl Default for MainConfig {
37 fn default() -> Self { 37 fn default() -> Self {
38 Self { 38 Self {
39 invidious_instance: invidious_instance_default(), 39 invidious_instance: invidious_instance_default(),
40 piped_instance: piped_instance_default(), 40 max_watch_history: max_watch_history_default(),
41 allow_unicode: allow_unicode_default(), 41 allow_unicode: allow_unicode_default(),
42 message_bar_default: message_bar_default_default(), 42 message_bar_default: message_bar_default_default(),
43 images: images_default(), 43 images: images_default(),
@@ -55,7 +55,8 @@ impl ConfigTrait for MainConfig {
55 const LABEL: &'static str = "main"; 55 const LABEL: &'static str = "main";
56} 56}
57 57
58#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] 58/// how images are handled/displayed
59#[derive(Clone, Copy, Serialize, Deserialize, PartialEq)]
59pub enum Images { 60pub enum Images {
60 r#None, 61 r#None,
61 HalfBlocks, 62 HalfBlocks,
@@ -101,16 +102,12 @@ fn invidious_instance_default() -> String {
101 String::from("https://vid.puffyan.us") 102 String::from("https://vid.puffyan.us")
102} 103}
103 104
104fn piped_instance_default() -> String {
105 String::from("https://piped.garudalinux.org")
106}
107
108fn message_bar_default_default() -> String { 105fn message_bar_default_default() -> String {
109 String::from("All good :)") 106 String::from("All good :)")
110} 107}
111 108
112const fn images_default() -> Images { 109const fn images_default() -> Images {
113 Images::HalfBlocks 110 Images::Sixels
114} 111}
115 112
116const fn image_index_default() -> usize { 113const fn image_index_default() -> usize {
@@ -129,6 +126,10 @@ const fn provider_default() -> Provider {
129 Provider::YouTube 126 Provider::YouTube
130} 127}
131 128
129const fn max_watch_history_default() -> usize {
130 50
131}
132
132fn default_env() -> HashMap<String, String> { 133fn default_env() -> HashMap<String, String> {
133 HashMap::from([ 134 HashMap::from([
134 (String::from("video-player"), String::from("mpv")), 135 (String::from("video-player"), String::from("mpv")),
src/config/pages.rs +20 −1
@@ -156,16 +156,29 @@ impl PageRow {
156/// All avaliable items for `PageConfig` 156/// All avaliable items for `PageConfig`
157#[derive(Clone, Copy, Serialize, Deserialize)] 157#[derive(Clone, Copy, Serialize, Deserialize)]
158pub enum PageItems { 158pub enum PageItems {
159 /// the search bar
159 SearchBar, 160 SearchBar,
161 /// a list of item e.g. in the main menu or search items
160 ItemList, 162 ItemList,
163 /// the bottom panel which optionally displays a text
161 MessageBar, 164 MessageBar,
165 /// the trending button which loads the trending page
162 Trending, 166 Trending,
167 /// the popular button which loads the popular page
163 Popular, 168 Popular,
169 /// the history button which loads the watch history page
170 History,
171 /// the search filters `...` button, displays a popup when selected
164 SearchFilters, 172 SearchFilters,
173 /// playlist and video info display
165 SingleItemInfo, 174 SingleItemInfo,
175 /// displays channel info
166 ChannelDisplay, 176 ChannelDisplay,
177 /// button which loads the main channel page
167 ChannelMain, 178 ChannelMain,
179 /// button which loads the channel videos page
168 ChannelVideos, 180 ChannelVideos,
181 /// button which loads the channel playlists page
169 ChannelPlaylists, 182 ChannelPlaylists,
170} 183}
171 184
@@ -176,6 +189,7 @@ impl PageItems {
176 Self::SearchBar => Box::new(SearchBar::default()), 189 Self::SearchBar => Box::new(SearchBar::default()),
177 Self::Popular => Box::new(PageButton::Popular), 190 Self::Popular => Box::new(PageButton::Popular),
178 Self::Trending => Box::new(PageButton::Trending), 191 Self::Trending => Box::new(PageButton::Trending),
192 Self::History => Box::new(PageButton::History),
179 Self::MessageBar => Box::new(MessageBar::default()), 193 Self::MessageBar => Box::new(MessageBar::default()),
180 Self::ItemList => Box::new(ItemList::default()), 194 Self::ItemList => Box::new(ItemList::default()),
181 Self::SearchFilters => Box::new(SearchFilter::default()), 195 Self::SearchFilters => Box::new(SearchFilter::default()),
@@ -191,6 +205,7 @@ impl PageItems {
191 match self { 205 match self {
192 Self::Popular 206 Self::Popular
193 | Self::Trending 207 | Self::Trending
208 | Self::History
194 | Self::ChannelMain 209 | Self::ChannelMain
195 | Self::ChannelVideos 210 | Self::ChannelVideos
196 | Self::ChannelPlaylists => Constraint::Length(15), 211 | Self::ChannelPlaylists => Constraint::Length(15),
@@ -204,6 +219,7 @@ impl PageItems {
204 pub fn height(&self) -> Constraint { 219 pub fn height(&self) -> Constraint {
205 match self { 220 match self {
206 Self::Popular 221 Self::Popular
222 | Self::History
207 | Self::ChannelMain 223 | Self::ChannelMain
208 | Self::ChannelVideos 224 | Self::ChannelVideos
209 | Self::ChannelPlaylists 225 | Self::ChannelPlaylists
@@ -244,7 +260,10 @@ fn main_menu_default() -> PageConfig {
244 PageConfig { 260 PageConfig {
245 layout: vec![ 261 layout: vec![
246 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false), 262 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
247 PageRow::from_vec(vec![PageItems::Trending, PageItems::Popular], true), 263 PageRow::from_vec(
264 vec![PageItems::Popular, PageItems::Trending, PageItems::History],
265 true,
266 ),
248 PageRow::from_vec(vec![PageItems::ItemList], false), 267 PageRow::from_vec(vec![PageItems::ItemList], false),
249 PageRow::from_vec(vec![PageItems::MessageBar], false), 268 PageRow::from_vec(vec![PageItems::MessageBar], false),
250 ], 269 ],
src/exit.rs +12 −1
@@ -1,10 +1,21 @@
1use home::home_dir; 1use home::home_dir;
2use std::{error::Error, fs}; 2use std::{error::Error, fs};
3use tui_additions::framework::Framework;
4
5use crate::global::structs::WatchHistory;
3 6
4/// function to run when the app ends 7/// function to run when the app ends
5// exit tasks: 8// exit tasks:
9// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
6// - remove `~/.cache` 10// - remove `~/.cache`
7pub fn exit() -> Result<(), Box<dyn Error>> { 11pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> {
12 framework
13 .data
14 .global
15 .get::<WatchHistory>()
16 .unwrap()
17 .exit_move();
18
8 let home_dir = home_dir().unwrap(); 19 let home_dir = home_dir().unwrap();
9 let cache_path = home_dir.join(".cache/youtube-tui/"); 20 let cache_path = home_dir.join(".cache/youtube-tui/");
10 21
src/global/functions/download_all_images.rs +2 −6
@@ -1,6 +1,6 @@
1use crate::global::structs::Item; 1use crate::global::structs::Item;
2use futures::future::join_all; 2use futures::future::join_all;
3use std::{error::Error, fs, io::Cursor, thread}; 3use std::{error::Error, io::Cursor, thread};
4use tokio::runtime::Runtime; 4use tokio::runtime::Runtime;
5 5
6pub struct DownloadRequest { 6pub struct DownloadRequest {
@@ -59,9 +59,7 @@ async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
59 path.push(".cache/youtube-tui/thumbnails/"); 59 path.push(".cache/youtube-tui/thumbnails/");
60 60
61 for download in downloads.into_iter() { 61 for download in downloads.into_iter() {
62 let mut path = path.clone(); 62 let path = path.clone().join(download.id);
63 fs::create_dir_all(&path).unwrap();
64 path.push(download.id);
65 63
66 if !path.exists() { 64 if !path.exists() {
67 actions.push(download_single( 65 actions.push(download_single(
@@ -69,8 +67,6 @@ async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
69 path.clone().into_os_string().into_string().unwrap(), 67 path.clone().into_os_string().into_string().unwrap(),
70 )); 68 ));
71 } 69 }
72
73 path.pop();
74 } 70 }
75 71
76 join_all(actions).await; 72 join_all(actions).await;
src/global/structs/item.rs +53 −24
@@ -8,11 +8,14 @@ use invidious::structs::{
8 universal::Playlist as FullPlaylist, 8 universal::Playlist as FullPlaylist,
9 video::Video, 9 video::Video,
10}; 10};
11use serde::{Deserialize, Serialize};
11use std::fmt::Display; 12use std::fmt::Display;
12 13
14use super::Errors;
15
13/// Items are things like a single video/playlist and channel 16/// Items are things like a single video/playlist and channel
14// they are displayed by the item info widget in `iteminfo.rs` 17// they are displayed by the item info widget in `iteminfo.rs`
15#[derive(Clone)] 18#[derive(Clone, Serialize, Deserialize)]
16pub enum Item { 19pub enum Item {
17 // minivideos are all videos that appeared without actually clicking into the video 20 // minivideos are all videos that appeared without actually clicking into the video
18 MiniVideo(MiniVideoItem), 21 MiniVideo(MiniVideoItem),
@@ -24,7 +27,7 @@ pub enum Item {
24 Unknown(SearchItemTransition), 27 Unknown(SearchItemTransition),
25} 28}
26 29
27#[derive(Clone)] 30#[derive(Clone, Serialize, Deserialize)]
28pub struct MiniVideoItem { 31pub struct MiniVideoItem {
29 pub title: String, 32 pub title: String,
30 pub id: String, 33 pub id: String,
@@ -37,7 +40,7 @@ pub struct MiniVideoItem {
37 pub description: Option<String>, 40 pub description: Option<String>,
38} 41}
39 42
40#[derive(Clone)] 43#[derive(Clone, Serialize, Deserialize)]
41pub struct MiniPlaylistItem { 44pub struct MiniPlaylistItem {
42 pub title: String, 45 pub title: String,
43 pub id: String, 46 pub id: String,
@@ -47,7 +50,7 @@ pub struct MiniPlaylistItem {
47 pub thumbnail_url: String, 50 pub thumbnail_url: String,
48} 51}
49 52
50#[derive(Clone)] 53#[derive(Clone, Serialize, Deserialize)]
51pub struct MiniChannelItem { 54pub struct MiniChannelItem {
52 pub name: String, 55 pub name: String,
53 pub id: String, 56 pub id: String,
@@ -58,7 +61,7 @@ pub struct MiniChannelItem {
58 pub description: String, 61 pub description: String,
59} 62}
60 63
61#[derive(Clone)] 64#[derive(Clone, Serialize, Deserialize)]
62pub struct FullVideoItem { 65pub struct FullVideoItem {
63 pub title: String, 66 pub title: String,
64 pub id: String, 67 pub id: String,
@@ -75,7 +78,7 @@ pub struct FullVideoItem {
75 pub genre: String, 78 pub genre: String,
76} 79}
77 80
78#[derive(Clone)] 81#[derive(Clone, Serialize, Deserialize)]
79pub struct FullPlaylistItem { 82pub struct FullPlaylistItem {
80 pub title: String, 83 pub title: String,
81 pub id: String, 84 pub id: String,
@@ -88,7 +91,7 @@ pub struct FullPlaylistItem {
88 pub videos: Vec<Item>, 91 pub videos: Vec<Item>,
89} 92}
90 93
91#[derive(Clone)] 94#[derive(Clone, Serialize, Deserialize)]
92pub struct FullChannelItem { 95pub struct FullChannelItem {
93 pub name: String, 96 pub name: String,
94 pub id: String, 97 pub id: String,
@@ -116,38 +119,56 @@ impl Display for Item {
116} 119}
117 120
118impl Item { 121impl Item {
119 pub fn fullvideo(&self) -> &FullVideoItem { 122 pub fn id(&self) -> Option<&str> {
123 match self {
124 Self::MiniVideo(MiniVideoItem { id, .. })
125 | Self::MiniChannel(MiniChannelItem { id, .. })
126 | Self::MiniPlaylist(MiniPlaylistItem { id, .. })
127 | Self::FullVideo(FullVideoItem { id, .. })
128 | Self::FullChannel(FullChannelItem { id, .. })
129 | Self::FullPlaylist(FullPlaylistItem { id, .. }) => Some(id),
130 _ => None,
131 }
132 }
133
134 pub fn is_unknown(&self) -> bool {
135 matches!(self, Self::Unknown(_))
136 }
137}
138
139impl Item {
140 pub fn fullvideo(&self) -> Result<&FullVideoItem, Errors> {
120 match self { 141 match self {
121 Self::FullVideo(fullvideo) => fullvideo, 142 Self::FullVideo(fullvideo) => Ok(fullvideo),
122 _ => panic!("not a fullvideo"), 143 _ => Err(Errors::StrError("not a full video")),
123 } 144 }
124 } 145 }
125 146
126 pub fn minivideo(&self) -> &MiniVideoItem { 147 pub fn minivideo(&self) -> Result<&MiniVideoItem, Errors> {
127 match self { 148 match self {
128 Self::MiniVideo(minivideo) => minivideo, 149 Self::MiniVideo(minivideo) => Ok(minivideo),
129 _ => panic!("not a minivideo"), 150 _ => Err(Errors::StrError("not a mini video")),
130 } 151 }
131 } 152 }
132 153
133 pub fn miniplaylist(&self) -> &MiniPlaylistItem { 154 pub fn miniplaylist(&self) -> Result<&MiniPlaylistItem, Errors> {
134 match self { 155 match self {
135 Self::MiniPlaylist(miniplaylist) => miniplaylist, 156 Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
136 _ => panic!("not a miniplaylist"), 157 _ => Err(Errors::StrError("not a mini playlist")),
137 } 158 }
138 } 159 }
139 160
140 pub fn fullplaylist(&self) -> &FullPlaylistItem { 161 pub fn fullplaylist(&self) -> Result<&FullPlaylistItem, Errors> {
141 match self { 162 match self {
142 Self::FullPlaylist(fullplaylist) => fullplaylist, 163 Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
143 _ => panic!("not a fullplaylist"), 164 _ => Err(Errors::StrError("not a full playlist")),
144 } 165 }
145 } 166 }
146 167
147 pub fn minichannel(&self) -> &MiniChannelItem { 168 pub fn minichannel(&self) -> Result<&MiniChannelItem, Errors> {
148 match self { 169 match self {
149 Self::MiniChannel(minichannel) => minichannel, 170 Self::MiniChannel(minichannel) => Ok(minichannel),
150 _ => panic!("not a minichannel"), 171 _ => Err(Errors::StrError("not a mini channel")),
151 } 172 }
152 } 173 }
153} 174}
@@ -286,7 +307,11 @@ impl Item {
286 channel: original.author, 307 channel: original.author,
287 channel_id: original.author_id, 308 channel_id: original.author_id,
288 sub_count: original.sub_count_text, 309 sub_count: original.sub_count_text,
289 published: original.published_text, 310 published: format!(
311 "{} [{}]",
312 original.published_text,
313 date_text(original.published)
314 ),
290 description: original.description, 315 description: original.description,
291 likes: viewcount_text(original.likes as u64), 316 likes: viewcount_text(original.likes as u64),
292 genre: original.genre, 317 genre: original.genre,
@@ -348,7 +373,11 @@ impl Item {
348 views: Some(viewcount_text(original.view_count)), 373 views: Some(viewcount_text(original.view_count)),
349 channel: original.author, 374 channel: original.author,
350 channel_id: original.author_id, 375 channel_id: original.author_id,
351 published: Some(date_text(original.published)), 376 published: Some(format!(
377 "{} [{}]",
378 original.published_text,
379 date_text(original.published)
380 )),
352 description: Some(original.description), 381 description: Some(original.description),
353 }) 382 })
354 } 383 }
src/global/structs/mod.rs +2
@@ -7,6 +7,7 @@ mod message;
7mod page; 7mod page;
8mod status; 8mod status;
9mod tasks; 9mod tasks;
10mod watchhistory;
10 11
11pub use errors::*; 12pub use errors::*;
12pub use invidiousclient::*; 13pub use invidiousclient::*;
@@ -16,3 +17,4 @@ pub use message::*;
16pub use page::*; 17pub use page::*;
17pub use status::*; 18pub use status::*;
18pub use tasks::*; 19pub use tasks::*;
20pub use watchhistory::*;
src/global/structs/page.rs +2
@@ -53,6 +53,7 @@ impl Key for Page {
53pub enum MainMenuPage { 53pub enum MainMenuPage {
54 Trending, 54 Trending,
55 Popular, 55 Popular,
56 History,
56} 57}
57 58
58impl Default for MainMenuPage { 59impl Default for MainMenuPage {
@@ -61,6 +62,7 @@ impl Default for MainMenuPage {
61 } 62 }
62} 63}
63 64
65/// variants of the coannel display page
64#[derive(Clone, PartialEq)] 66#[derive(Clone, PartialEq)]
65pub struct ChannelDisplayPage { 67pub struct ChannelDisplayPage {
66 pub id: String, 68 pub id: String,
src/global/structs/tasks.rs +1
@@ -189,6 +189,7 @@ impl TaskQueue {
189 } 189 }
190} 190}
191 191
192/// a single task
192#[derive(Clone, PartialEq, Eq, Debug)] 193#[derive(Clone, PartialEq, Eq, Debug)]
193pub enum RenderTask { 194pub enum RenderTask {
194 All, 195 All,
src/global/structs/watchhistory.rs added +119
@@ -0,0 +1,119 @@
1use super::Item;
2use home::home_dir;
3use serde::{Deserialize, Serialize};
4use std::{
5 error::Error,
6 fs::{self, OpenOptions},
7 io::Write,
8};
9use typemap::Key;
10
11#[derive(Clone, Default, Serialize, Deserialize)]
12pub struct WatchHistory(pub Vec<Item>);
13
14impl Key for WatchHistory {
15 type Value = Self;
16}
17
18impl WatchHistory {
19 /// saves the current state of watch history into a file
20 pub fn save(&self) -> Result<(), Box<dyn Error>> {
21 let save_string = serde_json::to_string(self)?;
22 let path = home_dir()
23 .unwrap()
24 .join(".local/share/youtube-tui/watch_history.json");
25
26 let mut file = OpenOptions::new()
27 .write(true)
28 .create(true)
29 .truncate(true)
30 .open(&path)?;
31
32 file.write_all(save_string.as_bytes())?;
33
34 Ok(())
35 }
36
37 /// add an item to watch history
38 pub fn push(&mut self, item: Item, max_items: usize) {
39 // removes duplicates and place them on top (if exists)
40 if let Some(index) = self
41 .0
42 .iter()
43 .position(|item_in_iter| item_in_iter.id() == item.id())
44 {
45 self.0.remove(index);
46 }
47 self.0.push(item);
48
49 // if length of history exceeds the maximum history length, removes that oldest item
50 if self.0.len() > max_items {
51 self.0.remove(0);
52 }
53 }
54
55 /// loads watch history from file
56 pub fn load() -> Self {
57 let path = home_dir()
58 .unwrap()
59 .join(".local/share/youtube-tui/watch_history.json");
60 let res = (|| -> Result<Self, Box<dyn Error>> {
61 let file_string = fs::read_to_string(&path)?;
62 let deserialized = serde_json::from_str(&file_string)?;
63 Ok(deserialized)
64 })();
65
66 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
67 // which case returns Self::default()
68 if let Ok(deserialized) = res {
69 deserialized
70 } else {
71 // if the file does exist, back it up
72 // if it doesn't exist, it will throw an error but we dont care
73 let mut new_path = path.clone();
74 new_path.pop();
75 new_path.push(format!(
76 "watch_history-{}.json",
77 chrono::offset::Local::now(),
78 ));
79 let _ = fs::rename(&path, &new_path);
80
81 Self::default()
82 }
83 }
84
85 /// moves all thumbnails from storage to cache when starting
86 pub fn init_move() {
87 let history_thumbnails_path = home_dir()
88 .unwrap()
89 .join(".local/share/youtube-tui/watch_history/thumbnails/");
90 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
91
92 fs::read_dir(history_thumbnails_path)
93 .unwrap()
94 .into_iter()
95 .for_each(|path| {
96 let path = path.unwrap().path();
97 let _ = fs::rename(
98 path.clone(),
99 cache_thumbnails_path.join(path.file_name().unwrap()),
100 );
101 });
102 }
103
104 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
105 pub fn exit_move(&self) {
106 let history_thumbnails_path = home_dir()
107 .unwrap()
108 .join(".local/share/youtube-tui/watch_history/thumbnails/");
109 let cache_thumbnails_path = home_dir().unwrap().join(".cache/youtube-tui/thumbnails/");
110
111 self.0.iter().for_each(|item| {
112 let id = item.id().unwrap();
113 let _ = fs::rename(
114 cache_thumbnails_path.join(id),
115 history_thumbnails_path.join(id),
116 );
117 })
118 }
119}
src/global/traits/configtrait.rs +4 −4
@@ -1,3 +1,4 @@
1use home::home_dir;
1use serde::{de::DeserializeOwned, Serialize}; 2use serde::{de::DeserializeOwned, Serialize};
2use std::{ 3use std::{
3 error::Error, 4 error::Error,
@@ -15,10 +16,9 @@ pub trait ConfigTrait {
15 where 16 where
16 Self: Serialize + DeserializeOwned + Default + Clone, 17 Self: Serialize + DeserializeOwned + Default + Clone,
17 { 18 {
18 let mut config_path = home::home_dir().expect("cannot get home directory"); 19 let home_dir = home_dir().unwrap();
19 config_path.push(".config"); 20 let config_path =
20 config_path.push("youtube-tui"); 21 home_dir.join(format!(".config/youtube-tui/{}.{}", Self::LABEL, EXTENSION));
21 config_path.push(format!("{}.{}", Self::LABEL, EXTENSION));
22 22
23 // The config struct 23 // The config struct
24 let config: Self = { 24 let config: Self = {
src/init.rs +17 −4
@@ -4,7 +4,7 @@ use crate::{
4 KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search, 4 KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
5 }, 5 },
6 global::{ 6 global::{
7 structs::{InvidiousClient, Message, Page, Status, Tasks}, 7 structs::{InvidiousClient, Message, Page, Status, Tasks, WatchHistory},
8 traits::ConfigTrait, 8 traits::ConfigTrait,
9 }, 9 },
10}; 10};
@@ -21,16 +21,25 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
21 // creating files 21 // creating files
22 let home_dir = home_dir().unwrap(); 22 let home_dir = home_dir().unwrap();
23 let config_path = home_dir.join(".config/youtube-tui/"); 23 let config_path = home_dir.join(".config/youtube-tui/");
24 let cache_path = home_dir.join(".cache/youtube-tui/"); 24 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
25 let history_thumbnails_path =
26 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/");
25 27
26 if !&config_path.exists() { 28 if !&config_path.exists() {
27 fs::create_dir_all(&config_path).unwrap(); 29 fs::create_dir_all(&config_path).unwrap();
28 } 30 }
29 31
30 if !&cache_path.exists() { 32 if !&cache_thumbnails_path.exists() {
31 fs::create_dir_all(&config_path).unwrap(); 33 fs::create_dir_all(&cache_thumbnails_path).unwrap();
34 }
35
36 if !&history_thumbnails_path.exists() {
37 fs::create_dir_all(&history_thumbnails_path).unwrap();
32 } 38 }
33 39
40 // watch history init
41 WatchHistory::init_move();
42
34 // inserting data 43 // inserting data
35 let main_config = *MainConfig::load()?; 44 let main_config = *MainConfig::load()?;
36 45
@@ -38,6 +47,10 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
38 .data 47 .data
39 .global 48 .global
40 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone())); 49 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone()));
50 framework
51 .data
52 .global
53 .insert::<WatchHistory>(WatchHistory::load());
41 framework 54 framework
42 .data 55 .data
43 .global 56 .global
src/items/channeldisplay.rs +10 −8
@@ -4,8 +4,8 @@ use crate::{
4 global::{ 4 global::{
5 functions::download_all_images, 5 functions::download_all_images,
6 structs::{ 6 structs::{
7 ChannelDisplayPageType, InvidiousClient, Item, KeyAction, Page, SingleItemPage, Task, 7 ChannelDisplayPageType, InvidiousClient, Item, KeyAction, Message, Page,
8 Tasks, Message, 8 SingleItemPage, Task, Tasks,
9 }, 9 },
10 }, 10 },
11}; 11};
@@ -217,13 +217,14 @@ impl FrameworkItem for ChannelDisplay {
217 .unwrap() 217 .unwrap()
218 .priority 218 .priority
219 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video( 219 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
220 videos[textlist.selected].minivideo().id.clone(), 220 videos[textlist.selected].minivideo()?.id.clone(),
221 )))); 221 ))));
222 } else { 222 } else {
223 *framework.data.global.get_mut::<Message>().unwrap() = Message::Error(String::from("There is nothing to select")); 223 *framework.data.global.get_mut::<Message>().unwrap() =
224 Message::Error(String::from("There is nothing to select"));
224 } 225 }
225 true 226 true
226 }, 227 }
227 _ => false, 228 _ => false,
228 }; 229 };
229 230
@@ -259,13 +260,14 @@ impl FrameworkItem for ChannelDisplay {
259 .unwrap() 260 .unwrap()
260 .priority 261 .priority
261 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist( 262 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
262 playlists[textlist.selected].miniplaylist().id.clone(), 263 playlists[textlist.selected].miniplaylist()?.id.clone(),
263 )))); 264 ))));
264 } else { 265 } else {
265 *framework.data.global.get_mut::<Message>().unwrap() = Message::Error(String::from("There is nothing to select")); 266 *framework.data.global.get_mut::<Message>().unwrap() =
267 Message::Error(String::from("There is nothing to select"));
266 } 268 }
267 true 269 true
268 }, 270 }
269 _ => false, 271 _ => false,
270 }; 272 };
271 273
src/items/itemlist.rs +15 −1
@@ -14,7 +14,7 @@ use crate::{
14 structs::{ 14 structs::{
15 ChannelDisplayPage, ChannelDisplayPageType, FullPlaylistItem, FullVideoItem, 15 ChannelDisplayPage, ChannelDisplayPageType, FullPlaylistItem, FullVideoItem,
16 InvidiousClient, Item, KeyAction, MainMenuPage, MiniChannelItem, MiniPlaylistItem, 16 InvidiousClient, Item, KeyAction, MainMenuPage, MiniChannelItem, MiniPlaylistItem,
17 MiniVideoItem, Page, SingleItemPage, Task, Tasks, 17 MiniVideoItem, Page, SingleItemPage, Task, Tasks, WatchHistory,
18 }, 18 },
19 }, 19 },
20}; 20};
@@ -159,6 +159,20 @@ impl FrameworkItem for ItemList {
159 .map(|item| Item::from_popular_item(item, image_index)) 159 .map(|item| Item::from_popular_item(item, image_index))
160 .collect(); 160 .collect();
161 } 161 }
162 Page::MainMenu(MainMenuPage::History) => {
163 // the vector needs to be reversed because the latest watch history is pushed to
164 // the back, meaning it needs to be reversed so that the latests one are on top
165 self.items = framework
166 .data
167 .global
168 .get::<WatchHistory>()
169 .unwrap()
170 .0
171 .clone()
172 .into_iter()
173 .rev()
174 .collect();
175 }
162 Page::Search(search) => { 176 Page::Search(search) => {
163 self.items = client 177 self.items = client
164 .search(Some(&search.to_string()))? 178 .search(Some(&search.to_string()))?
src/items/pagebutton.rs +10 −1
@@ -1,7 +1,7 @@
1use crate::{ 1use crate::{
2 config::AppearanceConfig, 2 config::AppearanceConfig,
3 global::structs::{ 3 global::structs::{
4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Page, Task, Tasks, 4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Page, Task, Tasks, Message,
5 }, 5 },
6}; 6};
7use tui::{ 7use tui::{
@@ -16,6 +16,7 @@ use tui_additions::framework::FrameworkItem;
16pub enum PageButton { 16pub enum PageButton {
17 Trending, 17 Trending,
18 Popular, 18 Popular,
19 History,
19 ChannelMain, 20 ChannelMain,
20 ChannelVideos, 21 ChannelVideos,
21 ChannelPlaylists, 22 ChannelPlaylists,
@@ -26,6 +27,7 @@ impl PageButton {
26 match self { 27 match self {
27 Self::Trending => Page::MainMenu(MainMenuPage::Trending), 28 Self::Trending => Page::MainMenu(MainMenuPage::Trending),
28 Self::Popular => Page::MainMenu(MainMenuPage::Popular), 29 Self::Popular => Page::MainMenu(MainMenuPage::Popular),
30 Self::History => Page::MainMenu(MainMenuPage::History),
29 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage { 31 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage {
30 id: current_page.channeldisplay().id.clone(), 32 id: current_page.channeldisplay().id.clone(),
31 r#type: ChannelDisplayPageType::Main, 33 r#type: ChannelDisplayPageType::Main,
@@ -47,6 +49,7 @@ impl ToString for PageButton {
47 match self { 49 match self {
48 Self::Popular => String::from("Popular"), 50 Self::Popular => String::from("Popular"),
49 Self::Trending => String::from("Trending"), 51 Self::Trending => String::from("Trending"),
52 Self::History => String::from("History"),
50 Self::ChannelMain => String::from("Main"), 53 Self::ChannelMain => String::from("Main"),
51 Self::ChannelVideos => String::from("Videos"), 54 Self::ChannelVideos => String::from("Videos"),
52 Self::ChannelPlaylists => String::from("Playlists"), 55 Self::ChannelPlaylists => String::from("Playlists"),
@@ -92,6 +95,12 @@ impl FrameworkItem for PageButton {
92 // when selected creates a load page task, but returns false to show that it is not being selected 95 // when selected creates a load page task, but returns false to show that it is not being selected
93 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool { 96 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
94 let current_page = framework.data.state.get::<Page>().unwrap().clone(); 97 let current_page = framework.data.state.get::<Page>().unwrap().clone();
98
99 if self.page(&current_page) == current_page {
100 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from("You are already on this page"));
101 return false;
102 }
103
95 let tasks = framework.data.state.get_mut::<Tasks>().unwrap(); 104 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
96 tasks 105 tasks
97 .priority 106 .priority
src/items/searchbar.rs +1
@@ -12,6 +12,7 @@ use tui::{
12}; 12};
13use tui_additions::{framework::FrameworkItem, widgets::TextField}; 13use tui_additions::{framework::FrameworkItem, widgets::TextField};
14 14
15/// the search bar item
15#[derive(Clone, Default)] 16#[derive(Clone, Default)]
16pub struct SearchBar { 17pub struct SearchBar {
17 pub text_field: TextField, 18 pub text_field: TextField,
src/items/singleitem.rs +32 −13
@@ -3,7 +3,10 @@ use crate::{
3 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider}, 3 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider},
4 global::{ 4 global::{
5 functions::download_all_images, 5 functions::download_all_images,
6 structs::{InvidiousClient, Item, KeyAction, Message, Page, SingleItemPage, Task, Tasks}, 6 structs::{
7 InvidiousClient, Item, KeyAction, Message, Page, SingleItemPage, Task, Tasks,
8 WatchHistory,
9 },
7 }, 10 },
8}; 11};
9use std::{collections::HashMap, thread}; 12use std::{collections::HashMap, thread};
@@ -115,7 +118,7 @@ impl SingleVideoItem {
115 118
116 /// creates a hashmap from `self`, containing info of the current item 119 /// creates a hashmap from `self`, containing info of the current item
117 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> { 120 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> {
118 let video_item = item.fullvideo(); 121 let video_item = item.fullvideo().unwrap();
119 122
120 HashMap::from([ 123 HashMap::from([
121 ( 124 (
@@ -182,7 +185,7 @@ impl SinglePlaylistItem {
182 items.extend( 185 items.extend(
183 playlist_items 186 playlist_items
184 .iter() 187 .iter()
185 .map(|item| item.minivideo().title.as_str()), 188 .map(|item| item.minivideo().unwrap().title.as_str()),
186 ); 189 );
187 items 190 items
188 }) 191 })
@@ -265,7 +268,7 @@ impl SinglePlaylistItem {
265 268
266 /// creates a hashmap from `self`, containing info of the current item 269 /// creates a hashmap from `self`, containing info of the current item
267 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> { 270 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> {
268 let playlist_item = item.fullplaylist(); 271 let playlist_item = item.fullplaylist().unwrap();
269 HashMap::from([ 272 HashMap::from([
270 ( 273 (
271 String::from("url"), 274 String::from("url"),
@@ -289,7 +292,9 @@ impl SinglePlaylistItem {
289 Provider::YouTube => playlist_item 292 Provider::YouTube => playlist_item
290 .videos 293 .videos
291 .iter() 294 .iter()
292 .map(|video| format!("'https://youtu.be/{}'", video.minivideo().id)) 295 .map(|video| {
296 format!("'https://youtu.be/{}'", video.minivideo().unwrap().id)
297 })
293 .collect::<Vec<_>>() 298 .collect::<Vec<_>>()
294 .join(" "), 299 .join(" "),
295 Provider::Invidious => playlist_item 300 Provider::Invidious => playlist_item
@@ -299,7 +304,7 @@ impl SinglePlaylistItem {
299 format!( 304 format!(
300 "'{}/watch?v={}'", 305 "'{}/watch?v={}'",
301 mainconfig.invidious_instance, 306 mainconfig.invidious_instance,
302 video.minivideo().id 307 video.minivideo().unwrap().id
303 ) 308 )
304 }) 309 })
305 .collect::<Vec<_>>() 310 .collect::<Vec<_>>()
@@ -486,7 +491,7 @@ impl FrameworkItem for SingleItem {
486 SingleItemPage::Playlist(id) => { 491 SingleItemPage::Playlist(id) => {
487 let playlist = 492 let playlist =
488 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index); 493 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index);
489 let videos = &playlist.fullplaylist().videos; 494 let videos = &playlist.fullplaylist()?.videos;
490 self.r#type = SingleItemType::Playlist( 495 self.r#type = SingleItemType::Playlist(
491 SinglePlaylistItem::new( 496 SinglePlaylistItem::new(
492 framework.data.global.get::<CommandsConfig>().unwrap(), 497 framework.data.global.get::<CommandsConfig>().unwrap(),
@@ -512,6 +517,20 @@ impl FrameworkItem for SingleItem {
512 // instead of the actual provider (e.g. `YouTube`) 517 // instead of the actual provider (e.g. `YouTube`)
513 self.update_provider(); 518 self.update_provider();
514 519
520 if let Some(item) = &self.item {
521 if item.is_unknown() {
522 return Ok(());
523 }
524
525 let item = item.clone();
526 let max_watch_history = mainconfig.max_watch_history;
527
528 // push to watch history
529 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
530 watch_history.push(item, max_watch_history);
531 watch_history.save()?;
532 }
533
515 Ok(()) 534 Ok(())
516 } 535 }
517 536
@@ -659,7 +678,7 @@ impl FrameworkItem for SingleItem {
659 let updated = singleplaylistitem.videos_view.up().is_ok(); 678 let updated = singleplaylistitem.videos_view.up().is_ok();
660 if updated && singleplaylistitem.videos_view.selected != 0 { 679 if updated && singleplaylistitem.videos_view.selected != 0 {
661 singleplaylistitem.hovered_video.item = Some( 680 singleplaylistitem.hovered_video.item = Some(
662 self.item.as_ref().unwrap().fullplaylist().videos 681 self.item.as_ref().unwrap().fullplaylist()?.videos
663 [singleplaylistitem.videos_view.selected - 1] 682 [singleplaylistitem.videos_view.selected - 1]
664 .clone(), 683 .clone(),
665 ); 684 );
@@ -681,7 +700,7 @@ impl FrameworkItem for SingleItem {
681 let updated = singleplaylistitem.videos_view.down().is_ok(); 700 let updated = singleplaylistitem.videos_view.down().is_ok();
682 if updated && singleplaylistitem.videos_view.selected != 0 { 701 if updated && singleplaylistitem.videos_view.selected != 0 {
683 singleplaylistitem.hovered_video.item = Some( 702 singleplaylistitem.hovered_video.item = Some(
684 self.item.as_ref().unwrap().fullplaylist().videos 703 self.item.as_ref().unwrap().fullplaylist()?.videos
685 [singleplaylistitem.videos_view.selected - 1] 704 [singleplaylistitem.videos_view.selected - 1]
686 .clone(), 705 .clone(),
687 ); 706 );
@@ -692,7 +711,7 @@ impl FrameworkItem for SingleItem {
692 let updated = singleplaylistitem.videos_view.first().is_ok(); 711 let updated = singleplaylistitem.videos_view.first().is_ok();
693 if updated && singleplaylistitem.videos_view.selected != 0 { 712 if updated && singleplaylistitem.videos_view.selected != 0 {
694 singleplaylistitem.hovered_video.item = Some( 713 singleplaylistitem.hovered_video.item = Some(
695 self.item.as_ref().unwrap().fullplaylist().videos 714 self.item.as_ref().unwrap().fullplaylist()?.videos
696 [singleplaylistitem.videos_view.selected - 1] 715 [singleplaylistitem.videos_view.selected - 1]
697 .clone(), 716 .clone(),
698 ); 717 );
@@ -703,7 +722,7 @@ impl FrameworkItem for SingleItem {
703 let updated = singleplaylistitem.videos_view.last().is_ok(); 722 let updated = singleplaylistitem.videos_view.last().is_ok();
704 if updated && singleplaylistitem.videos_view.selected != 0 { 723 if updated && singleplaylistitem.videos_view.selected != 0 {
705 singleplaylistitem.hovered_video.item = Some( 724 singleplaylistitem.hovered_video.item = Some(
706 self.item.as_ref().unwrap().fullplaylist().videos 725 self.item.as_ref().unwrap().fullplaylist()?.videos
707 [singleplaylistitem.videos_view.selected - 1] 726 [singleplaylistitem.videos_view.selected - 1]
708 .clone(), 727 .clone(),
709 ); 728 );
@@ -728,9 +747,9 @@ impl FrameworkItem for SingleItem {
728 .unwrap() 747 .unwrap()
729 .priority 748 .priority
730 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video( 749 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
731 self.item.as_ref().unwrap().fullplaylist().videos 750 self.item.as_ref().unwrap().fullplaylist()?.videos
732 [singleplaylistitem.videos_view.selected - 1] 751 [singleplaylistitem.videos_view.selected - 1]
733 .minivideo() 752 .minivideo()?
734 .id 753 .id
735 .clone(), 754 .clone(),
736 )))); 755 ))));
src/main.rs +2 −2
@@ -24,7 +24,7 @@ fn main() -> Result<(), Box<dyn Error>> {
24 let backend = CrosstermBackend::new(stdout); 24 let backend = CrosstermBackend::new(stdout);
25 let mut terminal = Terminal::new(backend)?; 25 let mut terminal = Terminal::new(backend)?;
26 26
27 let res = run(&mut terminal, framework); 27 let res = run(&mut terminal, &mut framework);
28 28
29 disable_raw_mode()?; 29 disable_raw_mode()?;
30 execute!( 30 execute!(
@@ -34,7 +34,7 @@ fn main() -> Result<(), Box<dyn Error>> {
34 )?; 34 )?;
35 terminal.show_cursor()?; 35 terminal.show_cursor()?;
36 36
37 let exit_res = exit(); 37 let exit_res = exit(&framework);
38 38
39 res?; 39 res?;
40 exit_res?; 40 exit_res?;
src/run.rs +4 −4
@@ -11,20 +11,20 @@ use crate::{
11/// the main event loop of the program 11/// the main event loop of the program
12pub fn run( 12pub fn run(
13 terminal: &mut Terminal<CrosstermBackend<Stdout>>, 13 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
14 mut framework: Framework, 14 framework: &mut Framework,
15) -> Result<(), Box<dyn Error>> { 15) -> Result<(), Box<dyn Error>> {
16 // push the initial page load 16 // push the initial page load
17 let tasks = framework.data.state.get_mut::<Tasks>().unwrap(); 17 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
18 tasks 18 tasks
19 .priority 19 .priority
20 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Trending))); 20 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Popular)));
21 tasks.pop().unwrap().run(&mut framework, terminal)?; 21 tasks.pop().unwrap().run(framework, terminal)?;
22 framework.clear_history(); 22 framework.clear_history();
23 23
24 loop { 24 loop {
25 // repeat forever until all tasks are ran (and Tasks is cleared) 25 // repeat forever until all tasks are ran (and Tasks is cleared)
26 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() { 26 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
27 tasks.run(&mut framework, terminal)?; 27 tasks.run(framework, terminal)?;
28 continue; 28 continue;
29 } 29 }
30 30