Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display progress in a better way #17

Merged
merged 2 commits into from
Mar 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 76 additions & 30 deletions src/actions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Debug;

use indicatif::{ProgressBar, ProgressStyle};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use reqwest::{Client, Url};
use serde::de::DeserializeOwned;

Expand All @@ -24,11 +24,6 @@ pub struct Action {
impl Action {
pub fn new(client: Client, base_url: Url) -> Self {
let pb = ProgressBar::new(0);
pb.set_style(
ProgressStyle::with_template("[{bar:60.cyan/blue}] {pos:>7}/{len:7}\n{msg}")
.unwrap()
.progress_chars("##-"),
);
Self {
client,
base_url,
Expand All @@ -39,25 +34,35 @@ impl Action {
}
}

async fn get_all<T>(&self, mut url: Url, limit_records: bool) -> Result<PaginatedResponse<T>, Box<dyn std::error::Error>>
async fn get_all<T>(
&self,
mut url: Url,
limit_records: bool,
) -> Result<PaginatedResponse<T>, Box<dyn std::error::Error>>
where
T: DeserializeOwned,
T: Debug,
{
if limit_records {
let length: i32 = match self.limit {
Some(val) => val as i32,
None => -1
None => -1,
};
url.query_pairs_mut().append_pair("length", &length.to_string()).append_pair("start", &self.offset.to_string());
url.query_pairs_mut()
.append_pair("length", &length.to_string())
.append_pair("start", &self.offset.to_string());
}
let req = self.client.get(url);
let res = req.send().await?;
let body: PaginatedResponse<T> = res.json().await?;
Ok(body)
}

async fn perform(&self, payload: ActionPayload, action: &ActionCommands) -> Result<(), Box<dyn std::error::Error>> {
async fn perform(
&self,
payload: ActionPayload,
action: &ActionCommands,
) -> Result<(), Box<dyn std::error::Error>> {
let mut url = self.base_url.clone();
url.path_segments_mut().unwrap().push("subtitles");
let action_string: String = action.to_string();
Expand All @@ -67,12 +72,18 @@ impl Action {
Ok(())
}

async fn process_episode_subtitle(&self, series: &TVShow, episode: Episode) {
async fn process_episode_subtitle(&self, pb: &ProgressBar, episode: Episode) {
for subtitle in episode.subtitles {
if !subtitle.is_valid() {
continue;
}

pb.set_message(format!(
"Performing action {} on {} subtitle of episode {}",
self.action.to_string(),
subtitle.audio_language_item.name,
episode.title,
));
let payload = ActionPayload {
id: episode.sonarr_episode_id,
media_type: String::from("episode"),
Expand All @@ -81,19 +92,19 @@ impl Action {
};
match self.perform(payload, &self.action).await {
Ok(_) => {
self.pb.set_message(format!("Successfully performed action `{}` on {} subtitle of episode `{}` of tv show `{}`",
self.action.to_string(),
pb.set_message(format!(
"Successfully performed action {} on {} subtitle of episode {}",
self.action.to_string(),
subtitle.audio_language_item.name,
episode.title,
series.title,
episode.title,
));
}
Err(err) => {
self.pb.set_message(format!("Error performing action `{}` on {} subtitle of episode `{}` of tv show `{}` due to error {}",
self.action.to_string(),
pb.set_message(format!(
"Error performing action {} on {} subtitle of episode {} due to error {}",
self.action.to_string(),
subtitle.audio_language_item.name,
episode.title,
series.title,
episode.title,
err,
));
}
Expand All @@ -106,6 +117,12 @@ impl Action {
if !subtitle.is_valid() {
continue;
}
self.pb.set_message(format!(
"Performing action {} on {} subtitle of movie {}",
self.action.to_string(),
subtitle.audio_language_item.name,
movie.title,
));
let payload = ActionPayload {
id: movie.radarr_id,
media_type: String::from("movie"),
Expand All @@ -115,18 +132,18 @@ impl Action {
match self.perform(payload, &self.action).await {
Ok(_) => {
self.pb.set_message(format!(
"Successfully performed action `{}` on {} subtitle of movie `{}`",
"Successfully performed action {} on {} subtitle of movie {}",
self.action.to_string(),
subtitle.audio_language_item.name,
movie.title,
));
}
Err(err) => {
self.pb.set_message(
format!("Error performing action `{}` on {} subtitle of movie `{}` due to error {}",
self.action.to_string(),
self.pb.set_message(format!(
"Error performing action {} on {} subtitle of movie {} due to error {}",
self.action.to_string(),
subtitle.audio_language_item.name,
movie.title,
movie.title,
err,
));
}
Expand All @@ -135,6 +152,11 @@ impl Action {
}

pub async fn movies(&self) -> Result<(), Box<dyn std::error::Error>> {
self.pb.set_style(
ProgressStyle::with_template("[{bar:60.green/yellow}] {pos:>7}/{len:7} Movies\n{msg}")
.unwrap()
.progress_chars("##-"),
);
let mut url = self.base_url.clone();
url.path_segments_mut().unwrap().push("movies");
let response = self.get_all::<Movie>(url, true).await?;
Expand All @@ -157,28 +179,52 @@ impl Action {
}

pub async fn tv_shows(&self) -> Result<(), Box<dyn std::error::Error>> {
let mp = MultiProgress::new();
let pb_main = mp.add(self.pb.clone());
pb_main.set_style(
ProgressStyle::with_template(
"[{bar:60.green/yellow}] {pos:>7}/{len:7} TV Shows\n{msg}",
)
.unwrap()
.progress_chars("##-"),
);
let mut url = self.base_url.clone();
url.path_segments_mut().unwrap().push("series");
let response = self.get_all::<TVShow>(url.clone(), true).await?;
let num_series: u64= response.data.len() as u64;
let num_series: u64 = response.data.len() as u64;
if num_series == 0 {
self.pb.finish_with_message("No tv shows found");
pb_main.finish_with_message("No tv shows found");
return Ok(());
}

self.pb.set_length(num_series);
pb_main.set_length(num_series);
let sub_pb = mp.insert_after(&pb_main, ProgressBar::new(0));
sub_pb.set_style(
ProgressStyle::with_template("[{bar:60.cyan/blue}] {pos:>7}/{len:7} Episodes\n{msg}")
.unwrap()
.progress_chars("##-"),
);
url.path_segments_mut().unwrap().pop().push("episodes");
for series in response.data {
pb_main.set_message(format!("Processing tv show {}", series.title,));
let query_param = format!("seriesid[]={}", series.sonarr_series_id);
let mut new_url = url.clone();
new_url.set_query(Some(&query_param));
let response = self.get_all::<Episode>(new_url, false).await?;
let num_episodes: u64 = response.data.len() as u64;
sub_pb.set_length(num_episodes);
if num_episodes == 0 {
sub_pb.finish_with_message("No episodes found");
return Ok(());
}
for episode in response.data {
self.process_episode_subtitle(&series, episode).await;
self.process_episode_subtitle(&sub_pb, episode).await;
sub_pb.inc(1);
}
self.pb.inc(1);
pb_main.inc(1);
pb_main.set_message(format!("Finished processing tv show {}", series.title,));
}
self.pb.finish_with_message(format!(
pb_main.finish_with_message(format!(
"Finished performing action {} on all tv shows",
self.action.to_string(),
));
Expand Down
Loading