diff --git a/crates/cli/src/commands.rs b/crates/cli/src/commands.rs index 7dfa3be..4374c87 100644 --- a/crates/cli/src/commands.rs +++ b/crates/cli/src/commands.rs @@ -11,14 +11,14 @@ pub async fn shows(api: &Api, command: ShowCommand) -> Result<()> { match command { ShowCommand::Order { show, episode } => { let order: p::EpisodeOrder = if episode.is_empty() { - serde_json::from_value( - api.json( - api.client() - .get_episode_order(p::GetEpisodeOrderParams { show_slug: show }), - &[200], - ) - .await?, - )? + match api + .client() + .get_episode_order(p::GetEpisodeOrderParams { show_slug: show }) + .await? + { + p::GetEpisodeOrderResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + } } else { listenbox_sync_engine::sync::set_order(api, &show, episode).await? }; @@ -59,8 +59,11 @@ pub async fn shows(api: &Api, command: ShowCommand) -> Result<()> { result?; } ShowCommand::List => { - let result = api.json(api.client().list_shows(), &[200]).await?; - let shows: Vec = serde_json::from_value(result)?; + let result = match api.client().list_shows().await? { + p::ListShowsResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; + let shows = result; for show in shows { println!("{}", show.slug); } @@ -77,22 +80,27 @@ pub async fn shows(api: &Api, command: ShowCommand) -> Result<()> { Some(path) => Some(upload_artwork(api, &id, &path).await?), None => None, }; - let request = api.client().create_show(p::CreateShowParams { - body: p::CreateShow { - id, - title, - slug: slug.clone(), - language, - image_asset_id, - youtube_source_url: None, - source_kind: serde_json::from_value(serde_json::to_value(source_kind)?)?, - }, - }); - let response = api.send(request).await?; - if response.status() == reqwest::StatusCode::CONFLICT { - bail!("create show: slug {slug:?} already exists"); - } - let show: p::Show = serde_json::from_value(api.accept(response, &[201]).await?)?; + let response = api + .client() + .create_show(p::CreateShowParams { + body: p::CreateShow { + id, + title, + slug: slug.clone(), + language, + image_asset_id, + youtube_source_url: None, + source_kind: serde_json::from_value(serde_json::to_value(source_kind)?)?, + }, + }) + .await?; + let show = match response { + p::CreateShowResponse::Status201(show) => show, + p::CreateShowResponse::Status409(()) => { + bail!("create show: slug {slug:?} already exists") + } + response => return Err(api.response_error(response).await), + }; println!( "Created show {:?}\nOpen in Listenbox: {}", show.slug, @@ -101,21 +109,23 @@ pub async fn shows(api: &Api, command: ShowCommand) -> Result<()> { } ShowCommand::Delete { show, yes } => { ensure!(yes, "shows delete: --yes is required"); - let result = api - .json( - api.client() - .create_show_deletion(p::CreateShowDeletionParams { - show_slug: show.clone(), - }), - &[202], - ) - .await?; + let result = match api + .client() + .create_show_deletion(p::CreateShowDeletionParams { + show_slug: show.clone(), + }) + .await? + { + p::CreateShowDeletionResponse::Status202(value) => value, + response => return Err(api.response_error(response).await), + }; delete_events( api, api.client() .show_deletion_events(p::ShowDeletionEventsParams { - show_deletion_run_id: string(&result, "show_deletion_run_id")?.into(), - }), + show_deletion_run_id: result.show_deletion_run_id, + }) + .await?, "show", "show_slug", &show, @@ -172,17 +182,23 @@ async fn upload_artwork(api: &Api, show: &str, path: &std::path::Path) -> Result width == height && (1400..=3000).contains(&width), "upload a square image between 1400 and 3000 pixels. Attempted resolution: {width} × {height} pixels" ); - let result = api.json(api.client().create_image_upload_presign(p::CreateImageUploadPresignParams { body: serde_json::from_value(json!({ - "show_id": show, "byte_length": raw.len(), "content_type": content_type, - "file_name": path.file_name().context("artwork filename")?.to_string_lossy(), - }))? }), &[201]).await?; + let result = match api + .client() + .create_image_upload_presign(p::CreateImageUploadPresignParams { + body: serde_json::from_value(json!({ + "show_id": show, "byte_length": raw.len(), "content_type": content_type, + "file_name": path.file_name().context("artwork filename")?.to_string_lossy(), + }))?, + }) + .await? + { + p::CreateImageUploadPresignResponse::Status201(value) => value, + response => return Err(api.response_error(response).await), + }; let response = api .send( api.http - .request( - string(&result, "method")?.parse()?, - string(&result, "upload_url")?, - ) + .request(reqwest::Method::PUT, &result.upload_url) .header("Content-Type", content_type) .body(raw), ) @@ -192,46 +208,49 @@ async fn upload_artwork(api: &Api, show: &str, path: &std::path::Path) -> Result "upload artwork: HTTP {}", response.status() ); - let completed = api - .json( - api.client() - .complete_image_upload(p::CompleteImageUploadParams { - image_asset_id: string(&result, "image_asset_id")?.into(), - body: p::CompleteImageUpload { - object_key: string(&result, "object_key")?.into(), - }, - }), - &[201], - ) - .await?; - Ok(string(&completed, "id")?.into()) + let completed = match api + .client() + .complete_image_upload(p::CompleteImageUploadParams { + image_asset_id: result.image_asset_id, + body: p::CompleteImageUpload { + object_key: result.object_key, + }, + }) + .await? + { + p::CompleteImageUploadResponse::Status201(value) => value, + response => return Err(api.response_error(response).await), + }; + Ok(completed.id) } pub async fn import_rss(api: &Api, source: &str, slug: Option<&str>) -> Result<()> { let response = api - .send(api.client().import_rss(p::ImportRSSParams { + .client() + .import_rss(p::ImportRSSParams { body: p::ImportRSSRequest { source_url: source.into(), slug: slug.map(str::to_owned), }, - })) + }) .await?; - if response.status() == reqwest::StatusCode::CONFLICT { - if let Some(slug) = slug { - bail!("requested slug {slug:?} conflicts"); + let created = match response { + p::ImportRSSResponse::Status202(created) => created, + p::ImportRSSResponse::Status409(()) => { + if let Some(slug) = slug { + bail!("requested slug {slug:?} conflicts"); + } + bail!("import choice conflicts"); } - bail!("import choice conflicts"); - } - if response.status() != reqwest::StatusCode::ACCEPTED { - return Err(api.response_error(response).await); - } - let created: p::CreatedPublicRSSImport = api.decode(response).await?; + response => return Err(api.response_error(response).await), + }; let mut stream = Events::open( api, api.client() .import_rss_run_events(p::ImportRSSRunEventsParams { import_run_id: created.import_run_id, - }), + }) + .await?, ) .await?; let mut progress = Progress::default(); @@ -268,14 +287,14 @@ pub async fn import_rss(api: &Api, source: &str, slug: Option<&str>) -> Result<( } } -pub async fn delete_events( +pub async fn delete_events( api: &Api, - request: reqwest_middleware::RequestBuilder, + response: R, kind: &str, identity_key: &str, identity: &str, ) -> Result<()> { - let mut stream = Events::open(api, request).await?; + let mut stream = Events::open(api, response).await?; let mut progress = Progress::default(); loop { let event = stream.next(api).await?; @@ -309,58 +328,73 @@ pub async fn delete_events( pub async fn members(api: &Api, command: MemberCommand) -> Result<()> { let client = api.client(); match command { - MemberCommand::List { show } => { - let request = match &show { - Some(show) => client.list_show_members(p::ListShowMembersParams { - show_slug: show.clone(), - }), - None => client.list_team_members(), + MemberCommand::List { show: Some(show) } => { + let result = match client + .list_show_members(p::ListShowMembersParams { show_slug: show }) + .await? + { + p::ListShowMembersResponse::Status200(result) => result, + response => return Err(api.response_error(response).await), }; - let result = api.json(request, &[200]).await?; - for member in result["members"].as_array().context("missing members")? { - if show.is_some() { - print!("{}\t", string(member, "access_source")?); - } - println!( - "{}\t{}\t{}", - string(member, "role")?, - string(&member["user"], "email")?, - string(&member["user"], "id")? + for member in result.members { + print!( + "{}\t", + match member.access_source { + p::ShowAccessSource::Team => "team", + p::ShowAccessSource::Show => "show", + } ); + print_member(&member.role, &member.user); } - for invite in result["invitations"] - .as_array() - .context("missing invitations")? - { - let expiry = chrono::DateTime::from_timestamp_millis(number(invite, "expires_at")?) - .context("invalid invitation expiry")?; - println!( - "pending\t{}\t{}\t{}\t{}", - string(invite, "role")?, - string(invite, "email")?, - string(invite, "id")?, - expiry.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - ); + for invite in result.invitations { + print_invitation(&invite.id, &invite.email, &invite.role, invite.expires_at)?; + } + } + MemberCommand::List { show: None } => { + let result = match client.list_team_members().await? { + p::ListTeamMembersResponse::Status200(result) => result, + response => return Err(api.response_error(response).await), + }; + for member in result.members { + print_member(&member.role, &member.user); + } + for invite in result.invitations { + print_invitation(&invite.id, &invite.email, &invite.role, invite.expires_at)?; } } MemberCommand::Invite { email, role, show } => { - let body = json!({"email": email.trim().to_lowercase(), "role": role}); - let request = match &show { - Some(show) => client.create_show_invitation(p::CreateShowInvitationParams { - show_slug: show.clone(), - body: serde_json::from_value(body)?, - }), - None => client.create_team_invitation(p::CreateTeamInvitationParams { - body: serde_json::from_value(body)?, - }), + let role = match role { + crate::Role::Read => p::AssignableTeamRole::Read, + crate::Role::Write => p::AssignableTeamRole::Write, + }; + let email = email.trim().to_lowercase(); + let (email, role) = match &show { + Some(show) => match client + .create_show_invitation(p::CreateShowInvitationParams { + show_slug: show.clone(), + body: p::CreateShowInvitation { email, role }, + }) + .await? + { + p::CreateShowInvitationResponse::Status201(invite) => { + (invite.email, invite.role) + } + response => return Err(api.response_error(response).await), + }, + None => match client + .create_team_invitation(p::CreateTeamInvitationParams { + body: p::CreateTeamInvitation { email, role }, + }) + .await? + { + p::CreateTeamInvitationResponse::Status201(invite) => { + (invite.email, invite.role) + } + response => return Err(api.response_error(response).await), + }, }; - let result = api.json(request, &[201]).await?; let target = show.map_or(String::new(), |show| format!(" to {show}")); - println!( - "Invited {}{target} as {}.", - string(&result, "email")?, - string(&result, "role")? - ); + println!("Invited {email}{target} as {}.", invitation_role(&role)); } MemberCommand::Role { member, role, show } => { let label = if show.is_some() { @@ -368,23 +402,34 @@ pub async fn members(api: &Api, command: MemberCommand) -> Result<()> { } else { "member" }; - let body = json!({"role": role}); - let request = match show { - Some(show) => client.update_show_member_role(p::UpdateShowMemberRoleParams { - show_slug: show, - user_id: member.clone(), - body: serde_json::from_value(body.clone())?, - }), - None => client.update_team_member_role(p::UpdateTeamMemberRoleParams { - user_id: member.clone(), - body: serde_json::from_value(body.clone())?, - }), + let role = match role { + crate::Role::Read => p::AssignableTeamRole::Read, + crate::Role::Write => p::AssignableTeamRole::Write, }; - api.json(request, &[204]).await?; - println!( - "Changed {label} {member} to {}.", - body["role"].as_str().unwrap_or("") - ); + match show { + Some(show) => match client + .update_show_member_role(p::UpdateShowMemberRoleParams { + show_slug: show, + user_id: member.clone(), + body: p::UpdateShowMemberRole { role: role.clone() }, + }) + .await? + { + p::UpdateShowMemberRoleResponse::Status204(()) => (), + response => return Err(api.response_error(response).await), + }, + None => match client + .update_team_member_role(p::UpdateTeamMemberRoleParams { + user_id: member.clone(), + body: p::UpdateTeamMemberRole { role: role.clone() }, + }) + .await? + { + p::UpdateTeamMemberRoleResponse::Status204(()) => (), + response => return Err(api.response_error(response).await), + }, + } + println!("Changed {label} {member} to {}.", invitation_role(&role)); } MemberCommand::Remove { member, yes, show } => { let label = if show.is_some() { @@ -393,18 +438,59 @@ pub async fn members(api: &Api, command: MemberCommand) -> Result<()> { "member" }; ensure!(yes, "members remove: --yes is required"); - let request = match show { - Some(show) => client.remove_show_member(p::RemoveShowMemberParams { - show_slug: show, - user_id: member.clone(), - }), - None => client.remove_team_member(p::RemoveTeamMemberParams { - user_id: member.clone(), - }), - }; - api.json(request, &[204]).await?; + match show { + Some(show) => match client + .remove_show_member(p::RemoveShowMemberParams { + show_slug: show, + user_id: member.clone(), + }) + .await? + { + p::RemoveShowMemberResponse::Status204(()) => (), + response => return Err(api.response_error(response).await), + }, + None => match client + .remove_team_member(p::RemoveTeamMemberParams { + user_id: member.clone(), + }) + .await? + { + p::RemoveTeamMemberResponse::Status204(()) => (), + response => return Err(api.response_error(response).await), + }, + } println!("Removed {label} {member}."); } } Ok(()) } + +fn print_member(role: &p::TeamRole, user: &p::User) { + let role = match role { + p::TeamRole::Owner => "owner", + p::TeamRole::Write => "write", + p::TeamRole::Read => "read", + }; + println!("{role}\t{}\t{}", user.email, user.id); +} +fn invitation_role(role: &p::AssignableTeamRole) -> &'static str { + match role { + p::AssignableTeamRole::Write => "write", + p::AssignableTeamRole::Read => "read", + } +} +fn print_invitation( + id: &str, + email: &str, + role: &p::AssignableTeamRole, + expires_at: i64, +) -> Result<()> { + let expiry = + chrono::DateTime::from_timestamp_millis(expires_at).context("invalid invitation expiry")?; + println!( + "pending\t{}\t{email}\t{id}\t{}", + invitation_role(role), + expiry.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) + ); + Ok(()) +} diff --git a/crates/cli/src/episodes.rs b/crates/cli/src/episodes.rs index b07f0e2..96bf32b 100644 --- a/crates/cli/src/episodes.rs +++ b/crates/cli/src/episodes.rs @@ -1,9 +1,6 @@ use crate::EpisodeCommand; -use anyhow::{Context, Result, ensure}; -use listenbox_sync_engine::{ - api::{Api, string}, - publicapi as p, -}; +use anyhow::{Result, ensure}; +use listenbox_sync_engine::{api::Api, publicapi as p}; use std::collections::HashSet; pub async fn run(api: &Api, command: EpisodeCommand) -> Result<()> { match command { @@ -11,25 +8,24 @@ pub async fn run(api: &Api, command: EpisodeCommand) -> Result<()> { let mut cursor = None; let mut seen = HashSet::new(); loop { - let page = api - .json( - api.client().list_episodes(p::ListEpisodesParams { - show_slug: show.clone(), - limit: Some(i64::from(limit)), - cursor, - }), - &[200], - ) - .await?; - for episode in page["episodes"] - .as_array() - .context("episode page missing episodes")? + let page = match api + .client() + .list_episodes(p::ListEpisodesParams { + show_slug: show.clone(), + limit: Some(i64::from(limit)), + cursor, + }) + .await? { - let id = string(episode, "id")?; - ensure!(crate::valid_id(id, "ep_"), "invalid episode ID in list"); + p::ListEpisodesResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; + for episode in page.episodes { + let id = episode.id; + ensure!(crate::valid_id(&id, "ep_"), "invalid episode ID in list"); println!("{id}"); } - cursor = page["next_cursor"].as_str().map(str::to_owned); + cursor = page.next_cursor; let Some(next) = &cursor else { return Ok(()); }; @@ -61,21 +57,23 @@ pub async fn run(api: &Api, command: EpisodeCommand) -> Result<()> { } EpisodeCommand::Delete { episode, yes } => { ensure!(yes, "episodes delete: --yes is required"); - let result = api - .json( - api.client() - .create_episode_deletion(p::CreateEpisodeDeletionParams { - episode_id: episode.clone(), - }), - &[202], - ) - .await?; + let result = match api + .client() + .create_episode_deletion(p::CreateEpisodeDeletionParams { + episode_id: episode.clone(), + }) + .await? + { + p::CreateEpisodeDeletionResponse::Status202(value) => value, + response => return Err(api.response_error(response).await), + }; crate::commands::delete_events( api, api.client() .episode_deletion_events(p::EpisodeDeletionEventsParams { - episode_deletion_run_id: string(&result, "episode_deletion_run_id")?.into(), - }), + episode_deletion_run_id: result.episode_deletion_run_id, + }) + .await?, "episode", "episode_id", &episode, diff --git a/crates/sync-engine/src/api.rs b/crates/sync-engine/src/api.rs index eee93df..9743f99 100644 --- a/crates/sync-engine/src/api.rs +++ b/crates/sync-engine/src/api.rs @@ -1,8 +1,7 @@ -use crate::{auth::StoredAuth, config::Config}; +use crate::{auth::StoredAuth, config::Config, publicapi as p}; use anyhow::{Context, Result, bail, ensure}; use reqwest::{Client, Response}; use reqwest_middleware::{ClientWithMiddleware, RequestBuilder}; -use serde::de::DeserializeOwned; use serde_json::Value; use std::{ future::Future, @@ -67,12 +66,13 @@ impl Api { Ok(reqwest_middleware::ClientBuilder::new(builder.build()?).build()) } - pub fn client(&self) -> crate::publicapi::Client { + pub fn client(&self) -> p::Client<&Self> { crate::publicapi::Client::new( self.http.clone(), self.config.api_origin.clone(), self.credential.clone(), ) + .with_transport(self) } pub async fn wait(&self, work: impl Future>) -> Result { @@ -136,31 +136,18 @@ impl Api { self.wait(read_bounded(response, limit)).await } - pub async fn decode(&self, response: Response) -> Result { - serde_json::from_slice(&self.bytes(response, 4 << 20).await?).context("decode API response") - } - - pub async fn json(&self, request: RequestBuilder, statuses: &[u16]) -> Result { - let response = self.send(request).await?; - self.accept(response, statuses).await - } - - pub async fn accept(&self, response: Response, statuses: &[u16]) -> Result { - if !statuses.contains(&response.status().as_u16()) { - return Err(self.response_error(response).await); - } - if response.status() == reqwest::StatusCode::NO_CONTENT { - return Ok(Value::Null); - } - self.decode(response).await - } - - pub async fn response_error(&self, response: Response) -> anyhow::Error { - let status = response.status().as_u16(); + pub async fn response_error(&self, response: R) -> anyhow::Error { + let status = response.status(); if status == 401 { return AuthenticationRequired.into(); } - let raw = self.bytes(response, 64 << 10).await.unwrap_or_default(); + let error = match self.wait(async { Ok(response.into_error().await) }).await { + Ok(error) => error, + Err(error) => return error, + }; + let p::Error::Http { body: raw, .. } = error else { + return error.into(); + }; let message = serde_json::from_slice::(&raw) .ok() .and_then(|body| { @@ -180,6 +167,19 @@ impl Api { } } +impl p::Transport for &Api { + type Error = anyhow::Error; + + async fn execute(&self, request: RequestBuilder, limit: usize) -> Result { + self.wait(async { + R::decode(self.send(request).await?, limit) + .await + .map_err(Into::into) + }) + .await + } +} + pub async fn read_bounded(mut response: Response, limit: usize) -> Result> { let mut body = Vec::new(); while let Some(chunk) = response.chunk().await? { diff --git a/crates/sync-engine/src/auth.rs b/crates/sync-engine/src/auth.rs index afd0185..37cee16 100644 --- a/crates/sync-engine/src/auth.rs +++ b/crates/sync-engine/src/auth.rs @@ -39,28 +39,29 @@ pub async fn login_with( mut open_browser: impl FnMut(&str), ) -> Result<()> { let mut response = api - .send( - api.client() - .create_cli_authorization(p::CreateCLIAuthorizationParams { - body: serde_json::from_value(json!({"client": client, "scopes": SCOPES}))?, - }), - ) + .client() + .create_cli_authorization(p::CreateCLIAuthorizationParams { + body: serde_json::from_value(json!({"client": client, "scopes": SCOPES}))?, + }) .await?; - if response.status() == reqwest::StatusCode::UNAUTHORIZED && api.credential.is_some() { + if matches!(response, p::CreateCLIAuthorizationResponse::Status401(())) + && api.credential.is_some() + { api.credential = None; response = api - .send( - api.client() - .create_cli_authorization(p::CreateCLIAuthorizationParams { - body: serde_json::from_value(json!({"client": client, "scopes": SCOPES}))?, - }), - ) + .client() + .create_cli_authorization(p::CreateCLIAuthorizationParams { + body: serde_json::from_value(json!({"client": client, "scopes": SCOPES}))?, + }) .await?; } - let created = api.accept(response, &[201]).await?; - let credential = string(&created, "credential")?; + let created = match response { + p::CreateCLIAuthorizationResponse::Status201(created) => created, + response => return Err(api.response_error(response).await), + }; + let credential = &created.credential; ensure!(credential_valid(credential), "invalid pending credential"); - let mut verification = Url::parse(string(&created, "verification_url")?)?; + let mut verification = Url::parse(&created.verification_url)?; ensure!( matches!(verification.scheme(), "http" | "https") && verification.host_str().is_some() @@ -81,27 +82,27 @@ pub async fn login_with( let mut events = Events::open( api, api.client() - .cli_authorization_events(p::CliAuthorizationEventsParams { - code: string(&created, "code")?.into(), - }), + .cli_authorization_events(p::CliAuthorizationEventsParams { code: created.code }) + .await?, ) .await?; let event = events.next(api).await?; match string(&event, "type")? { "cli.authorization.approved" => { api.credential = Some(credential.to_owned()); - let identity = api.json(api.client().whoami(), &[200]).await?; + let identity = match api.client().whoami().await? { + p::WhoamiResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; ensure!( - string(&identity, "team_id")? == string(&event, "team_id")?, + identity.team_id == string(&event, "team_id")?, "approved credential team does not match approved team" ); - let scopes = identity["scopes"] - .as_array() - .context("identity missing scopes")?; - for scope in SCOPES { + let scopes: Vec = serde_json::from_value(json!(SCOPES))?; + for scope in scopes { ensure!( - scopes.iter().any(|value| value.as_str() == Some(scope)), - "approved credential missing scope {scope}" + identity.scopes.contains(&scope), + "approved credential missing scope {scope:?}" ); } write_private_json( @@ -132,11 +133,15 @@ pub fn logout(config: &crate::config::Config) -> Result<()> { } pub async fn status(api: &Api) -> Result<()> { - let identity = api.json(api.client().whoami(), &[200]).await?; - let email = string(&identity, "email")?.trim(); + let identity = match api.client().whoami().await? { + p::WhoamiResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; + let email = identity.email.trim(); ensure!(!email.is_empty(), "identity email is empty"); - let name = identity["name"] - .as_str() + let name = identity + .name + .as_deref() .unwrap_or("") .split_whitespace() .collect::>() diff --git a/crates/sync-engine/src/client.rs b/crates/sync-engine/src/client.rs index 7acd71b..16f451d 100644 --- a/crates/sync-engine/src/client.rs +++ b/crates/sync-engine/src/client.rs @@ -71,17 +71,20 @@ impl Client { if api.credential.is_none() { return Err(crate::api::AuthenticationRequired.into()); } - Ok(serde_json::from_value( - api.json( - api.client().list_episodes(p::ListEpisodesParams { + Ok( + match api + .client() + .list_episodes(p::ListEpisodesParams { show_slug: slug, cursor, limit: Some(50), - }), - &[200], - ) - .await?, - )?) + }) + .await? + { + p::ListEpisodesResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }, + ) } fn api(&self, cancel: CancellationToken) -> Result { Api::new(self.config.clone(), cancel) @@ -103,15 +106,28 @@ impl Client { if api.credential.is_none() { return Err(crate::api::AuthenticationRequired.into()); } + let client = api.client(); let (teams, shows, account) = tokio::try_join!( - api.json(api.client().list_client_teams(), &[200]), - api.json(api.client().list_shows(), &[200]), - api.json(api.client().whoami(), &[200]) + client.list_client_teams(), + client.list_shows(), + client.whoami() )?; + let teams = match teams { + p::ListClientTeamsResponse::Status200(teams) => teams, + response => return Err(api.response_error(response).await), + }; + let shows = match shows { + p::ListShowsResponse::Status200(shows) => shows, + response => return Err(api.response_error(response).await), + }; + let account = match account { + p::WhoamiResponse::Status200(account) => account, + response => return Err(api.response_error(response).await), + }; Ok(Catalog { - teams: serde_json::from_value(teams)?, - import_team: Some(serde_json::from_value::(account)?.team_id), - shows: serde_json::from_value(shows)?, + teams, + import_team: Some(account.team_id), + shows, }) } pub async fn import_playlist( diff --git a/crates/sync-engine/src/episodes.rs b/crates/sync-engine/src/episodes.rs index e45d91b..5f2afbf 100644 --- a/crates/sync-engine/src/episodes.rs +++ b/crates/sync-engine/src/episodes.rs @@ -113,23 +113,34 @@ pub async fn create(api: &Api, args: EpisodeCreate) -> Result<()> { Err(error) => return Err(error.into()), }; if !["finalizing", "processing", "completed"].contains(&record.phase.as_str()) { - let request = api.client().create_episode_upload_session(p::CreateEpisodeUploadSessionParams { body: serde_json::from_value(json!({ + let response = api.client().create_episode_upload_session(p::CreateEpisodeUploadSessionParams { body: serde_json::from_value(json!({ "show_slug": args.show, "title": args.title, "file_name": path.file_name().context("source filename")?.to_string_lossy(), "content_type": content_type, "byte_length": length, "source_sha256": hash, "description": args.description, - }))? }); - let response = api.send(request).await?; - let session = api.accept(response, &[200, 201]).await?; - record.upload_session_id = string(&session, "upload_session_id")?.into(); - record.team_id = string(&session, "team_id")?.into(); - record.show_id = string(&session, "show_id")?.into(); - record.episode_id = session["episode_id"].as_str().unwrap_or("").into(); - record.expires_at = number(&session, "expires_at")?; - record.phase = string(&session, "phase")?.into(); - record.completed_parts = serde_json::from_value(session["completed_parts"].clone())?; + }))? }).await?; + let session = match response { + p::CreateEpisodeUploadSessionResponse::Status200(session) + | p::CreateEpisodeUploadSessionResponse::Status201(session) => session, + response => return Err(api.response_error(response).await), + }; + record.upload_session_id = session.upload_session_id.clone(); + record.team_id = session.team_id.clone(); + record.show_id = session.show_id.clone(); + record.episode_id = session.episode_id.clone().unwrap_or_default(); + record.expires_at = session.expires_at; + record.phase = match session.phase { + p::EpisodeUploadSessionPhase::Created => "created", + p::EpisodeUploadSessionPhase::Uploading => "uploading", + p::EpisodeUploadSessionPhase::Processing => "processing", + p::EpisodeUploadSessionPhase::Completed => "completed", + p::EpisodeUploadSessionPhase::Failed => "failed", + p::EpisodeUploadSessionPhase::Expired => "expired", + } + .into(); + record.completed_parts = session.completed_parts.clone(); write_private_json(&resume_path, &record)?; if record.phase != "finalizing" { - let part_size = u64::try_from(number(&session, "part_size")?)?; + let part_size = u64::try_from(session.part_size)?; ensure!(part_size >= 5 << 20, "invalid upload part size {part_size}"); let count = length.div_ceil(part_size); ensure!(count <= 10000, "episode source requires too many parts"); @@ -144,35 +155,31 @@ pub async fn create(api: &Api, args: EpisodeCreate) -> Result<()> { saved_progress(&record); if !missing.is_empty() { let response = api - .send(api.client().presign_episode_upload_session_parts( + .client() + .presign_episode_upload_session_parts( p::PresignEpisodeUploadSessionPartsParams { upload_session_id: record.upload_session_id.clone(), body: p::PresignEpisodeUploadSessionParts { part_numbers: missing.clone(), }, }, - )) + ) .await?; - let signed = api.accept(response, &[201]).await?; - let parts = signed["parts"].as_array().context("missing signed parts")?; + let parts = match response { + p::PresignEpisodeUploadSessionPartsResponse::Status201(signed) => signed.parts, + response => return Err(api.response_error(response).await), + }; let mut pending = missing.into_iter().collect::>(); for part in parts { - let number = number(part, "part_number")?; + let number = part.part_number; ensure!( pending.remove(&number), "unexpected or duplicate signed part {number}" ); let offset = (number as u64 - 1) * part_size; let size = part_size.min(length - offset); - let etag = upload_part( - api, - &path, - offset, - size, - string(part, "method")?, - string(part, "upload_url")?, - ) - .await?; + let etag = + upload_part(api, &path, offset, size, "PUT", &part.upload_url).await?; record.completed_parts.push(p::CompletedEpisodeUploadPart { part_number: number, etag, @@ -189,17 +196,20 @@ pub async fn create(api: &Api, args: EpisodeCreate) -> Result<()> { record.phase = "finalizing".into(); write_private_json(&resume_path, &record)?; } - let response = - api.send(api.client().complete_episode_upload_session( - p::CompleteEpisodeUploadSessionParams { - upload_session_id: record.upload_session_id.clone(), - body: serde_json::from_value(json!({"publication": args.publication}))?, - }, - )) + let response = api + .client() + .complete_episode_upload_session(p::CompleteEpisodeUploadSessionParams { + upload_session_id: record.upload_session_id.clone(), + body: serde_json::from_value(json!({"publication": args.publication}))?, + }) .await?; - let episode = api.accept(response, &[200, 201]).await?; - record.episode_id = string(&episode, "id")?.into(); - record.show_id = string(&episode, "show_id")?.into(); + let episode = match response { + p::CompleteEpisodeUploadSessionResponse::Status200(episode) + | p::CompleteEpisodeUploadSessionResponse::Status201(episode) => episode, + response => return Err(api.response_error(response).await), + }; + record.episode_id = episode.id; + record.show_id = episode.show_id; ensure!( crate::valid_id(&record.episode_id, "ep_"), "invalid episode management identifier" @@ -216,7 +226,8 @@ pub async fn create(api: &Api, args: EpisodeCreate) -> Result<()> { api.client() .episode_upload_session_events(p::EpisodeUploadSessionEventsParams { upload_session_id: record.upload_session_id.clone(), - }), + }) + .await?, ) .await?; loop { diff --git a/crates/sync-engine/src/events.rs b/crates/sync-engine/src/events.rs index 5d91baa..76e4195 100644 --- a/crates/sync-engine/src/events.rs +++ b/crates/sync-engine/src/events.rs @@ -1,7 +1,7 @@ use crate::api::Api; +use crate::publicapi as p; use anyhow::{Result, bail, ensure}; use reqwest::Response; -use reqwest_middleware::RequestBuilder; use serde_json::Value; pub struct Events { @@ -11,11 +11,11 @@ pub struct Events { } impl Events { - pub async fn open(api: &Api, request: RequestBuilder) -> Result { - let response = api.send(request).await?; - if !response.status().is_success() { - return Err(api.response_error(response).await); - } + pub async fn open(api: &Api, response: R) -> Result { + let response = match response.into_stream() { + Ok(response) => response, + Err(response) => return Err(api.response_error(response).await), + }; ensure!( response .headers() diff --git a/crates/sync-engine/src/publicapi/mod.rs b/crates/sync-engine/src/publicapi/mod.rs index 45e7b18..d8702a3 100644 --- a/crates/sync-engine/src/publicapi/mod.rs +++ b/crates/sync-engine/src/publicapi/mod.rs @@ -215,16 +215,36 @@ pub enum CancelEpisodePackageResponse { Status409(()), Unexpected(reqwest::Response), } -impl CancelEpisodePackageResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CancelEpisodePackageResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -241,17 +261,39 @@ pub enum CancelEpisodeUploadSessionResponse { Status409(()), Unexpected(reqwest::Response), } -impl CancelEpisodeUploadSessionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CancelEpisodeUploadSessionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 404 => Self::Status404(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -266,15 +308,39 @@ pub enum CliAuthorizationEventsResponse { Status404(()), Unexpected(reqwest::Response), } -impl CliAuthorizationEventsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CliAuthorizationEventsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(response), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + fn into_stream(self) -> Result { + match self { + Self::Status200(response) => Ok(response), + response => Err(response), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => read_body(body, 64 << 10).await, + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -299,16 +365,36 @@ pub enum CompleteEpisodePackageResponse { Status409(()), Unexpected(reqwest::Response), } -impl CompleteEpisodePackageResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CompleteEpisodePackageResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -336,12 +422,12 @@ pub enum CompleteEpisodeUploadSessionResponse { Status410(()), Unexpected(reqwest::Response), } -impl CompleteEpisodeUploadSessionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CompleteEpisodeUploadSessionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), @@ -350,6 +436,34 @@ impl CompleteEpisodeUploadSessionResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Status410(_) => 410, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Status410(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -375,10 +489,10 @@ pub enum CompleteImageUploadResponse { Status409(()), Unexpected(reqwest::Response), } -impl CompleteImageUploadResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CompleteImageUploadResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 400 => Self::Status400(()), 401 => Self::Status401(()), 403 => Self::Status403(()), @@ -387,6 +501,30 @@ impl CompleteImageUploadResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(_) => Ok(Vec::new()), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -421,15 +559,33 @@ pub enum CreateCLIAuthorizationResponse { Status401(()), Unexpected(reqwest::Response), } -impl CreateCLIAuthorizationResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateCLIAuthorizationResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -446,17 +602,39 @@ pub enum CreateEpisodeDeletionResponse { Status404(()), Unexpected(reqwest::Response), } -impl CreateEpisodeDeletionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateEpisodeDeletionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 202 => Self::Status202(response.json().await?), - 400 => Self::Status400(response.json().await?), + 202 => Self::Status202(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status202(_) => 202, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status202(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -495,18 +673,42 @@ pub enum CreateEpisodePackageResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateEpisodePackageResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateEpisodePackageResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), - 402 => Self::Status402(response.json().await?), + 402 => Self::Status402(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 404 => Self::Status404(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -547,12 +749,12 @@ pub enum CreateEpisodeUploadSessionResponse { Status410(()), Unexpected(reqwest::Response), } -impl CreateEpisodeUploadSessionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateEpisodeUploadSessionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), @@ -561,6 +763,34 @@ impl CreateEpisodeUploadSessionResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Status410(_) => 410, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Status410(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -599,10 +829,10 @@ pub enum CreateImageUploadPresignResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateImageUploadPresignResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateImageUploadPresignResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 400 => Self::Status400(()), 401 => Self::Status401(()), 402 => Self::Status402(()), @@ -611,6 +841,30 @@ impl CreateImageUploadPresignResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(_) => Ok(Vec::new()), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -646,17 +900,39 @@ pub enum CreateShowDeletionResponse { Status404(()), Unexpected(reqwest::Response), } -impl CreateShowDeletionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateShowDeletionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 202 => Self::Status202(response.json().await?), - 400 => Self::Status400(response.json().await?), + 202 => Self::Status202(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status202(_) => 202, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status202(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -684,11 +960,11 @@ pub enum CreateShowInvitationResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateShowInvitationResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateShowInvitationResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), @@ -696,6 +972,30 @@ impl CreateShowInvitationResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -713,10 +1013,10 @@ pub enum CreateShowResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateShowResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateShowResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 400 => Self::Status400(()), 401 => Self::Status401(()), 402 => Self::Status402(()), @@ -725,6 +1025,30 @@ impl CreateShowResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(_) => Ok(Vec::new()), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -744,11 +1068,11 @@ pub enum CreateSyncEpisodeDeletionResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateSyncEpisodeDeletionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateSyncEpisodeDeletionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 202 => Self::Status202(response.json().await?), - 400 => Self::Status400(response.json().await?), + 202 => Self::Status202(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 402 => Self::Status402(()), 403 => Self::Status403(()), @@ -757,6 +1081,32 @@ impl CreateSyncEpisodeDeletionResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status202(_) => 202, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status202(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -782,17 +1132,39 @@ pub enum CreateTeamInvitationResponse { Status409(()), Unexpected(reqwest::Response), } -impl CreateTeamInvitationResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for CreateTeamInvitationResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -973,17 +1345,45 @@ pub enum EpisodeDeletionEventsResponse { Status404(()), Unexpected(reqwest::Response), } -impl EpisodeDeletionEventsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for EpisodeDeletionEventsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(response), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + fn into_stream(self) -> Result { + match self { + Self::Status200(response) => Ok(response), + response => Err(response), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => read_body(body, 64 << 10).await, + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -1169,6 +1569,8 @@ pub struct EpisodePackage { pub team_id: TeamID, #[serde(rename = "upload_session_id")] pub upload_session_id: UploadSessionID, + #[serde(rename = "uploads")] + pub uploads: std::vec::Vec, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -1183,6 +1585,15 @@ pub enum EpisodePackageStatus { Expired, } +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EpisodePackageUpload { + #[serde(rename = "object_index")] + pub object_index: i64, + #[serde(rename = "parts")] + pub parts: std::vec::Vec, +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct EpisodePage { @@ -1457,16 +1868,42 @@ pub enum EpisodeUploadSessionEventsResponse { Status404(()), Unexpected(reqwest::Response), } -impl EpisodeUploadSessionEventsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for EpisodeUploadSessionEventsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(response), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + fn into_stream(self) -> Result { + match self { + Self::Status200(response) => Ok(response), + response => Err(response), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => read_body(body, 64 << 10).await, + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -1501,17 +1938,39 @@ pub enum GetEpisodeOrderResponse { Status404(()), Unexpected(reqwest::Response), } -impl GetEpisodeOrderResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for GetEpisodeOrderResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -1528,17 +1987,39 @@ pub enum GetEpisodeUploadSessionResponse { Status410(()), Unexpected(reqwest::Response), } -impl GetEpisodeUploadSessionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for GetEpisodeUploadSessionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 404 => Self::Status404(()), 410 => Self::Status410(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status404(_) => 404, + Self::Status410(_) => 410, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status410(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Debug)] @@ -1550,17 +2031,39 @@ pub enum GetImportCapacityResponse { Status404(()), Unexpected(reqwest::Response), } -impl GetImportCapacityResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for GetImportCapacityResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -1580,11 +2083,11 @@ pub enum GetSyncInventoryResponse { Status404(()), Unexpected(reqwest::Response), } -impl GetSyncInventoryResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for GetSyncInventoryResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 402 => Self::Status402(()), 403 => Self::Status403(()), @@ -1592,6 +2095,30 @@ impl GetSyncInventoryResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Debug)] @@ -1601,8 +2128,8 @@ pub enum HeadOpenapiResponse { Status400(()), Unexpected(reqwest::Response), } -impl HeadOpenapiResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for HeadOpenapiResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(()), 304 => Self::Status304(()), @@ -1610,6 +2137,24 @@ impl HeadOpenapiResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status304(_) => 304, + Self::Status400(_) => 400, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(_) => Ok(Vec::new()), + Self::Status304(_) => Ok(Vec::new()), + Self::Status400(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -1686,18 +2231,42 @@ pub enum ImportRSSResponse { Status409(()), Unexpected(reqwest::Response), } -impl ImportRSSResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ImportRSSResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 202 => Self::Status202(response.json().await?), - 400 => Self::Status400(response.json().await?), + 202 => Self::Status202(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), - 402 => Self::Status402(response.json().await?), + 402 => Self::Status402(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 403 => Self::Status403(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status202(_) => 202, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status202(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status403(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -1714,17 +2283,45 @@ pub enum ImportRSSRunEventsResponse { Status404(()), Unexpected(reqwest::Response), } -impl ImportRSSRunEventsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ImportRSSRunEventsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(response), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + fn into_stream(self) -> Result { + match self { + Self::Status200(response) => Ok(response), + response => Err(response), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => read_body(body, 64 << 10).await, + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } pub type ImportRunID = std::string::String; @@ -1737,16 +2334,36 @@ pub enum ListClientTeamsResponse { Status403(()), Unexpected(reqwest::Response), } -impl ListClientTeamsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ListClientTeamsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -1765,17 +2382,39 @@ pub enum ListEpisodesResponse { Status404(()), Unexpected(reqwest::Response), } -impl ListEpisodesResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ListEpisodesResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -1792,17 +2431,39 @@ pub enum ListShowMembersResponse { Status404(()), Unexpected(reqwest::Response), } -impl ListShowMembersResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ListShowMembersResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Debug)] @@ -1812,15 +2473,33 @@ pub enum ListShowsResponse { Status401(()), Unexpected(reqwest::Response), } -impl ListShowsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ListShowsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Debug)] @@ -1831,16 +2510,36 @@ pub enum ListTeamMembersResponse { Status403(()), Unexpected(reqwest::Response), } -impl ListTeamMembersResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ListTeamMembersResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } pub type MediaUploadPartNumber = i64; @@ -1860,15 +2559,33 @@ pub enum OpenapiResponse { Status400(ValidationErr), Unexpected(reqwest::Response), } -impl OpenapiResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for OpenapiResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 304 => Self::Status304(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status304(_) => 304, + Self::Status400(_) => 400, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status304(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -1948,16 +2665,36 @@ pub enum PresignEpisodePackagePartsResponse { Status409(()), Unexpected(reqwest::Response), } -impl PresignEpisodePackagePartsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for PresignEpisodePackagePartsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 409 => Self::Status409(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -1984,11 +2721,11 @@ pub enum PresignEpisodeUploadSessionPartsResponse { Status410(()), Unexpected(reqwest::Response), } -impl PresignEpisodeUploadSessionPartsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for PresignEpisodeUploadSessionPartsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 201 => Self::Status201(response.json().await?), - 400 => Self::Status400(response.json().await?), + 201 => Self::Status201(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 402 => Self::Status402(()), 404 => Self::Status404(()), @@ -1997,6 +2734,32 @@ impl PresignEpisodeUploadSessionPartsResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status201(_) => 201, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Status410(_) => 410, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status201(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Status410(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -2298,17 +3061,39 @@ pub enum RemoveShowMemberResponse { Status404(()), Unexpected(reqwest::Response), } -impl RemoveShowMemberResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for RemoveShowMemberResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -2325,17 +3110,39 @@ pub enum RemoveTeamMemberResponse { Status404(()), Unexpected(reqwest::Response), } -impl RemoveTeamMemberResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for RemoveTeamMemberResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -2353,17 +3160,39 @@ pub enum RevokeShowInvitationResponse { Status404(()), Unexpected(reqwest::Response), } -impl RevokeShowInvitationResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for RevokeShowInvitationResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -2380,17 +3209,39 @@ pub enum RevokeTeamInvitationResponse { Status404(()), Unexpected(reqwest::Response), } -impl RevokeTeamInvitationResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for RevokeTeamInvitationResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } pub type SHA256Hex = std::string::String; @@ -2419,11 +3270,11 @@ pub enum SetEpisodeOrderResponse { Status409(()), Unexpected(reqwest::Response), } -impl SetEpisodeOrderResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for SetEpisodeOrderResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 402 => Self::Status402(()), 403 => Self::Status403(()), @@ -2432,6 +3283,32 @@ impl SetEpisodeOrderResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status402(_) => 402, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status402(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -2549,17 +3426,45 @@ pub enum ShowDeletionEventsResponse { Status404(()), Unexpected(reqwest::Response), } -impl ShowDeletionEventsResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for ShowDeletionEventsResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 200 => Self::Status200(response), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + fn into_stream(self) -> Result { + match self { + Self::Status200(response) => Ok(response), + response => Err(response), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => read_body(body, 64 << 10).await, + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -2771,11 +3676,11 @@ pub enum UpdateEpisodeUploadSessionResponse { Status410(()), Unexpected(reqwest::Response), } -impl UpdateEpisodeUploadSessionResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for UpdateEpisodeUploadSessionResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 404 => Self::Status404(()), 409 => Self::Status409(()), @@ -2783,6 +3688,30 @@ impl UpdateEpisodeUploadSessionResponse { _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status404(_) => 404, + Self::Status409(_) => 409, + Self::Status410(_) => 410, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Status409(_) => Ok(Vec::new()), + Self::Status410(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -2801,17 +3730,39 @@ pub enum UpdateShowInvitationRoleResponse { Status404(()), Unexpected(reqwest::Response), } -impl UpdateShowInvitationRoleResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for UpdateShowInvitationRoleResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -2837,17 +3788,39 @@ pub enum UpdateShowMemberRoleResponse { Status404(()), Unexpected(reqwest::Response), } -impl UpdateShowMemberRoleResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for UpdateShowMemberRoleResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug)] @@ -2865,17 +3838,39 @@ pub enum UpdateTeamInvitationRoleResponse { Status404(()), Unexpected(reqwest::Response), } -impl UpdateTeamInvitationRoleResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for UpdateTeamInvitationRoleResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -2900,17 +3895,39 @@ pub enum UpdateTeamMemberRoleResponse { Status404(()), Unexpected(reqwest::Response), } -impl UpdateTeamMemberRoleResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for UpdateTeamMemberRoleResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { 204 => Self::Status204(()), - 400 => Self::Status400(response.json().await?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), 403 => Self::Status403(()), 404 => Self::Status404(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status204(_) => 204, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Status403(_) => 403, + Self::Status404(_) => 404, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status204(_) => Ok(Vec::new()), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Status403(_) => Ok(Vec::new()), + Self::Status404(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } pub type UploadSessionID = std::string::String; @@ -3036,15 +4053,33 @@ pub enum WhoamiResponse { Status401(()), Unexpected(reqwest::Response), } -impl WhoamiResponse { - pub async fn decode(response: reqwest::Response) -> Result { +impl Response for WhoamiResponse { + async fn decode(response: reqwest::Response, _limit: usize) -> Result { Ok(match response.status().as_u16() { - 200 => Self::Status200(response.json().await?), - 400 => Self::Status400(response.json().await?), + 200 => Self::Status200(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), + 400 => Self::Status400(serde_json::from_slice(&read_body(response, _limit).await?).map_err(Error::Decode)?), 401 => Self::Status401(()), _ => Self::Unexpected(response), }) } + fn status(&self) -> u16 { + match self { + Self::Status200(_) => 200, + Self::Status400(_) => 400, + Self::Status401(_) => 401, + Self::Unexpected(response) => response.status().as_u16(), + } + } + async fn into_error(self) -> Error { + let status = self.status(); + let body = match self { + Self::Status200(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status400(body) => serde_json::to_vec(&body).map_err(Error::Decode), + Self::Status401(_) => Ok(Vec::new()), + Self::Unexpected(response) => read_body(response, 64 << 10).await, + }; + match body { Ok(body) => Error::Http { status, body }, Err(error) => error } + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -3105,11 +4140,76 @@ pub enum YouTubeNoneKind { } +/// A declared response is decoded exactly once; unknown and streaming bodies stay unread. +pub trait Response: Sized + Send { + fn decode(response: reqwest::Response, limit: usize) -> impl std::future::Future> + Send; + fn status(&self) -> u16; + fn into_stream(self) -> Result { Err(self) } + /// Convert a response to an error only after the caller chooses not to handle it. + fn into_error(self) -> impl std::future::Future + Send; +} + +#[derive(Debug)] +pub enum Error { + Transport(reqwest_middleware::Error), + Body(reqwest::Error), + Decode(serde_json::Error), + BodyTooLarge { limit: usize }, + Http { status: u16, body: Vec }, +} +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Transport(error) => write!(f, "{error}"), + Self::Body(error) => write!(f, "{error}"), + Self::Decode(error) => write!(f, "decode API response: {error}"), + Self::BodyTooLarge { limit } => write!(f, "HTTP response exceeds {limit} bytes"), + Self::Http { status, body } => write!(f, "HTTP {status}: {}", String::from_utf8_lossy(body)), + } + } +} +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Transport(error) => Some(error), + Self::Body(error) => Some(error), + Self::Decode(error) => Some(error), + _ => None, + } + } +} +impl From for Error { + fn from(error: reqwest_middleware::Error) -> Self { Self::Transport(error.without_url()) } +} +async fn read_body(mut response: reqwest::Response, limit: usize) -> Result, Error> { + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|error| Error::Body(error.without_url()))? { + if chunk.len() > limit.saturating_sub(body.len()) { return Err(Error::BodyTooLarge { limit }); } + body.extend_from_slice(&chunk); + } + Ok(body) +} + +/// Configure application transport policy once, including sending and response reads. +pub trait Transport: Sync { + type Error: From + Send; + fn execute(&self, request: reqwest_middleware::RequestBuilder, limit: usize) + -> impl std::future::Future> + Send; +} +impl Transport for () { + type Error = Error; + async fn execute(&self, request: reqwest_middleware::RequestBuilder, limit: usize) -> Result { + R::decode(request.send().await.map_err(Error::from)?, limit).await + } +} + #[derive(Clone, Debug)] -pub struct Client { +pub struct Client { http: reqwest_middleware::ClientWithMiddleware, base_url: String, bearer_token: Option, + body_limit: usize, + transport: T, } fn encode_path(value: &str) -> String { value.bytes().map(|byte| { @@ -3119,292 +4219,344 @@ fn encode_path(value: &str) -> String { }).collect() } impl Client { - /// Every operation uses this client's middleware when its request is sent. + /// Operations send and decode directly through this client's middleware. pub fn new(http: reqwest_middleware::ClientWithMiddleware, base_url: String, bearer_token: Option) -> Self { - Self { http, base_url: base_url.trim_end_matches('/').to_owned(), bearer_token } + Self { http, base_url: base_url.trim_end_matches('/').to_owned(), bearer_token, body_limit: 4 << 20, transport: () } + } +} +impl Client { + /// Cap buffered JSON and raw bodies for every operation. Streaming and unknown responses stay unread. + pub fn body_limit(mut self, limit: usize) -> Self { self.body_limit = limit; self } + pub fn with_transport(self, transport: U) -> Client { + Client { http: self.http, base_url: self.base_url, bearer_token: self.bearer_token, body_limit: self.body_limit, transport } } - pub fn openapi(&self) -> reqwest_middleware::RequestBuilder { + pub async fn openapi(&self) -> Result { let path = "/".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn head_openapi(&self) -> reqwest_middleware::RequestBuilder { + pub async fn head_openapi(&self) -> Result { let path = "/".to_owned(); let request = self.http.request(reqwest::Method::HEAD, format!("{}{}", self.base_url, path)).header("Accept", "*/*"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_cli_authorization(&self, params: CreateCLIAuthorizationParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_cli_authorization(&self, params: CreateCLIAuthorizationParams) -> Result { let path = "/cli/authorizations".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn cli_authorization_events(&self, params: CliAuthorizationEventsParams) -> reqwest_middleware::RequestBuilder { + pub async fn cli_authorization_events(&self, params: CliAuthorizationEventsParams) -> Result { let path = "/cli/authorizations/{code}/events".to_owned(); let path = path.replace("{code}", &encode_path(¶ms.code.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "text/event-stream"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn episode_deletion_events(&self, params: EpisodeDeletionEventsParams) -> reqwest_middleware::RequestBuilder { + pub async fn episode_deletion_events(&self, params: EpisodeDeletionEventsParams) -> Result { let path = "/s/episode-deletions/{episode_deletion_run_id}/events".to_owned(); let path = path.replace("{episode_deletion_run_id}", &encode_path(¶ms.episode_deletion_run_id.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "text/event-stream"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_episode_package(&self, params: CreateEpisodePackageParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_episode_package(&self, params: CreateEpisodePackageParams) -> Result { let path = "/s/episode-packages".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn cancel_episode_package(&self, params: CancelEpisodePackageParams) -> reqwest_middleware::RequestBuilder { + pub async fn cancel_episode_package(&self, params: CancelEpisodePackageParams) -> Result { let path = "/s/episode-packages/{upload_session_id}".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn complete_episode_package(&self, params: CompleteEpisodePackageParams) -> reqwest_middleware::RequestBuilder { + pub async fn complete_episode_package(&self, params: CompleteEpisodePackageParams) -> Result { let path = "/s/episode-packages/{upload_session_id}/complete".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn presign_episode_package_parts(&self, params: PresignEpisodePackagePartsParams) -> reqwest_middleware::RequestBuilder { + pub async fn presign_episode_package_parts(&self, params: PresignEpisodePackagePartsParams) -> Result { let path = "/s/episode-packages/{upload_session_id}/objects/{object_index}/parts".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let path = path.replace("{object_index}", &encode_path(¶ms.object_index.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn create_episode_upload_session(&self, params: CreateEpisodeUploadSessionParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_episode_upload_session(&self, params: CreateEpisodeUploadSessionParams) -> Result { let path = "/s/episode-upload-sessions".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn get_episode_upload_session(&self, params: GetEpisodeUploadSessionParams) -> reqwest_middleware::RequestBuilder { + pub async fn get_episode_upload_session(&self, params: GetEpisodeUploadSessionParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn update_episode_upload_session(&self, params: UpdateEpisodeUploadSessionParams) -> reqwest_middleware::RequestBuilder { + pub async fn update_episode_upload_session(&self, params: UpdateEpisodeUploadSessionParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn cancel_episode_upload_session(&self, params: CancelEpisodeUploadSessionParams) -> reqwest_middleware::RequestBuilder { + pub async fn cancel_episode_upload_session(&self, params: CancelEpisodeUploadSessionParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn complete_episode_upload_session(&self, params: CompleteEpisodeUploadSessionParams) -> reqwest_middleware::RequestBuilder { + pub async fn complete_episode_upload_session(&self, params: CompleteEpisodeUploadSessionParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}/complete".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn episode_upload_session_events(&self, params: EpisodeUploadSessionEventsParams) -> reqwest_middleware::RequestBuilder { + pub async fn episode_upload_session_events(&self, params: EpisodeUploadSessionEventsParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}/events".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "text/event-stream"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn presign_episode_upload_session_parts(&self, params: PresignEpisodeUploadSessionPartsParams) -> reqwest_middleware::RequestBuilder { + pub async fn presign_episode_upload_session_parts(&self, params: PresignEpisodeUploadSessionPartsParams) -> Result { let path = "/s/episode-upload-sessions/{upload_session_id}/parts/presign".to_owned(); let path = path.replace("{upload_session_id}", &encode_path(¶ms.upload_session_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn create_episode_deletion(&self, params: CreateEpisodeDeletionParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_episode_deletion(&self, params: CreateEpisodeDeletionParams) -> Result { let path = "/s/episodes/{episode_id}/deletions".to_owned(); let path = path.replace("{episode_id}", &encode_path(¶ms.episode_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_image_upload_presign(&self, params: CreateImageUploadPresignParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_image_upload_presign(&self, params: CreateImageUploadPresignParams) -> Result { let path = "/s/image-uploads/presign".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn complete_image_upload(&self, params: CompleteImageUploadParams) -> reqwest_middleware::RequestBuilder { + pub async fn complete_image_upload(&self, params: CompleteImageUploadParams) -> Result { let path = "/s/image-uploads/{image_asset_id}/complete".to_owned(); let path = path.replace("{image_asset_id}", &encode_path(¶ms.image_asset_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn get_import_capacity(&self) -> reqwest_middleware::RequestBuilder { + pub async fn get_import_capacity(&self) -> Result { let path = "/s/import-capacity".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn import_rss(&self, params: ImportRSSParams) -> reqwest_middleware::RequestBuilder { + pub async fn import_rss(&self, params: ImportRSSParams) -> Result { let path = "/s/rss-imports".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn import_rss_run_events(&self, params: ImportRSSRunEventsParams) -> reqwest_middleware::RequestBuilder { + pub async fn import_rss_run_events(&self, params: ImportRSSRunEventsParams) -> Result { let path = "/s/rss-imports/{import_run_id}/events".to_owned(); let path = path.replace("{import_run_id}", &encode_path(¶ms.import_run_id.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "text/event-stream"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn show_deletion_events(&self, params: ShowDeletionEventsParams) -> reqwest_middleware::RequestBuilder { + pub async fn show_deletion_events(&self, params: ShowDeletionEventsParams) -> Result { let path = "/s/show-deletions/{show_deletion_run_id}/events".to_owned(); let path = path.replace("{show_deletion_run_id}", &encode_path(¶ms.show_deletion_run_id.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "text/event-stream"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn list_shows(&self) -> reqwest_middleware::RequestBuilder { + pub async fn list_shows(&self) -> Result { let path = "/s/shows".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_show(&self, params: CreateShowParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_show(&self, params: CreateShowParams) -> Result { let path = "/s/shows".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn create_show_deletion(&self, params: CreateShowDeletionParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_show_deletion(&self, params: CreateShowDeletionParams) -> Result { let path = "/s/shows/{show_slug}/deletions".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn get_episode_order(&self, params: GetEpisodeOrderParams) -> reqwest_middleware::RequestBuilder { + pub async fn get_episode_order(&self, params: GetEpisodeOrderParams) -> Result { let path = "/s/shows/{show_slug}/episode-order".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn set_episode_order(&self, params: SetEpisodeOrderParams) -> reqwest_middleware::RequestBuilder { + pub async fn set_episode_order(&self, params: SetEpisodeOrderParams) -> Result { let path = "/s/shows/{show_slug}/episode-order".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn list_episodes(&self, params: ListEpisodesParams) -> reqwest_middleware::RequestBuilder { + pub async fn list_episodes(&self, params: ListEpisodesParams) -> Result { let path = "/s/shows/{show_slug}/episodes".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; let request = match params.limit { Some(value) => request.query(&[("limit", value)]), None => request }; - match params.cursor { Some(value) => request.query(&[("cursor", value)]), None => request } + let request = match params.cursor { Some(value) => request.query(&[("cursor", value)]), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_show_invitation(&self, params: CreateShowInvitationParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_show_invitation(&self, params: CreateShowInvitationParams) -> Result { let path = "/s/shows/{show_slug}/invitations".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn update_show_invitation_role(&self, params: UpdateShowInvitationRoleParams) -> reqwest_middleware::RequestBuilder { + pub async fn update_show_invitation_role(&self, params: UpdateShowInvitationRoleParams) -> Result { let path = "/s/shows/{show_slug}/invitations/{invitation_id}".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let path = path.replace("{invitation_id}", &encode_path(¶ms.invitation_id.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn revoke_show_invitation(&self, params: RevokeShowInvitationParams) -> reqwest_middleware::RequestBuilder { + pub async fn revoke_show_invitation(&self, params: RevokeShowInvitationParams) -> Result { let path = "/s/shows/{show_slug}/invitations/{invitation_id}".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let path = path.replace("{invitation_id}", &encode_path(¶ms.invitation_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn list_show_members(&self, params: ListShowMembersParams) -> reqwest_middleware::RequestBuilder { + pub async fn list_show_members(&self, params: ListShowMembersParams) -> Result { let path = "/s/shows/{show_slug}/members".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn update_show_member_role(&self, params: UpdateShowMemberRoleParams) -> reqwest_middleware::RequestBuilder { + pub async fn update_show_member_role(&self, params: UpdateShowMemberRoleParams) -> Result { let path = "/s/shows/{show_slug}/members/{user_id}".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let path = path.replace("{user_id}", &encode_path(¶ms.user_id.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn remove_show_member(&self, params: RemoveShowMemberParams) -> reqwest_middleware::RequestBuilder { + pub async fn remove_show_member(&self, params: RemoveShowMemberParams) -> Result { let path = "/s/shows/{show_slug}/members/{user_id}".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let path = path.replace("{user_id}", &encode_path(¶ms.user_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn get_sync_inventory(&self, params: GetSyncInventoryParams) -> reqwest_middleware::RequestBuilder { + pub async fn get_sync_inventory(&self, params: GetSyncInventoryParams) -> Result { let path = "/s/shows/{show_slug}/sync".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; let request = match params.cursor { Some(value) => request.query(&[("cursor", value)]), None => request }; - match params.limit { Some(value) => request.query(&[("limit", value)]), None => request } + let request = match params.limit { Some(value) => request.query(&[("limit", value)]), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_sync_episode_deletion(&self, params: CreateSyncEpisodeDeletionParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_sync_episode_deletion(&self, params: CreateSyncEpisodeDeletionParams) -> Result { let path = "/s/shows/{show_slug}/sync/episodes/{episode_id}/deletion".to_owned(); let path = path.replace("{show_slug}", &encode_path(¶ms.show_slug.to_string())); let path = path.replace("{episode_id}", &encode_path(¶ms.episode_id.to_string())); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn create_team_invitation(&self, params: CreateTeamInvitationParams) -> reqwest_middleware::RequestBuilder { + pub async fn create_team_invitation(&self, params: CreateTeamInvitationParams) -> Result { let path = "/s/team/invitations".to_owned(); let request = self.http.request(reqwest::Method::POST, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn update_team_invitation_role(&self, params: UpdateTeamInvitationRoleParams) -> reqwest_middleware::RequestBuilder { + pub async fn update_team_invitation_role(&self, params: UpdateTeamInvitationRoleParams) -> Result { let path = "/s/team/invitations/{invitation_id}".to_owned(); let path = path.replace("{invitation_id}", &encode_path(¶ms.invitation_id.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn revoke_team_invitation(&self, params: RevokeTeamInvitationParams) -> reqwest_middleware::RequestBuilder { + pub async fn revoke_team_invitation(&self, params: RevokeTeamInvitationParams) -> Result { let path = "/s/team/invitations/{invitation_id}".to_owned(); let path = path.replace("{invitation_id}", &encode_path(¶ms.invitation_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn list_team_members(&self) -> reqwest_middleware::RequestBuilder { + pub async fn list_team_members(&self) -> Result { let path = "/s/team/members".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn update_team_member_role(&self, params: UpdateTeamMemberRoleParams) -> reqwest_middleware::RequestBuilder { + pub async fn update_team_member_role(&self, params: UpdateTeamMemberRoleParams) -> Result { let path = "/s/team/members/{user_id}".to_owned(); let path = path.replace("{user_id}", &encode_path(¶ms.user_id.to_string())); let request = self.http.request(reqwest::Method::PUT, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; - request.json(¶ms.body) + let request = request.json(¶ms.body); + self.transport.execute(request, self.body_limit).await } - pub fn remove_team_member(&self, params: RemoveTeamMemberParams) -> reqwest_middleware::RequestBuilder { + pub async fn remove_team_member(&self, params: RemoveTeamMemberParams) -> Result { let path = "/s/team/members/{user_id}".to_owned(); let path = path.replace("{user_id}", &encode_path(¶ms.user_id.to_string())); let request = self.http.request(reqwest::Method::DELETE, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn list_client_teams(&self) -> reqwest_middleware::RequestBuilder { + pub async fn list_client_teams(&self) -> Result { let path = "/s/teams".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } - pub fn whoami(&self) -> reqwest_middleware::RequestBuilder { + pub async fn whoami(&self) -> Result { let path = "/s/whoami".to_owned(); let request = self.http.request(reqwest::Method::GET, format!("{}{}", self.base_url, path)).header("Accept", "application/json"); - match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request } + let request = match &self.bearer_token { Some(token) => request.bearer_auth(token), None => request }; + self.transport.execute(request, self.body_limit).await } } diff --git a/crates/sync-engine/src/sync.rs b/crates/sync-engine/src/sync.rs index 6da1473..7259add 100644 --- a/crates/sync-engine/src/sync.rs +++ b/crates/sync-engine/src/sync.rs @@ -51,17 +51,19 @@ pub async fn inventory(api: &Api, slug: &str) -> Result { let mut cursors = HashSet::new(); let mut complete: Option = None; loop { - let result = api - .json( - api.client().get_sync_inventory(p::GetSyncInventoryParams { - show_slug: slug.into(), - cursor, - limit: Some(500), - }), - &[200], - ) - .await?; - let mut page: p::SyncInventory = serde_json::from_value(result)?; + let result = match api + .client() + .get_sync_inventory(p::GetSyncInventoryParams { + show_slug: slug.into(), + cursor, + limit: Some(500), + }) + .await? + { + p::GetSyncInventoryResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; + let mut page = result; ensure!( page.show.slug == slug, "Sync inventory returned a different show" @@ -399,35 +401,40 @@ impl Engine { } pub async fn set_order(api: &Api, slug: &str, episode_ids: Vec) -> Result { - Ok(serde_json::from_value( - api.json( - api.client().set_episode_order(p::SetEpisodeOrderParams { + Ok( + match api + .client() + .set_episode_order(p::SetEpisodeOrderParams { show_slug: slug.into(), body: p::SetEpisodeOrder { episode_ids }, - }), - &[200], - ) - .await?, - )?) + }) + .await? + { + p::SetEpisodeOrderResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }, + ) } async fn delete(api: &Api, slug: &str, episode: &str) -> Result<()> { - let result = api - .json( - api.client() - .create_sync_episode_deletion(p::CreateSyncEpisodeDeletionParams { - show_slug: slug.into(), - episode_id: episode.into(), - }), - &[202], - ) - .await?; + let result = match api + .client() + .create_sync_episode_deletion(p::CreateSyncEpisodeDeletionParams { + show_slug: slug.into(), + episode_id: episode.into(), + }) + .await? + { + p::CreateSyncEpisodeDeletionResponse::Status202(value) => value, + response => return Err(api.response_error(response).await), + }; let mut events = Events::open( api, api.client() .episode_deletion_events(p::EpisodeDeletionEventsParams { - episode_deletion_run_id: string(&result, "episode_deletion_run_id")?.into(), - }), + episode_deletion_run_id: result.episode_deletion_run_id, + }) + .await?, ) .await?; loop { diff --git a/crates/sync-engine/src/youtube.rs b/crates/sync-engine/src/youtube.rs index 4ca9ddd..49e502a 100644 --- a/crates/sync-engine/src/youtube.rs +++ b/crates/sync-engine/src/youtube.rs @@ -1,5 +1,5 @@ use crate::{ - api::{Api, PaymentRequired, string}, + api::{Api, PaymentRequired}, download::download, innertube::{Playback, PlaylistSnapshot, Video, YouTube}, publicapi as p, @@ -78,14 +78,18 @@ pub async fn import( ) }); let slug = crate::slug(&slug).map_err(anyhow::Error::msg)?; - let shows: Vec = - serde_json::from_value(api.json(api.client().list_shows(), &[200]).await?)?; + let shows: Vec = match api.client().list_shows().await? { + p::ListShowsResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; ensure!( !shows.iter().any(|show| show.slug == slug), "Podcast {slug:?} already exists. Use sync to resume an imported podcast, or choose a new slug." ); - let capacity: p::ImportCapacity = - serde_json::from_value(api.json(api.client().get_import_capacity(), &[200]).await?)?; + let capacity: p::ImportCapacity = match api.client().get_import_capacity().await? { + p::GetImportCapacityResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; if !capacity.has_active_subscription { return Err(PaymentRequired( "A paid podcast plan is required for YouTube imports. Choose a plan, then try again." @@ -158,13 +162,16 @@ pub async fn import( capacity.video_remaining_seconds as f64 / 3600.0, )).into()); } - let show: p::Show = serde_json::from_value(api.json(api.client().create_show(p::CreateShowParams { + let show = match api.client().create_show(p::CreateShowParams { body: p::CreateShow { id: format!("shw_{}", &uuid::Uuid::new_v4().simple().to_string()[..16]), title, slug: slug.clone(), source_kind: kind.clone(), language: "en".into(), image_asset_id: None, youtube_source_url: Some(canonical.clone()), }, - }), &[201]).await.with_context(|| format!("Create podcast {slug:?}. If creation completed but its reply was lost, reload your podcasts and resume with sync."))?)?; + }).await.with_context(|| format!("Create podcast {slug:?}. If creation completed but its reply was lost, reload your podcasts and resume with sync."))? { + p::CreateShowResponse::Status201(show) => show, + response => return Err(api.response_error(response).await).with_context(|| format!("Create podcast {slug:?}. If creation completed but its reply was lost, reload your podcasts and resume with sync.")), + }; created(&show); let report = async { let snapshot = match listing { @@ -323,17 +330,15 @@ pub(crate) async fn import_video( transfer.phase(crate::downloads::Phase::Uploading); } let response = api - .send( - api.client() - .create_episode_package(p::CreateEpisodePackageParams { - body: manifest.clone(), - }), - ) + .client() + .create_episode_package(p::CreateEpisodePackageParams { + body: manifest.clone(), + }) .await?; - if response.status() != reqwest::StatusCode::CREATED { - return Err(api.response_error(response).await); - } - let session: p::EpisodePackage = api.decode(response).await?; + let session = match response { + p::CreateEpisodePackageResponse::Status201(session) => session, + response => return Err(api.response_error(response).await), + }; if session.status == p::EpisodePackageStatus::Completed { journal.forget(&api.config.api_origin, slug, &source_url)?; return Ok(ImportOutcome::Published); @@ -342,6 +347,10 @@ pub(crate) async fn import_video( let result: Result<()> = async { ensure!(session.part_size >= 5 << 20, "invalid package part size"); for (ordinal, object) in objects.iter().enumerate() { + let initial = session + .uploads + .iter() + .find(|upload| upload.object_index == ordinal as i64); let mut offset = 0; let mut number = 1; while offset < object.byte_length { @@ -351,28 +360,32 @@ pub(crate) async fn import_video( number += 1; continue; } - let signed = api - .json( - api.client().presign_episode_package_parts( - p::PresignEpisodePackagePartsParams { - upload_session_id: session.upload_session_id.clone(), - object_index: ordinal as i64, - body: p::PresignEpisodeUploadSessionParts { - part_numbers: vec![number], - }, + let parts = if number == 1 + && let Some(initial) = initial + { + initial.parts.clone() + } else { + let signed: p::PresignedEpisodeUploadParts = match api + .client() + .presign_episode_package_parts(p::PresignEpisodePackagePartsParams { + upload_session_id: session.upload_session_id.clone(), + object_index: ordinal as i64, + body: p::PresignEpisodeUploadSessionParts { + part_numbers: vec![number], }, - ), - &[200], - ) - .await?; - let parts = signed["parts"] - .as_array() - .context("missing package signed parts")?; + }) + .await? + { + p::PresignEpisodePackagePartsResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; + signed.parts + }; if parts.is_empty() { break; } ensure!( - parts.len() == 1 && parts[0]["part_number"] == number, + parts.len() == 1 && parts[0].part_number == number, "invalid signed package part" ); let length = session.part_size.min(object.byte_length - offset); @@ -382,7 +395,7 @@ pub(crate) async fn import_video( offset as u64, length as u64, "PUT", - string(&parts[0], "upload_url")?, + &parts[0].upload_url, ) .await?; journal.save_part(&manifest.operation_id, ordinal, number)?; @@ -390,17 +403,18 @@ pub(crate) async fn import_video( number += 1; } } - let completed = api - .json( - api.client() - .complete_episode_package(p::CompleteEpisodePackageParams { - upload_session_id: session.upload_session_id.clone(), - }), - &[200], - ) - .await?; + let completed = match api + .client() + .complete_episode_package(p::CompleteEpisodePackageParams { + upload_session_id: session.upload_session_id.clone(), + }) + .await? + { + p::CompleteEpisodePackageResponse::Status200(value) => value, + response => return Err(api.response_error(response).await), + }; ensure!( - string(&completed, "status")? == "completed", + completed.status == p::EpisodePackageStatus::Completed, "prepared media did not complete" ); Ok(())