src/global/functions/download_all_images.rs
92 lines · 3183 bytes
1use crate::global::structs::Item;
2use futures::future::join_all;
3use std::{error::Error, io::Cursor, thread};
4use tokio::runtime::Runtime;
5
6pub struct DownloadRequest {
7 pub url: String,
8 pub id: String,
9}
10
11impl From<&Item> for Option<DownloadRequest> {
12 // turn `Item` into a thumbnail download request
13 fn from(item: &Item) -> Self {
14 Some(match item {
15 Item::MiniVideo(minivideo) => DownloadRequest {
16 url: minivideo.thumbnail_url.clone(),
17 id: minivideo.id.clone(),
18 },
19 Item::MiniPlaylist(miniplaylist) => DownloadRequest {
20 url: miniplaylist.thumbnail_url.clone(),
21 id: miniplaylist.id.clone(),
22 },
23 Item::MiniChannel(minichannel) => DownloadRequest {
24 url: minichannel.thumbnail_url.clone(),
25 id: minichannel.id.clone(),
26 },
27 Item::FullVideo(fullvideo) => DownloadRequest {
28 url: fullvideo.thumbnail_url.clone(),
29 id: fullvideo.id.clone(),
30 },
31 Item::FullPlaylist(fullplaylist) => DownloadRequest {
32 url: fullplaylist.thumbnail_url.clone(),
33 id: fullplaylist.id.clone(),
34 },
35 Item::FullChannel(fullchannel) => DownloadRequest {
36 url: fullchannel.thumbnail_url.clone(),
37 id: fullchannel.id.clone(),
38 },
39 Item::Unknown(_) | Item::Page(_) => return None,
40 })
41 }
42}
43
44/// Function to download all thumbnails (or just any files) to `~/.cache/thumbnails` with no file exitension (cuz its not needed)
45pub fn download_all_images(downloads: Vec<Option<DownloadRequest>>) {
46 // do not download the images if non of the features are enabled
47 if cfg!(not(any(feature = "sixel", feature = "halfblock"))) {
48 return;
49 }
50
51 thread::spawn(move || {
52 let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
53
54 rt.block_on(download_all_images_async(
55 downloads.into_iter().flatten().collect(),
56 ));
57 });
58}
59
60// Create a `download_single()`s and join them into 1 future
61// So all downloads will happen at the same time without waiting
62async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
63 let mut actions = Vec::new();
64 let mut path = home::home_dir().expect("Cannot get your home directory");
65 path.push(".cache/youtube-tui/thumbnails/");
66
67 for download in downloads.into_iter() {
68 let path = path.clone().join(download.id);
69
70 if !path.exists() {
71 actions.push(download_single(
72 download.url,
73 path.clone().into_os_string().into_string().unwrap(),
74 ));
75 }
76 }
77
78 join_all(actions).await;
79}
80
81// Download a single file
82async fn download_single(url: String, path: String) -> Result<(), Box<dyn Error>> {
83 let response = reqwest::get(url).await?;
84 if !response.status().is_success() {
85 return Ok(());
86 }
87
88 let mut file = std::fs::File::create(path)?;
89 let mut content = Cursor::new(response.bytes().await?);
90 std::io::copy(&mut content, &mut file)?;
91 Ok(())
92}