Debian Codegraph @

podcasts-data/src/utils.rs

raw symbols SCIP
1 // utils.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 //! Helper utilities for accomplishing various tasks.
21
22 use chrono::prelude::*;
23
24 use url::{Position, Url};
25
26 use crate::dbqueries;
27 use crate::errors::DownloadError;
28 use crate::models::{EpisodeCleanerModel, Save, Show};
29 use crate::xdg_dirs::{DL_DIR, PODCASTS_CACHE};
30
31 use glob::glob;
32 use std::fs;
33 use std::path::Path;
34 use std::path::PathBuf;
35
36 /// Convert a `u64` to a `Vec<u8>`.
37 ///
38 /// This function is used to convert hash values into a format suitable for the database, i.e. `Vec<u8>`.
39 /// The resulting vector will always have exactly 8 values.
40 /// The individual bytes are extracted from the given `u64`, which is parsed as little-endian.
41 pub fn u64_to_vec_u8(u: u64) -> Vec<u8> {
42 let bytes: Vec<u8> = u.to_le_bytes().to_vec();
43 debug_assert_eq!(bytes.len(), 8);
44 bytes
45 }
46
47 /// Convert a `Vec<u8>` of bytes to a `u64`.
48 ///
49 /// These values together should represent a `u64` value in little-endian byte order.
50 ///
51 /// # Panics
52 ///
53 /// The given vector must have exactly 8 elements otherwise it will panic.
54 ///
55 pub fn vec_u8_to_u64(v: Vec<u8>) -> u64 {
56 assert_eq!(v.len(), 8);
57 u64::from_le_bytes(v[..].try_into().unwrap())
58 }
59
60 /// Hash a given value.
61 pub fn calculate_hash<T: Hash + ?Sized>(t: &T) -> u64 {
62 let mut s = DefaultHasher::new();
63 t.hash(&mut s);
64 s.finish()
65 }
66
67 /// Scan downloaded `episode` entries that might have broken `local_uri`s and
68 /// set them to `None`.
69 fn download_checker() -> Result<(), DownloadError> {
70 let episodes = dbqueries::get_downloaded_episodes()?;
71
72 episodes
73 .into_iter()
74 .filter_map(|ep| {
75 if !Path::new(ep.local_uri()?).exists() {
76 return Some(ep);
77 }
78 None
79 })
80 .for_each(update_download_status);
81
82 Ok(())
83 }
84
85 fn update_download_status(mut ep: EpisodeCleanerModel) {
86 ep.set_local_uri(None);
87 if let Err(err) = ep.save() {
88 error!("{}", err);
89 error!("Error while trying to update episode: {:#?}", ep);
90 }
91 }
92
93 /// Delete watched `episodes` that have exceeded their lifetime after played.
94 fn played_cleaner(cleanup_date: DateTime<Utc>) -> Result<(), DownloadError> {
95 let episodes = dbqueries::get_played_cleaner_episodes()?;
96
97 episodes
98 .into_iter()
99 .filter(|ep| ep.local_uri().is_some() && ep.played().is_some())
100 .for_each(|ep| clean_played(cleanup_date, ep));
101 Ok(())
102 }
103
104 fn clean_played(now_utc: DateTime<Utc>, mut ep: EpisodeCleanerModel) {
105 let limit = ep.played().unwrap();
106 if now_utc > limit.and_utc() {
107 delete_local_content(&mut ep)
108 .map(|_| info!("Episode {:?} was deleted successfully.", ep.local_uri()))
109 .map_err(|err| error!("Error: {}", err))
110 .map_err(|_| error!("Failed to delete file: {:?}", ep.local_uri()))
111 .ok();
112 }
113 }
114
115 /// Check `ep.local_uri` field and delete the file it points to.
116 pub fn delete_local_content(ep: &mut EpisodeCleanerModel) -> Result<(), DownloadError> {
117 if ep.local_uri().is_some() {
118 let uri = ep.local_uri().unwrap().to_owned();
119 if Path::new(&uri).exists() {
120 let res = fs::remove_file(&uri);
121 if res.is_ok() {
122 ep.set_local_uri(None);
123 ep.save()?;
124 } else {
125 error!("Error while trying to delete file: {}", uri);
126 error!("{}", res.unwrap_err());
127 };
128 }
129 } else {
130 error!(
131 "Something went wrong evaluating the following path: {:?}",
132 ep.local_uri(),
133 );
134 }
135 Ok(())
136 }
137
138 /// Deletes covers that were last modified before the last `cleanup_date`.
139 fn cover_cleaner(cleanup_date: DateTime<Utc>) -> Result<(), DownloadError> {
140 let root_cover_dir = PODCASTS_CACHE
141 .to_str()
142 .ok_or(DownloadError::InvalidCachedImageLocation)?;
143 if let Ok(mut paths) = glob(&format!("{}/*/[0-9]*", root_cover_dir)) {
144 while let Some(path) = paths.next().and_then(|x| x.ok()) {
145 if let Err(err) = clean_cover_file(&path, &cleanup_date) {
146 error!("Could not cleanup cover image: {}", err);
147 }
148 }
149 }
150 Ok(())
151 }
152
153 fn clean_cover_file(path: &PathBuf, cleanup_date: &DateTime<Utc>) -> Result<(), DownloadError> {
154 let metadata = std::fs::metadata(path)?;
155 let mdate: DateTime<Utc> = metadata.modified().map(DateTime::from)?;
156 if &mdate < cleanup_date {
157 if let Err(err) = std::fs::remove_file(path) {
158 error!("Failed to std::remove cover image: {}", err);
159 }
160 }
161 Ok(())
162 }
163
164 /// Database cleaning tasks.
165 ///
166 /// * `cleanup_date` is the date when the last cleanup was run.
167 ///
168 /// Runs a download checker which looks for `Episode.local_uri` entries that
169 /// doesn't exist and sets them to None
170 ///
171 /// Runs a cleaner for played Episode's that are past the lifetime limit and
172 /// scheduled for removal.
173 ///
174 /// Runs a cleaner for downloaded Episode covers that have been downloaded
175 /// before the last cleanup and will likely not be viewed again.
176 pub fn checkup(cleanup_date: DateTime<Utc>) -> Result<(), DownloadError> {
177 info!("Running database checks.");
178 download_checker()?;
179 played_cleaner(cleanup_date)?;
180 cover_cleaner(cleanup_date)?;
181 info!("Checks completed.");
182 Ok(())
183 }
184
185 /// Remove fragment identifiers and query pairs from a URL
186 /// If url parsing fails, return's a trimmed version of the original input.
187 pub fn url_cleaner(s: &str) -> String {
188 // Copied from the cookbook.
189 // https://rust-lang-nursery.github.io/rust-cookbook/net.html
190 // #remove-fragment-identifiers-and-query-pairs-from-a-url
191 match Url::parse(s) {
192 Ok(parsed) => parsed[..Position::AfterQuery].to_owned(),
193 _ => s.trim().to_owned(),
194 }
195 }
196
197 /// Returns the URI of a Show' Download directory given it's title.
198 pub fn get_download_dir(pd_title: &str) -> Result<String, DownloadError> {
199 // It might be better to make it a hash of the title or the Show id
200 let mut dir = DL_DIR.clone();
201 dir.push(pd_title);
202
203 // Create the dir
204 fs::DirBuilder::new().recursive(true).create(&dir)?;
205 let dir_str = dir.to_str().ok_or(DownloadError::InvalidCacheLocation)?;
206 Ok(dir_str.to_owned())
207 }
208
209 /// Returns the URI of a Show's cover directory given it's title.
210 pub fn get_cover_dir(pd_title: &str) -> Result<String, DownloadError> {
211 let dir = get_cover_dir_path(pd_title);
212 // Create the dir
213 fs::DirBuilder::new().recursive(true).create(&dir)?;
214 let dir_str = dir
215 .to_str()
216 .ok_or(DownloadError::InvalidCachedImageLocation)?;
217 Ok(dir_str.to_owned())
218 }
219
220 /// Returns cover dir for a show, does not create it.
221 pub fn get_cover_dir_path(pd_title: &str) -> PathBuf {
222 // It might be better to make it a hash of the title or the Show id
223 let mut dir = PODCASTS_CACHE.clone();
224 dir.push(pd_title);
225 dir
226 }
227
228 /// Removes all the entries associated with the given show from the database,
229 /// and deletes all of the downloaded content.
230 // TODO: Write Tests
231 pub fn delete_show(pd: &Show) -> Result<(), DownloadError> {
232 dbqueries::remove_feed(pd)?;
233 info!("{} was removed successfully.", pd.title());
234
235 let download_dir = get_download_dir(pd.title())?;
236 fs::remove_dir_all(&download_dir)?;
237 info!(
238 "All the episodes at, {} was removed successfully",
239 &download_dir
240 );
241
242 let cover_dir = get_cover_dir(pd.title())?;
243 fs::remove_dir_all(&cover_dir)?;
244 info!("All the Covers at, {} was removed successfully", &cover_dir);
245 Ok(())
246 }
247
248 #[cfg(test)]
249 use crate::Feed;
250 use std::collections::hash_map::DefaultHasher;
251 use std::hash::{Hash, Hasher};
252
253 #[cfg(test)]
254 /// Helper function that open a local file, parse the rss::Channel and gives back a Feed object.
255 /// Alternative Feed constructor to be used for tests.
256 pub fn get_feed(file_path: &str, id: crate::SourceId) -> Feed {
257 use crate::feed::FeedBuilder;
258 use rss::Channel;
259 use std::io::BufReader;
260
261 // open the xml file
262 let feed = fs::File::open(file_path).unwrap();
263 // parse it into a channel
264 let chan = Channel::read_from(BufReader::new(feed)).unwrap();
265 FeedBuilder::default()
266 .channel(chan)
267 .source_id(id)
268 .build()
269 .unwrap()
270 }
271
272 #[cfg(test)]
273 mod tests {
274 use super::*;
275 use anyhow::Result;
276 use chrono::Duration;
277 use std::fs::File;
278 use std::io::Write;
279 use tempfile::TempDir;
280
281 use crate::ShowId;
282 use crate::database::truncate_db;
283 use crate::models::NewEpisodeBuilder;
284
285 fn helper_db() -> Result<TempDir> {
286 // Clean the db
287 truncate_db()?;
288 // Setup tmp file stuff
289 let tmp_dir = TempDir::with_prefix("podcasts_test")?;
290 let valid_path = tmp_dir.path().join("virtual_dl.mp3");
291 let bad_path = tmp_dir.path().join("invalid_thing.mp3");
292 let mut tmp_file = File::create(&valid_path)?;
293 writeln!(tmp_file, "Foooo")?;
294
295 // Setup episodes
296 let n1 = NewEpisodeBuilder::default()
297 .title("foo_bar".to_string())
298 .show_id(ShowId(0))
299 .build()
300 .unwrap()
301 .to_episode()?;
302
303 let n2 = NewEpisodeBuilder::default()
304 .title("bar_baz".to_string())
305 .show_id(ShowId(1))
306 .build()
307 .unwrap()
308 .to_episode()?;
309
310 let mut ep1 = dbqueries::get_episode_cleaner_from_title(n1.title(), n1.show_id())?;
311 let mut ep2 = dbqueries::get_episode_cleaner_from_title(n2.title(), n2.show_id())?;
312 ep1.set_local_uri(Some(valid_path.to_str().unwrap()));
313 ep2.set_local_uri(Some(bad_path.to_str().unwrap()));
314
315 ep1.save()?;
316 ep2.save()?;
317
318 Ok(tmp_dir)
319 }
320
321 #[test]
322 fn test_download_checker() -> Result<()> {
323 let tmp_dir = helper_db()?;
324 download_checker()?;
325 let episodes = dbqueries::get_downloaded_episodes()?;
326 let valid_path = tmp_dir.path().join("virtual_dl.mp3");
327
328 assert_eq!(episodes.len(), 1);
329 assert_eq!(
330 Some(valid_path.to_str().unwrap()),
331 episodes.first().unwrap().local_uri()
332 );
333
334 let _tmp_dir = helper_db()?;
335 download_checker()?;
336 let episode = dbqueries::get_episode_cleaner_from_title("bar_baz", ShowId(1))?;
337 assert!(episode.local_uri().is_none());
338 Ok(())
339 }
340
341 #[test]
342 fn test_download_cleaner() -> Result<()> {
343 let _tmp_dir = helper_db()?;
344 let mut episode: EpisodeCleanerModel =
345 dbqueries::get_episode_cleaner_from_title("foo_bar", ShowId(0))?;
346
347 let valid_path = episode.local_uri().unwrap().to_owned();
348 delete_local_content(&mut episode)?;
349 assert!(!Path::new(&valid_path).exists());
350 Ok(())
351 }
352
353 #[test]
354 fn test_played_cleaner_expired() -> Result<()> {
355 let _tmp_dir = helper_db()?;
356 let mut episode = dbqueries::get_episode_cleaner_from_title("foo_bar", ShowId(0))?;
357 let cleanup_date = Utc::now() - Duration::seconds(1000);
358 let epoch = DateTime::<Utc>::from_timestamp(cleanup_date.timestamp() - 1, 0);
359 episode.set_played(Some(epoch.unwrap().naive_utc()));
360 episode.save()?;
361 let valid_path = episode.local_uri().unwrap().to_owned();
362
363 // This should delete the file
364 played_cleaner(cleanup_date)?;
365 assert!(!Path::new(&valid_path).exists());
366 Ok(())
367 }
368
369 #[test]
370 fn test_played_cleaner_none() -> Result<()> {
371 let _tmp_dir = helper_db()?;
372 let mut episode = dbqueries::get_episode_cleaner_from_title("foo_bar", ShowId(0))?;
373 let cleanup_date = Utc::now() - Duration::seconds(1000);
374 let epoch = DateTime::<Utc>::from_timestamp(cleanup_date.timestamp() + 1, 0);
375 episode.set_played(Some(epoch.unwrap().naive_utc()));
376 episode.save()?;
377 let valid_path = episode.local_uri().unwrap().to_owned();
378
379 // This should not delete the file
380 played_cleaner(cleanup_date)?;
381 assert!(Path::new(&valid_path).exists());
382 Ok(())
383 }
384
385 #[test]
386 fn test_url_cleaner() -> Result<()> {
387 let good_url = "http://traffic.megaphone.fm/FL8608731318.mp3?updated=1484685184";
388 let bad_url = "http://traffic.megaphone.fm/FL8608731318.mp3?updated=1484685184#foobar";
389
390 assert_eq!(url_cleaner(bad_url), good_url);
391 assert_eq!(url_cleaner(good_url), good_url);
392 assert_eq!(url_cleaner(&format!(" {}\t\n", bad_url)), good_url);
393 Ok(())
394 }
395
396 #[test]
397 // This test needs access to local system so we ignore it by default.
398 #[ignore]
399 fn test_get_dl_dir() -> Result<()> {
400 let foo_ = format!("{}/{}", DL_DIR.to_str().unwrap(), "foo");
401 assert_eq!(get_download_dir("foo")?, foo_);
402 let _ = fs::remove_dir_all(foo_);
403 Ok(())
404 }
405
406 #[test]
407 fn hash_should_be_the_same_given_the_same_input() -> Result<()> {
408 let image_uri =
409 "http://www.jupiterbroadcasting.com/wp-content/uploads/2018/01/lup-0232-v.jpg";
410 let first_hash = calculate_hash(&image_uri);
411 let second_hash = calculate_hash(&image_uri);
412 assert_eq!(first_hash, second_hash);
413 Ok(())
414 }
415
416 #[test]
417 fn hash_should_be_different_for_different_inputs() -> Result<()> {
418 let old_image_uri =
419 "http://www.jupiterbroadcasting.com/wp-content/uploads/2018/01/lup-0232-v.jpg";
420 let new_image_uri = "https://assets.fireside.fm/file/fireside-images/podcasts/images/f/f31a453c-fa15-491f-8618-3f71f1d565e5/cover.jpg?v=3";
421 let old_hash = calculate_hash(&old_image_uri);
422 let new_hash = calculate_hash(&new_image_uri);
423 assert_ne!(old_hash, new_hash);
424 Ok(())
425 }
426
427 #[test]
428 fn hash_should_be_different_for_similar_inputs() -> Result<()> {
429 let image_uri_v2 = "https://assets.fireside.fm/file/fireside-images/podcasts/images/f/f31a453c-fa15-491f-8618-3f71f1d565e5/cover.jpg?v=2";
430 let image_uri_v3 = "https://assets.fireside.fm/file/fireside-images/podcasts/images/f/f31a453c-fa15-491f-8618-3f71f1d565e5/cover.jpg?v=3";
431 let v2_hash = calculate_hash(&image_uri_v2);
432 let v3_hash = calculate_hash(&image_uri_v3);
433 assert_ne!(v2_hash, v3_hash);
434 Ok(())
435 }
436
437 #[test]
438 fn u64_to_vec_u8_should_convert() -> Result<()> {
439 assert_eq!(
440 u64_to_vec_u8(16358564451669550783),
441 vec![191, 166, 24, 137, 178, 75, 5, 227]
442 );
443 Ok(())
444 }
445
446 #[test]
447 fn u64_to_vec_u8_should_produce_a_vector_of_exactly_8_elements() -> Result<()> {
448 assert_eq!(u64_to_vec_u8(u64::MAX).len(), 8);
449 Ok(())
450 }
451
452 #[test]
453 fn vec_u8_to_u64_should_convert() -> Result<()> {
454 assert_eq!(
455 vec_u8_to_u64(vec![0, 1, 2, 3, 4, 5, 6, 7]),
456 506097522914230528
457 );
458 Ok(())
459 }
460
461 #[test]
462 #[should_panic(expected = "8")]
463 fn vec_u8_to_u64_should_panic_given_an_empty_vector() {
464 vec_u8_to_u64(vec![]);
465 }
466
467 #[test]
468 #[should_panic(expected = "8")]
469 fn vec_u8_to_u64_should_panic_given_a_vector_with_1_element() {
470 vec_u8_to_u64(vec![1]);
471 }
472
473 #[test]
474 #[should_panic(expected = "8")]
475 fn vec_u8_to_u64_should_panic_given_a_vector_with_7_elements() {
476 vec_u8_to_u64(vec![10; 7]);
477 }
478
479 #[test]
480 #[should_panic(expected = "8")]
481 fn vec_u8_to_u64_should_panic_given_a_vector_with_9_elements() {
482 vec_u8_to_u64(vec![12; 9]);
483 }
484
485 #[test]
486 fn vec_u8_to_u64_should_be_the_inverse_of_u64_to_vec_u8() -> Result<()> {
487 assert_eq!(10, vec_u8_to_u64(u64_to_vec_u8(10)));
488 Ok(())
489 }
490 }