Skip to content

Commit

Permalink
chore: rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
CPU-Blanc committed Nov 24, 2024
1 parent c21c2c7 commit 8bc878c
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 133 deletions.
25 changes: 15 additions & 10 deletions client/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,29 @@ pub(super) struct Args {
pub(super) log_level: Level,

/// Sonarr port
#[arg(short, long, env="SCRUBARR_SONARR_PORT", default_value_t = 8989)]
pub(super) port:u16,
#[arg(short, long, env = "SCRUBARR_SONARR_PORT", default_value_t = 8989)]
pub(super) port: u16,

/// Whether to omit the port from the url
#[arg(long, env="SCRUBARR_OMIT_PORT", default_value_t = false)]
#[arg(long, env = "SCRUBARR_OMIT_PORT", default_value_t = false)]
pub(super) omit_port: bool,

/// Sonarr URL
#[arg(short, long, env="SCRUBARR_SONARR_URL", default_value = "http://localhost")]
#[arg(
short,
long,
env = "SCRUBARR_SONARR_URL",
default_value = "http://localhost"
)]
pub(super) url: Url,

/// Sonarr URL base
#[arg(short, long, env="SCRUBARR_SONARR_BASE_PATH")]
#[arg(short, long, env = "SCRUBARR_SONARR_BASE_PATH")]
pub(super) base_path: Option<String>,

/// Queue scan interval (in seconds)
#[arg(short, long, env="SCRUBARR_INTERVAL", default_value_t = 600)]
pub(super) interval: u64
#[arg(short, long, env = "SCRUBARR_INTERVAL", default_value_t = 600)]
pub(super) interval: u64,
}

#[derive(ValueEnum, Clone, Debug)]
Expand All @@ -41,7 +46,7 @@ pub(super) enum Level {
Debug,
Info,
Warn,
Error
Error,
}

impl From<Level> for LevelFilter {
Expand All @@ -51,7 +56,7 @@ impl From<Level> for LevelFilter {
Level::Debug => LevelFilter::Debug,
Level::Info => LevelFilter::Info,
Level::Warn => LevelFilter::Warn,
Level::Error => LevelFilter::Error
Level::Error => LevelFilter::Error,
}
}
}
Expand All @@ -61,4 +66,4 @@ impl Args {
dotenv().ok();
Self::parse()
}
}
}
71 changes: 39 additions & 32 deletions client/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
mod config;

use std::{env, time::{Duration, Instant}};
use std::collections::HashSet;
use tokio::time::sleep;
use sonarr_api::{
queue::{
QueueResource,
QueueStatus,
GetQueueQuery,
DeleteQueueQuery
},
Sonarr
queue::{DeleteQueueQuery, GetQueueQuery, QueueResource, QueueStatus},
Sonarr,
};
use std::collections::HashSet;
use std::{
env,
time::{Duration, Instant},
};
use tokio::time::sleep;

use log::{LevelFilter, info, debug, trace, error};
use log::{debug, error, info, trace, LevelFilter};
use log4rs::{
append::{console::ConsoleAppender},
encode::pattern::PatternEncoder,
append::console::ConsoleAppender,
config::{Appender, Config, Root},
filter::threshold::ThresholdFilter
encode::pattern::PatternEncoder,
filter::threshold::ThresholdFilter,
};

#[tokio::main]
async fn main() {
let args = config::Args::from_args_and_env();

let encoder = PatternEncoder::new("{h({d(%Y-%m-%d %H:%M:%S)} | {({l}):5.5} | {D({f}:{L} - )}{m}{n})}");
let stdout = ConsoleAppender::builder().encoder(Box::new(encoder)).build();
let stdout = ConsoleAppender::builder()
.encoder(Box::new(encoder))
.build();
let config = Config::builder()
.appender(
Appender::builder()
.filter(Box::new(ThresholdFilter::new(LevelFilter::Trace)))
.build("stdout", Box::new(stdout))
.build("stdout", Box::new(stdout)),
)
.build(
Root::builder()
.appender("stdout")
.build(LevelFilter::from(args.log_level)),
)
.build(Root::builder().appender("stdout").build(LevelFilter::from(args.log_level)))
.expect("error building logger");
let _ = log4rs::init_config(config).expect("error building logger");

Expand All @@ -51,8 +55,9 @@ async fn main() {
&args.api_key,
args.url.as_ref(),
args.base_path.as_deref(),
port
).expect("error creating Sonarr client");
port,
)
.expect("error creating Sonarr client");

let config_interval = Duration::from_secs(args.interval);

