src/global/functions/download_all_images.rs
67 lines · 2019 bytes
1use crate::global::item::Item;
2use futures::future::join_all;
3use std::{error::Error, fs, 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 DownloadRequest {
12 fn from(item: &Item) -> Self {
13 match item {
14 Item::MiniVideo(minivideo) => Self {
15 url: minivideo.thumbnail_url.clone(),
16 id: minivideo.id.clone(),
17 },
18 }
19 }
20}
21
22// Function to download all thumbnails (or just any files) to `~/.cache/thumbnails` with no file exitension (cuz its not needed)
23pub fn download_all_images(downloads: Vec<DownloadRequest>) {
24 thread::spawn(move || {
25 let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
26
27 let _ = rt.block_on(download_all_images_async(downloads));
28 });
29}
30
31// Create a `download_single()`s and join them into 1 future
32// So all downloads will happen at the same time without waiting
33async fn download_all_images_async(downloads: Vec<DownloadRequest>) {
34 let mut actions = Vec::new();
35 let mut path = home::home_dir().expect("Cannot get your home directory");
36 path.push(".cache/youtube-tui/thumbnails/");
37
38 for download in downloads.into_iter() {
39 let mut path = path.clone();
40 fs::create_dir_all(&path).unwrap();
41 path.push(download.id);
42
43 if !path.exists() {
44 actions.push(download_single(
45 download.url,
46 path.clone().into_os_string().into_string().unwrap(),
47 ));
48 }
49
50 path.pop();
51 }
52
53 join_all(actions).await;
54}
55
56// Download a single file
57async fn download_single(url: String, path: String) -> Result<(), Box<dyn Error>> {
58 let response = reqwest::get(url).await?;
59 if !response.status().is_success() {
60 return Ok(());
61 }
62
63 let mut file = std::fs::File::create(path)?;
64 let mut content = Cursor::new(response.bytes().await?);
65 std::io::copy(&mut content, &mut file)?;
66 Ok(())
67}