Skip to content

Commit

Permalink
Merge pull request #134 from SamTV12345/114-custom-folderfile-naming
Browse files Browse the repository at this point in the history
114 custom folderfile naming
  • Loading branch information
SamTV12345 authored May 20, 2023
2 parents 03c6abe + f43d6aa commit c83372b
Show file tree
Hide file tree
Showing 32 changed files with 676 additions and 113 deletions.
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ serde_json = "1.0.93"
dotenv = "0.15.0"
sha1 = "0.10.5"
sha256 = "1.1.3"
deunicode = "1.3.3"
strfmt="0.2.4"


[target.'cfg(not(windows))'.dependencies]
Expand Down
6 changes: 6 additions & 0 deletions migrations/2023-05-14-184857_podcast-name-adjustment/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- This file should undo anything in `up.sql`
ALTER TABLE settings DROP COLUMN replace_invalid_characters;
ALTER TABLE settings DROP COLUMN use_existing_filename;
ALTER TABLE settings DROP COLUMN replacement_strategy;
ALTER TABLE settings DROP COLUMN episode_format;
ALTER TABLE settings DROP COLUMN podcast_format;
8 changes: 8 additions & 0 deletions migrations/2023-05-14-184857_podcast-name-adjustment/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- Your SQL goes here
ALTER TABLE settings ADD COLUMN replace_invalid_characters BOOLEAN DEFAULT TRUE NOT NULL;
ALTER TABLE settings ADD COLUMN use_existing_filename BOOLEAN DEFAULT FALSE NOT NULL;
ALTER TABLE settings ADD COLUMN replacement_strategy TEXT CHECK(replacement_strategy IN
('replace-with-dash-and-underscore', 'remove', 'replace-with-dash')) NOT NULL DEFAULT
'replace-with-dash-and-underscore';
ALTER TABLE settings ADD COLUMN episode_format TEXT NOT NULL DEFAULT '{}';
ALTER TABLE settings ADD COLUMN podcast_format TEXT NOT NULL DEFAULT '{}';
24 changes: 20 additions & 4 deletions src/constants/constants.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::fmt;
use std::fmt::Formatter;
use std::str::FromStr;
use crate::models::settings::Setting;

pub static ITUNES_URL: &str = "https://itunes.apple.com/search?term=";

Expand All @@ -15,15 +14,25 @@ pub enum PodcastType {
OpmlErrored
}

pub const DEFAULT_SETTINGS: Setting = Setting {
pub const DEFAULT_SETTINGS: PartialSettings = PartialSettings {
id: 1,
auto_download: true,
auto_update: true,
auto_cleanup: true,
auto_cleanup_days: 30,
podcast_prefill: 5,
podcast_prefill: 5
};


pub struct PartialSettings {
pub id: i32,
pub auto_download: bool,
pub auto_update: bool,
pub auto_cleanup: bool,
pub auto_cleanup_days: i32,
pub podcast_prefill: i32,
}

pub const ERROR_LOGIN_MESSAGE: &str = "User either not found or password is incorrect";

pub const TELEGRAM_BOT_TOKEN: &str = "TELEGRAM_BOT_TOKEN";
Expand Down Expand Up @@ -81,4 +90,11 @@ pub const USERNAME:&str = "USERNAME";
pub const PASSWORD:&str = "PASSWORD";


pub const STANDARD_USER: &str = "user123";
pub const STANDARD_USER: &str = "user123";


pub const ERR_SETTINGS_FORMAT: &str = "A podcast/episode format needs to contain an opening and \
closing bracket ({}).";

pub const PODCAST_FILENAME: &str = "podcast";
pub const PODCAST_IMAGENAME:&str = "image";
58 changes: 58 additions & 0 deletions src/controllers/settings_controller.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::str::FromStr;
use crate::models::settings::Setting;
use crate::service::podcast_episode_service::PodcastEpisodeService;
use actix_web::web::{Data, Path};
Expand Down Expand Up @@ -152,4 +153,61 @@ fn add_podcasts(podcasts_found: Vec<Podcast>, env_service: MutexGuard<Environmen
body.add_child(outline).expect("TODO: panic message");
}
body
}


