hammond-data::utils: Modified EpisodeCleaner Diesel model to also be used with played_cleaner.

This commit is contained in:
Jordan Petridis 2017-12-20 19:18:20 +02:00
parent 3c24b9f9d9
commit db59bed69d
No known key found for this signature in database
GPG Key ID: CEABAD9F5683B9A6
4 changed files with 52 additions and 27 deletions

View File

@ -2,7 +2,7 @@
use diesel::prelude::*; use diesel::prelude::*;
use diesel; use diesel;
use models::queryables::{Episode, EpisodeDownloadCleanerQuery, EpisodeWidgetQuery, Podcast, use models::queryables::{Episode, EpisodeCleanerQuery, EpisodeWidgetQuery, Podcast,
PodcastCoverQuery, Source}; PodcastCoverQuery, Source};
use chrono::prelude::*; use chrono::prelude::*;
use errors::*; use errors::*;
@ -33,15 +33,15 @@ pub fn get_episodes() -> Result<Vec<Episode>> {
Ok(episode.order(epoch.desc()).load::<Episode>(&*con)?) Ok(episode.order(epoch.desc()).load::<Episode>(&*con)?)
} }
pub(crate) fn get_downloaded_episodes() -> Result<Vec<EpisodeDownloadCleanerQuery>> { pub(crate) fn get_downloaded_episodes() -> Result<Vec<EpisodeCleanerQuery>> {
use schema::episode::dsl::*; use schema::episode::dsl::*;
let db = connection(); let db = connection();
let con = db.get()?; let con = db.get()?;
Ok(episode Ok(episode
.select((rowid, local_uri)) .select((rowid, local_uri, played))
.filter(local_uri.is_not_null()) .filter(local_uri.is_not_null())
.load::<EpisodeDownloadCleanerQuery>(&*con)?) .load::<EpisodeCleanerQuery>(&*con)?)
} }
pub fn get_played_episodes() -> Result<Vec<Episode>> { pub fn get_played_episodes() -> Result<Vec<Episode>> {
@ -52,6 +52,17 @@ pub fn get_played_episodes() -> Result<Vec<Episode>> {
Ok(episode.filter(played.is_not_null()).load::<Episode>(&*con)?) Ok(episode.filter(played.is_not_null()).load::<Episode>(&*con)?)
} }
pub fn get_played_cleaner_episodes() -> Result<Vec<EpisodeCleanerQuery>> {
use schema::episode::dsl::*;
let db = connection();
let con = db.get()?;
Ok(episode
.select((rowid, local_uri, played))
.filter(played.is_not_null())
.load::<EpisodeCleanerQuery>(&*con)?)
}
pub fn get_episode_from_rowid(ep_id: i32) -> Result<Episode> { pub fn get_episode_from_rowid(ep_id: i32) -> Result<Episode> {
use schema::episode::dsl::*; use schema::episode::dsl::*;

View File

@ -325,24 +325,26 @@ impl EpisodeWidgetQuery {
#[changeset_options(treat_none_as_null = "true")] #[changeset_options(treat_none_as_null = "true")]
#[primary_key(title, podcast_id)] #[primary_key(title, podcast_id)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
/// Diesel Model to be used for constructing `EpisodeWidgets`. /// Diesel Model to be used internal with the `utils::checkup` function.
pub(crate) struct EpisodeDownloadCleanerQuery { pub struct EpisodeCleanerQuery {
rowid: i32, rowid: i32,
local_uri: Option<String>, local_uri: Option<String>,
played: Option<i32>,
} }
impl From<Episode> for EpisodeDownloadCleanerQuery { impl From<Episode> for EpisodeCleanerQuery {
fn from(e: Episode) -> EpisodeDownloadCleanerQuery { fn from(e: Episode) -> EpisodeCleanerQuery {
EpisodeDownloadCleanerQuery { EpisodeCleanerQuery {
rowid: e.rowid(), rowid: e.rowid(),
local_uri: e.local_uri, local_uri: e.local_uri,
played: e.played,
} }
} }
} }
impl EpisodeDownloadCleanerQuery { impl EpisodeCleanerQuery {
/// Get the value of the sqlite's `ROW_ID` /// Get the value of the sqlite's `ROW_ID`
pub(crate) fn rowid(&self) -> i32 { pub fn rowid(&self) -> i32 {
self.rowid self.rowid
} }
@ -350,17 +352,29 @@ impl EpisodeDownloadCleanerQuery {
/// ///
/// Represents the local uri,usually filesystem path, /// Represents the local uri,usually filesystem path,
/// that the media file will be located at. /// that the media file will be located at.
pub(crate) fn local_uri(&self) -> Option<&str> { pub fn local_uri(&self) -> Option<&str> {
self.local_uri.as_ref().map(|s| s.as_str()) self.local_uri.as_ref().map(|s| s.as_str())
} }
/// Set the `local_uri`. /// Set the `local_uri`.
pub(crate) fn set_local_uri(&mut self, value: Option<&str>) { pub fn set_local_uri(&mut self, value: Option<&str>) {
self.local_uri = value.map(|x| x.to_string()); self.local_uri = value.map(|x| x.to_string());
} }
/// Epoch representation of the last time the episode was played.
///
/// None/Null for unplayed.
pub fn played(&self) -> Option<i32> {
self.played
}
/// Set the `played` value.
pub fn set_played(&mut self, value: Option<i32>) {
self.played = value;
}
/// Helper method to easily save/"sync" current state of self to the Database. /// Helper method to easily save/"sync" current state of self to the Database.
pub(crate) fn save(&self) -> Result<usize> { pub fn save(&self) -> Result<usize> {
use schema::episode::dsl::*; use schema::episode::dsl::*;
let db = connection(); let db = connection();

View File

@ -8,14 +8,12 @@ use itertools::Itertools;
use errors::*; use errors::*;
use dbqueries; use dbqueries;
use models::queryables::{Episode, EpisodeDownloadCleanerQuery}; use models::queryables::EpisodeCleanerQuery;
use std::path::Path; use std::path::Path;
use std::fs; use std::fs;
fn download_checker() -> Result<()> { fn download_checker() -> Result<()> {
// TODO: give it it's own diesel model,
// so it does not pull useless and expensive stuff like description.
let episodes = dbqueries::get_downloaded_episodes()?; let episodes = dbqueries::get_downloaded_episodes()?;
episodes episodes
@ -25,7 +23,7 @@ fn download_checker() -> Result<()> {
Ok(()) Ok(())
} }
fn checker_helper(ep: &mut EpisodeDownloadCleanerQuery) { fn checker_helper(ep: &mut EpisodeCleanerQuery) {
if !Path::new(ep.local_uri().unwrap()).exists() { if !Path::new(ep.local_uri().unwrap()).exists() {
ep.set_local_uri(None); ep.set_local_uri(None);
let res = ep.save(); let res = ep.save();
@ -37,9 +35,7 @@ fn checker_helper(ep: &mut EpisodeDownloadCleanerQuery) {
} }
fn played_cleaner() -> Result<()> { fn played_cleaner() -> Result<()> {
// TODO: give it it's own diesel model, let episodes = dbqueries::get_played_cleaner_episodes()?;
// so it does not pull useless and expensive stuff like description.
let episodes = dbqueries::get_played_episodes()?;
let now_utc = Utc::now().timestamp() as i32; let now_utc = Utc::now().timestamp() as i32;
episodes.into_par_iter().for_each(|mut ep| { episodes.into_par_iter().for_each(|mut ep| {
@ -54,7 +50,7 @@ fn played_cleaner() -> Result<()> {
error!("Error while trying to delete file: {:?}", ep.local_uri()); error!("Error while trying to delete file: {:?}", ep.local_uri());
error!("Error: {}", err); error!("Error: {}", err);
} else { } else {
info!("Episode {:?} was deleted succesfully.", ep.title()); info!("Episode {:?} was deleted succesfully.", ep.local_uri());
}; };
} }
} }
@ -63,7 +59,7 @@ fn played_cleaner() -> Result<()> {
} }
/// Check `ep.local_uri` field and delete the file it points to. /// Check `ep.local_uri` field and delete the file it points to.
pub fn delete_local_content(ep: &mut Episode) -> Result<()> { pub fn delete_local_content(ep: &mut EpisodeCleanerQuery) -> Result<()> {
if ep.local_uri().is_some() { if ep.local_uri().is_some() {
let uri = ep.local_uri().unwrap().to_owned(); let uri = ep.local_uri().unwrap().to_owned();
if Path::new(&uri).exists() { if Path::new(&uri).exists() {
@ -110,7 +106,7 @@ pub fn url_cleaner(s: &str) -> String {
} }
} }
/// Helper functions that strips extra spaces and newlines and all the tabs. /// Helper functions that strips extra spaces and newlines and ignores the tabs.
#[allow(match_same_arms)] #[allow(match_same_arms)]
pub fn replace_extra_spaces(s: &str) -> String { pub fn replace_extra_spaces(s: &str) -> String {
s.trim() s.trim()
@ -210,10 +206,12 @@ mod tests {
#[test] #[test]
fn test_download_cleaner() { fn test_download_cleaner() {
let _tmp_dir = helper_db(); let _tmp_dir = helper_db();
let mut episode = { let mut episode: EpisodeCleanerQuery = {
let db = connection(); let db = connection();
let con = db.get().unwrap(); let con = db.get().unwrap();
dbqueries::get_episode_from_pk(&con, "foo_bar", 0).unwrap() dbqueries::get_episode_from_pk(&con, "foo_bar", 0)
.unwrap()
.into()
}; };
let valid_path = episode.local_uri().unwrap().to_owned(); let valid_path = episode.local_uri().unwrap().to_owned();

View File

@ -232,7 +232,9 @@ fn on_play_bttn_clicked(episode_id: i32) {
} }
fn on_delete_bttn_clicked(episode_id: i32) { fn on_delete_bttn_clicked(episode_id: i32) {
let mut ep = dbqueries::get_episode_from_rowid(episode_id).unwrap(); let mut ep = dbqueries::get_episode_from_rowid(episode_id)
.unwrap()
.into();
let e = delete_local_content(&mut ep); let e = delete_local_content(&mut ep);
if let Err(err) = e { if let Err(err) = e {