src/global/functions/download_all_images.rs

86 lines · 2964 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(_) => 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    thread::spawn(move || {
46        let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
47
48        let _ = rt.block_on(download_all_images_async(
49            downloads.into_iter().flatten().collect(),
50        ));
51    });
52}
53
54// Create a `download_single()`s and join them into 1 future
55// So all downloads will happen at the same time without waiting
56async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
57    let mut actions = Vec::new();
58    let mut path = home::home_dir().expect("Cannot get your home directory");
59    path.push(".cache/youtube-tui/thumbnails/");
60
61    for download in downloads.into_iter() {
62        let path = path.clone().join(download.id);
63
64        if !path.exists() {
65            actions.push(download_single(
66                download.url,
67                path.clone().into_os_string().into_string().unwrap(),
68            ));
69        }
70    }
71
72    join_all(actions).await;
73}
74
75// Download a single file
76async fn download_single(url: String, path: String) -> Result<(), Box<dyn Error>> {
77    let response = reqwest::get(url).await?;
78    if !response.status().is_success() {
79        return Ok(());
80    }
81
82    let mut file = std::fs::File::create(path)?;
83    let mut content = Cursor::new(response.bytes().await?);
84    std::io::copy(&mut content, &mut file)?;
85    Ok(())
86}