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