src/functions/download_all_thumbnails.rs

641938ba1f255069a13382c2a2903a32612e3873
youtube-tui/src/functions/download_all_thumbnails.rs history · blame · raw

60 lines · 1577 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, ItemType)>,
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(urls: LinkedList<(String, String, ItemType)>) -> Result<(), Box<dyn Error>> {
24    let mut actions = Vec::new();
25    let mut path = home::home_dir().expect("Cannot get your home directory");
26    path.push(".cache");
27    path.push("youtube-tui");
28    path.push("thumbnails");
29
30    for (url, video_id, item_type) in urls.iter() {
31        path.push(match item_type {
32            ItemType::Video => "videos",
33            ItemType::Playlist => "playlists",
34        });
35
36        path.push(format!("{}.png", video_id));
37
38        if !path.exists() {
39            actions.push(fetch_url(
40                url.as_str(),
41                path.clone().into_os_string().into_string().unwrap(),
42            ));
43        }
44
45        path.pop();
46        path.pop();
47    }
48
49    join_all(actions).await;
50
51    Ok(())
52}
53
54async fn fetch_url(url: &str, path: String) -> Result<(), Box<dyn Error>> {
55    let response = reqwest::get(url).await?;
56    let mut file = std::fs::File::create(path)?;
57    let mut content = Cursor::new(response.bytes().await?);
58    std::io::copy(&mut content, &mut file)?;
59    Ok(())
60}