src/global/functions/download_all_images.rs

70 lines · 2477 bytes

 1use crate::global::structs::Item;
 2use std::{error::Error, fs, io::Cursor, path::PathBuf, thread};
 3
 4pub struct DownloadRequest {
 5    pub url: String,
 6    pub id: String,
 7}
 8
 9impl From<&Item> for Option<DownloadRequest> {
10    // turn `Item` into a thumbnail download request
11    fn from(item: &Item) -> Self {
12        Some(match item {
13            Item::MiniVideo(minivideo) => DownloadRequest {
14                url: minivideo.thumbnail_url.clone(),
15                id: minivideo.id.clone(),
16            },
17            Item::MiniPlaylist(miniplaylist) => DownloadRequest {
18                url: miniplaylist.thumbnail_url.clone(),
19                id: miniplaylist.id.clone(),
20            },
21            Item::MiniChannel(minichannel) => DownloadRequest {
22                url: minichannel.thumbnail_url.clone(),
23                id: minichannel.id.clone(),
24            },
25            Item::FullVideo(fullvideo) => DownloadRequest {
26                url: fullvideo.thumbnail_url.clone(),
27                id: fullvideo.id.clone(),
28            },
29            Item::FullPlaylist(fullplaylist) => DownloadRequest {
30                url: fullplaylist.thumbnail_url.clone(),
31                id: fullplaylist.id.clone(),
32            },
33            Item::FullChannel(fullchannel) => DownloadRequest {
34                url: fullchannel.thumbnail_url.clone(),
35                id: fullchannel.id.clone(),
36            },
37            _ => return None,
38        })
39    }
40}
41
42/// Function to download all thumbnails (or just any files) to `~/.cache/thumbnails` with  no file exitension (cuz its not needed)
43pub fn download_all_images(downloads: Vec<Option<DownloadRequest>>) {
44    // do not download the images if non of the features are enabled
45    if cfg!(not(any(feature = "sixel", feature = "halfblock"))) {
46        return;
47    }
48
49    let path = home::home_dir()
50        .expect("Cannot get your home directory")
51        .join(".cache/youtube-tui/thumbnails/");
52
53    downloads.into_iter().flatten().for_each(|req| {
54        let path = path.clone().join(req.id);
55        if path.exists() {
56            return;
57        }
58        thread::spawn(move || {
59            let _ = download_single(&req.url, path);
60        });
61    })
62}
63
64fn download_single(url: &str, path: PathBuf) -> Result<(), Box<dyn Error>> {
65    let res = invidious::functions::httpreq_get(url)?;
66    let mut file = fs::File::create(path)?;
67    let mut content = Cursor::new(res);
68    std::io::copy(&mut content, &mut file)?;
69    Ok(())
70}