src/global/functions/download_all_images.rs

84c4617332578aaf4e9ee68a0a2d7d6258e48243
youtube-tui/src/global/functions/download_all_images.rs history · blame · raw

76 lines · 2615 bytes

5 symbols in this file
 1use crate::global::structs::{Item, LocalStore};
 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 = super::paths::data_dir().join("thumbnails");
50
51    downloads.into_iter().flatten().for_each(|req| {
52        LocalStore::add_image(req.id.clone());
53        let path = path.clone().join(req.id);
54        if path.exists() {
55            return;
56        }
57
58        thread::spawn(move || {
59            let _ = download_single(&req.url, path);
60        });
61    })
62}
63
64fn httpreq_get(url: &str) -> Result<Vec<u8>, http_req::error::Error> {
65    let mut buffer = Vec::new();
66    http_req::request::get(url, &mut buffer)?;
67    Ok(buffer)
68}
69
70fn download_single(url: &str, path: PathBuf) -> Result<(), Box<dyn Error>> {
71    let res = httpreq_get(url)?;
72    let mut file = fs::File::create(path)?;
73    let mut content = Cursor::new(res);
74    std::io::copy(&mut content, &mut file)?;
75    Ok(())
76}