src/functions/download_all_thumbnails.rs

2a2a2fa4a5238515d8e2b21c975824c74f72606c
youtube-tui/src/functions/download_all_thumbnails.rs history · blame · raw

57 lines · 1397 bytes

 1use std::{collections::LinkedList, error::Error, io::Cursor, thread};
 2
 3use futures::future::join_all;
 4use tokio::runtime::Runtime;
 5
 6pub enum ItemType {
 7    Video,
 8    Playlist,
 9}
10
11pub fn download_all_thumbnails(
12    list: LinkedList<(String, String)>,
13) -> Result<(), Box<dyn Error>> {
14    thread::spawn(move || {
15        let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
16
17        let _ = rt.block_on(download_items(list));
18    });
19
20    Ok(())
21}
22
23pub async fn download_items(
24    urls: LinkedList<(String, String)>,
25) -> Result<(), Box<dyn Error>> {
26    let mut actions = Vec::new();
27    let mut path = home::home_dir().expect("Cannot get your home directory");
28    path.push(".cache");
29    path.push("youtube-tui");
30    path.push("thumbnails");
31
32    for (url, video_id) in urls.iter() {
33
34        path.push(format!("{}.png", video_id));
35
36        if !path.exists() {
37            actions.push(fetch_url(
38                url.as_str(),
39                path.clone().into_os_string().into_string().unwrap(),
40            ));
41        }
42
43        path.pop();
44    }
45
46    join_all(actions).await;
47
48    Ok(())
49}
50
51async fn fetch_url(url: &str, path: String) -> Result<(), Box<dyn Error>> {
52    let response = reqwest::get(url).await?;
53    let mut file = std::fs::File::create(path)?;
54    let mut content = Cursor::new(response.bytes().await?);
55    std::io::copy(&mut content, &mut file)?;
56    Ok(())
57}