#[put("/settings/name")]
pub async fn update_name(db: Data<Mutex<SettingsService>>,
update_information: web::Json<UpdateNameSettings>, requester: Option<web::ReqData<User>>)
-> impl Responder {
if !requester.unwrap().is_admin() {
return HttpResponse::Unauthorized().finish();
}

let mut db = db.lock().ignore_poison();

let settings = db.update_name(update_information.into_inner());
HttpResponse::Ok().json(settings)
}

#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UpdateNameSettings{
pub use_existing_filenames: bool,
pub replace_invalid_characters: bool,
pub replacement_strategy: ReplacementStrategy,
pub episode_format: String,
pub podcast_format: String
}

#[derive(Deserialize, Clone)]
#[serde(rename_all="kebab-case")]
pub enum ReplacementStrategy{
ReplaceWithDashAndUnderscore,
Remove,
ReplaceWithDash
}

impl ToString for ReplacementStrategy{
fn to_string(&self) -> String {
match self {
ReplacementStrategy::ReplaceWithDashAndUnderscore => "replace-with-dash-and-underscore"
.to_string(),
ReplacementStrategy::Remove => "remove".to_string(),
ReplacementStrategy::ReplaceWithDash => "replace-with-dash".to_string()
}
}
}

impl FromStr for ReplacementStrategy{
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"replace-with-dash-and-underscore" => Ok(ReplacementStrategy::ReplaceWithDashAndUnderscore),
"remove" => Ok(ReplacementStrategy::Remove),
"replace-with-dash" => Ok(ReplacementStrategy::ReplaceWithDash),
_ => Err(())
}
}
}
1 change: 0 additions & 1 deletion src/controllers/watch_time_controller.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::cmp::Ordering;
use crate::db::DB;
use crate::models::models::{PodcastWatchedEpisodeModelWithPodcastEpisode, PodcastWatchedPostModel};
use actix_web::web::Data;
Expand Down
8 changes: 7 additions & 1 deletion src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,13 @@ impl DB {
use crate::schema::settings::dsl::*;

do_retry(||{insert_into(settings)
.values(DEFAULT_SETTINGS)
.values((
id.eq(1),
auto_download.eq(DEFAULT_SETTINGS.auto_download),
auto_cleanup.eq(DEFAULT_SETTINGS.auto_cleanup),
auto_cleanup_days.eq(DEFAULT_SETTINGS.auto_cleanup_days),
podcast_prefill.eq(DEFAULT_SETTINGS.podcast_prefill))
)
.execute(&mut self.conn)})
.expect("Error setting default values");
}
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use crate::controllers::podcast_controller::{
import_podcasts_from_opml, query_for_podcast, update_active_podcast,
};
use crate::controllers::podcast_episode_controller::{download_podcast_episodes_of_podcast, find_all_podcast_episodes_of_podcast, get_timeline};
use crate::controllers::settings_controller::{get_opml, get_settings, run_cleanup, update_settings};
use crate::controllers::settings_controller::{get_opml, get_settings, run_cleanup, update_name, update_settings};
use crate::controllers::sys_info_controller::{get_info, get_public_config, get_sys_info, login};
use crate::controllers::watch_time_controller::{get_last_watched, get_watchtime, log_watchtime};
use crate::controllers::websocket_controller::{
Expand Down Expand Up @@ -270,6 +270,7 @@ fn get_private_api() -> Scope<impl ServiceFactory<ServiceRequest, Config = (), R
let middleware = AuthFilter::new();
web::scope("")
.wrap(middleware)
.service(update_name)
.service(get_filter)
.service(search_podcasts)
.service(add_podcast_by_feed)
Expand Down
91 changes: 91 additions & 0 deletions src/models/file_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@



use crate::models::itunes_models::{Podcast, PodcastEpisode};
use crate::service::file_service::{prepare_podcast_episode_title_to_directory};
use crate::service::path_service::PathService;

#[derive(Default, Clone, Debug)]
pub struct FilenameBuilder {
episode: String,
raw_episode: PodcastEpisode,
directory: String,
suffix: String,
image_suffix: String,
image_filename: String,
filename: String,
raw_filename: bool,
podcast: Podcast
}

impl FilenameBuilder {

pub fn with_podcast_directory(mut self, directory: &str) -> FilenameBuilder {
self.directory = directory.to_string();
self
}

pub fn with_episode(mut self, podcast_episode: PodcastEpisode) -> FilenameBuilder {
self.episode = prepare_podcast_episode_title_to_directory(podcast_episode.clone());
self.raw_episode = podcast_episode;
self
}

pub fn with_filename(mut self, filename: &str) -> FilenameBuilder {
self.filename = filename.to_string();
self
}

pub fn with_image_filename(mut self, image_filename: &str) -> FilenameBuilder {
self.image_filename = image_filename.to_string();
self
}

pub fn with_suffix(mut self, suffix: &str) -> FilenameBuilder {
self.suffix = suffix.to_string();
self
}

pub fn with_image_suffix(mut self, image_suffix: &str) -> FilenameBuilder {
self.image_suffix = image_suffix.to_string();
self
}

pub fn with_raw_directory(mut self) -> FilenameBuilder {
self.directory = PathService::get_image_path(
&self.podcast.clone().directory_name,
Some(self.raw_episode.clone()),
&self.suffix,
&self.raw_episode.name
);
self.raw_filename = true;
self
}

pub fn with_podcast(mut self, podcast: Podcast) -> FilenameBuilder {
self.podcast = podcast;
self
}

pub fn build(self)->(String, String){
if self.raw_filename{
let resulting_directory = self.clone().create_podcast_episode_dir(self.directory.clone
());
return (format!("{}/{}.{}", resulting_directory,self.filename.clone(), self.suffix
.clone()),format!("{}/{}.{}", resulting_directory,self.image_filename.clone(), self.image_suffix
.clone()));
}
let resulting_directory = self.clone().create_podcast_episode_dir(format!("{}/{}",self
.directory.clone(), self.episode.clone()));

return (format!("{}/{}.{}", resulting_directory,self.filename.clone(), self.suffix.clone
()),format!("{}/{}.{}", resulting_directory,self.image_filename.clone(), self.image_suffix
.clone()));
}


fn create_podcast_episode_dir(self,dirname:String)->String{
PathService::check_if_podcast_episode_directory_available
(&dirname, self.podcast)
}
}
4 changes: 2 additions & 2 deletions src/models/itunes_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct ResponseModel {
}

#[derive(Queryable, Identifiable,QueryableByName, Selectable, Debug, PartialEq, Clone, ToSchema,
Serialize, Deserialize,)]
Serialize, Deserialize,Default)]
pub struct Podcast {
#[diesel(sql_type = Integer)]
pub(crate) id: i32,
Expand Down Expand Up @@ -116,7 +116,7 @@ pub struct PodcastDto {


#[derive(Queryable, Identifiable,QueryableByName, Selectable, Debug, PartialEq, Clone, ToSchema,
Serialize, Deserialize)]
Serialize, Deserialize, Default)]
pub struct PodcastEpisode {
#[diesel(sql_type = Integer)]
pub(crate) id: i32,
Expand Down
1 change: 1 addition & 0 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ pub mod episode;
pub mod podcast_rssadd_model;
pub mod order_criteria;
pub mod filter;
pub mod file_path;
7 changes: 6 additions & 1 deletion src/models/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ pub struct Setting {
pub auto_update: bool,
pub auto_cleanup: bool,
pub auto_cleanup_days: i32,
pub podcast_prefill: i32
pub podcast_prefill: i32,
pub replace_invalid_characters: bool,
pub use_existing_filename: bool,
pub replacement_strategy: String,
pub episode_format: String,
pub podcast_format: String
}

#[derive(Serialize, Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use diesel::prelude::{Insertable, Queryable};
use diesel::{OptionalExtension, RunQueryDsl, SqliteConnection, AsChangeset};
use diesel::associations::HasTable;
use utoipa::ToSchema;
use crate::schema::users;
use diesel::QueryDsl;
use diesel::ExpressionMethods;
use dotenv::var;
use crate::constants::constants::{BASIC_AUTH, OIDC_AUTH, Role, STANDARD_USER, USERNAME};
use crate::schema::users;

#[derive(Serialize, Deserialize, Queryable, Insertable, Clone, ToSchema, PartialEq, Debug, AsChangeset)]
#[serde(rename_all = "camelCase")]
Expand Down
5 changes: 5 additions & 0 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ diesel::table! {
auto_cleanup -> Bool,
auto_cleanup_days -> Integer,
podcast_prefill -> Integer,
replace_invalid_characters -> Bool,
use_existing_filename -> Bool,
replacement_strategy -> Text,
episode_format -> Text,
podcast_format -> Text,
}
}

Expand Down
Loading

0 comments on commit c83372b

Please sign in to comment.