src/functions/download_all_thumbnails.rs
54 lines · 1402 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)>, // (url, id)
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)>) -> 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) in urls.iter() {
31 path.push(format!("{}.png", video_id));
32
33 if !path.exists() {
34 actions.push(fetch_url(
35 url.as_str(),
36 path.clone().into_os_string().into_string().unwrap(),
37 ));
38 }
39
40 path.pop();
41 }
42
43 join_all(actions).await;
44
45 Ok(())
46}
47
48async fn fetch_url(url: &str, path: String) -> Result<(), Box<dyn Error>> {
49 let response = reqwest::get(url).await?;
50 let mut file = std::fs::File::create(path)?;
51 let mut content = Cursor::new(response.bytes().await?);
52 std::io::copy(&mut content, &mut file)?;
53 Ok(())
54}