Expand All @@ -65,7 +70,7 @@ async fn main() {

trace!("tbas - {:?} - replaced - {:?}", tbas, replaced);

let (mut success, mut failed): (i32,i32) = (0,0);
let (mut success, mut failed): (i32, i32) = (0, 0);

for id in tbas.into_iter().flatten() {
if let Err(e) = sonarr.refresh_series(&id).await {
Expand All @@ -74,8 +79,8 @@ async fn main() {
} else {
success += 1;
}
};
}

if success.is_positive() || failed.is_positive() {
info!("refreshed {success} series ({failed} failed)");
};
Expand All @@ -101,17 +106,15 @@ async fn get_queue(client: &Sonarr) -> Box<[QueueResource]> {
.status(QueueStatus::Warning);

match client.get_queue(query).await {
Err(e) => {
Err(e) => {
error!("error fetching sonarr queue - {e}");
Box::new([])
},
Ok(resource) => {
resource.records
}
Ok(resource) => resource.records,
}
}

async fn process_queue(client: &Sonarr) -> (HashSet<Option<i32>>, Vec<i32>){
async fn process_queue(client: &Sonarr) -> (HashSet<Option<i32>>, Vec<i32>) {
let mut tbas = HashSet::new();
let mut replaced = Vec::new();

Expand All @@ -120,17 +123,21 @@ async fn process_queue(client: &Sonarr) -> (HashSet<Option<i32>>, Vec<i32>){
for message in statuses.messages {
if message.contains("Episode has a TBA title and recently aired") {
if tbas.insert(item.series_id) {
debug!("found TBA in series [{id}] '{name}'", id = item.series_id.unwrap_or(0), name = item.series.unwrap().title.unwrap_or(Box::from("")));
debug!(
"found TBA in series [{id}] '{name}'",
id = item.series_id.unwrap_or(0),
name = item.series.unwrap().title.unwrap_or(Box::from(""))
);
};
continue 'item;
}
if message.contains("Not a Custom Format upgrade for existing episode file(s)") {
replaced.push(item.id);
continue 'item;
};
};
};
};
}
}
}

(tbas, replaced)
}
}
13 changes: 8 additions & 5 deletions sonarr_api/src/endpoints/command.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::time::Duration;
use crate::{error::SonarrResult, Sonarr};
use serde::Serialize;
use crate::{Sonarr, error::SonarrResult};
use std::time::Duration;

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct RefreshSeriesPayload {
name: String,
series_id: i32
series_id: i32,
}

impl Sonarr {
Expand All @@ -15,10 +15,13 @@ impl Sonarr {

self.client
.post(url)
.json(&RefreshSeriesPayload { name: String::from("RefreshSeries"), series_id: *series_id })
.json(&RefreshSeriesPayload {
name: String::from("RefreshSeries"),
series_id: *series_id,
})
.timeout(Duration::from_secs(10))
.send()
.await?;
Ok(())
}
}
}
42 changes: 22 additions & 20 deletions sonarr_api/src/endpoints/queue.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,48 @@
use std::collections::HashMap;
use crate::{
build_query_string,
error::SonarrResult,
queue::DeleteQueueQuery,
schema::queue::{GetQueueQuery, QueueResourcePagingResource},
Sonarr,
schema::queue::{QueueResourcePagingResource, GetQueueQuery}
};
use std::collections::HashMap;

impl Sonarr {
pub async fn get_queue(&self, query: GetQueueQuery) -> SonarrResult<QueueResourcePagingResource> {
pub async fn get_queue(
&self,
query: GetQueueQuery,
) -> SonarrResult<QueueResourcePagingResource> {
let mut url = self.build_url("/api/v3/queue")?;
url.set_query(build_query_string(query).as_deref());

Ok(
self.client
.get(url)
.send()
.await?
.error_for_status()?
.json::<QueueResourcePagingResource>()
.await?
)
Ok(self
.client
.get(url)
.send()
.await?
.error_for_status()?
.json::<QueueResourcePagingResource>()
.await?)
}
pub async fn queue_delete_item(&self, id: i32, query: DeleteQueueQuery) -> SonarrResult<()> {
let mut url = self.build_url(&format!("/api/v3/queue/{id}"))?;
url.set_query(build_query_string(query).as_deref());

self.client
.delete(url)
.send()
.await?
.error_for_status()?;
self.client.delete(url).send().await?.error_for_status()?;

Ok(())
}
pub async fn queue_delete_bulk(&self, ids: &[i32], query: DeleteQueueQuery) -> SonarrResult<()> {
pub async fn queue_delete_bulk(
&self,
ids: &[i32],
query: DeleteQueueQuery,
) -> SonarrResult<()> {
let mut url = self.build_url("/api/v3/queue/bulk")?;
url.set_query(build_query_string(query).as_deref());

let mut json = HashMap::with_capacity(1);
json.insert("ids", ids);

self.client
.delete(url)
.json(&json)
Expand All @@ -50,4 +52,4 @@ impl Sonarr {

Ok(())
}
}
}
4 changes: 2 additions & 2 deletions sonarr_api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ pub enum SonarrError {
#[error("url parsing failed: {0}")]
ParseError(#[from] url::ParseError),
#[error("invalid header value: {0}")]
InvalidHeader(#[from] reqwest::header::InvalidHeaderValue)
}
InvalidHeader(#[from] reqwest::header::InvalidHeaderValue),
}
Loading

0 comments on commit 8bc878c

Please sign in to comment.