src/functions/download_all_thumbnails.rs
52 lines · 1443 bytes
1use std::{collections::LinkedList, error::Error, io::Cursor};
2
3use futures::executor::block_on;
4
5use crate::app::pages::global::ListItem;
6
7pub enum ItemType {
8 Video,
9 Playlist,
10}
11
12pub fn download_all_thumbnails(list: &LinkedList<ListItem>) -> Result<(), Box<dyn Error>>{
13 let mut urls: Vec<(&str, &str, ItemType)> = Vec::new();
14 for i in list.iter() {
15 match i {
16 ListItem::Video(video) => {
17 urls.push((&video.video_thumbnail, &video.video_id, ItemType::Video));
18 }
19 _ => {}
20 }
21 }
22
23 block_on(download_items(urls))?;
24
25 Ok(())
26}
27
28pub async fn download_items(urls: Vec<(&str, &str, ItemType)>) -> Result<(), Box<dyn Error>>{
29 let mut dir = home::home_dir().expect("Cannot get your home directory");
30 dir.push(".siriusmart");
31 dir.push("youtube-tui");
32 dir.push("cache");
33
34 for (url, video_id, item_type) in urls {
35 dir.push(match item_type {
36 ItemType::Video => "videos",
37 ItemType::Playlist => "playlists",
38 });
39
40 fetch_url(url, &format!("{:?}/{}.png", dir, video_id)).await?;
41 }
42
43 Ok(())
44}
45
46async fn fetch_url(url: &str, file_name: &str) -> Result<(), Box<dyn Error>> {
47 let response = reqwest::get(url).await?;
48 let mut file = std::fs::File::create(file_name)?;
49 let mut content = Cursor::new(response.bytes().await?);
50 std::io::copy(&mut content, &mut file)?;
51 Ok(())
52}