Debian Codegraph @

podcasts-data/src/downloader.rs

raw symbols SCIP
1 // downloader.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // SPDX-License-Identifier: GPL-3.0-or-later
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 // TODO: Replace path that are of type &str with std::path.
40 // TODO: Have a convention/document absolute/relative paths, if they should end
41 // with / or not.
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 // Haven't included the loop check as
54 // Steal the Stars would trigger it as
55 // it has a loop back before giving correct url
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 // avoid redirect loops
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 // Adapted from https://github.com/mattgathu/rget .
75 // I never wanted to write a custom downloader.
76 // Sorry to those who will have to work with that code.
77 // Would much rather use a crate,
78 // or bindings for a lib like youtube-dl(python),
79 // But can't seem to find one.
80 // TODO: Write unit-tests.
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 // Construct a temp file to save desired content.
121 // It has to be a `new_in` instead of new cause rename can't move cross
122 // filesystems.
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 // Save requested content into the file.
135 save_io(&out_file, resp, progress).await?;
136
137 // Construct the desired path.
138 let target = format!("{}/{}.{}", dir, file_title, ext);
139 // Rename/move the tempfile into a permanent place upon success.
140 // Unlike rename(), copy() + remove_file() works even when the
141 // temp dir is on a different mount point than the target dir.
142 copy(&out_file, &target)?;
143 remove_file(out_file)?;
144 info!("Downloading of {} completed successfully.", &target);
145 Ok(target)
146 }
147
148 /// Determine the file extension from the http content-type header.
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 // TODO: Write unit-tests.
163 // TODO: Refactor... Somehow.
164 /// Handles the I/O of fetching a remote file and saving into a Buffer and A
165 /// File.
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 // This sucks.
182 // Actually the whole download module is hack, so w/e.
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 // TODO: Refactor
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 // Check if its alrdy downloaded
209 if ep.local_uri().is_some() {
210 if Path::new(ep.local_uri().unwrap()).exists() {
211 return Ok(());
212 }
213
214 // If the path is not valid, then set it to None.
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 // If download succeeds set episode local_uri to dlpath.
228 ep.set_local_uri(Some(&path));
229
230 // Over-write episode length
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 // Take the first file matching, disregard extension
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 }