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 @@
11/target
2*.svg
\ No newline at end of file
2/docs/book
Cargo.lock −25
@@ -426,7 +426,6 @@ checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0"
426426dependencies = [
427427 "futures-channel",
428428 "futures-core",
429 "futures-executor",
430429 "futures-io",
431430 "futures-sink",
432431 "futures-task",
@@ -449,34 +448,12 @@ version = "0.3.25"
449448source = "registry+https://github.com/rust-lang/crates.io-index"
450449checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"
451450
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
463451[[package]]
464452name = "futures-io"
465453version = "0.3.25"
466454source = "registry+https://github.com/rust-lang/crates.io-index"
467455checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb"
468456
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
480457[[package]]
481458name = "futures-sink"
482459version = "0.3.25"
@@ -495,10 +472,8 @@ version = "0.3.25"
495472source = "registry+https://github.com/rust-lang/crates.io-index"
496473checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"
497474dependencies = [
498 "futures-channel",
499475 "futures-core",
500476 "futures-io",
501 "futures-macro",
502477 "futures-sink",
503478 "futures-task",
504479 "memchr",
Cargo.toml +18 −14
@@ -1,34 +1,38 @@
11[package]
22name = "youtube-tui"
33version = "0.5.0"
4edition = "2021"
54authors = ["Siriusmart <siriusmart@tuta.io>"]
5edition = "2021"
66description = "An aesthetically pleasing YouTube TUI written in Rust"
7documentation = "https://docs.rs/youtube-tui"
78readme = "README.md"
9homepage = "https://siriusmart.github.io/youtube-tui"
10repository = "https://github.com/siriusmart/youtube-tui"
811license = "GPL-3.0"
12license-file = "LICENSE"
913keywords = ["cli", "terminal", "youtube", "tui"]
1014categories =["command-line-interface", "command-line-utilities"]
11repository = "https://github.com/Siriusmart/youtube-tui"
15exclude = ["/docs"]
1216
1317# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
1418
1519[dependencies]
16serde = {version = "1.0", features = ["derive"]}
17tui = {version = "0.19", features = ["serde"]}
18crossterm = {version = "0.25", features = ["serde"]}
19viuer = {version = "0.6", features = ["sixel"]}
20serde = {version = "1.0", default-features = false, features = ["derive"]}
21tui = {version = "0.19", default-features = false, features = ["serde"]}
22crossterm = {version = "0.25", default-features = false, features = ["serde"]}
23viuer = {version = "0.6", default-features = false, features = ["sixel"]}
2024home = "0.5"
2125chrono = {version = "0.4", default-features = false, features = ["clock"]}
2226tui-additions = {version = "0.1", default-features = false, features = ["framework", "widgets"]}
23typemap = "0.3"
27typemap = {version = "0.3", default-features = false}
2428invidious = {version = "0.4", default-features = false, features = ["reqwest"]}
25serde_yaml = "0.9"
26dyn-clone = "1.0"
27tokio = "1.21"
28futures = "0.3"
29reqwest = "0.11"
30serde_json = "1.0"
31execute = "0.2"
29serde_yaml = {version = "0.9", default-features = false}
30dyn-clone = {version = "1.0", default-features = false}
31tokio = {version = "1.21", default-features = false}
32futures = {version = "0.3", default-features = false}
33reqwest = {version = "0.11", default-features = false}
34serde_json = {version = "1.0", default-features = false}
35execute = {version = "0.2", default-features = false}
3236
3337# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
3438# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]}
README.md +44 −66
@@ -4,93 +4,71 @@
44[![](https://img.shields.io/crates/v/youtube-tui?label=crates.io%20version)](https://crates.io/crates/youtube-tui)
55![](https://shields.io/github/stars/siriusmart/youtube-tui?style=social)
66
7# YouTube TUI
7*Read more in the [user manual](https://siriusmart.github.io/youtube-tui) (including installation gude and documentation).*
88
9An aesthetically pleasing YouTube TUI written in Rust.
9# Overview
1010
11> ## Warning
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.
11Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal.
2112
13![](./docs/src/images/search-showcase.png)
2214
23## Overview
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.
15It is like an *app launcher*, it launches other programs to do the heavy lifting (for example, `mpv` for playing videos).
2516
26![Screenshot](https://cdn.discordapp.com/attachments/906941311142219816/990684947830419526/Screenshot_20220626_192433.png)
17## Customisable
2718
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.
2920
30[YouTube TUI user manual](https://siriusmart.github.io/youtube-tui)
21Here's an example of the config file:
3122
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
3335
34### Install from crates.io
35
36```bash
37cargo install youtube-tui
3836```
3937
40## Usage
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
38Anything from layouts to colours and keybindings can be customised, more on that later.
6539
66## Known issues
40## Dependency-free
6741
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`.
6943
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.
7145
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)
7347
74Here's the [opened issue](https://github.com/iv-org/invidious/issues/3154)
48## Powerful
7549
76## Todo (First priority on top)
50The YouTube TUI allows you to browse YouTube with (almost) all of it's features, functions including:
7751
78* Go directly to a page by URL
79* Vim-like commands in the status bar
80* Save as local playlist/video
81* Command line launch options
82* Channel search and channel video sort
83* Recommended videos
52- View popular/trending videos
53- View information about channels, playlists and videos
54- Use search filters to sort and filter search results
55- Save browsing history
8456
85## Credits
57### What it doesn't have
8658
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
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
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)
59- Vim-like commands (first priority)
60- Channel search (will implement)
61- Channel videos sorting (will implement)
62- Subscriptions (will implement)
63- Recommendations/comments (probably will not implement)
9064
65## How to contribute
9166
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*.
9368
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?
9573
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 {
209209}
210210
211211fn sub_count_default() -> Color {
212 Color::LightYellow
212 Color::Rgb(101, 255, 186)
213213}
214214
215215fn likes_default() -> Color {
src/config/commands.rs +2
@@ -5,6 +5,7 @@ use typemap::Key;
55
66use crate::global::traits::ConfigTrait;
77
8/// Stores combinations of label and commands
89#[derive(Clone)]
910pub struct CommandsConfig {
1011 pub video: Vec<(String, String)>,
@@ -32,6 +33,7 @@ impl From<CommandsConfigSerde> for CommandsConfig {
3233 }
3334}
3435
36/// Hashmaps are better formatted in YAML, impls Into<CommandsConfig>
3537// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look
3638#[derive(Serialize, Deserialize, Clone)]
3739pub struct CommandsConfigSerde {
src/config/keybindings.rs +1 −1
@@ -49,7 +49,7 @@ impl Default for KeyBindingsConfig {
4949 (KeyCode::Enter, HashMap::from([(0, KeyAction::Select)])),
5050 (KeyCode::Esc, HashMap::from([(0, KeyAction::Deselect)])),
5151 (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)])),
5353 // history
5454 (KeyCode::Backspace, HashMap::from([(0, KeyAction::Back)])),
5555 (KeyCode::End, HashMap::from([(0, KeyAction::ClearHistory)])),
src/config/main.rs +10 −9
@@ -8,8 +8,8 @@ use typemap::Key;
88pub struct MainConfig {
99 #[serde(default = "invidious_instance_default")]
1010 pub invidious_instance: String,
11 #[serde(default = "piped_instance_default")]
12 pub piped_instance: String,
11 #[serde(default = "max_watch_history_default")]
12 pub max_watch_history: usize,
1313 #[serde(default = "allow_unicode_default")]
1414 pub allow_unicode: bool,
1515 #[serde(default = "message_bar_default_default")]
@@ -37,7 +37,7 @@ impl Default for MainConfig {
3737 fn default() -> Self {
3838 Self {
3939 invidious_instance: invidious_instance_default(),
40 piped_instance: piped_instance_default(),
40 max_watch_history: max_watch_history_default(),
4141 allow_unicode: allow_unicode_default(),
4242 message_bar_default: message_bar_default_default(),
4343 images: images_default(),
@@ -55,7 +55,8 @@ impl ConfigTrait for MainConfig {
5555 const LABEL: &'static str = "main";
5656}
5757
58#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
58/// how images are handled/displayed
59#[derive(Clone, Copy, Serialize, Deserialize, PartialEq)]
5960pub enum Images {
6061 r#None,
6162 HalfBlocks,
@@ -101,16 +102,12 @@ fn invidious_instance_default() -> String {
101102 String::from("https://vid.puffyan.us")
102103}
103104
104fn piped_instance_default() -> String {
105 String::from("https://piped.garudalinux.org")
106}
107
108105fn message_bar_default_default() -> String {
109106 String::from("All good :)")
110107}
111108
112109const fn images_default() -> Images {
113 Images::HalfBlocks
110 Images::Sixels
114111}
115112
116113const fn image_index_default() -> usize {
@@ -129,6 +126,10 @@ const fn provider_default() -> Provider {
129126 Provider::YouTube
130127}
131128
129const fn max_watch_history_default() -> usize {
130 50
131}
132
132133fn default_env() -> HashMap<String, String> {
133134 HashMap::from([
134135 (String::from("video-player"), String::from("mpv")),
src/config/pages.rs +20 −1
@@ -156,16 +156,29 @@ impl PageRow {
156156/// All avaliable items for `PageConfig`
157157#[derive(Clone, Copy, Serialize, Deserialize)]
158158pub enum PageItems {
159 /// the search bar
159160 SearchBar,
161 /// a list of item e.g. in the main menu or search items
160162 ItemList,
163 /// the bottom panel which optionally displays a text
161164 MessageBar,
165 /// the trending button which loads the trending page
162166 Trending,
167 /// the popular button which loads the popular page
163168 Popular,
169 /// the history button which loads the watch history page
170 History,
171 /// the search filters `...` button, displays a popup when selected
164172 SearchFilters,
173 /// playlist and video info display
165174 SingleItemInfo,
175 /// displays channel info
166176 ChannelDisplay,
177 /// button which loads the main channel page
167178 ChannelMain,
179 /// button which loads the channel videos page
168180 ChannelVideos,
181 /// button which loads the channel playlists page
169182 ChannelPlaylists,
170183}
171184
@@ -176,6 +189,7 @@ impl PageItems {
176189 Self::SearchBar => Box::new(SearchBar::default()),
177190 Self::Popular => Box::new(PageButton::Popular),
178191 Self::Trending => Box::new(PageButton::Trending),
192 Self::History => Box::new(PageButton::History),
179193 Self::MessageBar => Box::new(MessageBar::default()),
180194 Self::ItemList => Box::new(ItemList::default()),
181195 Self::SearchFilters => Box::new(SearchFilter::default()),
@@ -191,6 +205,7 @@ impl PageItems {
191205 match self {
192206 Self::Popular
193207 | Self::Trending
208 | Self::History
194209 | Self::ChannelMain
195210 | Self::ChannelVideos
196211 | Self::ChannelPlaylists => Constraint::Length(15),
@@ -204,6 +219,7 @@ impl PageItems {
204219 pub fn height(&self) -> Constraint {
205220 match self {
206221 Self::Popular
222 | Self::History
207223 | Self::ChannelMain
208224 | Self::ChannelVideos
209225 | Self::ChannelPlaylists
@@ -244,7 +260,10 @@ fn main_menu_default() -> PageConfig {
244260 PageConfig {
245261 layout: vec![
246262 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 ),
248267 PageRow::from_vec(vec![PageItems::ItemList], false),
249268 PageRow::from_vec(vec![PageItems::MessageBar], false),
250269 ],
src/exit.rs +12 −1
@@ -1,10 +1,21 @@
11use home::home_dir;
22use std::{error::Error, fs};
3use tui_additions::framework::Framework;
4
5use crate::global::structs::WatchHistory;
36
47/// function to run when the app ends
58// exit tasks:
9// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
610// - 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
819 let home_dir = home_dir().unwrap();
920 let cache_path = home_dir.join(".cache/youtube-tui/");
1021
src/global/functions/download_all_images.rs +2 −6
@@ -1,6 +1,6 @@
11use crate::global::structs::Item;
22use futures::future::join_all;
3use std::{error::Error, fs, io::Cursor, thread};
3use std::{error::Error, io::Cursor, thread};
44use tokio::runtime::Runtime;
55
66pub struct DownloadRequest {
@@ -59,9 +59,7 @@ async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
5959 path.push(".cache/youtube-tui/thumbnails/");
6060
6161 for download in downloads.into_iter() {
62 let mut path = path.clone();
63 fs::create_dir_all(&path).unwrap();
64 path.push(download.id);
62 let path = path.clone().join(download.id);
6563
6664 if !path.exists() {
6765 actions.push(download_single(
@@ -69,8 +67,6 @@ async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
6967 path.clone().into_os_string().into_string().unwrap(),
7068 ));
7169 }
72
73 path.pop();
7470 }
7571
7672 join_all(actions).await;
src/global/structs/item.rs +53 −24
@@ -8,11 +8,14 @@ use invidious::structs::{
88 universal::Playlist as FullPlaylist,
99 video::Video,
1010};
11use serde::{Deserialize, Serialize};
1112use std::fmt::Display;
1213
14use super::Errors;
15
1316/// Items are things like a single video/playlist and channel
1417// they are displayed by the item info widget in `iteminfo.rs`
15#[derive(Clone)]
18#[derive(Clone, Serialize, Deserialize)]
1619pub enum Item {
1720 // minivideos are all videos that appeared without actually clicking into the video
1821 MiniVideo(MiniVideoItem),
@@ -24,7 +27,7 @@ pub enum Item {
2427 Unknown(SearchItemTransition),
2528}
2629
27#[derive(Clone)]
30#[derive(Clone, Serialize, Deserialize)]
2831pub struct MiniVideoItem {
2932 pub title: String,
3033 pub id: String,
@@ -37,7 +40,7 @@ pub struct MiniVideoItem {
3740 pub description: Option<String>,
3841}
3942
40#[derive(Clone)]
43#[derive(Clone, Serialize, Deserialize)]
4144pub struct MiniPlaylistItem {
4245 pub title: String,
4346 pub id: String,
@@ -47,7 +50,7 @@ pub struct MiniPlaylistItem {
4750 pub thumbnail_url: String,
4851}
4952
50#[derive(Clone)]
53#[derive(Clone, Serialize, Deserialize)]
5154pub struct MiniChannelItem {
5255 pub name: String,
5356 pub id: String,
@@ -58,7 +61,7 @@ pub struct MiniChannelItem {
5861 pub description: String,
5962}
6063
61#[derive(Clone)]
64#[derive(Clone, Serialize, Deserialize)]
6265pub struct FullVideoItem {
6366 pub title: String,
6467 pub id: String,
@@ -75,7 +78,7 @@ pub struct FullVideoItem {
7578 pub genre: String,
7679}
7780
78#[derive(Clone)]
81#[derive(Clone, Serialize, Deserialize)]
7982pub struct FullPlaylistItem {
8083 pub title: String,
8184 pub id: String,
@@ -88,7 +91,7 @@ pub struct FullPlaylistItem {
8891 pub videos: Vec<Item>,
8992}
9093
91#[derive(Clone)]
94#[derive(Clone, Serialize, Deserialize)]
9295pub struct FullChannelItem {
9396 pub name: String,
9497 pub id: String,
@@ -116,38 +119,56 @@ impl Display for Item {
116119}
117120
118121impl 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> {
120141 match self {
121 Self::FullVideo(fullvideo) => fullvideo,
122 _ => panic!("not a fullvideo"),
142 Self::FullVideo(fullvideo) => Ok(fullvideo),
143 _ => Err(Errors::StrError("not a full video")),
123144 }
124145 }
125146
126 pub fn minivideo(&self) -> &MiniVideoItem {
147 pub fn minivideo(&self) -> Result<&MiniVideoItem, Errors> {
127148 match self {
128 Self::MiniVideo(minivideo) => minivideo,
129 _ => panic!("not a minivideo"),
149 Self::MiniVideo(minivideo) => Ok(minivideo),
150 _ => Err(Errors::StrError("not a mini video")),
130151 }
131152 }
132153
133 pub fn miniplaylist(&self) -> &MiniPlaylistItem {
154 pub fn miniplaylist(&self) -> Result<&MiniPlaylistItem, Errors> {
134155 match self {
135 Self::MiniPlaylist(miniplaylist) => miniplaylist,
136 _ => panic!("not a miniplaylist"),
156 Self::MiniPlaylist(miniplaylist) => Ok(miniplaylist),
157 _ => Err(Errors::StrError("not a mini playlist")),
137158 }
138159 }
139160
140 pub fn fullplaylist(&self) -> &FullPlaylistItem {
161 pub fn fullplaylist(&self) -> Result<&FullPlaylistItem, Errors> {
141162 match self {
142 Self::FullPlaylist(fullplaylist) => fullplaylist,
143 _ => panic!("not a fullplaylist"),
163 Self::FullPlaylist(fullplaylist) => Ok(fullplaylist),
164 _ => Err(Errors::StrError("not a full playlist")),
144165 }
145166 }
146167
147 pub fn minichannel(&self) -> &MiniChannelItem {
168 pub fn minichannel(&self) -> Result<&MiniChannelItem, Errors> {
148169 match self {
149 Self::MiniChannel(minichannel) => minichannel,
150 _ => panic!("not a minichannel"),
170 Self::MiniChannel(minichannel) => Ok(minichannel),
171 _ => Err(Errors::StrError("not a mini channel")),
151172 }
152173 }
153174}
@@ -286,7 +307,11 @@ impl Item {
286307 channel: original.author,
287308 channel_id: original.author_id,
288309 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 ),
290315 description: original.description,
291316 likes: viewcount_text(original.likes as u64),
292317 genre: original.genre,
@@ -348,7 +373,11 @@ impl Item {
348373 views: Some(viewcount_text(original.view_count)),
349374 channel: original.author,
350375 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 )),
352381 description: Some(original.description),
353382 })
354383 }
src/global/structs/mod.rs +2
@@ -7,6 +7,7 @@ mod message;
77mod page;
88mod status;
99mod tasks;
10mod watchhistory;
1011
1112pub use errors::*;
1213pub use invidiousclient::*;
@@ -16,3 +17,4 @@ pub use message::*;
1617pub use page::*;
1718pub use status::*;
1819pub use tasks::*;
20pub use watchhistory::*;
src/global/structs/page.rs +2
@@ -53,6 +53,7 @@ impl Key for Page {
5353pub enum MainMenuPage {
5454 Trending,
5555 Popular,
56 History,
5657}
5758
5859impl Default for MainMenuPage {
@@ -61,6 +62,7 @@ impl Default for MainMenuPage {
6162 }
6263}
6364
65/// variants of the coannel display page
6466#[derive(Clone, PartialEq)]
6567pub struct ChannelDisplayPage {
6668 pub id: String,
src/global/structs/tasks.rs +1
@@ -189,6 +189,7 @@ impl TaskQueue {
189189 }
190190}
191191
192/// a single task
192193#[derive(Clone, PartialEq, Eq, Debug)]
193194pub enum RenderTask {
194195 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;
12use serde::{de::DeserializeOwned, Serialize};
23use std::{
34 error::Error,
@@ -15,10 +16,9 @@ pub trait ConfigTrait {
1516 where
1617 Self: Serialize + DeserializeOwned + Default + Clone,
1718 {
18 let mut config_path = home::home_dir().expect("cannot get home directory");
19 config_path.push(".config");
20 config_path.push("youtube-tui");
21 config_path.push(format!("{}.{}", Self::LABEL, EXTENSION));
19 let home_dir = home_dir().unwrap();
20 let config_path =
21 home_dir.join(format!(".config/youtube-tui/{}.{}", Self::LABEL, EXTENSION));
2222
2323 // The config struct
2424 let config: Self = {
src/init.rs +17 −4
@@ -4,7 +4,7 @@ use crate::{
44 KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
55 },
66 global::{
7 structs::{InvidiousClient, Message, Page, Status, Tasks},
7 structs::{InvidiousClient, Message, Page, Status, Tasks, WatchHistory},
88 traits::ConfigTrait,
99 },
1010};
@@ -21,16 +21,25 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
2121 // creating files
2222 let home_dir = home_dir().unwrap();
2323 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/");
2527
2628 if !&config_path.exists() {
2729 fs::create_dir_all(&config_path).unwrap();
2830 }
2931
30 if !&cache_path.exists() {
31 fs::create_dir_all(&config_path).unwrap();
32 if !&cache_thumbnails_path.exists() {
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();
3238 }
3339
40 // watch history init
41 WatchHistory::init_move();
42
3443 // inserting data
3544 let main_config = *MainConfig::load()?;
3645
@@ -38,6 +47,10 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
3847 .data
3948 .global
4049 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone()));
50 framework
51 .data
52 .global
53 .insert::<WatchHistory>(WatchHistory::load());
4154 framework
4255 .data
4356 .global
src/items/channeldisplay.rs +10 −8
@@ -4,8 +4,8 @@ use crate::{
44 global::{
55 functions::download_all_images,
66 structs::{
7 ChannelDisplayPageType, InvidiousClient, Item, KeyAction, Page, SingleItemPage, Task,
8 Tasks, Message,
7 ChannelDisplayPageType, InvidiousClient, Item, KeyAction, Message, Page,
8 SingleItemPage, Task, Tasks,
99 },
1010 },
1111};
@@ -217,13 +217,14 @@ impl FrameworkItem for ChannelDisplay {
217217 .unwrap()
218218 .priority
219219 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
220 videos[textlist.selected].minivideo().id.clone(),
220 videos[textlist.selected].minivideo()?.id.clone(),
221221 ))));
222222 } 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"));
224225 }
225226 true
226 },
227 }
227228 _ => false,
228229 };
229230
@@ -259,13 +260,14 @@ impl FrameworkItem for ChannelDisplay {
259260 .unwrap()
260261 .priority
261262 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
262 playlists[textlist.selected].miniplaylist().id.clone(),
263 playlists[textlist.selected].miniplaylist()?.id.clone(),
263264 ))));
264265 } 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"));
266268 }
267269 true
268 },
270 }
269271 _ => false,
270272 };
271273
src/items/itemlist.rs +15 −1
@@ -14,7 +14,7 @@ use crate::{
1414 structs::{
1515 ChannelDisplayPage, ChannelDisplayPageType, FullPlaylistItem, FullVideoItem,
1616 InvidiousClient, Item, KeyAction, MainMenuPage, MiniChannelItem, MiniPlaylistItem,
17 MiniVideoItem, Page, SingleItemPage, Task, Tasks,
17 MiniVideoItem, Page, SingleItemPage, Task, Tasks, WatchHistory,
1818 },
1919 },
2020};
@@ -159,6 +159,20 @@ impl FrameworkItem for ItemList {
159159 .map(|item| Item::from_popular_item(item, image_index))
160160 .collect();
161161 }
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 }
162176 Page::Search(search) => {
163177 self.items = client
164178 .search(Some(&search.to_string()))?
src/items/pagebutton.rs +10 −1
@@ -1,7 +1,7 @@
11use crate::{
22 config::AppearanceConfig,
33 global::structs::{
4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Page, Task, Tasks,
4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Page, Task, Tasks, Message,
55 },
66};
77use tui::{
@@ -16,6 +16,7 @@ use tui_additions::framework::FrameworkItem;
1616pub enum PageButton {
1717 Trending,
1818 Popular,
19 History,
1920 ChannelMain,
2021 ChannelVideos,
2122 ChannelPlaylists,
@@ -26,6 +27,7 @@ impl PageButton {
2627 match self {
2728 Self::Trending => Page::MainMenu(MainMenuPage::Trending),
2829 Self::Popular => Page::MainMenu(MainMenuPage::Popular),
30 Self::History => Page::MainMenu(MainMenuPage::History),
2931 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage {
3032 id: current_page.channeldisplay().id.clone(),
3133 r#type: ChannelDisplayPageType::Main,
@@ -47,6 +49,7 @@ impl ToString for PageButton {
4749 match self {
4850 Self::Popular => String::from("Popular"),
4951 Self::Trending => String::from("Trending"),
52 Self::History => String::from("History"),
5053 Self::ChannelMain => String::from("Main"),
5154 Self::ChannelVideos => String::from("Videos"),
5255 Self::ChannelPlaylists => String::from("Playlists"),
@@ -92,6 +95,12 @@ impl FrameworkItem for PageButton {
9295 // when selected creates a load page task, but returns false to show that it is not being selected
9396 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
9497 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
95104 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
96105 tasks
97106 .priority
src/items/searchbar.rs +1
@@ -12,6 +12,7 @@ use tui::{
1212};
1313use tui_additions::{framework::FrameworkItem, widgets::TextField};
1414
15/// the search bar item
1516#[derive(Clone, Default)]
1617pub struct SearchBar {
1718 pub text_field: TextField,
src/items/singleitem.rs +32 −13
@@ -3,7 +3,10 @@ use crate::{
33 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider},
44 global::{
55 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 },
710 },
811};
912use std::{collections::HashMap, thread};
@@ -115,7 +118,7 @@ impl SingleVideoItem {
115118
116119 /// creates a hashmap from `self`, containing info of the current item
117120 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();
119122
120123 HashMap::from([
121124 (
@@ -182,7 +185,7 @@ impl SinglePlaylistItem {
182185 items.extend(
183186 playlist_items
184187 .iter()
185 .map(|item| item.minivideo().title.as_str()),
188 .map(|item| item.minivideo().unwrap().title.as_str()),
186189 );
187190 items
188191 })
@@ -265,7 +268,7 @@ impl SinglePlaylistItem {
265268
266269 /// creates a hashmap from `self`, containing info of the current item
267270 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();
269272 HashMap::from([
270273 (
271274 String::from("url"),
@@ -289,7 +292,9 @@ impl SinglePlaylistItem {
289292 Provider::YouTube => playlist_item
290293 .videos
291294 .iter()
292 .map(|video| format!("'https://youtu.be/{}'", video.minivideo().id))
295 .map(|video| {
296 format!("'https://youtu.be/{}'", video.minivideo().unwrap().id)
297 })
293298 .collect::<Vec<_>>()
294299 .join(" "),
295300 Provider::Invidious => playlist_item
@@ -299,7 +304,7 @@ impl SinglePlaylistItem {
299304 format!(
300305 "'{}/watch?v={}'",
301306 mainconfig.invidious_instance,
302 video.minivideo().id
307 video.minivideo().unwrap().id
303308 )
304309 })
305310 .collect::<Vec<_>>()
@@ -486,7 +491,7 @@ impl FrameworkItem for SingleItem {
486491 SingleItemPage::Playlist(id) => {
487492 let playlist =
488493 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index);
489 let videos = &playlist.fullplaylist().videos;
494 let videos = &playlist.fullplaylist()?.videos;
490495 self.r#type = SingleItemType::Playlist(
491496 SinglePlaylistItem::new(
492497 framework.data.global.get::<CommandsConfig>().unwrap(),
@@ -512,6 +517,20 @@ impl FrameworkItem for SingleItem {
512517 // instead of the actual provider (e.g. `YouTube`)
513518 self.update_provider();
514519
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
515534 Ok(())
516535 }
517536
@@ -659,7 +678,7 @@ impl FrameworkItem for SingleItem {
659678 let updated = singleplaylistitem.videos_view.up().is_ok();
660679 if updated && singleplaylistitem.videos_view.selected != 0 {
661680 singleplaylistitem.hovered_video.item = Some(
662 self.item.as_ref().unwrap().fullplaylist().videos
681 self.item.as_ref().unwrap().fullplaylist()?.videos
663682 [singleplaylistitem.videos_view.selected - 1]
664683 .clone(),
665684 );
@@ -681,7 +700,7 @@ impl FrameworkItem for SingleItem {
681700 let updated = singleplaylistitem.videos_view.down().is_ok();
682701 if updated && singleplaylistitem.videos_view.selected != 0 {
683702 singleplaylistitem.hovered_video.item = Some(
684 self.item.as_ref().unwrap().fullplaylist().videos
703 self.item.as_ref().unwrap().fullplaylist()?.videos
685704 [singleplaylistitem.videos_view.selected - 1]
686705 .clone(),
687706 );
@@ -692,7 +711,7 @@ impl FrameworkItem for SingleItem {
692711 let updated = singleplaylistitem.videos_view.first().is_ok();
693712 if updated && singleplaylistitem.videos_view.selected != 0 {
694713 singleplaylistitem.hovered_video.item = Some(
695 self.item.as_ref().unwrap().fullplaylist().videos
714 self.item.as_ref().unwrap().fullplaylist()?.videos
696715 [singleplaylistitem.videos_view.selected - 1]
697716 .clone(),
698717 );
@@ -703,7 +722,7 @@ impl FrameworkItem for SingleItem {
703722 let updated = singleplaylistitem.videos_view.last().is_ok();
704723 if updated && singleplaylistitem.videos_view.selected != 0 {
705724 singleplaylistitem.hovered_video.item = Some(
706 self.item.as_ref().unwrap().fullplaylist().videos
725 self.item.as_ref().unwrap().fullplaylist()?.videos
707726 [singleplaylistitem.videos_view.selected - 1]
708727 .clone(),
709728 );
@@ -728,9 +747,9 @@ impl FrameworkItem for SingleItem {
728747 .unwrap()
729748 .priority
730749 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
731 self.item.as_ref().unwrap().fullplaylist().videos
750 self.item.as_ref().unwrap().fullplaylist()?.videos
732751 [singleplaylistitem.videos_view.selected - 1]
733 .minivideo()
752 .minivideo()?
734753 .id
735754 .clone(),
736755 ))));
src/main.rs +2 −2
@@ -24,7 +24,7 @@ fn main() -> Result<(), Box<dyn Error>> {
2424 let backend = CrosstermBackend::new(stdout);
2525 let mut terminal = Terminal::new(backend)?;
2626
27 let res = run(&mut terminal, framework);
27 let res = run(&mut terminal, &mut framework);
2828
2929 disable_raw_mode()?;
3030 execute!(
@@ -34,7 +34,7 @@ fn main() -> Result<(), Box<dyn Error>> {
3434 )?;
3535 terminal.show_cursor()?;
3636
37 let exit_res = exit();
37 let exit_res = exit(&framework);
3838
3939 res?;
4040 exit_res?;
src/run.rs +4 −4
@@ -11,20 +11,20 @@ use crate::{
1111/// the main event loop of the program
1212pub fn run(
1313 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
14 mut framework: Framework,
14 framework: &mut Framework,
1515) -> Result<(), Box<dyn Error>> {
1616 // push the initial page load
1717 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
1818 tasks
1919 .priority
20 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Trending)));
21 tasks.pop().unwrap().run(&mut framework, terminal)?;
20 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Popular)));
21 tasks.pop().unwrap().run(framework, terminal)?;
2222 framework.clear_history();
2323
2424 loop {
2525 // repeat forever until all tasks are ran (and Tasks is cleared)
2626 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
27 tasks.run(&mut framework, terminal)?;
27 tasks.run(framework, terminal)?;
2828 continue;
2929 }
3030