src/global/functions/download_all_images.rs
78 lines · 2692 bytes
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 = home::home_dir()
50 .expect("Cannot get your home directory")
51 .join(".local/share/youtube-tui/thumbnails/");
52
53 downloads.into_iter().flatten().for_each(|req| {
54 LocalStore::add_image(req.id.clone());
55 let path = path.clone().join(req.id);
56 if path.exists() {
57 return;
58 }
59
60 thread::spawn(move || {
61 let _ = download_single(&req.url, path);
62 });
63 })
64}
65
66fn httpreq_get(url: &str) -> Result<Vec<u8>, http_req::error::Error> {
67 let mut buffer = Vec::new();
68 http_req::request::get(url, &mut buffer)?;
69 Ok(buffer)
70}
71
72fn download_single(url: &str, path: PathBuf) -> Result<(), Box<dyn Error>> {
73 let res = httpreq_get(url)?;
74 let mut file = fs::File::create(path)?;
75 let mut content = Cursor::new(res);
76 std::io::copy(&mut content, &mut file)?;
77 Ok(())
78}