use crate::ScootalooError; use reqwest::Url; use std::error::Error; use tokio::{ fs::{create_dir_all, File}, io::copy, }; /// Gets and caches Twitter Media inside the determined temp dir pub async fn cache_media(u: &str, t: &str) -> Result> { // create dir create_dir_all(t).await?; // get file let mut response = reqwest::get(u).await?; // create local file let url = Url::parse(u)?; let dest_filename = url .path_segments() .ok_or_else(|| { ScootalooError::new(&format!( "Cannot determine the destination filename for {}", u )) })? .last() .ok_or_else(|| { ScootalooError::new(&format!( "Cannot determine the destination filename for {}", u )) })?; let dest_filepath = format!("{}/{}", t, dest_filename); let mut dest_file = File::create(&dest_filepath).await?; while let Some(chunk) = response.chunk().await? { copy(&mut &*chunk, &mut dest_file).await?; } Ok(dest_filepath) } #[cfg(test)] mod tests { use super::*; use std::{fs::remove_dir_all, path::Path}; const TMP_DIR: &'static str = "/tmp/scootaloo_test"; #[tokio::test] async fn test_cache_media() { let dest = cache_media( "https://forum.nintendojo.fr/styles/prosilver/theme/images/ndfr_casual.png", TMP_DIR, ) .await .unwrap(); assert!(Path::new(&dest).exists()); remove_dir_all(TMP_DIR).unwrap(); } }