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