| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
use reqwest::header::*; |
| 21 |
use reqwest::redirect::Policy; |
| 22 |
use tempfile::TempDir; |
| 23 |
|
| 24 |
use std::fs; |
| 25 |
use std::fs::{File, copy, remove_file}; |
| 26 |
use std::io::{BufWriter, Write}; |
| 27 |
use std::path::Path; |
| 28 |
use std::sync::{Arc, Mutex}; |
| 29 |
|
| 30 |
use crate::errors::DownloadError; |
| 31 |
use crate::xdg_dirs::PODCASTS_CACHE; |
| 32 |
use crate::{EpisodeModel, EpisodeWidgetModel, Save}; |
| 33 |
|
| 34 |
use crate::ShowCoverModel; |
| 35 |
use crate::utils; |
| 36 |
use glob::glob; |
| 37 |
use std::path::PathBuf; |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
pub trait DownloadProgress { |
| 44 |
fn get_downloaded(&self) -> u64; |
| 45 |
fn set_downloaded(&mut self, downloaded: u64); |
| 46 |
fn get_size(&self) -> u64; |
| 47 |
fn set_size(&mut self, bytes: u64); |
| 48 |
fn should_cancel(&self) -> bool; |
| 49 |
fn cancel(&mut self); |
| 50 |
} |
| 51 |
|
| 52 |
pub fn client_builder() -> reqwest::ClientBuilder { |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
let policy = Policy::custom(|attempt| { |
| 57 |
info!("Redirect Attempt URL: {:?}", attempt.url()); |
| 58 |
if attempt.previous().len() > 20 { |
| 59 |
attempt.error("too many redirects") |
| 60 |
} else if Some(attempt.url()) == attempt.previous().last() { |
| 61 |
|
| 62 |
attempt.stop() |
| 63 |
} else { |
| 64 |
attempt.follow() |
| 65 |
} |
| 66 |
}); |
| 67 |
|
| 68 |
reqwest::Client::builder() |
| 69 |
.redirect(policy) |
| 70 |
.referer(false) |
| 71 |
.user_agent(crate::USER_AGENT) |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
async fn download_into( |
| 82 |
dir: &str, |
| 83 |
file_title: &str, |
| 84 |
url: &str, |
| 85 |
progress: Option<Arc<Mutex<dyn DownloadProgress + Send>>>, |
| 86 |
) -> Result<String, DownloadError> { |
| 87 |
info!("GET request to: {}", url); |
| 88 |
|
| 89 |
let client = client_builder().build()?; |
| 90 |
let resp = client.get(url).send().await?; |
| 91 |
info!("Status Resp: {}", resp.status()); |
| 92 |
|
| 93 |
if !resp.status().is_success() { |
| 94 |
if let Some(ref prog) = progress { |
| 95 |
if let Ok(mut m) = prog.lock() { |
| 96 |
m.cancel(); |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
return Err(DownloadError::UnexpectedResponse(resp.status())); |
| 101 |
} |
| 102 |
|
| 103 |
let headers = resp.headers().clone(); |
| 104 |
let ct_len = headers |
| 105 |
.get(CONTENT_LENGTH) |
| 106 |
.and_then(|h| h.to_str().ok()) |
| 107 |
.and_then(|len| len.parse().ok()); |
| 108 |
let ct_type = headers.get(CONTENT_TYPE).and_then(|h| h.to_str().ok()); |
| 109 |
|
| 110 |
if let Some(ct_len) = ct_len { |
| 111 |
info!("File Length: {}", ct_len); |
| 112 |
} |
| 113 |
if let Some(ct_type) = ct_type { |
| 114 |
info!("Content Type: {}", ct_type); |
| 115 |
} |
| 116 |
|
| 117 |
let ext = get_ext(ct_type).unwrap_or_else(|| String::from("unknown")); |
| 118 |
info!("Extension: {}", ext); |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
let tempdir = TempDir::with_prefix_in("temp_download", PODCASTS_CACHE.to_str().unwrap())?; |
| 124 |
let out_file = format!("{}/temp.part", tempdir.path().to_str().unwrap(),); |
| 125 |
|
| 126 |
if let Some(ct_len) = ct_len { |
| 127 |
if let Some(ref p) = progress { |
| 128 |
if let Ok(mut m) = p.lock() { |
| 129 |
m.set_size(ct_len); |
| 130 |
} |
| 131 |
} |
| 132 |
}; |
| 133 |
|
| 134 |
|
| 135 |
save_io(&out_file, resp, progress).await?; |
| 136 |
|
| 137 |
|
| 138 |
let target = format!("{}/{}.{}", dir, file_title, ext); |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
copy(&out_file, &target)?; |
| 143 |
remove_file(out_file)?; |
| 144 |
info!("Downloading of {} completed successfully.", &target); |
| 145 |
Ok(target) |
| 146 |
} |
| 147 |
|
| 148 |
|
| 149 |
fn get_ext(content: Option<&str>) -> Option<String> { |
| 150 |
let mut iter = content?.split('/'); |
| 151 |
let type_ = iter.next()?; |
| 152 |
let subtype = iter.next()?; |
| 153 |
mime_guess::get_extensions(type_, subtype).and_then(|c| { |
| 154 |
if c.contains(&subtype) { |
| 155 |
Some(subtype.to_string()) |
| 156 |
} else { |
| 157 |
Some(c.first()?.to_string()) |
| 158 |
} |
| 159 |
}) |
| 160 |
} |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
async fn save_io( |
| 167 |
file: &str, |
| 168 |
resp: reqwest::Response, |
| 169 |
progress: Option<Arc<Mutex<dyn DownloadProgress + Send>>>, |
| 170 |
) -> Result<(), DownloadError> { |
| 171 |
use futures_util::StreamExt; |
| 172 |
use std::ops::Deref; |
| 173 |
|
| 174 |
info!("Downloading into: {}", file); |
| 175 |
let mut writer = BufWriter::new(File::create(file)?); |
| 176 |
let mut body_stream = resp.bytes_stream(); |
| 177 |
|
| 178 |
while let Some(chunk) = body_stream.next().await { |
| 179 |
if let Ok(chunk) = chunk { |
| 180 |
writer.write_all(chunk.deref())?; |
| 181 |
|
| 182 |
|
| 183 |
if let Some(prog) = progress.clone() { |
| 184 |
let len = writer.get_ref().metadata().map(|x| x.len()); |
| 185 |
if let Ok(l) = len { |
| 186 |
if let Ok(mut m) = prog.lock() { |
| 187 |
if m.should_cancel() { |
| 188 |
return Err(DownloadError::DownloadCancelled); |
| 189 |
} |
| 190 |
m.set_downloaded(l); |
| 191 |
} |
| 192 |
} |
| 193 |
} |
| 194 |
} else { |
| 195 |
break; |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
Ok(()) |
| 200 |
} |
| 201 |
|
| 202 |
|
| 203 |
pub async fn get_episode( |
| 204 |
ep: &mut EpisodeWidgetModel, |
| 205 |
download_dir: &str, |
| 206 |
progress: Option<Arc<Mutex<dyn DownloadProgress + Send>>>, |
| 207 |
) -> Result<(), DownloadError> { |
| 208 |
|
| 209 |
if ep.local_uri().is_some() { |
| 210 |
if Path::new(ep.local_uri().unwrap()).exists() { |
| 211 |
return Ok(()); |
| 212 |
} |
| 213 |
|
| 214 |
|
| 215 |
ep.set_local_uri(None); |
| 216 |
ep.save()?; |
| 217 |
}; |
| 218 |
|
| 219 |
let path = download_into( |
| 220 |
download_dir, |
| 221 |
&ep.id().0.to_string(), |
| 222 |
ep.uri().unwrap(), |
| 223 |
progress, |
| 224 |
) |
| 225 |
.await?; |
| 226 |
|
| 227 |
|
| 228 |
ep.set_local_uri(Some(&path)); |
| 229 |
|
| 230 |
|
| 231 |
let size = fs::metadata(path); |
| 232 |
if let Ok(s) = size { |
| 233 |
ep.set_length(Some(s.len() as i32)) |
| 234 |
}; |
| 235 |
|
| 236 |
ep.save()?; |
| 237 |
Ok(()) |
| 238 |
} |
| 239 |
|
| 240 |
pub fn check_for_cached_image(pd: &ShowCoverModel, uri: &str) -> Option<PathBuf> { |
| 241 |
let cache_path = utils::get_cover_dir(pd.title()).ok()?; |
| 242 |
let hash = utils::calculate_hash(uri); |
| 243 |
|
| 244 |
if let Ok(mut paths) = glob(&format!("{}/{}.*", hash, cache_path)) { |
| 245 |
|
| 246 |
let path = paths.next().and_then(|x| x.ok()); |
| 247 |
return path; |
| 248 |
} |
| 249 |
|
| 250 |
None |
| 251 |
} |
| 252 |
|
| 253 |
pub async fn cache_episode_image( |
| 254 |
pd: &ShowCoverModel, |
| 255 |
uri: &str, |
| 256 |
download: bool, |
| 257 |
) -> Result<String, DownloadError> { |
| 258 |
if let Some(path) = check_for_cached_image(pd, uri) { |
| 259 |
return Ok(path |
| 260 |
.to_str() |
| 261 |
.ok_or(DownloadError::InvalidCachedImageLocation)? |
| 262 |
.to_owned()); |
| 263 |
} |
| 264 |
|
| 265 |
if uri.is_empty() { |
| 266 |
return Err(DownloadError::NoImageLocation); |
| 267 |
} |
| 268 |
|
| 269 |
let cache_path = utils::get_cover_dir(pd.title())?; |
| 270 |
let hash = utils::calculate_hash(uri); |
| 271 |
|
| 272 |
if download { |
| 273 |
let path = download_into(&cache_path, &format!("{}", hash), uri, None).await?; |
| 274 |
info!("Cached img into: {}", &path); |
| 275 |
Ok(path) |
| 276 |
} else { |
| 277 |
Err(DownloadError::DownloadCancelled) |
| 278 |
} |
| 279 |
} |