From 19c582a3cf1c42e9c75170650ccd141eda903479 Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Tue, 9 Feb 2021 18:57:00 -0800 Subject: move source code to top-level directory --- rust/fatcat-cli/Cargo.toml | 55 - rust/fatcat-cli/README.md | 2 - rust/fatcat-cli/binary_size.md | 88 - rust/fatcat-cli/fatcat-cli.1 | 64 - rust/fatcat-cli/fatcat-cli.1.scdoc | 48 - rust/fatcat-cli/plan.txt | 146 - rust/fatcat-cli/src/api.rs | 440 - rust/fatcat-cli/src/commands.rs | 491 - rust/fatcat-cli/src/download.rs | 261 - rust/fatcat-cli/src/entities.rs | 411 - rust/fatcat-cli/src/lib.rs | 93 - rust/fatcat-cli/src/main.rs | 631 - rust/fatcat-cli/src/search.rs | 186 - rust/fatcat-cli/src/specifier.rs | 584 - rust/fatcat-openapi/.cargo/config | 18 - rust/fatcat-openapi/.gitignore | 2 - rust/fatcat-openapi/Cargo.toml | 79 - rust/fatcat-openapi/README.md | 316 - rust/fatcat-openapi/docs/AuthOidc.md | 13 - rust/fatcat-openapi/docs/AuthOidcResult.md | 11 - rust/fatcat-openapi/docs/AuthTokenResult.md | 10 - rust/fatcat-openapi/docs/ChangelogEntry.md | 13 - rust/fatcat-openapi/docs/ContainerAutoBatch.md | 11 - rust/fatcat-openapi/docs/ContainerEntity.md | 20 - rust/fatcat-openapi/docs/CreatorAutoBatch.md | 11 - rust/fatcat-openapi/docs/CreatorEntity.md | 20 - rust/fatcat-openapi/docs/Editgroup.md | 19 - rust/fatcat-openapi/docs/EditgroupAnnotation.md | 16 - rust/fatcat-openapi/docs/EditgroupEdits.md | 16 - rust/fatcat-openapi/docs/Editor.md | 14 - rust/fatcat-openapi/docs/EntityEdit.md | 16 - rust/fatcat-openapi/docs/EntityHistoryEntry.md | 12 - rust/fatcat-openapi/docs/ErrorResponse.md | 12 - rust/fatcat-openapi/docs/FileAutoBatch.md | 11 - rust/fatcat-openapi/docs/FileEntity.md | 23 - rust/fatcat-openapi/docs/FileUrl.md | 11 - rust/fatcat-openapi/docs/FilesetAutoBatch.md | 11 - rust/fatcat-openapi/docs/FilesetEntity.md | 19 - rust/fatcat-openapi/docs/FilesetFile.md | 15 - rust/fatcat-openapi/docs/FilesetUrl.md | 11 - rust/fatcat-openapi/docs/ReleaseAbstract.md | 13 - rust/fatcat-openapi/docs/ReleaseAutoBatch.md | 11 - rust/fatcat-openapi/docs/ReleaseContrib.md | 18 - rust/fatcat-openapi/docs/ReleaseEntity.md | 43 - rust/fatcat-openapi/docs/ReleaseExtIds.md | 22 - rust/fatcat-openapi/docs/ReleaseRef.md | 17 - rust/fatcat-openapi/docs/Success.md | 11 - rust/fatcat-openapi/docs/WebcaptureAutoBatch.md | 11 - rust/fatcat-openapi/docs/WebcaptureCdxLine.md | 17 - rust/fatcat-openapi/docs/WebcaptureEntity.md | 21 - rust/fatcat-openapi/docs/WebcaptureUrl.md | 11 - rust/fatcat-openapi/docs/WorkAutoBatch.md | 11 - rust/fatcat-openapi/docs/WorkEntity.md | 15 - rust/fatcat-openapi/docs/default_api.md | 3019 ---- rust/fatcat-openapi/examples/ca.pem | 17 - rust/fatcat-openapi/examples/client/main.rs | 1148 -- rust/fatcat-openapi/examples/server-chain.pem | 66 - rust/fatcat-openapi/examples/server-key.pem | 28 - rust/fatcat-openapi/examples/server/main.rs | 26 - rust/fatcat-openapi/examples/server/server.rs | 1687 --- rust/fatcat-openapi/src/client/mod.rs | 16107 ---------------------- rust/fatcat-openapi/src/context.rs | 120 - rust/fatcat-openapi/src/header.rs | 197 - rust/fatcat-openapi/src/lib.rs | 3844 ------ rust/fatcat-openapi/src/models.rs | 7621 ---------- rust/fatcat-openapi/src/server/mod.rs | 15856 --------------------- 66 files changed, 54187 deletions(-) delete mode 100644 rust/fatcat-cli/Cargo.toml delete mode 100644 rust/fatcat-cli/README.md delete mode 100644 rust/fatcat-cli/binary_size.md delete mode 100644 rust/fatcat-cli/fatcat-cli.1 delete mode 100644 rust/fatcat-cli/fatcat-cli.1.scdoc delete mode 100644 rust/fatcat-cli/plan.txt delete mode 100644 rust/fatcat-cli/src/api.rs delete mode 100644 rust/fatcat-cli/src/commands.rs delete mode 100644 rust/fatcat-cli/src/download.rs delete mode 100644 rust/fatcat-cli/src/entities.rs delete mode 100644 rust/fatcat-cli/src/lib.rs delete mode 100644 rust/fatcat-cli/src/main.rs delete mode 100644 rust/fatcat-cli/src/search.rs delete mode 100644 rust/fatcat-cli/src/specifier.rs delete mode 100644 rust/fatcat-openapi/.cargo/config delete mode 100644 rust/fatcat-openapi/.gitignore delete mode 100644 rust/fatcat-openapi/Cargo.toml delete mode 100644 rust/fatcat-openapi/README.md delete mode 100644 rust/fatcat-openapi/docs/AuthOidc.md delete mode 100644 rust/fatcat-openapi/docs/AuthOidcResult.md delete mode 100644 rust/fatcat-openapi/docs/AuthTokenResult.md delete mode 100644 rust/fatcat-openapi/docs/ChangelogEntry.md delete mode 100644 rust/fatcat-openapi/docs/ContainerAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/ContainerEntity.md delete mode 100644 rust/fatcat-openapi/docs/CreatorAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/CreatorEntity.md delete mode 100644 rust/fatcat-openapi/docs/Editgroup.md delete mode 100644 rust/fatcat-openapi/docs/EditgroupAnnotation.md delete mode 100644 rust/fatcat-openapi/docs/EditgroupEdits.md delete mode 100644 rust/fatcat-openapi/docs/Editor.md delete mode 100644 rust/fatcat-openapi/docs/EntityEdit.md delete mode 100644 rust/fatcat-openapi/docs/EntityHistoryEntry.md delete mode 100644 rust/fatcat-openapi/docs/ErrorResponse.md delete mode 100644 rust/fatcat-openapi/docs/FileAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/FileEntity.md delete mode 100644 rust/fatcat-openapi/docs/FileUrl.md delete mode 100644 rust/fatcat-openapi/docs/FilesetAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/FilesetEntity.md delete mode 100644 rust/fatcat-openapi/docs/FilesetFile.md delete mode 100644 rust/fatcat-openapi/docs/FilesetUrl.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseAbstract.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseContrib.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseEntity.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseExtIds.md delete mode 100644 rust/fatcat-openapi/docs/ReleaseRef.md delete mode 100644 rust/fatcat-openapi/docs/Success.md delete mode 100644 rust/fatcat-openapi/docs/WebcaptureAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/WebcaptureCdxLine.md delete mode 100644 rust/fatcat-openapi/docs/WebcaptureEntity.md delete mode 100644 rust/fatcat-openapi/docs/WebcaptureUrl.md delete mode 100644 rust/fatcat-openapi/docs/WorkAutoBatch.md delete mode 100644 rust/fatcat-openapi/docs/WorkEntity.md delete mode 100644 rust/fatcat-openapi/docs/default_api.md delete mode 100644 rust/fatcat-openapi/examples/ca.pem delete mode 100644 rust/fatcat-openapi/examples/client/main.rs delete mode 100644 rust/fatcat-openapi/examples/server-chain.pem delete mode 100644 rust/fatcat-openapi/examples/server-key.pem delete mode 100644 rust/fatcat-openapi/examples/server/main.rs delete mode 100644 rust/fatcat-openapi/examples/server/server.rs delete mode 100644 rust/fatcat-openapi/src/client/mod.rs delete mode 100644 rust/fatcat-openapi/src/context.rs delete mode 100644 rust/fatcat-openapi/src/header.rs delete mode 100644 rust/fatcat-openapi/src/lib.rs delete mode 100644 rust/fatcat-openapi/src/models.rs delete mode 100644 rust/fatcat-openapi/src/server/mod.rs (limited to 'rust') diff --git a/rust/fatcat-cli/Cargo.toml b/rust/fatcat-cli/Cargo.toml deleted file mode 100644 index dbb114a..0000000 --- a/rust/fatcat-cli/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "fatcat-cli" -version = "0.3.0-dev" -edition = "2018" -authors = ["Bryan Newbold "] -license = "AGPL-3+" -#license-file = "../../LICENSE.AGPLv3.txt" -description = "CLI tool for fatcat.wiki, an open digital catalog of research papers" -readme = "fatcat-cli/README.md" -homepage = "https://fatcat.wiki" -repository = "https://github.com/internetarchive/fatcat" -keywords = ["cli", "fatcat", "digital-library"] -categories = ["command-line-utilities"] - - -[dependencies] -data-encoding = "2.1" -fatcat-openapi = { version = "*", path = "../fatcat-openapi", default-features = false, features = ["client"] } -macaroon = { git = "https://github.com/bnewbold/libmacaroon-rs", branch = "bnewbold-broken" } -toml = "0.5" -termcolor = "1" -atty = "0.2" -tabwriter = "1.2" -#human-panic = "1" -structopt = "0.3" -swagger = "5.0.2" -hyper = "0.13" -tokio = { version = "0.2", features = ["rt-threaded", "macros", "stream"] } -serde_json = "1.0" -anyhow = "1.0" -log = "0.4" -env_logger = "0.7" -regex = { version = "1.3", default-features = false, features = ["perf-literal"] } -lazy_static = "1" -serde = "1.0" -reqwest = { version = "0.10", features = ["blocking", "json"] } -chrono-humanize = "*" -tempfile = "3" -indicatif = "0.15" -url = "*" - - -[dev-dependencies] -assert_cmd = "1" - - -[package.metadata.deb] -maintainer = "Bryan Newbold " -depends = "$auto" -section = "utility" -priority = "optional" -assets = [ - ["target/release/fatcat-cli", "usr/bin/", "755"], - ["fatcat-cli.1", "usr/share/man/man1/", "644"], -] diff --git a/rust/fatcat-cli/README.md b/rust/fatcat-cli/README.md deleted file mode 100644 index 1652d61..0000000 --- a/rust/fatcat-cli/README.md +++ /dev/null @@ -1,2 +0,0 @@ - -`fatcat-cli` README. diff --git a/rust/fatcat-cli/binary_size.md b/rust/fatcat-cli/binary_size.md deleted file mode 100644 index a79cf9b..0000000 --- a/rust/fatcat-cli/binary_size.md +++ /dev/null @@ -1,88 +0,0 @@ - -## Binary Size - -As of 2020-05-24, in early development, the relative binary sizes are: - - 121 MB default debug build - 12 MB default release build - 8.2 MB release build w/ LTO - 6.6 MB release build w/ LTO, striped - -After some small changes: - - 5.9 MB release build w/ LTO, size optimization, other flags - 4.1 MB release build w/ LTO, size optimization, other flags, striped - -Replacing reqwest with minreq: - - 6.3 MB release build w/ LTO, size optimization, other flags - 4.1 MB release build w/ LTO, size optimization, other flags, striped - - (so, not worth it, at least while using fatcat_openapi with hyper+tokio) - -Note that release builds with LTO take *quite* a long time (many minutes). We -probably don't want that to be the defualt for `fatcatd` builds. - - cargo bloat --release --crates - - File .text Size Crate - 12.2% 21.4% 1021.5KiB fatcat_cli - 7.1% 12.5% 596.7KiB fatcat_openapi - 6.3% 11.1% 529.6KiB reqwest - 6.2% 10.9% 518.5KiB std - 3.5% 6.1% 290.3KiB clap - 2.5% 4.3% 205.9KiB regex - 2.4% 4.2% 198.7KiB regex_syntax - 2.1% 3.6% 172.8KiB h2 - 1.9% 3.4% 162.7KiB hyper - 1.8% 3.1% 149.9KiB futures - 1.4% 2.4% 116.9KiB serde_json - 1.3% 2.3% 111.2KiB macaroon - 1.0% 1.8% 85.3KiB unicode_normalization - 0.7% 1.3% 62.4KiB http - 0.6% 1.0% 50.1KiB serde - 0.6% 1.0% 47.5KiB url - 0.5% 0.9% 41.9KiB [Unknown] - 0.4% 0.8% 36.5KiB tokio_reactor - 0.4% 0.7% 31.8KiB env_logger - 0.3% 0.6% 26.6KiB chrono - 3.4% 5.9% 283.3KiB And 57 more crates. Use -n N to show more. - 57.2% 100.0% 4.7MiB .text section size, the file size is 8.2MiB - - - bnewbold@orithena$ cargo bloat --release - Finished release [optimized] target(s) in 0.27s - Analyzing target/release/fatcat-cli - - File .text Size Crate Name - 0.4% 1.0% 53.2KiB regex ::capture... - 0.4% 0.8% 44.1KiB regex_syntax regex_syntax::ast::parse::ParserI

::parse_with_comments - 0.3% 0.7% 36.8KiB unicode_normalization unicode_normalization::tables::compatibility_fully_decomposed - 0.3% 0.6% 30.3KiB unicode_normalization unicode_normalization::tables::canonical_fully_decomposed - 0.2% 0.5% 25.2KiB data_encoding data_encoding::Encoding::decode_mut - 0.2% 0.5% 24.0KiB fatcat_openapi? as serde::de::Deserializer>::deser... - 0.1% 0.3% 16.4KiB fatcat_cli <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 0.1% 0.3% 16.2KiB fatcat_cli <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 0.1% 0.3% 16.1KiB fatcat_cli fatcat_cli::run - 0.1% 0.3% 15.2KiB fatcat_cli <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 0.1% 0.3% 14.3KiB serde_json? <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 0.1% 0.3% 14.2KiB fatcat_cli <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 0.1% 0.3% 14.0KiB regex regex::exec::ExecBuilder::build - 0.1% 0.3% 13.8KiB unicode_normalization unicode_normalization::tables::composition_table - 0.1% 0.3% 13.6KiB fatcat_cli <&mut serde_json::de::Deserializer as serde::de::Deserializer>::deser... - 38.6% 89.5% 4.5MiB And 13832 smaller methods. Use -n N to show more. - 43.1% 100.0% 5.1MiB .text section size, the file size is 11.8MiB - -Low hanging fruit includes: - -- reviewing features for reqwest, clap, regex, fatcat_openapi -- replace reqwest with something smaller -- use `ansi-term` (already part of clap) -- consider removing fancy clap features? meh -- look at graph; probably duplicate versions of things - diff --git a/rust/fatcat-cli/fatcat-cli.1 b/rust/fatcat-cli/fatcat-cli.1 deleted file mode 100644 index 0831773..0000000 --- a/rust/fatcat-cli/fatcat-cli.1 +++ /dev/null @@ -1,64 +0,0 @@ -.\" Generated by scdoc 1.9.0 -.ie \n(.g .ds Aq \(aq -.el .ds Aq ' -.nh -.ad l -.\" Begin generated content: -.TH "fatcat-cli" "1" "2020-06-14" "fatcat.wiki CLI Manual Page" -.P -.SH NAME -.P -fatcat-cli - something something -.P -.SH SYNOPSIS -.P -fatcat-cli [FLAGS] [OPTIONS] -.P -Subcommands: -.P -.RS 4 -create -delete -edit -editgroup -get -help -search -status -update -.P -.RE -.SH DESCRIPTION -.P -.SH OPTIONS -.P -\fB-h, --help\fR -.RS 4 -Prints help information -.P -.RE -\fB-V, --version\fR -.RS 4 -Prints version information -.P -.RE -\fB-v, --verbose\fR -.RS 4 -Pass many times for more log output -By default, it'll only report errors. Passing `-v` one time also prints warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace. -.P -.RE -\fB--api-host \fR [env: FATCAT_API_HOST] [default: https://api.fatcat.wiki] -.P -\fB--api-token \fR [env: FATCAT_API_AUTH_TOKEN] -.P -\fB--search-host \fR [env: FATCAT_SEARCH_HOST] [default: https://search.fatcat.wiki] -.P -.SH EXAMPLES -.P -Some examples of usage will go here, like: -.P -.RS 4 -fatcat-cli get thing -.P -.RE diff --git a/rust/fatcat-cli/fatcat-cli.1.scdoc b/rust/fatcat-cli/fatcat-cli.1.scdoc deleted file mode 100644 index 6a176aa..0000000 --- a/rust/fatcat-cli/fatcat-cli.1.scdoc +++ /dev/null @@ -1,48 +0,0 @@ -fatcat-cli(1) "fatcat.wiki CLI Manual Page" - -# NAME - -fatcat-cli - something something - -# SYNOPSIS - -fatcat-cli [FLAGS] [OPTIONS] - -Subcommands: - - create - delete - edit - editgroup - get - help - search - status - update - -# DESCRIPTION - -# OPTIONS - -*-h, --help* - Prints help information - -*-V, --version* - Prints version information - -*-v, --verbose* - Pass many times for more log output - By default, it'll only report errors. Passing `-v` one time also prints warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace. - -*--api-host * [env: FATCAT_API_HOST] [default: https://api.fatcat.wiki] - -*--api-token * [env: FATCAT_API_AUTH_TOKEN] - -*--search-host * [env: FATCAT_SEARCH_HOST] [default: https://search.fatcat.wiki] - -# EXAMPLES - -Some examples of usage will go here, like: - - fatcat-cli get thing - diff --git a/rust/fatcat-cli/plan.txt b/rust/fatcat-cli/plan.txt deleted file mode 100644 index 651acac..0000000 --- a/rust/fatcat-cli/plan.txt +++ /dev/null @@ -1,146 +0,0 @@ - -x search release, query string, limit, dumping search doc JSON -x search release, query string, limit, fetching API for each -x search release, query string, scroll API, fetching API for each - -x handle stdout terminated - -x editgroup creation - => set agent -x editgroup accept -x editgroup submit -x editgroup list - -x release create from json/TOML, to an editgroup -x release delete, to an editgroup -x release update from full json/TOML to API -x release edit (using $EDITOR, temp file) - -x release update fields and submit to editgroup - => more fields, like 2-5 for all entity types -x expand/hide flags for get, search - -- search/update/etc containers (and files?) - -- polish and test so actually usable for release edits from search - x consider moving to new repo, with copy of fatcat-openapi-client - x manpage - x .deb generation - => write actual manpage (and, HTML output? ronn? pandoc?) - => write actual README - -- implement @-syntax for create/update - => TODO: what was the proposal here? - => some variant of @-syntax for stream of multiple updates/creations? - -- get revisions for all entity types - - -#### Milestones - -- ability (at all) to revise edits for a single entity in editgroup - => clobber existing edits on update - => edits: get entity in current edit state -- streaming updates from search, with either pipe (jq) or field mutations - => syntax/commands - => batching (syntax? subcommand?) - => auto-accept mode -- download many PDFs from search query - => parallelism could be GNU/parallel - => don't clobber existing - -#### Editgroup Workflow - -- editgroup creation outputs just editgroup_id on stdout (unless output type selected), plus "success" to stderr -- parse editgroup specifier - => "auto": fetch from recent; default? - => "new": create - => editgroup_blah or blah -- implement "delete from editgroup" for updates, edit - => no updates with current setup - => fetch editgroup helper - => helper function that takes editgroup (model) and expanded specifier; deletes existing edit from editgroup if necessary - => skip this codepath for "new" and batch creation - -#### File Downloads - -- download single file: - => try archive.org files, then wayback, then original URLs - => download to current directory as {sha1hex}.pdf.partial, then atomic move on success -- optional directory structure: {dir}/{hex}/{hex}/{sha1hex}.pdf -- parallelism of downloads - -#### Backburner - -- -o/--output and -i/--input for format/schema selection (including 'es-json') -- search release, filters, scroll API, fetching API for each - => structopt parses: query, filter, anti-filter -- search release, filters, scroll API, fetching API for each, verifying revision and filters for each - -## Design Decisions - -- batch/multi behavior for mutations - => need some option to do auto-accept batches -- updates and create, from-file vs. args - => basically, could be any of specifier, input_file, mutations supplied on command-line - => could use httpie @file.blah syntax to load entire file - => "edit" as an option for reading single files from disk? meh - proposal: - create - either reads a file from path/stdin, or has mutation args - optionally --new-editgroup - create-multi - reads multiple JSON from file or stdin - optionally --auto-batch in chunks - optionally --new-editgroup - update - takes a specifier - either reads a file from path/stdin, or has mutation args - update-multi - reads multiple JSON from file or stdin - creates new editgroup? - edit - delete - delete-multi - reads multiple entities from stdin - - --skip-check controls whether to do a GET and validate mutations - => eg, don't update if equal -- holding state about current editgroup - => env var, with helpful output to show how to export - => spawn sub-shell with FATCAT_EDITGROUP set - => state in a config file somewhere (user homedir?) - => "smart" select most recent fatcat-cli editgroup from editor's list -- release revision checking on updates - => could re-fetch and check rev and/or mutations against current before making edit -- delete edit from editgroup - -## Rust refactors - -In rust code, all entity responses could have trait object implementations, -which would transform to either returning the entity (trait object) or error. - -## API refactors - -Could significantly reduce number of response types and endpoints by making -many methods generic (same endpoint URL, but entity type as a keyword): - -- entity history -- delete -- get edit - -Should allow destructive updates in editgroups with "clobber" flag. In -implementation, could either delete first or on conflict do upsert. - -More consistent use of generic success/error? - -## Feature Ideas - -- changelog (table): under editgroup command? -- syntect coloring of output for stdout -- cross build for OS X? homebrew? -- shell (bash) completions from clap -- fcid/UUID helper -- history for all entity types - => pretty table, json optional -- "edit editgroup" as a text file, `git rebase -i` style diff --git a/rust/fatcat-cli/src/api.rs b/rust/fatcat-cli/src/api.rs deleted file mode 100644 index 2463aab..0000000 --- a/rust/fatcat-cli/src/api.rs +++ /dev/null @@ -1,440 +0,0 @@ -use crate::{parse_macaroon_editor_id, EntityType, Specifier}; -use anyhow::{anyhow, Context, Result}; -use fatcat_openapi::models; -use fatcat_openapi::{ApiNoContext, ContextWrapperExt}; -use swagger::{auth, AuthData, ContextBuilder, EmptyContext, Push, XSpanIdString}; - -type FatcatApiContextType = swagger::make_context_ty!( - ContextBuilder, - EmptyContext, - Option, - XSpanIdString -); - -pub struct FatcatApiClient { - pub api: Box>, - pub rt: tokio::runtime::Runtime, - pub api_token: Option, - pub api_host: String, - pub editor_id: Option, -} - -impl FatcatApiClient { - pub fn new(api_host: String, api_token: Option) -> Result { - let auth_data = match api_token { - Some(ref token) => Some(AuthData::Bearer(auth::Bearer { - token: token.clone(), - })), - None => None, - }; - //info!("{:?}", auth_data); - let context: FatcatApiContextType = swagger::make_context!( - ContextBuilder, - EmptyContext, - auth_data, - XSpanIdString::default() - ); - - //let wrapped_client: swagger::ContextWrapper< - let client = fatcat_openapi::client::Client::try_new(&api_host) - .context("failed to create HTTP(S) client")?; - let wrapped_client = Box::new(client.with_context(context)); - let rt: tokio::runtime::Runtime = - tokio::runtime::Runtime::new().expect("create tokio runtime"); - - let editor_id = match api_token { - Some(ref token) => { - Some(parse_macaroon_editor_id(token).context("parse API auth token")?) - } - None => None, - }; - - Ok(FatcatApiClient { - api: wrapped_client, - rt, - api_token, - editor_id, - api_host, - }) - } - - pub fn update_editgroup_submit( - &mut self, - editgroup_id: String, - submit: bool, - ) -> Result { - let result = self - .rt - .block_on(self.api.get_editgroup(editgroup_id.clone())) - .context("fetch editgroups")?; - let eg = match result { - fatcat_openapi::GetEditgroupResponse::Found(eg) => eg, - other => { - return Err(anyhow!("{:?}", other)) - .with_context(|| format!("failed to fetch editgroup {}", editgroup_id)) - } - }; - let result = self - .rt - .block_on( - self.api - .update_editgroup(editgroup_id.clone(), eg, Some(submit)), - ) - .context("submit editgroup")?; - match result { - fatcat_openapi::UpdateEditgroupResponse::UpdatedEditgroup(eg) => Ok(eg), - other => Err(anyhow!("{:?}", other)) - .with_context(|| format!("failed to submit editgroup {}", editgroup_id)), - } - } - - pub fn delete_entity( - &mut self, - specifier: Specifier, - editgroup_id: String, - ) -> Result { - use Specifier::*; - let specifier = specifier.into_entity_specifier(self)?; - match specifier.clone() { - Release(fcid) => match self - .rt - .block_on(self.api.delete_release(editgroup_id, fcid))? - { - fatcat_openapi::DeleteReleaseResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Work(fcid) => match self.rt.block_on(self.api.delete_work(editgroup_id, fcid))? { - fatcat_openapi::DeleteWorkResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Container(fcid) => match self - .rt - .block_on(self.api.delete_container(editgroup_id, fcid))? - { - fatcat_openapi::DeleteContainerResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Creator(fcid) => match self - .rt - .block_on(self.api.delete_creator(editgroup_id, fcid))? - { - fatcat_openapi::DeleteCreatorResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - File(fcid) => match self.rt.block_on(self.api.delete_file(editgroup_id, fcid))? { - fatcat_openapi::DeleteFileResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - FileSet(fcid) => match self - .rt - .block_on(self.api.delete_fileset(editgroup_id, fcid))? - { - fatcat_openapi::DeleteFilesetResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - WebCapture(fcid) => match self - .rt - .block_on(self.api.delete_webcapture(editgroup_id, fcid))? - { - fatcat_openapi::DeleteWebcaptureResponse::DeletedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Editgroup(..) | Editor(..) => unimplemented!("deletion for this entity type"), - Changelog(..) => return Err(anyhow!("mutating this entity type doesn't make sense")), - EditorUsername(..) | ReleaseLookup(..) | ContainerLookup(..) | FileLookup(..) - | CreatorLookup(..) => return Err(anyhow!("into_entity_specifier() didn't work?")), - } - .with_context(|| format!("failed to delete {:?}", specifier)) - } - - pub fn create_entity_from_json( - &mut self, - entity_type: EntityType, - json_str: &str, - editgroup_id: String, - ) -> Result { - match entity_type { - EntityType::Release => { - match self.rt.block_on( - self.api - .create_release(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateReleaseResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::Work => { - match self.rt.block_on( - self.api - .create_work(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateWorkResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::Creator => { - match self.rt.block_on( - self.api - .create_creator(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateCreatorResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::Container => { - match self.rt.block_on( - self.api - .create_container(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateContainerResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::File => { - match self.rt.block_on( - self.api - .create_file(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateFileResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::FileSet => { - match self.rt.block_on( - self.api - .create_fileset(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateFilesetResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - EntityType::WebCapture => { - match self.rt.block_on( - self.api - .create_webcapture(editgroup_id, serde_json::from_str(&json_str)?), - )? { - fatcat_openapi::CreateWebcaptureResponse::CreatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - } - } - } - .with_context(|| format!("parsing and creating {:?} entity", entity_type)) - } - - pub fn existing_edit_in_editgroup( - &mut self, - editgroup: &models::Editgroup, - specifier: &Specifier, - ) -> Option { - use Specifier::*; - let (fcid, edit_list) = match specifier.clone() { - Release(fcid) => (fcid, editgroup.edits.as_ref().unwrap().releases.clone()), - Work(fcid) => (fcid, editgroup.edits.as_ref().unwrap().works.clone()), - Container(fcid) => (fcid, editgroup.edits.as_ref().unwrap().containers.clone()), - Creator(fcid) => (fcid, editgroup.edits.as_ref().unwrap().creators.clone()), - File(fcid) => (fcid, editgroup.edits.as_ref().unwrap().files.clone()), - FileSet(fcid) => (fcid, editgroup.edits.as_ref().unwrap().filesets.clone()), - WebCapture(fcid) => (fcid, editgroup.edits.as_ref().unwrap().webcaptures.clone()), - EditorUsername(..) | ReleaseLookup(..) | ContainerLookup(..) | FileLookup(..) - | CreatorLookup(..) | Editgroup(..) | Editor(..) | Changelog(..) => { - panic!("this entity type doesn't exist in editgroups") - } - }; - for entity_edit in edit_list.unwrap() { - if entity_edit.ident == fcid { - return Some(entity_edit); - } - } - None - } - - pub fn delete_editgroup_edit( - &mut self, - editgroup: &models::Editgroup, - specifier: &Specifier, - edit: &models::EntityEdit, - ) -> Result<()> { - use Specifier::*; - let editgroup_id = editgroup.editgroup_id.clone().unwrap(); - let edit_id = edit.edit_id.clone(); - match specifier.clone() { - Release(..) => match self - .rt - .block_on(self.api.delete_release_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteReleaseEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - Work(..) => match self - .rt - .block_on(self.api.delete_work_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteWorkEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - Container(..) => match self - .rt - .block_on(self.api.delete_container_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteContainerEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - Creator(..) => match self - .rt - .block_on(self.api.delete_creator_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteCreatorEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - File(..) => match self - .rt - .block_on(self.api.delete_file_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteFileEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - FileSet(..) => match self - .rt - .block_on(self.api.delete_fileset_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteFilesetEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - WebCapture(..) => match self - .rt - .block_on(self.api.delete_webcapture_edit(editgroup_id, edit_id))? - { - fatcat_openapi::DeleteWebcaptureEditResponse::DeletedEdit(..) => Ok(()), - other => Err(anyhow!("{:?}", other)), - }, - EditorUsername(..) | ReleaseLookup(..) | ContainerLookup(..) | FileLookup(..) - | CreatorLookup(..) | Editgroup(..) | Editor(..) | Changelog(..) => { - panic!("this entity type doesn't exist in editgroups") - } - } - } - - pub fn update_entity_from_json( - &mut self, - specifier: Specifier, - json_str: &str, - editgroup_id: String, - ) -> Result { - use Specifier::*; - let specifier = specifier.into_entity_specifier(self)?; - let eg = match self - .rt - .block_on(self.api.get_editgroup(editgroup_id.clone()))? - { - fatcat_openapi::GetEditgroupResponse::Found(model) => Ok(model), - fatcat_openapi::GetEditgroupResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetEditgroupResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: editgroup_{:?}", editgroup_id)), - }?; - if let Some(entity_edit) = self.existing_edit_in_editgroup(&eg, &specifier) { - self.delete_editgroup_edit(&eg, &specifier, &entity_edit)?; - }; - match specifier.clone() { - Release(fcid) => match self.rt.block_on(self.api.update_release( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateReleaseResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Work(fcid) => match self.rt.block_on(self.api.update_work( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateWorkResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Container(fcid) => match self.rt.block_on(self.api.update_container( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateContainerResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Creator(fcid) => match self.rt.block_on(self.api.update_creator( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateCreatorResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - File(fcid) => match self.rt.block_on(self.api.update_file( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateFileResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - FileSet(fcid) => match self.rt.block_on(self.api.update_fileset( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateFilesetResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - WebCapture(fcid) => match self.rt.block_on(self.api.update_webcapture( - editgroup_id, - fcid, - serde_json::from_str(&json_str)?, - ))? { - fatcat_openapi::UpdateWebcaptureResponse::UpdatedEntity(ee) => Ok(ee), - other => Err(anyhow!("{:?}", other)), - }, - Editgroup(..) | Editor(..) => unimplemented!("updates for this entity type"), - Changelog(..) => return Err(anyhow!("deleting this entity type doesn't make sense")), - EditorUsername(..) | ReleaseLookup(..) | ContainerLookup(..) | FileLookup(..) - | CreatorLookup(..) => return Err(anyhow!("into_entity_specifier() didn't work?")), - } - .with_context(|| format!("failed to update {:?}", specifier)) - } - - pub fn create_editgroup(&mut self, description: Option) -> Result { - let mut eg = models::Editgroup::new(); - eg.description = description; - eg.extra = Some({ - let mut extra = std::collections::HashMap::new(); - extra.insert( - "agent".to_string(), - serde_json::Value::String("fatcat-cli".to_string()), - // TODO: version? - ); - extra - }); - let result = self.rt.block_on(self.api.create_editgroup(eg))?; - match result { - fatcat_openapi::CreateEditgroupResponse::SuccessfullyCreated(eg) => Ok(eg), - other => Err(anyhow!("{:?}", other)).context("failed to create editgroup"), - } - } - - pub fn accept_editgroup(&mut self, editgroup_id: String) -> Result { - let result = self - .rt - .block_on(self.api.accept_editgroup(editgroup_id.clone())) - .context("accept editgroup")?; - match result { - fatcat_openapi::AcceptEditgroupResponse::MergedSuccessfully(msg) => Ok(msg), - other => Err(anyhow!( - "failed to accept editgroup {}: {:?}", - editgroup_id, - other - )), - } - } -} diff --git a/rust/fatcat-cli/src/commands.rs b/rust/fatcat-cli/src/commands.rs deleted file mode 100644 index 15bfc81..0000000 --- a/rust/fatcat-cli/src/commands.rs +++ /dev/null @@ -1,491 +0,0 @@ -use anyhow::{anyhow, Context, Result}; -use chrono_humanize::HumanTime; -use fatcat_openapi::models; -#[allow(unused_imports)] -use log::{self, debug, info}; -use std::convert::TryInto; -use std::fs::File; -use std::io::{self, BufRead, Write}; -use std::path::PathBuf; -use tabwriter::TabWriter; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; - -use crate::{ - entity_model_from_json_str, read_entity_file, ApiModelSer, EntityType, FatcatApiClient, - Mutation, Specifier, -}; - -// Want to show: -// - whether api_token found -// - configured api_host we are connecting to -// - whether we can connect to remote host (eg, get most recent changelog) -// - whether our auth is valid -// - current active editgroup -#[derive(Debug, PartialEq, Clone, serde::Serialize)] -pub struct ClientStatus { - pub has_api_token: bool, - pub api_host: String, - pub last_changelog: Option, - pub account: Option, -} - -impl ClientStatus { - pub fn generate(api_client: &mut FatcatApiClient) -> Result { - let last_changelog = match api_client - .rt - .block_on(api_client.api.get_changelog(Some(1))) - { - Ok(fatcat_openapi::GetChangelogResponse::Success(entry_vec)) => { - Some(entry_vec[0].index) - } - Ok(_) | Err(_) => None, - }; - let has_api_token = api_client.api_token.is_some(); - let account: Option = if has_api_token && last_changelog.is_some() { - match api_client - .rt - .block_on(api_client.api.auth_check(None)) - .context("check auth token")? - { - fatcat_openapi::AuthCheckResponse::Success(_) => Ok(()), - fatcat_openapi::AuthCheckResponse::Forbidden(err) => { - Err(anyhow!("Forbidden ({}): {}", err.error, err.message)) - } - fatcat_openapi::AuthCheckResponse::NotAuthorized { body: err, .. } => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - resp => return Err(anyhow!("{:?}", resp)).context("auth check failed"), - } - .context("check auth token")?; - match api_client - .rt - .block_on( - api_client - .api - .get_editor(api_client.editor_id.as_ref().unwrap().to_string()), - ) - .context("fetching editor account info")? - { - fatcat_openapi::GetEditorResponse::Found(editor) => Some(editor), - fatcat_openapi::GetEditorResponse::NotFound(err) => { - return Err(anyhow!("Not Found: {}", err.message)) - } - resp => return Err(anyhow!("{:?}", resp)).context("editor fetch failed"), - } - } else { - None - }; - Ok(ClientStatus { - api_host: api_client.api_host.clone(), - has_api_token, - last_changelog, - account, - }) - } - - pub fn pretty_print(self) -> Result<()> { - let mut color_stdout = StandardStream::stdout(if atty::is(atty::Stream::Stdout) { - ColorChoice::Auto - } else { - ColorChoice::Never - }); - let color_normal = ColorSpec::new(); - let mut color_bold = ColorSpec::new(); - color_bold.set_bold(true); - let mut color_happy = ColorSpec::new(); - color_happy.set_fg(Some(Color::Green)).set_bold(true); - let mut color_sad = ColorSpec::new(); - color_sad.set_fg(Some(Color::Red)).set_bold(true); - - color_stdout.set_color(&color_normal)?; - write!(&mut color_stdout, "{:>16}: ", "API host")?; - color_stdout.set_color(&color_bold)?; - write!(&mut color_stdout, "{}", self.api_host)?; - match self.last_changelog { - Some(index) => { - color_stdout.set_color(&color_happy)?; - writeln!(&mut color_stdout, " [successfully connected]")?; - color_stdout.set_color(&color_normal)?; - write!(&mut color_stdout, "{:>16}: ", "Last changelog")?; - color_stdout.set_color(&color_bold)?; - writeln!(&mut color_stdout, "{}", index)?; - } - None => { - color_stdout.set_color(&color_sad)?; - writeln!(&mut color_stdout, " [Failed to connect]")?; - } - }; - color_stdout.set_color(&color_normal)?; - write!(&mut color_stdout, "{:>16}: ", "API auth token")?; - if self.has_api_token { - color_stdout.set_color(&color_happy)?; - writeln!(&mut color_stdout, "[configured]")?; - } else { - color_stdout.set_color(&color_sad)?; - writeln!(&mut color_stdout, "[not configured]")?; - }; - if let Some(editor) = self.account { - color_stdout.set_color(&color_normal)?; - write!(&mut color_stdout, "{:>16}: ", "Account")?; - color_stdout.set_color(&color_bold)?; - write!(&mut color_stdout, "{}", editor.username)?; - if editor.is_bot == Some(true) { - color_stdout - .set_color(ColorSpec::new().set_fg(Some(Color::Blue)).set_bold(true))?; - write!(&mut color_stdout, " [bot]")?; - } - if editor.is_admin == Some(true) { - color_stdout - .set_color(ColorSpec::new().set_fg(Some(Color::Magenta)).set_bold(true))?; - write!(&mut color_stdout, " [admin]")?; - } - match editor.is_active { - Some(true) => { - color_stdout.set_color(&color_happy)?; - writeln!(&mut color_stdout, " [active]")?; - } - Some(false) | None => { - color_stdout.set_color(&color_sad)?; - writeln!(&mut color_stdout, " [disabled]")?; - } - }; - color_stdout.set_color(&color_normal)?; - writeln!( - &mut color_stdout, - "{:>16} editor_{}", - "", - editor.editor_id.unwrap() - )?; - }; - color_stdout.set_color(&color_normal)?; - Ok(()) - } -} - -pub fn print_editgroups(eg_list: Vec, json: bool) -> Result<()> { - if json { - for eg in eg_list { - writeln!(&mut std::io::stdout(), "{}", eg.to_json_string()?)?; - } - } else { - let mut tw = TabWriter::new(std::io::stdout()); - writeln!( - tw, - "editgroup_id\tchangelog_index\tcreated\tsubmitted\tdescription" - )?; - for eg in eg_list { - writeln!( - tw, - "{}\t{}\t{}\t{}\t{}", - eg.editgroup_id.unwrap(), - eg.changelog_index - .map_or("-".to_string(), |v| v.to_string()), - eg.created - .map_or("-".to_string(), |v| HumanTime::from(v).to_string()), - eg.submitted - .map_or("-".to_string(), |v| HumanTime::from(v).to_string()), - eg.description.unwrap_or_else(|| "-".to_string()) - )?; - } - tw.flush()?; - } - Ok(()) -} - -pub fn print_changelog_entries(entry_list: Vec, json: bool) -> Result<()> { - if json { - for entry in entry_list { - writeln!(&mut std::io::stdout(), "{}", entry.to_json_string()?)?; - } - } else { - let mut tw = TabWriter::new(std::io::stdout()); - writeln!(tw, "index\ttimestamp\teditor\teditgroup_description")?; - for entry in entry_list { - writeln!( - tw, - "{}\t{}\t{}\t{}", - entry.index, - HumanTime::from(entry.timestamp).to_string(), - entry - .editgroup - .as_ref() - .unwrap() - .editor - .as_ref() - .map_or("-".to_string(), |v| v.username.to_string()), - entry - .editgroup - .as_ref() - .unwrap() - .description - .as_ref() - .map_or("-".to_string(), |v| v.to_string()), - )?; - } - tw.flush()?; - } - Ok(()) -} - -pub fn print_entity_histories( - history_list: Vec, - json: bool, -) -> Result<()> { - if json { - for history in history_list { - writeln!(&mut std::io::stdout(), "{}", history.to_json_string()?)?; - } - } else { - let mut tw = TabWriter::new(std::io::stdout()); - writeln!( - tw, - "changelog_index\ttype\ttimestamp\teditor\teditgroup_description" - )?; - for history in history_list { - let state = match ( - history.edit.revision, - history.edit.prev_revision, - history.edit.redirect_ident, - ) { - (Some(_), None, None) => "create", - (Some(_), Some(_), None) => "update", - (None, _, None) => "delete", - (None, _, Some(_)) => "redirect", - _ => "-", - }; - writeln!( - tw, - "{}\t{}\t{}\t{}\t{}", - history.changelog_entry.index, - state, - HumanTime::from(history.changelog_entry.timestamp).to_string(), - history - .editgroup - .editor - .map_or("-".to_string(), |v| v.username.to_string()), - history - .editgroup - .description - .unwrap_or_else(|| "-".to_string()) - )?; - } - tw.flush()?; - } - Ok(()) -} - -pub fn edit_entity_locally( - api_client: &mut FatcatApiClient, - specifier: Specifier, - editgroup_id: String, - json: bool, - editing_command: String, -) -> Result { - // TODO: fetch editgroup, check if this entity is already being updated in it. If so, - // need to fetch that revision, do the edit, parse that synatx is good, then delete the - // existing edit and update with the new one. - let original_entity = specifier.get_from_api(api_client, None, None)?; - let exact_specifier = original_entity.specifier(); - let tmp_file = tempfile::Builder::new() - .suffix(if json { ".json" } else { ".toml" }) - .tempfile()?; - if json { - writeln!(&tmp_file, "{}", original_entity.to_json_string()?)? - } else { - writeln!(&tmp_file, "{}", original_entity.to_toml_string()?)? - } - let mut editor_cmd = std::process::Command::new(&editing_command) - .arg(tmp_file.path()) - .spawn() - .expect("failed to execute process"); - let cmd_status = editor_cmd.wait()?; - if !cmd_status.success() { - return Err(anyhow!( - "editor ({}) exited with non-success status code ({}), bailing on edit", - editing_command, - cmd_status - .code() - .map(|v| v.to_string()) - .unwrap_or_else(|| "N/A".to_string()) - )); - }; - let json_str = read_entity_file(Some(tmp_file.path().to_path_buf()))?; - // for whatever reason api_client's TCP connection is broken after spawning, so try a - // dummy call, expected to fail, but connection should re-establish after this - specifier - .get_from_api(api_client, None, None) - .context("re-fetch") - .ok(); - let ee = api_client - .update_entity_from_json(exact_specifier, &json_str, editgroup_id) - .context("updating after edit")?; - Ok(ee) -} - -pub enum BatchOp { - Create, - Update, - Delete, -} - -pub struct BatchGrouper { - entity_type: EntityType, - batch_size: u64, - limit: Option, - auto_accept: bool, - editgroup_description: String, - current_count: u64, - current_editgroup_id: Option, - total_count: u64, -} - -// Note: should be possible to add support for the single-call batch create endpoint by storing -// edits in a batch within this object. Might need to change control flow a bit. This optimization -// was mostly intended for bootstrapping of tens of thousands of entities, so not including for -// now. -impl BatchGrouper { - pub fn new( - entity_type: EntityType, - batch_size: u64, - limit: Option, - auto_accept: bool, - ) -> Self { - let editgroup_description = "part of a fatcat-cli batch operation".to_string(); - BatchGrouper { - entity_type, - batch_size, - limit, - auto_accept, - editgroup_description, - current_count: 0, - current_editgroup_id: None, - total_count: 0, - } - } - - pub fn run( - &mut self, - api_client: &mut FatcatApiClient, - input_path: Option, - op: BatchOp, - mutations: Option>, - ) -> Result<()> { - match input_path { - None => { - let stdin = io::stdin(); - let stdin_lock = stdin.lock(); - let lines = stdin_lock.lines(); - for line in lines { - let json_str = line?; - match op { - BatchOp::Create => self.push_create(api_client, &json_str)?, - BatchOp::Update => self.push_update( - api_client, - &json_str, - mutations.clone().unwrap_or(vec![]), - )?, - BatchOp::Delete => self.push_delete(api_client, &json_str)?, - }; - if let Some(limit) = self.limit { - if self.total_count + self.current_count >= limit { - break; - } - } - } - } - Some(path) => { - let input_file = File::open(path)?; - let buffered = io::BufReader::new(input_file); - let lines = buffered.lines(); - for line in lines { - let json_str = line?; - match op { - BatchOp::Create => self.push_create(api_client, &json_str)?, - BatchOp::Update => self.push_update( - api_client, - &json_str, - mutations.clone().unwrap_or(vec![]), - )?, - BatchOp::Delete => self.push_delete(api_client, &json_str)?, - }; - if let Some(limit) = self.limit { - if self.total_count + self.current_count >= limit { - break; - } - } - } - } - } - self.flush(api_client)?; - Ok(()) - } - - pub fn push_create( - &mut self, - api_client: &mut FatcatApiClient, - json_str: &str, - ) -> Result { - let editgroup_id = self.increment_editgroup(api_client)?; - api_client.create_entity_from_json(self.entity_type, json_str, editgroup_id) - } - - pub fn push_update( - &mut self, - api_client: &mut FatcatApiClient, - json_str: &str, - mutations: Vec, - ) -> Result { - let obj: serde_json::Value = serde_json::from_str(json_str)?; - let ident = obj["ident"].as_str().unwrap(); // TODO: safer extraction of this ident? - let editgroup_id = self.increment_editgroup(api_client)?; - let mut entity = entity_model_from_json_str(self.entity_type, &json_str)?; - entity.mutate(mutations)?; - api_client.update_entity_from_json( - Specifier::from_ident(self.entity_type, ident.to_string()), - &entity.to_json_string()?, - editgroup_id, - ) - } - - pub fn push_delete( - &mut self, - api_client: &mut FatcatApiClient, - json_str: &str, - ) -> Result { - let obj: serde_json::Value = serde_json::from_str(json_str)?; - let ident = obj["ident"].as_str().unwrap(); // TODO: safer extraction of this ident? - let editgroup_id = self.increment_editgroup(api_client)?; - api_client.delete_entity( - Specifier::from_ident(self.entity_type, ident.to_string()), - editgroup_id, - ) - } - - pub fn increment_editgroup(&mut self, api_client: &mut FatcatApiClient) -> Result { - if self.current_count >= self.batch_size.try_into().unwrap() { - self.flush(api_client)?; - }; - self.current_count += 1; - if let Some(eg) = &self.current_editgroup_id { - return Ok(eg.to_string()); - } - let eg = api_client.create_editgroup(Some(self.editgroup_description.clone()))?; - self.current_editgroup_id = eg.editgroup_id; - Ok(self.current_editgroup_id.as_ref().unwrap().to_string()) - } - - pub fn flush(&mut self, api_client: &mut FatcatApiClient) -> Result<()> { - if self.current_count > 0 && self.current_editgroup_id.is_some() { - let eg_id = self.current_editgroup_id.clone().unwrap(); - if self.auto_accept { - api_client.accept_editgroup(eg_id)?; - } else { - api_client.update_editgroup_submit(eg_id, true)?; - } - self.total_count += self.current_count; - self.current_count = 0; - self.current_editgroup_id = None; - } - Ok(()) - } -} diff --git a/rust/fatcat-cli/src/download.rs b/rust/fatcat-cli/src/download.rs deleted file mode 100644 index 7821b70..0000000 --- a/rust/fatcat-cli/src/download.rs +++ /dev/null @@ -1,261 +0,0 @@ -use anyhow::{anyhow, Context, Result}; -use fatcat_openapi::models::{FileEntity, ReleaseEntity}; -use indicatif::ProgressBar; -use log::info; -use reqwest::header::USER_AGENT; -use std::fmt; -use std::fs::File; -use std::io::{self, BufRead}; -use std::path::Path; -use std::path::PathBuf; -use url::Url; - -#[derive(Debug, PartialEq, Clone)] -pub enum DownloadStatus { - Exists(String), - Downloaded(String), - NetworkError(String), - HttpError(u16), - PartialExists(String), - NoPublicFile, - FileMissingMetadata, - WrongSize, - WrongHash, -} - -impl DownloadStatus { - pub fn details(&self) -> Option { - match self { - Self::Exists(p) => Some(p.to_string()), - Self::Downloaded(p) => Some(p.to_string()), - Self::NetworkError(p) => Some(p.to_string()), - Self::PartialExists(p) => Some(p.to_string()), - _ => None, - } - } -} - -impl fmt::Display for DownloadStatus { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Exists(_) => write!(f, "exists"), - Self::Downloaded(_) => write!(f, "success"), - Self::NetworkError(_) => write!(f, "network-error"), - Self::HttpError(p) => write!(f, "http-{}", p), - Self::PartialExists(_) => write!(f, "partial-exists"), - Self::NoPublicFile => write!(f, "no-public-file"), - Self::FileMissingMetadata => write!(f, "missing-file-metadata"), - Self::WrongSize => write!(f, "wrong-file-size"), - Self::WrongHash => write!(f, "wrong-file-hash"), - } - } -} - -// eg, https://web.archive.org/web/20140802044207/http://www.geo.coop:80/sites/default/files/labs_of_oligarchy.pdf -fn rewrite_wayback_url(url: Url) -> Result { - // TODO: make this function correct, and add tests - let mut segments: Vec = url - .path_segments() - .unwrap() - .map(|x| x.to_string()) - .collect(); - if segments[0] == "web" && segments[1].len() == 14 { - segments[1] = format!("{}id_", segments[1]); - } - Ok(url) -} - -/// Attempts to download a file entity, including verifying checksum. -pub fn download_file(fe: &FileEntity) -> Result { - let sha1hex = match &fe.sha1 { - Some(v) => v, - None => return Ok(DownloadStatus::FileMissingMetadata), - }; - let expected_size = match fe.size { - Some(v) => v as u64, - None => return Ok(DownloadStatus::FileMissingMetadata), - }; - - let file_suffix = match fe.mimetype.as_ref().map(String::as_str) { - Some("application/pdf") => ".pdf", - Some("application/postscript") => ".pdf", - Some("text/html") => ".html", - Some("text/xml") => ".xml", - _ => ".unknown", - }; - - // TODO: output directory - let path_string = format!("{}{}", sha1hex, file_suffix); - let final_path = Path::new(&path_string); - - // NOTE: this isn't perfect; there could have been a race condition - if final_path.exists() { - return Ok(DownloadStatus::Exists( - final_path.to_string_lossy().to_string(), - )); - }; - - let path_string = format!("{}{}.partial", sha1hex, file_suffix); - let download_path = Path::new(&path_string); - - // TODO: only archive.org URLs (?) - let raw_url = match fe.urls.as_ref() { - None => return Ok(DownloadStatus::NoPublicFile), - Some(url_list) if url_list.len() == 0 => return Ok(DownloadStatus::NoPublicFile), - // TODO: remove clone (?) - // TODO: better heuristic than "just try first URL" - Some(url_list) => url_list[0].url.clone(), - }; - - let mut url = Url::parse(&raw_url)?; - if url.host_str() == Some("web.archive.org") { - url = rewrite_wayback_url(url)?; - } - - let download_file = match std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(download_path) - { - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { - return Ok(DownloadStatus::PartialExists( - download_path.to_string_lossy().to_string(), - )) - } - Err(e) => return Err(e).context("opening temporary download file"), - Ok(f) => f, - }; - - // TODO: print to stderr - info!("downloading: {}", url); - let client = reqwest::blocking::Client::new(); - let mut resp = match client - .get(url) - .header(USER_AGENT, "fatcat-cli/0.0.0") - .send() - { - Ok(r) => r, - Err(e) => { - std::fs::remove_file(download_path)?; - return Ok(DownloadStatus::NetworkError(format!("{:?}", e))); - } - }; - - // TODO: parse headers, eg size (?) - if !resp.status().is_success() { - std::fs::remove_file(download_path)?; - return Ok(DownloadStatus::HttpError(resp.status().as_u16())); - } - - // TODO: what if no filesize? - // TODO: compare with resp.content_length(() -> Option - let pb = ProgressBar::new(fe.size.unwrap() as u64); - let out_size = match resp.copy_to(&mut pb.wrap_write(download_file)) { - Ok(r) => r, - Err(e) => { - std::fs::remove_file(download_path)?; - return Ok(DownloadStatus::NetworkError(format!("{:?}", e))); - } - }; - - if out_size != expected_size { - std::fs::remove_file(download_path)?; - return Ok(DownloadStatus::WrongSize); - } - - std::fs::rename(download_path, final_path)?; - Ok(DownloadStatus::Downloaded( - final_path.to_string_lossy().to_string(), - )) -} - -pub fn download_release(re: &ReleaseEntity) -> Result { - let file_entities = match &re.files { - None => { - return Err(anyhow!( - "expected file sub-entities to be 'expanded' on release" - )) - } - Some(list) => list, - }; - let mut status = DownloadStatus::NoPublicFile; - for fe in file_entities { - status = download_file(&fe)?; - match status { - DownloadStatus::Exists(_) | DownloadStatus::Downloaded(_) => break, - _ => (), - }; - } - Ok(status) -} - -/// Tries either file or release -fn download_entity(json_str: String) -> Result { - let release_attempt = serde_json::from_str::(&json_str); - if let Ok(re) = release_attempt { - if re.ident.is_some() && (re.title.is_some() || re.files.is_some()) { - let status = download_release(&re)?; - println!( - "release_{}\t{}\t{}", - re.ident.unwrap(), - status, - status.details().unwrap_or("".to_string()) - ); - return Ok(status); - }; - } - let file_attempt = - serde_json::from_str::(&json_str).context("parsing entity for download"); - match file_attempt { - Ok(fe) => { - if fe.ident.is_some() && fe.urls.is_some() { - let status = download_file(&fe)?; - println!( - "file_{}\t{}\t{}", - fe.ident.unwrap(), - status, - status.details().unwrap_or("".to_string()) - ); - return Ok(status); - } else { - Err(anyhow!("not a file entity (JSON)")) - } - } - Err(e) => Err(e), - } -} - -pub fn download_batch(input_path: Option, limit: Option) -> Result { - let count = 0; - match input_path { - None => { - let stdin = io::stdin(); - let stdin_lock = stdin.lock(); - let lines = stdin_lock.lines(); - for line in lines { - let json_str = line?; - download_entity(json_str)?; - if let Some(limit) = limit { - if count >= limit { - break; - } - } - } - } - Some(path) => { - let input_file = File::open(path)?; - let buffered = io::BufReader::new(input_file); - let lines = buffered.lines(); - for line in lines { - let json_str = line?; - download_entity(json_str)?; - if let Some(limit) = limit { - if count >= limit { - break; - } - } - } - } - }; - Ok(count) -} diff --git a/rust/fatcat-cli/src/entities.rs b/rust/fatcat-cli/src/entities.rs deleted file mode 100644 index d61f6dc..0000000 --- a/rust/fatcat-cli/src/entities.rs +++ /dev/null @@ -1,411 +0,0 @@ -use crate::{EntityType, Specifier}; -use anyhow::{anyhow, Context, Result}; -use fatcat_openapi::models; -use lazy_static::lazy_static; -use log::{self, info}; -use regex::Regex; -use std::io::{BufRead, Read}; -use std::path::PathBuf; -use std::str::FromStr; - -#[derive(Debug, PartialEq, Clone)] -pub struct Mutation { - field: String, - value: Option, -} - -impl FromStr for Mutation { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - // first try simple entity prefixes - lazy_static! { - static ref MUTATE_ENTITY_RE: Regex = Regex::new(r"^([a-z_]+)=(.*)$").unwrap(); - } - if let Some(captures) = MUTATE_ENTITY_RE.captures(s) { - return Ok(Mutation { - field: captures[1].to_string(), - value: match &captures[2] { - "" => None, - val => Some(val.to_string()), - }, - }); - } - Err(anyhow!("not a field mutation: {}", s)) - } -} - -/* - * Goal is to have traits around API entities. Things we'll want to do on concrete entities: - * - * - print, or pretty-print, as JSON or TOML - * - get fcid (or, self-specifier) - * - update (mutate or return copy) fields based on parameters - * - update self to remote API - * - * Methods that might return trait objects: - * - * - get by specifier - */ - -pub trait ApiEntityModel: ApiModelSer + ApiModelIdent + ApiModelMutate {} - -impl ApiEntityModel for models::ReleaseEntity {} -impl ApiEntityModel for models::ContainerEntity {} -impl ApiEntityModel for models::CreatorEntity {} -impl ApiEntityModel for models::WorkEntity {} -impl ApiEntityModel for models::FileEntity {} -impl ApiEntityModel for models::FilesetEntity {} -impl ApiEntityModel for models::WebcaptureEntity {} -impl ApiEntityModel for models::Editor {} -impl ApiEntityModel for models::Editgroup {} -impl ApiEntityModel for models::ChangelogEntry {} - -pub fn read_entity_file(input_path: Option) -> Result { - // treat "-" as "use stdin" - let input_path = match input_path { - Some(s) if s.to_string_lossy() == "-" => None, - _ => input_path, - }; - match input_path { - None => { - let mut line = String::new(); - std::io::stdin().read_line(&mut line)?; - Ok(line) - } - Some(path) if path.extension().map(|v| v.to_str()) == Some(Some("toml")) => { - info!("reading {:?} as TOML", path); - // as a hack, read TOML but then serialize it back to JSON - let mut contents = String::new(); - let mut input_file = - std::fs::File::open(path).context("reading entity from TOML file")?; - input_file.read_to_string(&mut contents)?; - let value: toml::Value = contents.parse().context("parsing TOML file")?; - Ok(serde_json::to_string(&value)?) - } - Some(path) => { - let mut line = String::new(); - let input_file = std::fs::File::open(path)?; - let mut buffered = std::io::BufReader::new(input_file); - buffered.read_line(&mut line)?; - Ok(line) - } - } -} - -pub fn entity_model_from_json_str( - entity_type: EntityType, - json_str: &str, -) -> Result> { - match entity_type { - EntityType::Release => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::Work => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::Container => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::Creator => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::File => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::FileSet => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - EntityType::WebCapture => Ok(Box::new(serde_json::from_str::( - &json_str, - )?)), - } -} - -pub trait ApiModelSer { - fn to_json_string(&self) -> Result; - fn to_toml_string(&self) -> Result; -} - -impl ApiModelSer for T { - fn to_json_string(&self) -> Result { - Ok(serde_json::to_string(self)?) - } - - fn to_toml_string(&self) -> Result { - Ok(toml::Value::try_from(self)?.to_string()) - } -} - -pub trait ApiModelIdent { - fn specifier(&self) -> Specifier; -} - -macro_rules! generic_entity_specifier { - ($specifier_type:ident) => { - fn specifier(&self) -> Specifier { - if let Some(fcid) = &self.ident { - Specifier::$specifier_type(fcid.to_string()) - } else { - panic!("expected full entity") - } - } - }; -} - -impl ApiModelIdent for models::ReleaseEntity { - generic_entity_specifier!(Release); -} -impl ApiModelIdent for models::ContainerEntity { - generic_entity_specifier!(Container); -} -impl ApiModelIdent for models::CreatorEntity { - generic_entity_specifier!(Creator); -} -impl ApiModelIdent for models::WorkEntity { - generic_entity_specifier!(Work); -} -impl ApiModelIdent for models::FileEntity { - generic_entity_specifier!(File); -} -impl ApiModelIdent for models::FilesetEntity { - generic_entity_specifier!(FileSet); -} -impl ApiModelIdent for models::WebcaptureEntity { - generic_entity_specifier!(WebCapture); -} - -impl ApiModelIdent for models::ChangelogEntry { - fn specifier(&self) -> Specifier { - Specifier::Changelog(self.index) - } -} - -impl ApiModelIdent for models::Editgroup { - fn specifier(&self) -> Specifier { - if let Some(fcid) = &self.editgroup_id { - Specifier::Editgroup(fcid.to_string()) - } else { - panic!("expected full entity") - } - } -} - -impl ApiModelIdent for models::Editor { - fn specifier(&self) -> Specifier { - if let Some(fcid) = &self.editor_id { - Specifier::Editor(fcid.to_string()) - } else { - panic!("expected full entity") - } - } -} - -pub trait ApiModelMutate { - fn mutate(&mut self, mutations: Vec) -> Result<()>; -} - -impl ApiModelMutate for models::ReleaseEntity { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("title", val) => { - self.title = val; - } - ("subtitle", val) => { - self.subtitle = val; - } - ("container_id", val) => { - self.container_id = val; - } - ("work_id", val) => { - self.work_id = val; - } - ("release_type", val) => { - self.release_type = val; - } - ("release_stage", val) => { - self.release_stage = val; - } - ("withdrawn_status", val) => { - self.withdrawn_status = val; - } - ("license_slug", val) => { - self.license_slug = val; - } - ("volume", val) => { - self.volume = val; - } - ("issue", val) => { - self.issue = val; - } - ("number", val) => { - self.number = val; - } - ("publisher", val) => { - self.publisher = val; - } - ("language", val) => { - self.language = val; - } - (field, _) => unimplemented!("setting field {} on a release", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::ContainerEntity { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("name", val) => { - self.name = val; - } - ("container_type", val) => { - self.container_type = val; - } - ("publisher", val) => { - self.publisher = val; - } - ("issnl", val) => { - self.issnl = val; - } - (field, _) => unimplemented!("setting field {} on a container", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::CreatorEntity { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("display_name", val) => { - self.display_name = val; - } - ("given_name", val) => { - self.given_name = val; - } - ("surname", val) => { - self.surname = val; - } - (field, _) => unimplemented!("setting field {} on a creator", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::WorkEntity { - fn mutate(&mut self, _mutations: Vec) -> Result<()> { - unimplemented!("mutations") - } -} - -impl ApiModelMutate for models::FileEntity { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("size", Some(val)) => { - self.size = Some(i64::from_str(&val)?); - } - ("size", None) => { - self.size = None; - } - ("md5", val) => { - self.md5 = val; - } - ("sha1", val) => { - self.sha1 = val; - } - ("sha256", val) => { - self.sha256 = val; - } - ("mimetype", val) => { - self.mimetype = val; - } - (field, _) => unimplemented!("setting field {} on a file", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::FilesetEntity { - fn mutate(&mut self, _mutations: Vec) -> Result<()> { - unimplemented!("mutations") - } -} - -impl ApiModelMutate for models::WebcaptureEntity { - fn mutate(&mut self, _mutations: Vec) -> Result<()> { - unimplemented!("mutations") - } -} - -impl ApiModelMutate for models::Editor { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("username", Some(val)) => { - self.username = val; - } - (field, _) => unimplemented!("setting field {} on an editor", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::Editgroup { - fn mutate(&mut self, mutations: Vec) -> Result<()> { - for m in mutations { - match (m.field.as_str(), m.value) { - ("description", val) => { - self.description = val; - } - (field, _) => unimplemented!("setting field {} on an editgroup", field), - } - } - Ok(()) - } -} - -impl ApiModelMutate for models::ChangelogEntry { - fn mutate(&mut self, _mutations: Vec) -> Result<()> { - unimplemented!("mutations") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_mutation_from_str() -> () { - assert!(Mutation::from_str("release_asdf").is_err()); - assert_eq!( - Mutation::from_str("title=blah").unwrap(), - Mutation { - field: "title".to_string(), - value: Some("blah".to_string()) - } - ); - assert_eq!( - Mutation::from_str("title=").unwrap(), - Mutation { - field: "title".to_string(), - value: None - } - ); - assert_eq!( - Mutation::from_str("title=string with spaces and stuff").unwrap(), - Mutation { - field: "title".to_string(), - value: Some("string with spaces and stuff".to_string()) - } - ); - } -} diff --git a/rust/fatcat-cli/src/lib.rs b/rust/fatcat-cli/src/lib.rs deleted file mode 100644 index d648c1c..0000000 --- a/rust/fatcat-cli/src/lib.rs +++ /dev/null @@ -1,93 +0,0 @@ -use anyhow::{anyhow, Context, Result}; -use data_encoding::BASE64; -use macaroon::{Macaroon, Verifier}; -use std::path::PathBuf; -use std::str::FromStr; - -mod api; -mod commands; -mod download; -mod entities; -mod search; -mod specifier; - -pub use api::FatcatApiClient; -pub use commands::{ - edit_entity_locally, print_changelog_entries, print_editgroups, print_entity_histories, - BatchGrouper, BatchOp, ClientStatus, -}; -pub use download::{download_batch, download_file, download_release}; -pub use entities::{ - entity_model_from_json_str, read_entity_file, ApiEntityModel, ApiModelIdent, ApiModelSer, - Mutation, -}; -pub use search::crude_search; -pub use specifier::Specifier; - -#[derive(Debug, PartialEq, Clone, Copy)] -pub enum EntityType { - Release, - Work, - Container, - Creator, - File, - FileSet, - WebCapture, -} - -impl FromStr for EntityType { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - match s { - "release" | "releases" => Ok(EntityType::Release), - "work" | "works" => Ok(EntityType::Work), - "container" | "containers" => Ok(EntityType::Container), - "creator" | "creators" => Ok(EntityType::Creator), - "file" | "files" => Ok(EntityType::File), - "fileset" | "filesets" => Ok(EntityType::FileSet), - "webcapture" | "webcaptures" => Ok(EntityType::WebCapture), - _ => Err(anyhow!("invalid entity type : {}", s)), - } - } -} - -/// Takes a macaroon token (as base64-encoded string) and tries to parse out an editor id -pub fn parse_macaroon_editor_id(s: &str) -> Result { - let raw = BASE64 - .decode(s.as_bytes()) - .context("macaroon parsing failed")?; - let mac = Macaroon::deserialize(&raw) - .map_err(|err| anyhow!("macaroon deserialization failed: {:?}", err))?; - let mac = mac - .validate() - .map_err(|err| anyhow!("macaroon validation failed: {:?}", err))?; - let mut verifier = Verifier::new(); - let mut editor_id: Option = None; - for caveat in mac.first_party_caveats() { - if caveat.predicate().starts_with("editor_id = ") { - editor_id = Some( - caveat - .predicate() - .get(12..) - .context("parsing macaroon")? - .to_string(), - ); - break; - } - } - let editor_id = match editor_id { - Some(id) => id, - None => return Err(anyhow!("expected an editor_id caveat in macaroon token")), - }; - verifier.satisfy_exact(&format!("editor_id = {}", editor_id.to_string())); - Ok(editor_id) -} - -pub fn path_or_stdin(raw: Option) -> Option { - // treat "-" as "use stdin" - match raw { - Some(s) if s.to_string_lossy() == "-" => None, - _ => raw, - } -} diff --git a/rust/fatcat-cli/src/main.rs b/rust/fatcat-cli/src/main.rs deleted file mode 100644 index 3b0d382..0000000 --- a/rust/fatcat-cli/src/main.rs +++ /dev/null @@ -1,631 +0,0 @@ -use crate::{path_or_stdin, BatchGrouper, BatchOp}; -use anyhow::{anyhow, Context, Result}; -use fatcat_cli::ApiModelSer; -use fatcat_cli::*; -#[allow(unused_imports)] -use log::{self, debug, info}; -use std::io::Write; -use std::path::PathBuf; -use structopt::StructOpt; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; - -#[derive(StructOpt)] -#[structopt(rename_all = "kebab-case", about = "CLI interface to Fatcat API")] -struct Opt { - #[structopt( - global = true, - long = "--api-host", - env = "FATCAT_API_HOST", - default_value = "https://api.fatcat.wiki" - )] - api_host: String, - - /// API auth tokens can be generated from the account page in the fatcat.wiki web interface - #[structopt( - global = true, - long = "--api-token", - env = "FATCAT_API_AUTH_TOKEN", - hide_env_values = true - )] - api_token: Option, - - #[structopt( - global = true, - long = "--search-host", - env = "FATCAT_SEARCH_HOST", - default_value = "https://search.fatcat.wiki" - )] - search_host: String, - - /// Log more messages. Pass multiple times for ever more verbosity - /// - /// By default, it'll only report errors. Passing `-v` one time also prints - /// warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace. - #[structopt(global = true, long, short = "v", parse(from_occurrences))] - verbose: i8, - - #[structopt(subcommand)] - cmd: Command, -} - -#[derive(StructOpt)] -enum EditgroupCommand { - /// Create a new editgroup - Create { - #[structopt(long, short)] - description: String, - }, - /// Print editgroups for current user - List { - #[structopt(long = "--editor-id", short)] - editor_id: Option, - - #[structopt(long, short = "-n", default_value = "20")] - limit: i64, - - #[structopt(long)] - json: bool, - }, - /// Print recent editgroups from any user which need review - Reviewable { - #[structopt(long, short = "-n", default_value = "20")] - limit: i64, - - #[structopt(long)] - json: bool, - }, - /// Accept (merge) a single editgroup - Accept { - #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)] - editgroup_id: String, - }, - /// Submit a single editgroup for review - Submit { - #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)] - editgroup_id: String, - }, - /// Un-submit a single editgroup (for more editing) - Unsubmit { - #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)] - editgroup_id: String, - }, -} - -#[derive(StructOpt)] -enum BatchCommand { - Create { - entity_type: EntityType, - - #[structopt(long, default_value = "50")] - batch_size: u64, - - #[structopt(long)] - auto_accept: bool, - }, - Update { - entity_type: EntityType, - mutations: Vec, - - #[structopt(long, default_value = "50")] - batch_size: u64, - - #[structopt(long)] - auto_accept: bool, - }, - Delete { - entity_type: EntityType, - - #[structopt(long, default_value = "50")] - batch_size: u64, - - #[structopt(long)] - auto_accept: bool, - }, - Download {}, -} - -#[derive(StructOpt)] -enum Command { - Get { - specifier: Specifier, - - #[structopt(long = "--expand")] - expand: Option, - - #[structopt(long = "--hide")] - hide: Option, - - #[structopt(long)] - json: bool, - - #[structopt(long)] - toml: bool, - }, - Create { - entity_type: EntityType, - - /// Input file, "-" for stdin. - #[structopt(long = "--file", short = "-f", parse(from_os_str))] - input_path: Option, - - #[structopt( - long = "--editgroup-id", - short, - env = "FATCAT_EDITGROUP", - hide_env_values = true - )] - editgroup_id: String, - }, - Update { - specifier: Specifier, - - /// Input file, "-" for stdin. - #[structopt(long = "--file", short = "-f", parse(from_os_str))] - input_path: Option, - - #[structopt( - long = "--editgroup-id", - short, - env = "FATCAT_EDITGROUP", - hide_env_values = true - )] - editgroup_id: String, - - mutations: Vec, - }, - Delete { - specifier: Specifier, - - #[structopt( - long = "--editgroup-id", - short, - env = "FATCAT_EDITGROUP", - hide_env_values = true - )] - editgroup_id: String, - }, - Edit { - specifier: Specifier, - - #[structopt( - long = "--editgroup-id", - short, - env = "FATCAT_EDITGROUP", - hide_env_values = true - )] - editgroup_id: String, - - #[structopt(long)] - json: bool, - - #[allow(dead_code)] - #[structopt(long)] - toml: bool, - - #[structopt(long = "--editing-command", env = "EDITOR")] - editing_command: String, - }, - Download { - specifier: Specifier, - }, - History { - specifier: Specifier, - - #[structopt(long, short = "-n", default_value = "100")] - limit: u64, - - #[structopt(long)] - json: bool, - }, - Search { - entity_type: EntityType, - - terms: Vec, - - #[structopt(long = "--expand")] - expand: Option, - - #[structopt(long = "--hide")] - hide: Option, - - #[structopt(long, short = "-n", default_value = "20")] - limit: i64, - - #[structopt(long = "--search-schema")] - search_schema: bool, - }, - Editgroup { - #[structopt(subcommand)] - cmd: EditgroupCommand, - }, - Changelog { - #[structopt(long, short = "-n", default_value = "20")] - limit: i64, - - /* TODO: follow (streaming) mode for changelog - #[structopt(long, short = "-f")] - follow: bool, - */ - #[structopt(long)] - json: bool, - }, - Batch { - #[structopt(subcommand)] - cmd: BatchCommand, - - /// Input file, "-" for stdin. - #[structopt(long = "--file", short = "-f", parse(from_os_str))] - input_path: Option, - - #[structopt(long)] - limit: Option, - }, - Status { - #[structopt(long)] - json: bool, - }, -} - -fn main() -> Result<()> { - let opt = Opt::from_args(); - - let log_level = match opt.verbose { - std::i8::MIN..=-1 => "none", - 0 => "error", - 1 => "warn", - 2 => "info", - 3 => "debug", - 4..=std::i8::MAX => "trace", - }; - // hyper logging is very verbose, so crank that down even if everything else is more verbose - let log_filter = format!("{},hyper=error", log_level); - env_logger::from_env(env_logger::Env::default().default_filter_or(log_filter)) - .format_timestamp(None) - .init(); - - debug!("Args parsed, starting up"); - - if let Err(err) = run(opt) { - // Be graceful about some errors - if let Some(io_err) = err.root_cause().downcast_ref::() { - if let std::io::ErrorKind::BrokenPipe = io_err.kind() { - // presumably due to something like writing to stdout and piped to `head -n10` and - // stdout was closed - debug!("got BrokenPipe error, assuming stdout closed as expected and exiting with success"); - std::process::exit(0); - } - } - let mut color_stderr = StandardStream::stderr(if atty::is(atty::Stream::Stderr) { - ColorChoice::Auto - } else { - ColorChoice::Never - }); - color_stderr.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true))?; - eprintln!("Error: {:?}", err); - color_stderr.set_color(&ColorSpec::new())?; - std::process::exit(1); - } - Ok(()) -} - -fn run(opt: Opt) -> Result<()> { - let mut api_client = FatcatApiClient::new(opt.api_host.clone(), opt.api_token.clone())?; - - match opt.cmd { - Command::Get { - specifier, - expand, - hide, - json, - toml, - } => { - let result = specifier.get_from_api(&mut api_client, expand, hide)?; - if toml { - writeln!(&mut std::io::stdout(), "{}", result.to_toml_string()?)? - } else if json || true { - writeln!(&mut std::io::stdout(), "{}", result.to_json_string()?)? - } - } - Command::Create { - entity_type, - input_path, - editgroup_id, - } => { - let json_str = read_entity_file(input_path)?; - let ee = api_client.create_entity_from_json(entity_type, &json_str, editgroup_id)?; - println!("{}", serde_json::to_string(&ee)?); - } - Command::Update { - specifier, - input_path, - editgroup_id, - mutations, - } => { - let (json_str, exact_specifier): (String, Specifier) = - match (&input_path, mutations.len()) { - // input path or no mutations: read from path or stdin - (Some(_), _) | (None, 0) => ( - read_entity_file(input_path)?, - specifier.into_entity_specifier(&mut api_client)?, - ), - // no input path *and* mutations: fetch from API - (None, _) => { - let mut entity = specifier.get_from_api(&mut api_client, None, None)?; - entity.mutate(mutations)?; - (entity.to_json_string()?, entity.specifier()) - } - }; - let ee = - api_client.update_entity_from_json(exact_specifier, &json_str, editgroup_id)?; - println!("{}", serde_json::to_string(&ee)?); - } - Command::Edit { - specifier, - editgroup_id, - json, - toml: _, - editing_command, - } => { - let ee = edit_entity_locally( - &mut api_client, - specifier, - editgroup_id, - json, - editing_command, - )?; - println!("{}", serde_json::to_string(&ee)?); - } - Command::Changelog { limit, json } => { - let resp = api_client - .rt - .block_on(api_client.api.get_changelog(Some(limit))) - .context("fetch recent changelogs")?; - match resp { - fatcat_openapi::GetChangelogResponse::Success(change_list) => { - print_changelog_entries(change_list, json)?; - } - other => { - return Err(anyhow!("{:?}", other)) - .with_context(|| format!("failed to fetch changelogs")) - } - } - } - Command::Batch { - cmd: - BatchCommand::Create { - entity_type, - batch_size, - auto_accept, - }, - input_path, - limit, - } => { - let input_path = path_or_stdin(input_path); - let mut batch = BatchGrouper::new(entity_type, batch_size, limit, auto_accept); - batch.run(&mut api_client, input_path, BatchOp::Create, None)?; - } - Command::Batch { - cmd: - BatchCommand::Update { - entity_type, - mutations, - batch_size, - auto_accept, - }, - input_path, - limit, - } => { - let input_path = path_or_stdin(input_path); - let mut batch = BatchGrouper::new(entity_type, batch_size, limit, auto_accept); - batch.run( - &mut api_client, - input_path, - BatchOp::Update, - Some(mutations), - )?; - } - Command::Batch { - cmd: - BatchCommand::Delete { - entity_type, - batch_size, - auto_accept, - }, - input_path, - limit, - } => { - let input_path = path_or_stdin(input_path); - let mut batch = BatchGrouper::new(entity_type, batch_size, limit, auto_accept); - batch.run(&mut api_client, input_path, BatchOp::Delete, None)?; - } - Command::Batch { - cmd: BatchCommand::Download {}, - input_path, - limit, - } => { - let input_path = path_or_stdin(input_path); - download_batch(input_path, limit)?; - } - Command::Download { specifier } => { - // run lookups if necessary (inefficient) - let specifier = match specifier { - Specifier::ReleaseLookup(_, _) | Specifier::FileLookup(_, _) => { - specifier.into_entity_specifier(&mut api_client)? - } - _ => specifier, - }; - let status = match specifier { - Specifier::Release(ident) => { - let result = api_client.rt.block_on(api_client.api.get_release( - ident.clone(), - Some("files".to_string()), - Some("abstracts,refs".to_string()), - ))?; - let release_entity = match result { - fatcat_openapi::GetReleaseResponse::FoundEntity(model) => Ok(model), - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", ident)), - }?; - download_release(&release_entity) - } - Specifier::File(ident) => { - let result = api_client.rt.block_on(api_client.api.get_file( - ident.clone(), - None, - None, - ))?; - let file_entity = match result { - fatcat_openapi::GetFileResponse::FoundEntity(model) => Ok(model), - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", ident)), - }?; - download_file(&file_entity) - } - other => Err(anyhow!("Don't know how to download: {:?}", other)), - }?; - if let Some(detail) = status.details() { - println!("{}: {}", status, detail); - } else { - println!("{}", status); - } - } - Command::Search { - entity_type, - terms, - limit, - search_schema, - expand, - hide, - } => { - let limit: Option = match limit { - l if l <= 0 => None, - l => Some(l as u64), - }; - let results = fatcat_cli::crude_search(&opt.search_host, entity_type, limit, terms) - .with_context(|| format!("searching for {:?}", entity_type))?; - eprintln!("Got {} hits in {}ms", results.count, results.took_ms); - for hit in results { - let hit = hit?; - match (search_schema, entity_type) { - (true, _) => writeln!(&mut std::io::stdout(), "{}", hit.to_string())?, - (false, EntityType::Release) => { - let specifier = - Specifier::Release(hit["ident"].as_str().unwrap().to_string()); - let entity = specifier.get_from_api( - &mut api_client, - expand.clone(), - hide.clone(), - )?; - writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)? - } - (false, _) => unimplemented!("searching other entity types"), - } - } - } - Command::Delete { - specifier, - editgroup_id, - } => { - let result = api_client - .delete_entity(specifier.clone(), editgroup_id) - .with_context(|| format!("delete entity: {:?}", specifier))?; - println!("{}", serde_json::to_string(&result)?); - } - Command::History { - specifier, - limit, - json, - } => { - let specifier = specifier.into_entity_specifier(&mut api_client)?; - let history_entries = specifier.get_history(&mut api_client, Some(limit))?; - print_entity_histories(history_entries, json)?; - } - Command::Editgroup { - cmd: - EditgroupCommand::List { - editor_id, - limit, - json, - }, - } => { - let editor_id = match editor_id.or(api_client.editor_id) { - Some(eid) => eid, - None => return Err(anyhow!("require either working auth token or --editor-id")), - }; - let result = api_client - .rt - .block_on(api_client.api.get_editor_editgroups( - editor_id.clone(), - Some(limit), - None, - None, - )) - .context("fetch editgroups")?; - match result { - fatcat_openapi::GetEditorEditgroupsResponse::Found(eg_list) => { - print_editgroups(eg_list, json)?; - } - other => { - return Err(anyhow!("{:?}", other)).with_context(|| { - format!("failed to fetch editgroups for editor_{}", editor_id) - }) - } - } - } - Command::Editgroup { - cmd: EditgroupCommand::Reviewable { limit, json }, - } => { - let result = api_client - .rt - .block_on(api_client.api.get_editgroups_reviewable( - Some("editors".to_string()), - Some(limit), - None, - None, - )) - .context("fetch reviewable editgroups")?; - match result { - fatcat_openapi::GetEditgroupsReviewableResponse::Found(eg_list) => { - print_editgroups(eg_list, json)?; - } - other => { - return Err(anyhow!("{:?}", other)) - .context("failed to fetch reviewable editgroups") - } - } - } - Command::Editgroup { - cmd: EditgroupCommand::Create { description }, - } => { - let eg = api_client.create_editgroup(Some(description))?; - println!("{}", serde_json::to_string(&eg)?) - } - Command::Editgroup { - cmd: EditgroupCommand::Accept { editgroup_id }, - } => { - let msg = api_client.accept_editgroup(editgroup_id.clone())?; - println!("{}", serde_json::to_string(&msg)?); - } - Command::Editgroup { - cmd: EditgroupCommand::Submit { editgroup_id }, - } => { - let eg = api_client.update_editgroup_submit(editgroup_id, true)?; - println!("{}", eg.to_json_string()?); - } - Command::Editgroup { - cmd: EditgroupCommand::Unsubmit { editgroup_id }, - } => { - let eg = api_client.update_editgroup_submit(editgroup_id, false)?; - println!("{}", eg.to_json_string()?); - } - Command::Status { json } => { - let status = ClientStatus::generate(&mut api_client)?; - if json { - println!("{}", serde_json::to_string(&status)?) - } else { - status.pretty_print()?; - } - } - } - Ok(()) -} diff --git a/rust/fatcat-cli/src/search.rs b/rust/fatcat-cli/src/search.rs deleted file mode 100644 index f778477..0000000 --- a/rust/fatcat-cli/src/search.rs +++ /dev/null @@ -1,186 +0,0 @@ -use crate::EntityType; -use anyhow::{anyhow, Result}; -use log::{self, info}; -use serde_json::json; -use std::time::Duration; - -pub struct SearchResults { - pub entity_type: EntityType, - pub limit: Option, - pub count: u64, - pub took_ms: u64, - offset: u64, - batch: Vec, - scroll_id: Option, - scroll_url: String, - http_client: reqwest::blocking::Client, -} - -impl Iterator for SearchResults { - type Item = Result; - - fn next(&mut self) -> Option> { - // if we already hit limit, bail early - if let Some(l) = self.limit { - if self.offset >= l { - return None; - } - } - // if current batch is empty, and we are scrolling, refill the current batch - if self.batch.is_empty() && self.scroll_id.is_some() { - let response = self - .http_client - .get(&self.scroll_url) - .header("Content-Type", "application/json") - .body( - json!({ - "scroll": "2m", - "scroll_id": self.scroll_id.clone().unwrap(), - }) - .to_string(), - ) - .send(); - let response = match response { - Err(e) => return Some(Err(e.into())), - Ok(v) => v, - }; - if !response.status().is_success() { - return Some(Err(anyhow!("search error, status={}", response.status()))); - }; - let body: serde_json::Value = match response.json() { - Err(e) => return Some(Err(e.into())), - Ok(v) => v, - }; - self.scroll_id = Some(body["_scroll_id"].as_str().unwrap().to_string()); - self.batch = body["hits"]["hits"].as_array().unwrap().to_vec(); - } - - // return next hit from the most recent batch - if !self.batch.is_empty() { - self.offset += 1; - let val = self.batch.pop().unwrap(); - let source = val["_source"].clone(); - return Some(Ok(source)); - } - - // if batch is empty and couldn't be refilled, terminate - // TODO: should we raise error if ended early? - None - } -} - -pub fn crude_search( - api_host: &str, - entity_type: EntityType, - limit: Option, - terms: Vec, -) -> Result { - let index = match entity_type { - EntityType::Release => "fatcat_release", - EntityType::File => "fatcat_file", - EntityType::Container => "fatcat_container", - _ => { - return Err(anyhow!( - "No search index for entity type: {:?}", - entity_type - )) - } - }; - let http_client = reqwest::blocking::Client::builder() - .timeout(Duration::from_secs(10)) - .danger_accept_invalid_certs(true) - .build() - .expect("ERROR :: Could not build reqwest client"); - - let query: String = if terms.is_empty() { - "*".to_string() - } else { - terms.join(" ") - }; - info!("Search query string: {}", query); - let request_url = format!("{}/{}/_search", api_host, index); - let scroll_url = format!("{}/_search/scroll", api_host); - - // sort by _doc for (potentially) very large result sets - let (scroll_mode, sort_mode, size) = match limit { - None => (true, "_doc", 100), - Some(l) if l > 100 => (true, "_doc", 100), - Some(l) => (false, "_score", l), - }; - - let query_body = json!({ - "query": { - "boosting": { - "positive": { - "bool": { - "must": { - "query_string": { - "query": query, - "default_operator": "AND", - "analyze_wildcard": true, - "allow_leading_wildcard": false, - "lenient": true, - "fields": [ - "title^2", - "biblio", - ], - }, - }, - "should": { - "term": { "in_ia": true }, - }, - }, - }, - "negative": { - "bool": { - "should": [ - {"bool": { "must_not" : { "exists": { "field": "title" }}}}, - {"bool": { "must_not" : { "exists": { "field": "year" }}}}, - {"bool": { "must_not" : { "exists": { "field": "type" }}}}, - {"bool": { "must_not" : { "exists": { "field": "stage" }}}}, - ], - }, - }, - "negative_boost": 0.5, - }, - }, - "size": size, - "sort": [ sort_mode ], - }) - .to_string(); - - let mut request = http_client - .get(&request_url) - .header("Content-Type", "application/json") - .body(query_body); - - if scroll_mode { - request = request.query(&[("scroll", "2m")]); - } - - let response = request.send()?; - - if !response.status().is_success() { - return Err(anyhow!("search error, status={}", response.status())); - } - //println!("{:?}", response); - let body: serde_json::Value = response.json()?; - - let scroll_id = if scroll_mode { - Some(body["_scroll_id"].as_str().unwrap().to_string()) - } else { - None - }; - - Ok(SearchResults { - entity_type, - limit, - count: body["hits"]["total"].as_u64().unwrap(), - took_ms: body["took"].as_u64().unwrap(), - offset: 0, - batch: body["hits"]["hits"].as_array().unwrap().to_vec(), - scroll_id, - scroll_url, - http_client, - }) -} diff --git a/rust/fatcat-cli/src/specifier.rs b/rust/fatcat-cli/src/specifier.rs deleted file mode 100644 index 0d8d209..0000000 --- a/rust/fatcat-cli/src/specifier.rs +++ /dev/null @@ -1,584 +0,0 @@ -use crate::{ApiEntityModel, EntityType, FatcatApiClient}; -use anyhow::{anyhow, Context, Result}; -use lazy_static::lazy_static; -use regex::Regex; -use std::str::FromStr; - -#[derive(Debug, PartialEq, Clone)] -pub enum ReleaseLookupKey { - DOI, - PMCID, - PMID, - Arxiv, - // TODO: the others -} - -#[derive(Debug, PartialEq, Clone)] -pub enum ContainerLookupKey { - ISSNL, -} - -#[derive(Debug, PartialEq, Clone)] -pub enum CreatorLookupKey { - Orcid, -} - -#[derive(Debug, PartialEq, Clone)] -pub enum FileLookupKey { - SHA1, - SHA256, - MD5, -} - -#[derive(Debug, PartialEq, Clone)] -pub enum Specifier { - Release(String), - ReleaseLookup(ReleaseLookupKey, String), - Work(String), - Container(String), - ContainerLookup(ContainerLookupKey, String), - Creator(String), - CreatorLookup(CreatorLookupKey, String), - File(String), - FileLookup(FileLookupKey, String), - FileSet(String), - WebCapture(String), - Editgroup(String), - Editor(String), - EditorUsername(String), - Changelog(i64), -} - -impl Specifier { - pub fn from_ident(entity_type: EntityType, ident: String) -> Specifier { - match entity_type { - EntityType::Release => Specifier::Release(ident), - EntityType::Work => Specifier::Work(ident), - EntityType::Container => Specifier::Container(ident), - EntityType::Creator => Specifier::Creator(ident), - EntityType::File => Specifier::File(ident), - EntityType::FileSet => Specifier::FileSet(ident), - EntityType::WebCapture => Specifier::WebCapture(ident), - } - } - - /// If this Specifier is a lookup, call the API to do the lookup and return the resulting - /// specific entity specifier (eg, with an FCID). If already specific, just pass through. - pub fn into_entity_specifier(self, api_client: &mut FatcatApiClient) -> Result { - use Specifier::*; - match self { - Release(_) | Work(_) | Creator(_) | Container(_) | File(_) | FileSet(_) - | WebCapture(_) | Editgroup(_) | Editor(_) | Changelog(_) => Ok(self), - ReleaseLookup(_, _) => Ok(self.get_from_api(api_client, None, None)?.specifier()), - ContainerLookup(_, _) => Ok(self.get_from_api(api_client, None, None)?.specifier()), - CreatorLookup(_, _) => Ok(self.get_from_api(api_client, None, None)?.specifier()), - FileLookup(_, _) => Ok(self.get_from_api(api_client, None, None)?.specifier()), - EditorUsername(_username) => Err(anyhow!( - "editor lookup by username isn't implemented in fatcat-server API yet, sorry" - )), - } - } - - pub fn get_from_api( - &self, - api_client: &mut FatcatApiClient, - expand: Option, - hide: Option, - ) -> Result> { - use Specifier::*; - let ret: Result> = match self { - Release(fcid) => match api_client.rt.block_on(api_client.api.get_release( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetReleaseResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetReleaseResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetReleaseResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - ReleaseLookup(ext_id, key) => { - use ReleaseLookupKey::*; - let (doi, pmcid, pmid, arxiv) = ( - if let DOI = ext_id { - Some(key.to_string()) - } else { - None - }, - if let PMCID = ext_id { - Some(key.to_string()) - } else { - None - }, - if let PMID = ext_id { - Some(key.to_string()) - } else { - None - }, - if let Arxiv = ext_id { - Some(key.to_string()) - } else { - None - }, - ); - // doi, wikidata, isbn13, pmid, pmcid, core, arxiv, jstor, ark, mag - let result = api_client.rt.block_on(api_client.api.lookup_release( - doi, None, None, pmid, pmcid, None, arxiv, None, None, None, None, None, None, - expand, hide, - ))?; - match result { - fatcat_openapi::LookupReleaseResponse::FoundEntity(model) => { - Ok(Box::new(model)) - } - fatcat_openapi::LookupReleaseResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::LookupReleaseResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - } - } - Work(fcid) => match api_client.rt.block_on(api_client.api.get_work( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetWorkResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetWorkResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetWorkResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Container(fcid) => match api_client.rt.block_on(api_client.api.get_container( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetContainerResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetContainerResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetContainerResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - ContainerLookup(ext_id, key) => { - let result = api_client.rt.block_on(match ext_id { - ContainerLookupKey::ISSNL => { - api_client - .api - .lookup_container(Some(key.to_string()), None, expand, hide) - } - })?; - match result { - fatcat_openapi::LookupContainerResponse::FoundEntity(model) => { - Ok(Box::new(model)) - } - fatcat_openapi::LookupContainerResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::LookupContainerResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - } - } - Creator(fcid) => match api_client.rt.block_on(api_client.api.get_creator( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetCreatorResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetCreatorResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetCreatorResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - CreatorLookup(ext_id, key) => { - let result = api_client.rt.block_on(match ext_id { - CreatorLookupKey::Orcid => { - api_client - .api - .lookup_creator(Some(key.to_string()), None, expand, hide) - } - })?; - match result { - fatcat_openapi::LookupCreatorResponse::FoundEntity(model) => { - Ok(Box::new(model)) - } - fatcat_openapi::LookupCreatorResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::LookupCreatorResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - } - } - File(fcid) => match api_client.rt.block_on(api_client.api.get_file( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetFileResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetFileResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetFileResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - FileLookup(hash, key) => { - use FileLookupKey::*; - let (sha1, sha256, md5) = ( - if let SHA1 = hash { - Some(key.to_string()) - } else { - None - }, - if let SHA256 = hash { - Some(key.to_string()) - } else { - None - }, - if let MD5 = hash { - Some(key.to_string()) - } else { - None - }, - ); - let result = api_client - .rt - .block_on(api_client.api.lookup_file(sha1, sha256, md5, expand, hide))?; - match result { - fatcat_openapi::LookupFileResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::LookupFileResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::LookupFileResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - } - } - FileSet(fcid) => match api_client.rt.block_on(api_client.api.get_fileset( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetFilesetResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetFilesetResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetFilesetResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - WebCapture(fcid) => match api_client.rt.block_on(api_client.api.get_webcapture( - fcid.to_string(), - expand, - hide, - ))? { - fatcat_openapi::GetWebcaptureResponse::FoundEntity(model) => Ok(Box::new(model)), - fatcat_openapi::GetWebcaptureResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetWebcaptureResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Editgroup(fcid) => match api_client - .rt - .block_on(api_client.api.get_editgroup(fcid.to_string()))? - { - fatcat_openapi::GetEditgroupResponse::Found(model) => Ok(Box::new(model)), - fatcat_openapi::GetEditgroupResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetEditgroupResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Editor(fcid) => match api_client - .rt - .block_on(api_client.api.get_editor(fcid.to_string()))? - { - fatcat_openapi::GetEditorResponse::Found(model) => Ok(Box::new(model)), - fatcat_openapi::GetEditorResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetEditorResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Changelog(index) => match api_client - .rt - .block_on(api_client.api.get_changelog_entry(*index))? - { - fatcat_openapi::GetChangelogEntryResponse::FoundChangelogEntry(model) => { - Ok(Box::new(model)) - } - fatcat_openapi::GetChangelogEntryResponse::BadRequest(err) => { - Err(anyhow!("Bad Request ({}): {}", err.error, err.message)) - } - fatcat_openapi::GetChangelogEntryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - EditorUsername(_username) => { - unimplemented!( - "editor lookup by username isn't implemented in fatcat-server API yet, sorry" - ) - } - }; - match ret { - Ok(_) => ret, - Err(_) => ret.with_context(|| format!("Failed to GET {:?}", self)), - } - } - - pub fn get_history( - &self, - api_client: &mut FatcatApiClient, - limit: Option, - ) -> Result> { - let limit: Option = limit.map(|v| v as i64); - use Specifier::*; - let ret: Result> = match self { - Release(fcid) => match api_client - .rt - .block_on(api_client.api.get_release_history(fcid.to_string(), limit))? - { - fatcat_openapi::GetReleaseHistoryResponse::FoundEntityHistory(entries) => { - Ok(entries) - } - fatcat_openapi::GetReleaseHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Work(fcid) => match api_client - .rt - .block_on(api_client.api.get_work_history(fcid.to_string(), limit))? - { - fatcat_openapi::GetWorkHistoryResponse::FoundEntityHistory(entries) => Ok(entries), - fatcat_openapi::GetWorkHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Container(fcid) => match api_client.rt.block_on( - api_client - .api - .get_container_history(fcid.to_string(), limit), - )? { - fatcat_openapi::GetContainerHistoryResponse::FoundEntityHistory(entries) => { - Ok(entries) - } - fatcat_openapi::GetContainerHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - Creator(fcid) => match api_client - .rt - .block_on(api_client.api.get_creator_history(fcid.to_string(), limit))? - { - fatcat_openapi::GetCreatorHistoryResponse::FoundEntityHistory(entries) => { - Ok(entries) - } - fatcat_openapi::GetCreatorHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - File(fcid) => match api_client - .rt - .block_on(api_client.api.get_file_history(fcid.to_string(), limit))? - { - fatcat_openapi::GetFileHistoryResponse::FoundEntityHistory(entries) => Ok(entries), - fatcat_openapi::GetFileHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - FileSet(fcid) => match api_client - .rt - .block_on(api_client.api.get_fileset_history(fcid.to_string(), limit))? - { - fatcat_openapi::GetFilesetHistoryResponse::FoundEntityHistory(entries) => { - Ok(entries) - } - fatcat_openapi::GetFilesetHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - WebCapture(fcid) => match api_client.rt.block_on( - api_client - .api - .get_webcapture_history(fcid.to_string(), limit), - )? { - fatcat_openapi::GetWebcaptureHistoryResponse::FoundEntityHistory(entries) => { - Ok(entries) - } - fatcat_openapi::GetWebcaptureHistoryResponse::NotFound(err) => { - Err(anyhow!("Not Found: {}", err.message)) - } - resp => Err(anyhow!("{:?}", resp)) - .with_context(|| format!("API GET failed: {:?}", self)), - }, - _ => Err(anyhow!("Don't know how to look up history for: {:?}", self)), - }; - match ret { - Ok(_) => ret, - Err(_) => ret.with_context(|| format!("Failed to GET history: {:?}", self)), - } - } -} - -impl FromStr for Specifier { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - // first try simple entity prefixes - lazy_static! { - static ref SPEC_ENTITY_RE: Regex = Regex::new(r"^(release|work|creator|container|file|fileset|webcapture|editgroup|editor)_([2-7a-z]{26})$").unwrap(); - } - if let Some(caps) = SPEC_ENTITY_RE.captures(s) { - return match (&caps[1], &caps[2]) { - ("release", fcid) => Ok(Specifier::Release(fcid.to_string())), - ("work", fcid) => Ok(Specifier::Work(fcid.to_string())), - ("container", fcid) => Ok(Specifier::Container(fcid.to_string())), - ("creator", fcid) => Ok(Specifier::Creator(fcid.to_string())), - ("file", fcid) => Ok(Specifier::File(fcid.to_string())), - ("fileset", fcid) => Ok(Specifier::FileSet(fcid.to_string())), - ("webcapture", fcid) => Ok(Specifier::WebCapture(fcid.to_string())), - ("editgroup", fcid) => Ok(Specifier::Editgroup(fcid.to_string())), - ("editor", fcid) => Ok(Specifier::Editor(fcid.to_string())), - _ => Err(anyhow!("unexpected fatcat FCID type: {}", &caps[1])), - }; - } - - // then try lookup prefixes - lazy_static! { - static ref SPEC_LOOKUP_RE: Regex = Regex::new( - r"^(doi|pmcid|pmid|arxiv|issnl|orcid|sha1|sha256|md5|username|changelog):(\S+)$" - ) - .unwrap(); - } - if let Some(caps) = SPEC_LOOKUP_RE.captures(s) { - return match (&caps[1], &caps[2]) { - ("doi", key) => Ok(Specifier::ReleaseLookup( - ReleaseLookupKey::DOI, - key.to_string(), - )), - ("pmcid", key) => Ok(Specifier::ReleaseLookup( - ReleaseLookupKey::PMCID, - key.to_string(), - )), - ("pmid", key) => Ok(Specifier::ReleaseLookup( - ReleaseLookupKey::PMID, - key.to_string(), - )), - ("arxiv", key) => Ok(Specifier::ReleaseLookup( - ReleaseLookupKey::Arxiv, - key.to_string(), - )), - ("issnl", key) => Ok(Specifier::ContainerLookup( - ContainerLookupKey::ISSNL, - key.to_string(), - )), - ("orcid", key) => Ok(Specifier::CreatorLookup( - CreatorLookupKey::Orcid, - key.to_string(), - )), - ("sha1", key) => Ok(Specifier::FileLookup(FileLookupKey::SHA1, key.to_string())), - ("sha256", key) => Ok(Specifier::FileLookup( - FileLookupKey::SHA256, - key.to_string(), - )), - ("md5", key) => Ok(Specifier::FileLookup(FileLookupKey::MD5, key.to_string())), - ("username", key) => Ok(Specifier::EditorUsername(key.to_string())), - _ => Err(anyhow!("unexpected entity lookup type: {}", &caps[1])), - }; - } - // lastly, changelog entity lookup - lazy_static! { - static ref SPEC_CHANGELOG_RE: Regex = Regex::new(r"^changelog_(\d+)$").unwrap(); - }; - if let Some(caps) = SPEC_CHANGELOG_RE.captures(s) { - return Ok(Specifier::Changelog(caps[1].parse::()?)); - } - Err(anyhow!( - "expecting a specifier: entity identifier or key/value lookup: {}", - s - )) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_specifier_from_str() -> () { - assert!(Specifier::from_str("release_asdf").is_err()); - assert_eq!( - Specifier::from_str("creator_iimvc523xbhqlav6j3sbthuehu").unwrap(), - Specifier::Creator("iimvc523xbhqlav6j3sbthuehu".to_string()) - ); - assert_eq!( - Specifier::from_str("username:big-bot").unwrap(), - Specifier::EditorUsername("big-bot".to_string()) - ); - assert_eq!( - Specifier::from_str("doi:10.1234/a!s.df+-d").unwrap(), - Specifier::ReleaseLookup(ReleaseLookupKey::DOI, "10.1234/a!s.df+-d".to_string()) - ); - assert!(Specifier::from_str("doi:").is_err()); - assert_eq!( - Specifier::from_str("changelog_1234").unwrap(), - Specifier::Changelog(1234) - ); - assert!(Specifier::from_str("changelog_12E4").is_err()); - } -} diff --git a/rust/fatcat-openapi/.cargo/config b/rust/fatcat-openapi/.cargo/config deleted file mode 100644 index b8acc9c..0000000 --- a/rust/fatcat-openapi/.cargo/config +++ /dev/null @@ -1,18 +0,0 @@ -[build] -rustflags = [ - "-W", "missing_docs", # detects missing documentation for public members - - "-W", "trivial_casts", # detects trivial casts which could be removed - - "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed - - "-W", "unsafe_code", # usage of `unsafe` code - - "-W", "unused_qualifications", # detects unnecessarily qualified names - - "-W", "unused_extern_crates", # extern crates that are never used - - "-W", "unused_import_braces", # unnecessary braces around an imported item - - "-D", "warnings", # all warnings should be denied -] diff --git a/rust/fatcat-openapi/.gitignore b/rust/fatcat-openapi/.gitignore deleted file mode 100644 index a9d37c5..0000000 --- a/rust/fatcat-openapi/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -target -Cargo.lock diff --git a/rust/fatcat-openapi/Cargo.toml b/rust/fatcat-openapi/Cargo.toml deleted file mode 100644 index d0f12f2..0000000 --- a/rust/fatcat-openapi/Cargo.toml +++ /dev/null @@ -1,79 +0,0 @@ -[package] -name = "fatcat-openapi" -version = "0.3.3" -edition = "2018" -authors = ["Bryan Newbold "] -description = "Fatcat is an editable bibliographic database. This OpenAPI code-generated crate container HTTP API models, endpoints, and other auto-generated types useful for both client and server implementations of the catalog API." -homepage = "https://fatcat.wiki" -repository = "https://github.com/internetarchive/fatcat" -license = "CC0-1.0" - -[features] -default = ["client", "server"] -client = [ - "hyper", "hyper-openssl", "hyper-tls", "native-tls", "openssl", "url" -] -server = [ - "serde_ignored", "hyper", "regex", "percent-encoding", "url", "lazy_static" -] -conversion = ["frunk", "frunk_derives", "frunk_core", "frunk-enum-core", "frunk-enum-derive"] - -[target.'cfg(any(target_os = "macos", target_os = "windows", target_os = "ios"))'.dependencies] -native-tls = { version = "0.2", optional = true } -hyper-tls = { version = "0.4", optional = true } - -[target.'cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))'.dependencies] -hyper-openssl = { version = "0.8", optional = true } -openssl = {version = "0.10", optional = true } - -[dependencies] -# Common -async-trait = "0.1.24" -chrono = { version = "0.4", features = ["serde"] } -futures = "0.3" -swagger = "5.0.2" -log = "0.4.0" -mime = "0.3" - -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" - -# Crates included if required by the API definition - -# Common between server and client features -hyper = {version = "0.13", optional = true} -serde_ignored = {version = "0.1.1", optional = true} -url = {version = "2.1", optional = true} - -# Client-specific - -# Server, and client callback-specific -lazy_static = { version = "1.4", optional = true } -percent-encoding = {version = "2.1.0", optional = true} -regex = {version = "1.3", optional = true} - -# Conversion -frunk = { version = "0.3.0", optional = true } -frunk_derives = { version = "0.3.0", optional = true } -frunk_core = { version = "0.3.0", optional = true } -frunk-enum-derive = { version = "0.2.0", optional = true } -frunk-enum-core = { version = "0.2.0", optional = true } - -[dev-dependencies] -clap = "2.25" -env_logger = "0.7" -tokio = { version = "0.2", features = ["rt-threaded", "macros", "stream"] } -native-tls = "0.2" -tokio-tls = "0.3" - -[target.'cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))'.dev-dependencies] -tokio-openssl = "0.4" -openssl = "0.10" - -[[example]] -name = "client" -required-features = ["client"] - -[[example]] -name = "server" -required-features = ["server"] diff --git a/rust/fatcat-openapi/README.md b/rust/fatcat-openapi/README.md deleted file mode 100644 index acb0fbc..0000000 --- a/rust/fatcat-openapi/README.md +++ /dev/null @@ -1,316 +0,0 @@ -# Rust API for fatcat-openapi - -Fatcat is a scalable, versioned, API-oriented catalog of bibliographic -entities and file metadata. - - -## Overview - -This client/server was generated by the [openapi-generator] -(https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote -server, you can easily generate a server stub. - -To see how to make this your own, look here: - -[README]((https://openapi-generator.tech)) - -- API version: 0.3.3 -- Build date: 2021-02-02T11:39:37.681488-08:00[America/Los_Angeles] - -For more information, please visit [https://fatcat.wiki](https://fatcat.wiki) - -This autogenerated project defines an API crate `fatcat-openapi` which contains: -* An `Api` trait defining the API in Rust. -* Data types representing the underlying data model. -* A `Client` type which implements `Api` and issues HTTP requests for each operation. -* A router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. - -It also contains an example server and client which make use of `fatcat-openapi`: - -* The example server starts up a web server using the `fatcat-openapi` - router, and supplies a trivial implementation of `Api` which returns failure - for every operation. -* The example client provides a CLI which lets you invoke - any single operation on the `fatcat-openapi` client by passing appropriate - arguments on the command line. - -You can use the example server and client as a basis for your own code. -See below for [more detail on implementing a server](#writing-a-server). - -## Examples - -Run examples with: - -``` -cargo run --example -``` - -To pass in arguments to the examples, put them after `--`, for example: - -``` -cargo run --example client -- --help -``` - -### Running the example server -To run the server, follow these simple steps: - -``` -cargo run --example server -``` - -### Running the example client -To run a client, follow one of the following simple steps: - -``` -cargo run --example client AcceptEditgroup -cargo run --example client AuthCheck -cargo run --example client CreateAuthToken -cargo run --example client DeleteContainer -cargo run --example client DeleteContainerEdit -cargo run --example client DeleteCreator -cargo run --example client DeleteCreatorEdit -cargo run --example client DeleteFile -cargo run --example client DeleteFileEdit -cargo run --example client DeleteFileset -cargo run --example client DeleteFilesetEdit -cargo run --example client DeleteRelease -cargo run --example client DeleteReleaseEdit -cargo run --example client DeleteWebcapture -cargo run --example client DeleteWebcaptureEdit -cargo run --example client DeleteWork -cargo run --example client DeleteWorkEdit -cargo run --example client GetChangelog -cargo run --example client GetChangelogEntry -cargo run --example client GetContainer -cargo run --example client GetContainerEdit -cargo run --example client GetContainerHistory -cargo run --example client GetContainerRedirects -cargo run --example client GetContainerRevision -cargo run --example client GetCreator -cargo run --example client GetCreatorEdit -cargo run --example client GetCreatorHistory -cargo run --example client GetCreatorRedirects -cargo run --example client GetCreatorReleases -cargo run --example client GetCreatorRevision -cargo run --example client GetEditgroup -cargo run --example client GetEditgroupAnnotations -cargo run --example client GetEditgroupsReviewable -cargo run --example client GetEditor -cargo run --example client GetEditorAnnotations -cargo run --example client GetEditorEditgroups -cargo run --example client GetFile -cargo run --example client GetFileEdit -cargo run --example client GetFileHistory -cargo run --example client GetFileRedirects -cargo run --example client GetFileRevision -cargo run --example client GetFileset -cargo run --example client GetFilesetEdit -cargo run --example client GetFilesetHistory -cargo run --example client GetFilesetRedirects -cargo run --example client GetFilesetRevision -cargo run --example client GetRelease -cargo run --example client GetReleaseEdit -cargo run --example client GetReleaseFiles -cargo run --example client GetReleaseFilesets -cargo run --example client GetReleaseHistory -cargo run --example client GetReleaseRedirects -cargo run --example client GetReleaseRevision -cargo run --example client GetReleaseWebcaptures -cargo run --example client GetWebcapture -cargo run --example client GetWebcaptureEdit -cargo run --example client GetWebcaptureHistory -cargo run --example client GetWebcaptureRedirects -cargo run --example client GetWebcaptureRevision -cargo run --example client GetWork -cargo run --example client GetWorkEdit -cargo run --example client GetWorkHistory -cargo run --example client GetWorkRedirects -cargo run --example client GetWorkReleases -cargo run --example client GetWorkRevision -cargo run --example client LookupContainer -cargo run --example client LookupCreator -cargo run --example client LookupFile -cargo run --example client LookupRelease -``` - -### HTTPS -The examples can be run in HTTPS mode by passing in the flag `--https`, for example: - -``` -cargo run --example server -- --https -``` - -This will use the keys/certificates from the examples directory. Note that the -server chain is signed with `CN=localhost`. - -## Using the generated library - -The generated library has a few optional features that can be activated through Cargo. - -* `server` - * This defaults to enabled and creates the basic skeleton of a server implementation based on hyper - * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. -* `client` - * This defaults to enabled and creates the basic skeleton of a client implementation based on hyper - * The constructed client implements the API trait by making remote API call. -* `conversions` - * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. - -See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. - -## Documentation for API Endpoints - -All URIs are relative to *https://api.fatcat.wiki/v0* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**accept_editgroup**](docs/default_api.md#accept_editgroup) | **POST** /editgroup/{editgroup_id}/accept | -[**auth_check**](docs/default_api.md#auth_check) | **GET** /auth/check | -[**auth_oidc**](docs/default_api.md#auth_oidc) | **POST** /auth/oidc | -[**create_auth_token**](docs/default_api.md#create_auth_token) | **POST** /auth/token/{editor_id} | -[**create_container**](docs/default_api.md#create_container) | **POST** /editgroup/{editgroup_id}/container | -[**create_container_auto_batch**](docs/default_api.md#create_container_auto_batch) | **POST** /editgroup/auto/container/batch | -[**create_creator**](docs/default_api.md#create_creator) | **POST** /editgroup/{editgroup_id}/creator | -[**create_creator_auto_batch**](docs/default_api.md#create_creator_auto_batch) | **POST** /editgroup/auto/creator/batch | -[**create_editgroup**](docs/default_api.md#create_editgroup) | **POST** /editgroup | -[**create_editgroup_annotation**](docs/default_api.md#create_editgroup_annotation) | **POST** /editgroup/{editgroup_id}/annotation | -[**create_file**](docs/default_api.md#create_file) | **POST** /editgroup/{editgroup_id}/file | -[**create_file_auto_batch**](docs/default_api.md#create_file_auto_batch) | **POST** /editgroup/auto/file/batch | -[**create_fileset**](docs/default_api.md#create_fileset) | **POST** /editgroup/{editgroup_id}/fileset | -[**create_fileset_auto_batch**](docs/default_api.md#create_fileset_auto_batch) | **POST** /editgroup/auto/fileset/batch | -[**create_release**](docs/default_api.md#create_release) | **POST** /editgroup/{editgroup_id}/release | -[**create_release_auto_batch**](docs/default_api.md#create_release_auto_batch) | **POST** /editgroup/auto/release/batch | -[**create_webcapture**](docs/default_api.md#create_webcapture) | **POST** /editgroup/{editgroup_id}/webcapture | -[**create_webcapture_auto_batch**](docs/default_api.md#create_webcapture_auto_batch) | **POST** /editgroup/auto/webcapture/batch | -[**create_work**](docs/default_api.md#create_work) | **POST** /editgroup/{editgroup_id}/work | -[**create_work_auto_batch**](docs/default_api.md#create_work_auto_batch) | **POST** /editgroup/auto/work/batch | -[**delete_container**](docs/default_api.md#delete_container) | **DELETE** /editgroup/{editgroup_id}/container/{ident} | -[**delete_container_edit**](docs/default_api.md#delete_container_edit) | **DELETE** /editgroup/{editgroup_id}/container/edit/{edit_id} | -[**delete_creator**](docs/default_api.md#delete_creator) | **DELETE** /editgroup/{editgroup_id}/creator/{ident} | -[**delete_creator_edit**](docs/default_api.md#delete_creator_edit) | **DELETE** /editgroup/{editgroup_id}/creator/edit/{edit_id} | -[**delete_file**](docs/default_api.md#delete_file) | **DELETE** /editgroup/{editgroup_id}/file/{ident} | -[**delete_file_edit**](docs/default_api.md#delete_file_edit) | **DELETE** /editgroup/{editgroup_id}/file/edit/{edit_id} | -[**delete_fileset**](docs/default_api.md#delete_fileset) | **DELETE** /editgroup/{editgroup_id}/fileset/{ident} | -[**delete_fileset_edit**](docs/default_api.md#delete_fileset_edit) | **DELETE** /editgroup/{editgroup_id}/fileset/edit/{edit_id} | -[**delete_release**](docs/default_api.md#delete_release) | **DELETE** /editgroup/{editgroup_id}/release/{ident} | -[**delete_release_edit**](docs/default_api.md#delete_release_edit) | **DELETE** /editgroup/{editgroup_id}/release/edit/{edit_id} | -[**delete_webcapture**](docs/default_api.md#delete_webcapture) | **DELETE** /editgroup/{editgroup_id}/webcapture/{ident} | -[**delete_webcapture_edit**](docs/default_api.md#delete_webcapture_edit) | **DELETE** /editgroup/{editgroup_id}/webcapture/edit/{edit_id} | -[**delete_work**](docs/default_api.md#delete_work) | **DELETE** /editgroup/{editgroup_id}/work/{ident} | -[**delete_work_edit**](docs/default_api.md#delete_work_edit) | **DELETE** /editgroup/{editgroup_id}/work/edit/{edit_id} | -[**get_changelog**](docs/default_api.md#get_changelog) | **GET** /changelog | -[**get_changelog_entry**](docs/default_api.md#get_changelog_entry) | **GET** /changelog/{index} | -[**get_container**](docs/default_api.md#get_container) | **GET** /container/{ident} | -[**get_container_edit**](docs/default_api.md#get_container_edit) | **GET** /container/edit/{edit_id} | -[**get_container_history**](docs/default_api.md#get_container_history) | **GET** /container/{ident}/history | -[**get_container_redirects**](docs/default_api.md#get_container_redirects) | **GET** /container/{ident}/redirects | -[**get_container_revision**](docs/default_api.md#get_container_revision) | **GET** /container/rev/{rev_id} | -[**get_creator**](docs/default_api.md#get_creator) | **GET** /creator/{ident} | -[**get_creator_edit**](docs/default_api.md#get_creator_edit) | **GET** /creator/edit/{edit_id} | -[**get_creator_history**](docs/default_api.md#get_creator_history) | **GET** /creator/{ident}/history | -[**get_creator_redirects**](docs/default_api.md#get_creator_redirects) | **GET** /creator/{ident}/redirects | -[**get_creator_releases**](docs/default_api.md#get_creator_releases) | **GET** /creator/{ident}/releases | -[**get_creator_revision**](docs/default_api.md#get_creator_revision) | **GET** /creator/rev/{rev_id} | -[**get_editgroup**](docs/default_api.md#get_editgroup) | **GET** /editgroup/{editgroup_id} | -[**get_editgroup_annotations**](docs/default_api.md#get_editgroup_annotations) | **GET** /editgroup/{editgroup_id}/annotations | -[**get_editgroups_reviewable**](docs/default_api.md#get_editgroups_reviewable) | **GET** /editgroup/reviewable | -[**get_editor**](docs/default_api.md#get_editor) | **GET** /editor/{editor_id} | -[**get_editor_annotations**](docs/default_api.md#get_editor_annotations) | **GET** /editor/{editor_id}/annotations | -[**get_editor_editgroups**](docs/default_api.md#get_editor_editgroups) | **GET** /editor/{editor_id}/editgroups | -[**get_file**](docs/default_api.md#get_file) | **GET** /file/{ident} | -[**get_file_edit**](docs/default_api.md#get_file_edit) | **GET** /file/edit/{edit_id} | -[**get_file_history**](docs/default_api.md#get_file_history) | **GET** /file/{ident}/history | -[**get_file_redirects**](docs/default_api.md#get_file_redirects) | **GET** /file/{ident}/redirects | -[**get_file_revision**](docs/default_api.md#get_file_revision) | **GET** /file/rev/{rev_id} | -[**get_fileset**](docs/default_api.md#get_fileset) | **GET** /fileset/{ident} | -[**get_fileset_edit**](docs/default_api.md#get_fileset_edit) | **GET** /fileset/edit/{edit_id} | -[**get_fileset_history**](docs/default_api.md#get_fileset_history) | **GET** /fileset/{ident}/history | -[**get_fileset_redirects**](docs/default_api.md#get_fileset_redirects) | **GET** /fileset/{ident}/redirects | -[**get_fileset_revision**](docs/default_api.md#get_fileset_revision) | **GET** /fileset/rev/{rev_id} | -[**get_release**](docs/default_api.md#get_release) | **GET** /release/{ident} | -[**get_release_edit**](docs/default_api.md#get_release_edit) | **GET** /release/edit/{edit_id} | -[**get_release_files**](docs/default_api.md#get_release_files) | **GET** /release/{ident}/files | -[**get_release_filesets**](docs/default_api.md#get_release_filesets) | **GET** /release/{ident}/filesets | -[**get_release_history**](docs/default_api.md#get_release_history) | **GET** /release/{ident}/history | -[**get_release_redirects**](docs/default_api.md#get_release_redirects) | **GET** /release/{ident}/redirects | -[**get_release_revision**](docs/default_api.md#get_release_revision) | **GET** /release/rev/{rev_id} | -[**get_release_webcaptures**](docs/default_api.md#get_release_webcaptures) | **GET** /release/{ident}/webcaptures | -[**get_webcapture**](docs/default_api.md#get_webcapture) | **GET** /webcapture/{ident} | -[**get_webcapture_edit**](docs/default_api.md#get_webcapture_edit) | **GET** /webcapture/edit/{edit_id} | -[**get_webcapture_history**](docs/default_api.md#get_webcapture_history) | **GET** /webcapture/{ident}/history | -[**get_webcapture_redirects**](docs/default_api.md#get_webcapture_redirects) | **GET** /webcapture/{ident}/redirects | -[**get_webcapture_revision**](docs/default_api.md#get_webcapture_revision) | **GET** /webcapture/rev/{rev_id} | -[**get_work**](docs/default_api.md#get_work) | **GET** /work/{ident} | -[**get_work_edit**](docs/default_api.md#get_work_edit) | **GET** /work/edit/{edit_id} | -[**get_work_history**](docs/default_api.md#get_work_history) | **GET** /work/{ident}/history | -[**get_work_redirects**](docs/default_api.md#get_work_redirects) | **GET** /work/{ident}/redirects | -[**get_work_releases**](docs/default_api.md#get_work_releases) | **GET** /work/{ident}/releases | -[**get_work_revision**](docs/default_api.md#get_work_revision) | **GET** /work/rev/{rev_id} | -[**lookup_container**](docs/default_api.md#lookup_container) | **GET** /container/lookup | -[**lookup_creator**](docs/default_api.md#lookup_creator) | **GET** /creator/lookup | -[**lookup_file**](docs/default_api.md#lookup_file) | **GET** /file/lookup | -[**lookup_release**](docs/default_api.md#lookup_release) | **GET** /release/lookup | -[**update_container**](docs/default_api.md#update_container) | **PUT** /editgroup/{editgroup_id}/container/{ident} | -[**update_creator**](docs/default_api.md#update_creator) | **PUT** /editgroup/{editgroup_id}/creator/{ident} | -[**update_editgroup**](docs/default_api.md#update_editgroup) | **PUT** /editgroup/{editgroup_id} | -[**update_editor**](docs/default_api.md#update_editor) | **PUT** /editor/{editor_id} | -[**update_file**](docs/default_api.md#update_file) | **PUT** /editgroup/{editgroup_id}/file/{ident} | -[**update_fileset**](docs/default_api.md#update_fileset) | **PUT** /editgroup/{editgroup_id}/fileset/{ident} | -[**update_release**](docs/default_api.md#update_release) | **PUT** /editgroup/{editgroup_id}/release/{ident} | -[**update_webcapture**](docs/default_api.md#update_webcapture) | **PUT** /editgroup/{editgroup_id}/webcapture/{ident} | -[**update_work**](docs/default_api.md#update_work) | **PUT** /editgroup/{editgroup_id}/work/{ident} | - - -## Documentation For Models - - - [AuthOidc](docs/AuthOidc.md) - - [AuthOidcResult](docs/AuthOidcResult.md) - - [AuthTokenResult](docs/AuthTokenResult.md) - - [ChangelogEntry](docs/ChangelogEntry.md) - - [ContainerAutoBatch](docs/ContainerAutoBatch.md) - - [ContainerEntity](docs/ContainerEntity.md) - - [CreatorAutoBatch](docs/CreatorAutoBatch.md) - - [CreatorEntity](docs/CreatorEntity.md) - - [Editgroup](docs/Editgroup.md) - - [EditgroupAnnotation](docs/EditgroupAnnotation.md) - - [EditgroupEdits](docs/EditgroupEdits.md) - - [Editor](docs/Editor.md) - - [EntityEdit](docs/EntityEdit.md) - - [EntityHistoryEntry](docs/EntityHistoryEntry.md) - - [ErrorResponse](docs/ErrorResponse.md) - - [FileAutoBatch](docs/FileAutoBatch.md) - - [FileEntity](docs/FileEntity.md) - - [FileUrl](docs/FileUrl.md) - - [FilesetAutoBatch](docs/FilesetAutoBatch.md) - - [FilesetEntity](docs/FilesetEntity.md) - - [FilesetFile](docs/FilesetFile.md) - - [FilesetUrl](docs/FilesetUrl.md) - - [ReleaseAbstract](docs/ReleaseAbstract.md) - - [ReleaseAutoBatch](docs/ReleaseAutoBatch.md) - - [ReleaseContrib](docs/ReleaseContrib.md) - - [ReleaseEntity](docs/ReleaseEntity.md) - - [ReleaseExtIds](docs/ReleaseExtIds.md) - - [ReleaseRef](docs/ReleaseRef.md) - - [Success](docs/Success.md) - - [WebcaptureAutoBatch](docs/WebcaptureAutoBatch.md) - - [WebcaptureCdxLine](docs/WebcaptureCdxLine.md) - - [WebcaptureEntity](docs/WebcaptureEntity.md) - - [WebcaptureUrl](docs/WebcaptureUrl.md) - - [WorkAutoBatch](docs/WorkAutoBatch.md) - - [WorkEntity](docs/WorkEntity.md) - - -## Documentation For Authorization - -## Bearer -- **Type**: HTTP basic authentication - -Example -``` -``` - -## Author - -webservices@archive.org - diff --git a/rust/fatcat-openapi/docs/AuthOidc.md b/rust/fatcat-openapi/docs/AuthOidc.md deleted file mode 100644 index de80baa..0000000 --- a/rust/fatcat-openapi/docs/AuthOidc.md +++ /dev/null @@ -1,13 +0,0 @@ -# AuthOidc - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**provider** | **String** | Fatcat-specific short name (slug) for remote service being used for authentication. | -**sub** | **String** | `SUB` from OIDC protocol. Usually a URL. | -**iss** | **String** | `ISS` from OIDC protocol. Usually a stable account username, number, or identifier. | -**preferred_username** | **String** | What it sounds like; returned by OIDC, and used as a hint when creating new editor accounts. Fatcat usernames are usually this string with the `provider` slug as a suffix, though some munging may occur. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/AuthOidcResult.md b/rust/fatcat-openapi/docs/AuthOidcResult.md deleted file mode 100644 index 3418bea..0000000 --- a/rust/fatcat-openapi/docs/AuthOidcResult.md +++ /dev/null @@ -1,11 +0,0 @@ -# AuthOidcResult - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editor** | [***models::Editor**](editor.md) | | -**token** | **String** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/AuthTokenResult.md b/rust/fatcat-openapi/docs/AuthTokenResult.md deleted file mode 100644 index 2bb3dd7..0000000 --- a/rust/fatcat-openapi/docs/AuthTokenResult.md +++ /dev/null @@ -1,10 +0,0 @@ -# AuthTokenResult - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**token** | **String** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ChangelogEntry.md b/rust/fatcat-openapi/docs/ChangelogEntry.md deleted file mode 100644 index 3f62f70..0000000 --- a/rust/fatcat-openapi/docs/ChangelogEntry.md +++ /dev/null @@ -1,13 +0,0 @@ -# ChangelogEntry - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**index** | **i64** | Monotonically increasing sequence number of this changelog entry. | -**editgroup_id** | **String** | Identifier of editgroup accepted/merged in this changelog entry. | -**timestamp** | [**chrono::DateTime::**](DateTime.md) | Date and time when the editgroup was accpeted. | -**editgroup** | [***models::Editgroup**](editgroup.md) | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ContainerAutoBatch.md b/rust/fatcat-openapi/docs/ContainerAutoBatch.md deleted file mode 100644 index 0413aac..0000000 --- a/rust/fatcat-openapi/docs/ContainerAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# ContainerAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](container_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ContainerEntity.md b/rust/fatcat-openapi/docs/ContainerEntity.md deleted file mode 100644 index 376130e..0000000 --- a/rust/fatcat-openapi/docs/ContainerEntity.md +++ /dev/null @@ -1,20 +0,0 @@ -# ContainerEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**name** | **String** | Name of the container (eg, Journal title). Required for entity creation. | [optional] [default to None] -**container_type** | **String** | Type of container, eg 'journal' or 'proceedings'. See Guide for list of valid types. | [optional] [default to None] -**publisher** | **String** | Name of the organization or entity responsible for publication. Not the complete imprint/brand. | [optional] [default to None] -**issnl** | **String** | Linking ISSN number (ISSN-L). Should be valid and registered with issn.org | [optional] [default to None] -**wikidata_qid** | **String** | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/CreatorAutoBatch.md b/rust/fatcat-openapi/docs/CreatorAutoBatch.md deleted file mode 100644 index b30375c..0000000 --- a/rust/fatcat-openapi/docs/CreatorAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# CreatorAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](creator_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/CreatorEntity.md b/rust/fatcat-openapi/docs/CreatorEntity.md deleted file mode 100644 index 2b7306c..0000000 --- a/rust/fatcat-openapi/docs/CreatorEntity.md +++ /dev/null @@ -1,20 +0,0 @@ -# CreatorEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**display_name** | **String** | Name as should be displayed in web interface or in author lists (not index/sorted). Required for valid entities. | [optional] [default to None] -**given_name** | **String** | In English commonly the first name, but ordering is context and culture specific. | [optional] [default to None] -**surname** | **String** | In English commonly the last, or family name, but ordering is context and culture specific. | [optional] [default to None] -**orcid** | **String** | ORCiD (https://orcid.org) identifier | [optional] [default to None] -**wikidata_qid** | **String** | Wikidata entity QID | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/Editgroup.md b/rust/fatcat-openapi/docs/Editgroup.md deleted file mode 100644 index 5faafd6..0000000 --- a/rust/fatcat-openapi/docs/Editgroup.md +++ /dev/null @@ -1,19 +0,0 @@ -# Editgroup - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup_id** | **String** | Fatcat identifier for this editgroup. Assigned on creation. | [optional] [default to None] -**editor_id** | **String** | Fatcat identifer of editor that created this editgroup. | [optional] [default to None] -**editor** | [***models::Editor**](editor.md) | | [optional] [default to None] -**changelog_index** | **i64** | For accepted/merged editgroups, the changelog index that the accept occured at. WARNING: not populated in all contexts that an editgroup could be included in a response. | [optional] [default to None] -**created** | [**chrono::DateTime::**](DateTime.md) | Timestamp when this editgroup was first created. | [optional] [default to None] -**submitted** | [**chrono::DateTime::**](DateTime.md) | Timestamp when this editgroup was most recently submitted for review. If withdrawn, or never submitted, will be `null`. | [optional] [default to None] -**description** | **String** | Comment describing the changes in this editgroup. Can be updated with PUT request. | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata attached to this editgroup. Eg, metadata provenance, or script user-agent details. See guide for (unenforced) schema norms. | [optional] [default to None] -**annotations** | [**Vec**](editgroup_annotation.md) | Only included in GET responses, and not in all contexts. Do not include this field in PUT or POST requests. | [optional] [default to None] -**edits** | [***models::EditgroupEdits**](editgroup_edits.md) | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/EditgroupAnnotation.md b/rust/fatcat-openapi/docs/EditgroupAnnotation.md deleted file mode 100644 index 3450e4d..0000000 --- a/rust/fatcat-openapi/docs/EditgroupAnnotation.md +++ /dev/null @@ -1,16 +0,0 @@ -# EditgroupAnnotation - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**annotation_id** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**editgroup_id** | **String** | Editgroup that this annotation applies to. Set automatically in creations based on URL parameter. | [optional] [default to None] -**editor_id** | **String** | Defaults to editor created the annotation via POST request. | [optional] [default to None] -**editor** | [***models::Editor**](editor.md) | | [optional] [default to None] -**created** | [**chrono::DateTime::**](DateTime.md) | Timestamp when annotation was first created. | [optional] [default to None] -**comment_markdown** | **String** | | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Additional free-form JSON metadata that can be included as part of the annotation (or even as the primary annotation itself). See guide for details. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/EditgroupEdits.md b/rust/fatcat-openapi/docs/EditgroupEdits.md deleted file mode 100644 index cb3cd82..0000000 --- a/rust/fatcat-openapi/docs/EditgroupEdits.md +++ /dev/null @@ -1,16 +0,0 @@ -# EditgroupEdits - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**containers** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**creators** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**files** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**filesets** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**webcaptures** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**releases** | [**Vec**](entity_edit.md) | | [optional] [default to None] -**works** | [**Vec**](entity_edit.md) | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/Editor.md b/rust/fatcat-openapi/docs/Editor.md deleted file mode 100644 index 4cf495f..0000000 --- a/rust/fatcat-openapi/docs/Editor.md +++ /dev/null @@ -1,14 +0,0 @@ -# Editor - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editor_id** | **String** | Fatcat identifier for the editor. Can not be changed. | [optional] [default to None] -**username** | **String** | Username/handle (short slug-like string) to identify this editor. May be changed at any time by the editor; use the `editor_id` as a persistend identifer. | -**is_admin** | **bool** | Whether this editor has the `admin` role. | [optional] [default to None] -**is_bot** | **bool** | Whether this editor is a bot (as opposed to a human making manual edits) | [optional] [default to None] -**is_active** | **bool** | Whether this editor's account is enabled (if not API tokens and web logins will not work). | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/EntityEdit.md b/rust/fatcat-openapi/docs/EntityEdit.md deleted file mode 100644 index 5d51a87..0000000 --- a/rust/fatcat-openapi/docs/EntityEdit.md +++ /dev/null @@ -1,16 +0,0 @@ -# EntityEdit - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**edit_id** | **String** | Unique UUID for this specific edit object. | -**ident** | **String** | Fatcat identifier of the entity this edit is mutating. | -**revision** | **String** | Entity revision that this edit will set the entity to. May be `null` in the case of deletions. | [optional] [default to None] -**prev_revision** | **String** | Revision of entity just before this edit. May be used in the future to prevent edit race conditions. | [optional] [default to None] -**redirect_ident** | **String** | When an edit is to merge entities (redirect one to another), this is the entity fatcat identifier for the target entity. | [optional] [default to None] -**editgroup_id** | **String** | Editgroup identifier that this edit is part of. | -**extra** | [**std::collections::HashMap**](AnyType.md) | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/EntityHistoryEntry.md b/rust/fatcat-openapi/docs/EntityHistoryEntry.md deleted file mode 100644 index 4df6b5f..0000000 --- a/rust/fatcat-openapi/docs/EntityHistoryEntry.md +++ /dev/null @@ -1,12 +0,0 @@ -# EntityHistoryEntry - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**edit** | [***models::EntityEdit**](entity_edit.md) | | -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**changelog_entry** | [***models::ChangelogEntry**](changelog_entry.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ErrorResponse.md b/rust/fatcat-openapi/docs/ErrorResponse.md deleted file mode 100644 index 89008f1..0000000 --- a/rust/fatcat-openapi/docs/ErrorResponse.md +++ /dev/null @@ -1,12 +0,0 @@ -# ErrorResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**success** | **bool** | | -**error** | **String** | | -**message** | **String** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FileAutoBatch.md b/rust/fatcat-openapi/docs/FileAutoBatch.md deleted file mode 100644 index d45685e..0000000 --- a/rust/fatcat-openapi/docs/FileAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# FileAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](file_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FileEntity.md b/rust/fatcat-openapi/docs/FileEntity.md deleted file mode 100644 index 496e797..0000000 --- a/rust/fatcat-openapi/docs/FileEntity.md +++ /dev/null @@ -1,23 +0,0 @@ -# FileEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**size** | **i64** | Size of file in bytes. Non-zero. | [optional] [default to None] -**md5** | **String** | MD5 hash of data, in hex encoding | [optional] [default to None] -**sha1** | **String** | SHA-1 hash of data, in hex encoding | [optional] [default to None] -**sha256** | **String** | SHA-256 hash of data, in hex encoding | [optional] [default to None] -**urls** | [**Vec**](file_url.md) | | [optional] [default to None] -**mimetype** | **String** | | [optional] [default to None] -**release_ids** | **Vec** | Set of identifier of release entities this file represents a full manifestation of. Usually a single release, but some files contain content of multiple full releases (eg, an issue of a journal). | [optional] [default to None] -**releases** | [**Vec**](release_entity.md) | Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FileUrl.md b/rust/fatcat-openapi/docs/FileUrl.md deleted file mode 100644 index 89a832e..0000000 --- a/rust/fatcat-openapi/docs/FileUrl.md +++ /dev/null @@ -1,11 +0,0 @@ -# FileUrl - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**url** | **String** | URL/URI pointing directly to a machine retrievable copy of this exact file. | -**rel** | **String** | Indicates type of host this URL points to. Eg, \"publisher\", \"repository\", \"webarchive\". See guide for list of acceptable values. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FilesetAutoBatch.md b/rust/fatcat-openapi/docs/FilesetAutoBatch.md deleted file mode 100644 index df41e6b..0000000 --- a/rust/fatcat-openapi/docs/FilesetAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# FilesetAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](fileset_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FilesetEntity.md b/rust/fatcat-openapi/docs/FilesetEntity.md deleted file mode 100644 index 14ce4bf..0000000 --- a/rust/fatcat-openapi/docs/FilesetEntity.md +++ /dev/null @@ -1,19 +0,0 @@ -# FilesetEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**manifest** | [**Vec**](fileset_file.md) | | [optional] [default to None] -**urls** | [**Vec**](fileset_url.md) | | [optional] [default to None] -**release_ids** | **Vec** | Set of identifier of release entities this fileset represents a full manifestation of. Usually a single release. | [optional] [default to None] -**releases** | [**Vec**](release_entity.md) | Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FilesetFile.md b/rust/fatcat-openapi/docs/FilesetFile.md deleted file mode 100644 index b023e4a..0000000 --- a/rust/fatcat-openapi/docs/FilesetFile.md +++ /dev/null @@ -1,15 +0,0 @@ -# FilesetFile - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**path** | **String** | Path name of file within this fileset (eg, directory) | -**size** | **i64** | File size in bytes | -**md5** | **String** | MD5 hash of data, in hex encoding | [optional] [default to None] -**sha1** | **String** | SHA-1 hash of data, in hex encoding | [optional] [default to None] -**sha256** | **String** | SHA-256 hash of data, in hex encoding | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form additional metadata about this specific file in the set. Eg, `mimetype`. See guide for nomative (but unenforced) schema fields. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/FilesetUrl.md b/rust/fatcat-openapi/docs/FilesetUrl.md deleted file mode 100644 index 2c38760..0000000 --- a/rust/fatcat-openapi/docs/FilesetUrl.md +++ /dev/null @@ -1,11 +0,0 @@ -# FilesetUrl - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**url** | **String** | | -**rel** | **String** | Indicates type of host this URL points to. See guide for list of acceptable values. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseAbstract.md b/rust/fatcat-openapi/docs/ReleaseAbstract.md deleted file mode 100644 index 32f9bdc..0000000 --- a/rust/fatcat-openapi/docs/ReleaseAbstract.md +++ /dev/null @@ -1,13 +0,0 @@ -# ReleaseAbstract - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**sha1** | **String** | SHA-1 hash of data, in hex encoding | [optional] [default to None] -**content** | **String** | Abstract content. May be encoded, as per `mimetype` field, but only string/text content may be included. | [optional] [default to None] -**mimetype** | **String** | Mimetype of abstract contents. `text/plain` is the default if content isn't encoded. | [optional] [default to None] -**lang** | **String** | ISO language code of the abstract. Same semantics as release `language` field. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseAutoBatch.md b/rust/fatcat-openapi/docs/ReleaseAutoBatch.md deleted file mode 100644 index 8f60344..0000000 --- a/rust/fatcat-openapi/docs/ReleaseAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# ReleaseAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](release_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseContrib.md b/rust/fatcat-openapi/docs/ReleaseContrib.md deleted file mode 100644 index b30b1d8..0000000 --- a/rust/fatcat-openapi/docs/ReleaseContrib.md +++ /dev/null @@ -1,18 +0,0 @@ -# ReleaseContrib - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**index** | **i64** | Internally assigned zero-indexed sequence number of contribution. Authors should come first; this encodes the order of attriubtion. | [optional] [default to None] -**creator_id** | **String** | If known, indicates the creator entity this contribution was made by. | [optional] [default to None] -**creator** | [***models::CreatorEntity**](creator_entity.md) | | [optional] [default to None] -**raw_name** | **String** | Full name of the contributor as typeset in the release. | [optional] [default to None] -**given_name** | **String** | In English commonly the first name, but ordering is context and culture specific. | [optional] [default to None] -**surname** | **String** | In English commonly the last, or family name, but ordering is context and culture specific. | [optional] [default to None] -**role** | **String** | Short string (slug) indicating type of contribution (eg, \"author\", \"translator\"). See guide for list of accpeted values. | [optional] [default to None] -**raw_affiliation** | **String** | Raw affiliation string as displayed in text | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Additional free-form JSON metadata about this contributor/contribution. See guide for normative schema. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseEntity.md b/rust/fatcat-openapi/docs/ReleaseEntity.md deleted file mode 100644 index a30561c..0000000 --- a/rust/fatcat-openapi/docs/ReleaseEntity.md +++ /dev/null @@ -1,43 +0,0 @@ -# ReleaseEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**title** | **String** | Required for valid entities. The title used in citations and for display. Sometimes the English translation of title e even if release content is not English. | [optional] [default to None] -**subtitle** | **String** | Subtitle of release. In many cases, better to merge with title than include as separate field (unless combined title would be very long). See guide for details. | [optional] [default to None] -**original_title** | **String** | Title in original language if `title` field has been translated. See guide for details. | [optional] [default to None] -**work_id** | **String** | Identifier of work this release is part of. In creation (POST) requests, a work entity will be created automatically if this field is not set. | [optional] [default to None] -**container** | [***models::ContainerEntity**](container_entity.md) | | [optional] [default to None] -**files** | [**Vec**](file_entity.md) | Complete file entities identified by `file_ids` field. Only included in GET responses when `files` included in `expand` parameter; ignored in PUT or POST requests. | [optional] [default to None] -**filesets** | [**Vec**](fileset_entity.md) | Complete file entities identified by `filesets_ids` field. Only included in GET responses when `filesets` included in `expand` parameter; ignored in PUT or POST requests. | [optional] [default to None] -**webcaptures** | [**Vec**](webcapture_entity.md) | Complete webcapture entities identified by `webcapture_ids` field. Only included in GET responses when `webcaptures` included in `expand` parameter; ignored in PUT or POST requests. | [optional] [default to None] -**container_id** | **String** | Used to link this release to a container entity that the release was published as part of. | [optional] [default to None] -**release_type** | **String** | \"Type\" or \"medium\" that this release is published as. See guide for valid values. | [optional] [default to None] -**release_stage** | **String** | The stage of publication of this specific release. See guide for valid values and semantics. | [optional] [default to None] -**release_date** | [***chrono::DateTime::**](date.md) | Full date when this release was formally published. ISO format, like `2019-03-05`. See guide for semantics. | [optional] [default to None] -**release_year** | **i64** | Year when this release was formally published. Must match `release_date` if that field is set; this field exists because sometimes only the year is known. | [optional] [default to None] -**withdrawn_status** | **String** | Type of withdrawl or retraction of this release, if applicable. If release has not been withdrawn, should be `null` (aka, not set, not the string \"null\" or an empty string). | [optional] [default to None] -**withdrawn_date** | [***chrono::DateTime::**](date.md) | Full date when this release was formally withdrawn (if applicable). ISO format, like `release_date`. | [optional] [default to None] -**withdrawn_year** | **i64** | Year corresponding with `withdrawn_date` like `release_year`/`release_date`. | [optional] [default to None] -**ext_ids** | [***models::ReleaseExtIds**](release_ext_ids.md) | | -**volume** | **String** | Volume number of container that this release was published in. Often corresponds to the \"Nth\" year of publication, but can be any string. See guide. | [optional] [default to None] -**issue** | **String** | Issue number of volume/container that this release was published in. Sometimes coresponds to a month number in the year, but can be any string. See guide. | [optional] [default to None] -**pages** | **String** | Either a single page number (\"first page\") or a range of pages separated by a dash (\"-\"). See guide for details. | [optional] [default to None] -**number** | **String** | For, eg, technical reports, which are published in series or assigned some other institutional or container-specific identifier. | [optional] [default to None] -**version** | **String** | For, eg, updated technical reports or software packages, where the version string may be the only field disambiguating between releases. | [optional] [default to None] -**publisher** | **String** | Name, usually English, of the entity or institution responsible for publication of this release. Not necessarily the imprint/brand. See guide. | [optional] [default to None] -**language** | **String** | Primary language of the content of the full release. Two-letter RFC1766/ISO639-1 language code, with some custom extensions/additions. See guide. | [optional] [default to None] -**license_slug** | **String** | Short string (slug) name of license under which release is openly published (if applicable). | [optional] [default to None] -**contribs** | [**Vec**](release_contrib.md) | | [optional] [default to None] -**refs** | [**Vec**](release_ref.md) | | [optional] [default to None] -**abstracts** | [**Vec**](release_abstract.md) | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseExtIds.md b/rust/fatcat-openapi/docs/ReleaseExtIds.md deleted file mode 100644 index 416d595..0000000 --- a/rust/fatcat-openapi/docs/ReleaseExtIds.md +++ /dev/null @@ -1,22 +0,0 @@ -# ReleaseExtIds - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**doi** | **String** | Digital Object Identifier (DOI), mostly for published papers and datasets. Should be registered and resolvable via https://doi.org/ | [optional] [default to None] -**wikidata_qid** | **String** | Wikidata entity QID | [optional] [default to None] -**isbn13** | **String** | ISBN-13, for books. Usually not set for chapters. ISBN-10 should be converted to ISBN-13. | [optional] [default to None] -**pmid** | **String** | PubMed Identifier | [optional] [default to None] -**pmcid** | **String** | PubMed Central Identifier | [optional] [default to None] -**core** | **String** | CORE (https://core.ac.uk) identifier | [optional] [default to None] -**arxiv** | **String** | arXiv (https://arxiv.org) identifier; must include version | [optional] [default to None] -**jstor** | **String** | JSTOR work identifier | [optional] [default to None] -**ark** | **String** | ARK identifier | [optional] [default to None] -**mag** | **String** | Microsoft Academic Graph identifier | [optional] [default to None] -**doaj** | **String** | DOAJ article-level identifier | [optional] [default to None] -**dblp** | **String** | dblp (https://dblp.uni-trier.de/) paper identifier; eg for conference proceedings | [optional] [default to None] -**oai** | **String** | OAI-PMH identifier; only used when an OAI-PMH record is the only authoritative metadata (eg, journal OAI-PMH feeds w/o DOIs) | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/ReleaseRef.md b/rust/fatcat-openapi/docs/ReleaseRef.md deleted file mode 100644 index 980cb0b..0000000 --- a/rust/fatcat-openapi/docs/ReleaseRef.md +++ /dev/null @@ -1,17 +0,0 @@ -# ReleaseRef - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**index** | **i64** | Zero-indexed sequence number of this reference in the list of references. Assigned automatically and used internally; don't confuse with `key`. | [optional] [default to None] -**target_release_id** | **String** | Optional, fatcat identifier of release entity that this reference is citing. | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Additional free-form JSON metadata about this citation. Generally follows Citation Style Language (CSL) JSON schema. See guide for details. | [optional] [default to None] -**key** | **String** | Short string used to indicate this reference from within the release text; or numbering of references as typeset in the release itself. Optional; don't confuse with `index` field. | [optional] [default to None] -**year** | **i64** | Year that the cited work was published in. | [optional] [default to None] -**container_name** | **String** | Name of the container (eg, journal) that the citation work was published as part of. May be an acronym or full name. | [optional] [default to None] -**title** | **String** | Name of the work being cited. | [optional] [default to None] -**locator** | **String** | Page number or other indicator of the specific subset of a work being cited. Not to be confused with the first page (or page range) of an entire paper or chapter being cited. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/Success.md b/rust/fatcat-openapi/docs/Success.md deleted file mode 100644 index 1264ddb..0000000 --- a/rust/fatcat-openapi/docs/Success.md +++ /dev/null @@ -1,11 +0,0 @@ -# Success - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**success** | **bool** | | -**message** | **String** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WebcaptureAutoBatch.md b/rust/fatcat-openapi/docs/WebcaptureAutoBatch.md deleted file mode 100644 index 94bfbb2..0000000 --- a/rust/fatcat-openapi/docs/WebcaptureAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# WebcaptureAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](webcapture_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WebcaptureCdxLine.md b/rust/fatcat-openapi/docs/WebcaptureCdxLine.md deleted file mode 100644 index 9f1ef49..0000000 --- a/rust/fatcat-openapi/docs/WebcaptureCdxLine.md +++ /dev/null @@ -1,17 +0,0 @@ -# WebcaptureCdxLine - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**surt** | **String** | \"Sortable URL\" format. See guide for details. | -**timestamp** | [**chrono::DateTime::**](DateTime.md) | Date and time of capture, in ISO format. UTC, 'Z'-terminated, second (or better) precision. | -**url** | **String** | Full URL/URI of resource captured. | -**mimetype** | **String** | Mimetype of the resource at this URL. May be the Content-Type header, or the actually sniffed file type. | [optional] [default to None] -**status_code** | **i64** | HTTP status code. Should generally be 200, especially for the primary resource, but may be 3xx (redirect) or even error codes if embedded resources can not be fetched successfully. | [optional] [default to None] -**size** | **i64** | Resource (file) size in bytes | [optional] [default to None] -**sha1** | **String** | SHA-1 hash of data, in hex encoding | -**sha256** | **String** | SHA-256 hash of data, in hex encoding | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WebcaptureEntity.md b/rust/fatcat-openapi/docs/WebcaptureEntity.md deleted file mode 100644 index 64558c9..0000000 --- a/rust/fatcat-openapi/docs/WebcaptureEntity.md +++ /dev/null @@ -1,21 +0,0 @@ -# WebcaptureEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] -**cdx** | [**Vec**](webcapture_cdx_line.md) | | [optional] [default to None] -**archive_urls** | [**Vec**](webcapture_url.md) | | [optional] [default to None] -**original_url** | **String** | Base URL of the primary resource this is a capture of | [optional] [default to None] -**timestamp** | [**chrono::DateTime::**](DateTime.md) | Same format as CDX line timestamp (UTC, etc). Corresponds to the overall capture timestamp. Should generally be the timestamp of capture of the primary resource URL. | [optional] [default to None] -**release_ids** | **Vec** | Set of identifier of release entities this fileset represents a full manifestation of. Usually a single release. | [optional] [default to None] -**releases** | [**Vec**](release_entity.md) | Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WebcaptureUrl.md b/rust/fatcat-openapi/docs/WebcaptureUrl.md deleted file mode 100644 index fd21e92..0000000 --- a/rust/fatcat-openapi/docs/WebcaptureUrl.md +++ /dev/null @@ -1,11 +0,0 @@ -# WebcaptureUrl - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**url** | **String** | URL/URI pointing to archive of this web resource. | -**rel** | **String** | Type of archive endpoint. Usually `wayback` (WBM replay of primary resource), or `warc` (direct URL to a WARC file containing all resources of the capture). See guide for full list. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WorkAutoBatch.md b/rust/fatcat-openapi/docs/WorkAutoBatch.md deleted file mode 100644 index a508d1d..0000000 --- a/rust/fatcat-openapi/docs/WorkAutoBatch.md +++ /dev/null @@ -1,11 +0,0 @@ -# WorkAutoBatch - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**editgroup** | [***models::Editgroup**](editgroup.md) | | -**entity_list** | [**Vec**](work_entity.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/WorkEntity.md b/rust/fatcat-openapi/docs/WorkEntity.md deleted file mode 100644 index 2b31d12..0000000 --- a/rust/fatcat-openapi/docs/WorkEntity.md +++ /dev/null @@ -1,15 +0,0 @@ -# WorkEntity - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**state** | **String** | | [optional] [default to None] -**ident** | **String** | base32-encoded unique identifier | [optional] [default to None] -**revision** | **String** | UUID (lower-case, dash-separated, hex-encoded 128-bit) | [optional] [default to None] -**redirect** | **String** | base32-encoded unique identifier | [optional] [default to None] -**extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. | [optional] [default to None] -**edit_extra** | [**std::collections::HashMap**](AnyType.md) | Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/rust/fatcat-openapi/docs/default_api.md b/rust/fatcat-openapi/docs/default_api.md deleted file mode 100644 index 5308e84..0000000 --- a/rust/fatcat-openapi/docs/default_api.md +++ /dev/null @@ -1,3019 +0,0 @@ -# default_api - -All URIs are relative to *https://api.fatcat.wiki/v0* - -Method | HTTP request | Description -------------- | ------------- | ------------- -**accept_editgroup**](default_api.md#accept_editgroup) | **POST** /editgroup/{editgroup_id}/accept | -**auth_check**](default_api.md#auth_check) | **GET** /auth/check | -**auth_oidc**](default_api.md#auth_oidc) | **POST** /auth/oidc | -**create_auth_token**](default_api.md#create_auth_token) | **POST** /auth/token/{editor_id} | -**create_container**](default_api.md#create_container) | **POST** /editgroup/{editgroup_id}/container | -**create_container_auto_batch**](default_api.md#create_container_auto_batch) | **POST** /editgroup/auto/container/batch | -**create_creator**](default_api.md#create_creator) | **POST** /editgroup/{editgroup_id}/creator | -**create_creator_auto_batch**](default_api.md#create_creator_auto_batch) | **POST** /editgroup/auto/creator/batch | -**create_editgroup**](default_api.md#create_editgroup) | **POST** /editgroup | -**create_editgroup_annotation**](default_api.md#create_editgroup_annotation) | **POST** /editgroup/{editgroup_id}/annotation | -**create_file**](default_api.md#create_file) | **POST** /editgroup/{editgroup_id}/file | -**create_file_auto_batch**](default_api.md#create_file_auto_batch) | **POST** /editgroup/auto/file/batch | -**create_fileset**](default_api.md#create_fileset) | **POST** /editgroup/{editgroup_id}/fileset | -**create_fileset_auto_batch**](default_api.md#create_fileset_auto_batch) | **POST** /editgroup/auto/fileset/batch | -**create_release**](default_api.md#create_release) | **POST** /editgroup/{editgroup_id}/release | -**create_release_auto_batch**](default_api.md#create_release_auto_batch) | **POST** /editgroup/auto/release/batch | -**create_webcapture**](default_api.md#create_webcapture) | **POST** /editgroup/{editgroup_id}/webcapture | -**create_webcapture_auto_batch**](default_api.md#create_webcapture_auto_batch) | **POST** /editgroup/auto/webcapture/batch | -**create_work**](default_api.md#create_work) | **POST** /editgroup/{editgroup_id}/work | -**create_work_auto_batch**](default_api.md#create_work_auto_batch) | **POST** /editgroup/auto/work/batch | -**delete_container**](default_api.md#delete_container) | **DELETE** /editgroup/{editgroup_id}/container/{ident} | -**delete_container_edit**](default_api.md#delete_container_edit) | **DELETE** /editgroup/{editgroup_id}/container/edit/{edit_id} | -**delete_creator**](default_api.md#delete_creator) | **DELETE** /editgroup/{editgroup_id}/creator/{ident} | -**delete_creator_edit**](default_api.md#delete_creator_edit) | **DELETE** /editgroup/{editgroup_id}/creator/edit/{edit_id} | -**delete_file**](default_api.md#delete_file) | **DELETE** /editgroup/{editgroup_id}/file/{ident} | -**delete_file_edit**](default_api.md#delete_file_edit) | **DELETE** /editgroup/{editgroup_id}/file/edit/{edit_id} | -**delete_fileset**](default_api.md#delete_fileset) | **DELETE** /editgroup/{editgroup_id}/fileset/{ident} | -**delete_fileset_edit**](default_api.md#delete_fileset_edit) | **DELETE** /editgroup/{editgroup_id}/fileset/edit/{edit_id} | -**delete_release**](default_api.md#delete_release) | **DELETE** /editgroup/{editgroup_id}/release/{ident} | -**delete_release_edit**](default_api.md#delete_release_edit) | **DELETE** /editgroup/{editgroup_id}/release/edit/{edit_id} | -**delete_webcapture**](default_api.md#delete_webcapture) | **DELETE** /editgroup/{editgroup_id}/webcapture/{ident} | -**delete_webcapture_edit**](default_api.md#delete_webcapture_edit) | **DELETE** /editgroup/{editgroup_id}/webcapture/edit/{edit_id} | -**delete_work**](default_api.md#delete_work) | **DELETE** /editgroup/{editgroup_id}/work/{ident} | -**delete_work_edit**](default_api.md#delete_work_edit) | **DELETE** /editgroup/{editgroup_id}/work/edit/{edit_id} | -**get_changelog**](default_api.md#get_changelog) | **GET** /changelog | -**get_changelog_entry**](default_api.md#get_changelog_entry) | **GET** /changelog/{index} | -**get_container**](default_api.md#get_container) | **GET** /container/{ident} | -**get_container_edit**](default_api.md#get_container_edit) | **GET** /container/edit/{edit_id} | -**get_container_history**](default_api.md#get_container_history) | **GET** /container/{ident}/history | -**get_container_redirects**](default_api.md#get_container_redirects) | **GET** /container/{ident}/redirects | -**get_container_revision**](default_api.md#get_container_revision) | **GET** /container/rev/{rev_id} | -**get_creator**](default_api.md#get_creator) | **GET** /creator/{ident} | -**get_creator_edit**](default_api.md#get_creator_edit) | **GET** /creator/edit/{edit_id} | -**get_creator_history**](default_api.md#get_creator_history) | **GET** /creator/{ident}/history | -**get_creator_redirects**](default_api.md#get_creator_redirects) | **GET** /creator/{ident}/redirects | -**get_creator_releases**](default_api.md#get_creator_releases) | **GET** /creator/{ident}/releases | -**get_creator_revision**](default_api.md#get_creator_revision) | **GET** /creator/rev/{rev_id} | -**get_editgroup**](default_api.md#get_editgroup) | **GET** /editgroup/{editgroup_id} | -**get_editgroup_annotations**](default_api.md#get_editgroup_annotations) | **GET** /editgroup/{editgroup_id}/annotations | -**get_editgroups_reviewable**](default_api.md#get_editgroups_reviewable) | **GET** /editgroup/reviewable | -**get_editor**](default_api.md#get_editor) | **GET** /editor/{editor_id} | -**get_editor_annotations**](default_api.md#get_editor_annotations) | **GET** /editor/{editor_id}/annotations | -**get_editor_editgroups**](default_api.md#get_editor_editgroups) | **GET** /editor/{editor_id}/editgroups | -**get_file**](default_api.md#get_file) | **GET** /file/{ident} | -**get_file_edit**](default_api.md#get_file_edit) | **GET** /file/edit/{edit_id} | -**get_file_history**](default_api.md#get_file_history) | **GET** /file/{ident}/history | -**get_file_redirects**](default_api.md#get_file_redirects) | **GET** /file/{ident}/redirects | -**get_file_revision**](default_api.md#get_file_revision) | **GET** /file/rev/{rev_id} | -**get_fileset**](default_api.md#get_fileset) | **GET** /fileset/{ident} | -**get_fileset_edit**](default_api.md#get_fileset_edit) | **GET** /fileset/edit/{edit_id} | -**get_fileset_history**](default_api.md#get_fileset_history) | **GET** /fileset/{ident}/history | -**get_fileset_redirects**](default_api.md#get_fileset_redirects) | **GET** /fileset/{ident}/redirects | -**get_fileset_revision**](default_api.md#get_fileset_revision) | **GET** /fileset/rev/{rev_id} | -**get_release**](default_api.md#get_release) | **GET** /release/{ident} | -**get_release_edit**](default_api.md#get_release_edit) | **GET** /release/edit/{edit_id} | -**get_release_files**](default_api.md#get_release_files) | **GET** /release/{ident}/files | -**get_release_filesets**](default_api.md#get_release_filesets) | **GET** /release/{ident}/filesets | -**get_release_history**](default_api.md#get_release_history) | **GET** /release/{ident}/history | -**get_release_redirects**](default_api.md#get_release_redirects) | **GET** /release/{ident}/redirects | -**get_release_revision**](default_api.md#get_release_revision) | **GET** /release/rev/{rev_id} | -**get_release_webcaptures**](default_api.md#get_release_webcaptures) | **GET** /release/{ident}/webcaptures | -**get_webcapture**](default_api.md#get_webcapture) | **GET** /webcapture/{ident} | -**get_webcapture_edit**](default_api.md#get_webcapture_edit) | **GET** /webcapture/edit/{edit_id} | -**get_webcapture_history**](default_api.md#get_webcapture_history) | **GET** /webcapture/{ident}/history | -**get_webcapture_redirects**](default_api.md#get_webcapture_redirects) | **GET** /webcapture/{ident}/redirects | -**get_webcapture_revision**](default_api.md#get_webcapture_revision) | **GET** /webcapture/rev/{rev_id} | -**get_work**](default_api.md#get_work) | **GET** /work/{ident} | -**get_work_edit**](default_api.md#get_work_edit) | **GET** /work/edit/{edit_id} | -**get_work_history**](default_api.md#get_work_history) | **GET** /work/{ident}/history | -**get_work_redirects**](default_api.md#get_work_redirects) | **GET** /work/{ident}/redirects | -**get_work_releases**](default_api.md#get_work_releases) | **GET** /work/{ident}/releases | -**get_work_revision**](default_api.md#get_work_revision) | **GET** /work/rev/{rev_id} | -**lookup_container**](default_api.md#lookup_container) | **GET** /container/lookup | -**lookup_creator**](default_api.md#lookup_creator) | **GET** /creator/lookup | -**lookup_file**](default_api.md#lookup_file) | **GET** /file/lookup | -**lookup_release**](default_api.md#lookup_release) | **GET** /release/lookup | -**update_container**](default_api.md#update_container) | **PUT** /editgroup/{editgroup_id}/container/{ident} | -**update_creator**](default_api.md#update_creator) | **PUT** /editgroup/{editgroup_id}/creator/{ident} | -**update_editgroup**](default_api.md#update_editgroup) | **PUT** /editgroup/{editgroup_id} | -**update_editor**](default_api.md#update_editor) | **PUT** /editor/{editor_id} | -**update_file**](default_api.md#update_file) | **PUT** /editgroup/{editgroup_id}/file/{ident} | -**update_fileset**](default_api.md#update_fileset) | **PUT** /editgroup/{editgroup_id}/fileset/{ident} | -**update_release**](default_api.md#update_release) | **PUT** /editgroup/{editgroup_id}/release/{ident} | -**update_webcapture**](default_api.md#update_webcapture) | **PUT** /editgroup/{editgroup_id}/webcapture/{ident} | -**update_work**](default_api.md#update_work) | **PUT** /editgroup/{editgroup_id}/work/{ident} | - - -# **accept_editgroup** -> models::Success accept_editgroup(ctx, editgroup_id) - - -Accept (\"merge\") the given editgroup into the catalog. The editgroup must be open (not already accepted), and the editor making this request must have the `admin` role. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| base32-encoded unique identifier | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **auth_check** -> models::Success auth_check(ctx, optional) - - -Verify that authentication (API token) is working as expected. The optional `role` parameter can be used to verify that the current account (editor) has permissions for the given role. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **role** | **String**| | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **auth_oidc** -> models::AuthOidcResult auth_oidc(ctx, auth_oidc) - - -Login or create editor account using OIDC metadata (internal method). This method is used by privileged front-end tools (like the web interface service) to process editor logins using OpenID Connect (OIDC) and/or OAuth. Most accounts (including tool and bot accounts) do not have sufficient privileges to call this method, which requires the `admin` role. The method returns an API token; the HTTP status code indicates whether an existing account was logged in, or a new account was created. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **auth_oidc** | [**AuthOidc**](AuthOidc.md)| | - -### Return type - -[**models::AuthOidcResult**](auth_oidc_result.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_auth_token** -> models::AuthTokenResult create_auth_token(ctx, editor_id, optional) - - -Generate a new auth token for a given editor (internal method). This method is used by the web interface to generate API tokens for users. It can not be called by editors (human or bot) to generate new tokens for themselves, at least at this time. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editor_id** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| | - **duration_seconds** | **i32**| How long API token should be valid for (in seconds) | - -### Return type - -[**models::AuthTokenResult**](auth_token_result.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_container** -> models::EntityEdit create_container(ctx, editgroup_id, container_entity) - - -Create a single Container entity as part of an existing editgroup. Editgroup must be mutable (aka, not accepted) and editor must have permission (aka, have created the editgroup or have `admin` role). - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **container_entity** | [**ContainerEntity**](ContainerEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_container_auto_batch** -> models::Editgroup create_container_auto_batch(ctx, container_auto_batch) - - -Create a set of Container entities as part of a new editgroup, and accept that editgroup in the same atomic request. This method is mostly useful for bulk import of new entities by carefully written bots. This method is more efficient than creating an editgroup, several entities, then accepting the editgroup, both in terms of API requests required and database load. Requires `admin` role. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **container_auto_batch** | [**ContainerAutoBatch**](ContainerAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_creator** -> models::EntityEdit create_creator(ctx, editgroup_id, creator_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **creator_entity** | [**CreatorEntity**](CreatorEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_creator_auto_batch** -> models::Editgroup create_creator_auto_batch(ctx, creator_auto_batch) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **creator_auto_batch** | [**CreatorAutoBatch**](CreatorAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_editgroup** -> models::Editgroup create_editgroup(ctx, editgroup) - - -Creates a new editgroup. By default the editor making this request will be the author of the editgroup. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup** | [**Editgroup**](Editgroup.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_editgroup_annotation** -> models::EditgroupAnnotation create_editgroup_annotation(ctx, editgroup_id, editgroup_annotation) - - -Submits a new annotation to the specified editgroup. The editgroup must be open (not already accepted). The annotation will automatically have authorship of the editor making this request. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| base32-encoded unique identifier | - **editgroup_annotation** | [**EditgroupAnnotation**](EditgroupAnnotation.md)| | - -### Return type - -[**models::EditgroupAnnotation**](editgroup_annotation.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_file** -> models::EntityEdit create_file(ctx, editgroup_id, file_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **file_entity** | [**FileEntity**](FileEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_file_auto_batch** -> models::Editgroup create_file_auto_batch(ctx, file_auto_batch) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **file_auto_batch** | [**FileAutoBatch**](FileAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_fileset** -> models::EntityEdit create_fileset(ctx, editgroup_id, fileset_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **fileset_entity** | [**FilesetEntity**](FilesetEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_fileset_auto_batch** -> models::Editgroup create_fileset_auto_batch(ctx, fileset_auto_batch) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **fileset_auto_batch** | [**FilesetAutoBatch**](FilesetAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_release** -> models::EntityEdit create_release(ctx, editgroup_id, release_entity) - - -Create a single Release entity as part of an existing editgroup. If the `work_id` field is not set, a work entity will be created automatically and this field set pointing to the new work. Editgroup must be mutable (aka, not accepted) and editor must have permission (aka, have created the editgrou p or have `admin` role). - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **release_entity** | [**ReleaseEntity**](ReleaseEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_release_auto_batch** -> models::Editgroup create_release_auto_batch(ctx, release_auto_batch) - - -Create a set of Release entities as part of a new editgroup, and accept that editgroup in the same atomic request. This method is mostly useful for bulk import of new entities by carefully written bots. This method is more efficient than creating an editgroup, several entities, then accepting the editgroup, both in terms of API requests required and database load. Requires `admin` role. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **release_auto_batch** | [**ReleaseAutoBatch**](ReleaseAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_webcapture** -> models::EntityEdit create_webcapture(ctx, editgroup_id, webcapture_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **webcapture_entity** | [**WebcaptureEntity**](WebcaptureEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_webcapture_auto_batch** -> models::Editgroup create_webcapture_auto_batch(ctx, webcapture_auto_batch) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **webcapture_auto_batch** | [**WebcaptureAutoBatch**](WebcaptureAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_work** -> models::EntityEdit create_work(ctx, editgroup_id, work_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **work_entity** | [**WorkEntity**](WorkEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_work_auto_batch** -> models::Editgroup create_work_auto_batch(ctx, work_auto_batch) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **work_auto_batch** | [**WorkAutoBatch**](WorkAutoBatch.md)| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_container** -> models::EntityEdit delete_container(ctx, editgroup_id, ident) - - -Creates a new \"deletion\" edit for a specific entity as part of an existing editgroup. This is not the method to use to remove an edit from an editgroup; for that use `delete_container_edit`. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_container_edit** -> models::Success delete_container_edit(ctx, editgroup_id, edit_id) - - -Removes a single edit from the specified editgroup. The editgroup must be mutable (aka, not accepted/merged), and the editor making this request must have permission (aka, have created the editgroup or hold the `admin` role). Not to be confused with the `delete_container` method, which *creates* a new edit in the given editgroup. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_creator** -> models::EntityEdit delete_creator(ctx, editgroup_id, ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_creator_edit** -> models::Success delete_creator_edit(ctx, editgroup_id, edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_file** -> models::EntityEdit delete_file(ctx, editgroup_id, ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_file_edit** -> models::Success delete_file_edit(ctx, editgroup_id, edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_fileset** -> models::EntityEdit delete_fileset(ctx, editgroup_id, ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_fileset_edit** -> models::Success delete_fileset_edit(ctx, editgroup_id, edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_release** -> models::EntityEdit delete_release(ctx, editgroup_id, ident) - - -Creates a new \"deletion\" edit for a specific entity as part of an existing editgroup. This is not the method to use to remove an edit from an editgroup; for that use `delete_release_edit`. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_release_edit** -> models::Success delete_release_edit(ctx, editgroup_id, edit_id) - - -Removes a single edit from the specified editgroup. The editgroup must be mutable (aka, not accepted/merged), and the editor making this request must have permission (aka, have created the editgroup or hold the `admin` role). Not to be confused with the `delete_container` method, which *creates* a new edit in the given editgroup. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_webcapture** -> models::EntityEdit delete_webcapture(ctx, editgroup_id, ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_webcapture_edit** -> models::Success delete_webcapture_edit(ctx, editgroup_id, edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_work** -> models::EntityEdit delete_work(ctx, editgroup_id, ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_work_edit** -> models::Success delete_work_edit(ctx, editgroup_id, edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::Success**](success.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_changelog** -> Vec get_changelog(optional) - - -Returns a list of the most recent changelog entries accepted (merged) into the catalog. List is sorted by changelog index in descending order. Note that the accepted timestamp roughly corresponds to order, but not strictly; there exist out-of-order timestamps on the order of several seconds. As a known database issue, it is technically possible for there to be a gap in changelog index numbers (aka, a missing changelog entry). There are no currently known gaps and this is considered a bug that will be addressed. There are millions of entries; to paginate through all of them, use this method to discover the highest existing entry number, then request the entries using `get_changelog_entry` one at a time. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **limit** | **i64**| Maximum count of changelog entries to return in response | - -### Return type - -[**Vec**](changelog_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_changelog_entry** -> models::ChangelogEntry get_changelog_entry(index) - - -Returns a single changelog entry. As a known database issue, it is technically possible for there to be a gap in changelog index numbers (aka, a missing changelog entry). There are no currently known gaps and this is considered a bug that will be addressed. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **index** | **i64**| Changelog index of entry to return | - -### Return type - -[**models::ChangelogEntry**](changelog_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_container** -> models::ContainerEntity get_container(ident, optional) - - -Fetches a single container entity from the catalog. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For containers, none accepted (yet). | - **hide** | **String**| List of entity fields to elide in response. For containers, none accepted (yet). | - -### Return type - -[**models::ContainerEntity**](container_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_container_edit** -> models::EntityEdit get_container_edit(edit_id) - - -Returns the entity edit object with the given identifier. This method is expected to be used rarely. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_container_history** -> Vec get_container_history(ident, optional) - - -Fetches the history of accepted edits (changelog entries) for a specific entity fatcat identifier. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| Maximum number of changelog entries to return | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_container_redirects** -> Vec get_container_redirects(ident) - - -Returns the set of entity identifiers which currently redirect to this identifier. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_container_revision** -> models::ContainerEntity get_container_revision(rev_id, optional) - - -Fetches a specific entity revision. Note that the returned revision will not be associated with any particular fatcat identifier (even if one or more identifiers do currently point to this revision). The revision may even be part of an un-merged editgroup. Revisions are immutable and can not be deleted or updated. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_container`. | - **hide** | **String**| List of entity fields to elide in response. See `get_container`. | - -### Return type - -[**models::ContainerEntity**](container_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator** -> models::CreatorEntity get_creator(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For creators, none accepted (yet). | - **hide** | **String**| List of entity fields to elide in response. For creators, none accepted (yet). | - -### Return type - -[**models::CreatorEntity**](creator_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator_edit** -> models::EntityEdit get_creator_edit(edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator_history** -> Vec get_creator_history(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator_redirects** -> Vec get_creator_redirects(ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator_releases** -> Vec get_creator_releases(ident, optional) - - -Returns the set of Release entities having a `contrib` entry pointing to the creator entity. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **hide** | **String**| List of entity fields to elide in response. See `get_release`. | - -### Return type - -[**Vec**](release_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_creator_revision** -> models::CreatorEntity get_creator_revision(rev_id, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_creator`, though note that identifier-based expansions (like `releases`) will always be empty for revisions. | - **hide** | **String**| List of entity fields to elide in response. See `get_creator`. | - -### Return type - -[**models::CreatorEntity**](creator_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editgroup** -> models::Editgroup get_editgroup(editgroup_id) - - -Returns a single editgroup object. Unlike some similar methods, this method will return a full/expanded editgroup object, which includes edit lists of each entity type (though will not include the complete entity objects). - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editgroup_id** | **String**| base32-encoded unique identifier | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editgroup_annotations** -> Vec get_editgroup_annotations(editgroup_id, optional) - - -Returns a list of annotations made to a specific editgroup. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editgroup_id** | **String**| base32-encoded unique identifier | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editgroup_id** | **String**| base32-encoded unique identifier | - **expand** | **String**| List of sub-entities to expand in response. For editgroup annotations: 'editors' | - -### Return type - -[**Vec**](editgroup_annotation.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editgroups_reviewable** -> Vec get_editgroups_reviewable(optional) - - -Returns a set of editgroups which have been submitted but not yet accepted. Query parameters can be used to sort and paginate the list returned. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **expand** | **String**| List of sub-entities to expand in response. For editgroups: 'editors' | - **limit** | **i64**| Maximum number of reviewable editgroups to return in response | - **before** | **chrono::DateTime::**| Return only reviewable editgroups submitted *before* the given timestamp (not inclusive). Editgroups will be sorted by submission time in descending order (most recent first). For use in pagination. | - **since** | **chrono::DateTime::**| Return only reviewable editgroups submitted *after* the given timestamp (not inclusive). Editgroups will be sorted by submission time in ascending order (most recent last). For use in pagination. | - -### Return type - -[**Vec**](editgroup.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editor** -> models::Editor get_editor(editor_id) - - -Returns an editor object, including metadata such as the username, type, and role of editor. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| | - -### Return type - -[**models::Editor**](editor.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editor_annotations** -> Vec get_editor_annotations(editor_id, optional) - - -Fetches a list of annotations made by a particular editor. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| base32-encoded unique identifier | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| base32-encoded unique identifier | - **limit** | **i64**| Maximum number (count) of annotations to return in response | - **before** | **chrono::DateTime::**| Return only annotations made *before* the given timestamp (not inclusive). Annotations will be sorted by creation time in descending order (most recent first). For use in pagination. | - **since** | **chrono::DateTime::**| Return only annotations made *after* the given timestamp (not inclusive). Annotations will be sorted by creation time in ascending order (most recent last). For use in pagination. | - -### Return type - -[**Vec**](editgroup_annotation.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_editor_editgroups** -> Vec get_editor_editgroups(editor_id, optional) - - -Returns a set of editgroups created by the given editor, regardless of the status (accepted/submitted) of the editgroups. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editor_id** | **String**| | - **limit** | **i64**| | - **before** | **chrono::DateTime::**| Return only editgroups created *before* the given timestamp (not inclusive). Editgroups will be sorted by creation time in descending order (most recent first). For use in pagination. | - **since** | **chrono::DateTime::**| Return only editgroups created *after* the given timestamp (not inclusive). Editgroups will be sorted by creation time in ascending order (most recent last). For use in pagination. | - -### Return type - -[**Vec**](editgroup.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_file** -> models::FileEntity get_file(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For files, `releases` is accepted. | - **hide** | **String**| List of entity fields to elide in response. For files, none accepted (yet). | - -### Return type - -[**models::FileEntity**](file_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_file_edit** -> models::EntityEdit get_file_edit(edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_file_history** -> Vec get_file_history(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_file_redirects** -> Vec get_file_redirects(ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_file_revision** -> models::FileEntity get_file_revision(rev_id, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_file`. | - **hide** | **String**| List of entity fields to elide in response. See `get_file`. | - -### Return type - -[**models::FileEntity**](file_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fileset** -> models::FilesetEntity get_fileset(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For filesets, `releases` is accepted. | - **hide** | **String**| List of entity fields to elide in response. For filesets, 'manifest' is accepted. | - -### Return type - -[**models::FilesetEntity**](fileset_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fileset_edit** -> models::EntityEdit get_fileset_edit(edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fileset_history** -> Vec get_fileset_history(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fileset_redirects** -> Vec get_fileset_redirects(ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fileset_revision** -> models::FilesetEntity get_fileset_revision(rev_id, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_fileset`. | - **hide** | **String**| List of entity fields to elide in response. See `get_fileset`. | - -### Return type - -[**models::FilesetEntity**](fileset_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release** -> models::ReleaseEntity get_release(ident, optional) - - -Fetches a single Release entity from the catalog. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For releases, 'files', 'filesets, 'webcaptures', 'container', and 'creators' are valid. | - **hide** | **String**| List of entity fields to elide in response (for efficiency). For releases, 'abstracts', 'refs', and 'contribs' are valid. | - -### Return type - -[**models::ReleaseEntity**](release_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_edit** -> models::EntityEdit get_release_edit(edit_id) - - -Returns the entity edit object with the given identifier. This method is expected to be used rarely. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_files** -> Vec get_release_files(ident, optional) - - -Returns the set of File entities that have a `release_id` pointing to this release entity. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **hide** | **String**| List of entity fields to elide in response. See `get_file`. | - -### Return type - -[**Vec**](file_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_filesets** -> Vec get_release_filesets(ident, optional) - - -Returns the set of Fileset entities that have a `release_id` pointing to this release entity. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **hide** | **String**| List of entity fields to elide in response. See `get_fileset`. | - -### Return type - -[**Vec**](fileset_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_history** -> Vec get_release_history(ident, optional) - - -Fetches the history of accepted edits (changelog entries) for a specific entity fatcat identifier. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_redirects** -> Vec get_release_redirects(ident) - - -Returns the set of entity identifiers which currently redirect to this identifier. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_revision** -> models::ReleaseEntity get_release_revision(rev_id, optional) - - -Fetches a specific entity revision. Note that the returned revision will not be associated with any particular fatcat identifier (even if one or more identifiers do currently point to this revision). The revision may even be part of an un-merged editgroup. Revisions are immutable and can not be deleted or updated. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_release`, though note that identifier-based exapansions like `file` will always be empty for revisions. | - **hide** | **String**| List of entity fields to elide in response. See `get_release`. | - -### Return type - -[**models::ReleaseEntity**](release_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_release_webcaptures** -> Vec get_release_webcaptures(ident, optional) - - -Returns the set of Web Capture entities that have a `release_id` pointing to this release entity. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **hide** | **String**| List of entity fields to elide in response. See `get_webcapture`. | - -### Return type - -[**Vec**](webcapture_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_webcapture** -> models::WebcaptureEntity get_webcapture(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For webcaptures, `releases` is accepted. | - **hide** | **String**| List of entity fields to elide in response. For webcaptures, 'cdx' is accepted. | - -### Return type - -[**models::WebcaptureEntity**](webcapture_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_webcapture_edit** -> models::EntityEdit get_webcapture_edit(edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_webcapture_history** -> Vec get_webcapture_history(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_webcapture_redirects** -> Vec get_webcapture_redirects(ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_webcapture_revision** -> models::WebcaptureEntity get_webcapture_revision(rev_id, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_webcapture`. | - **hide** | **String**| List of entity fields to elide in response. See `get_webcapture`. | - -### Return type - -[**models::WebcaptureEntity**](webcapture_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work** -> models::WorkEntity get_work(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. For works, none accepted (yet). | - **hide** | **String**| List of entity fields to elide in response. For works, none accepted (yet). | - -### Return type - -[**models::WorkEntity**](work_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work_edit** -> models::EntityEdit get_work_edit(edit_id) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **edit_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work_history** -> Vec get_work_history(ident, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **limit** | **i64**| | - -### Return type - -[**Vec**](entity_history_entry.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work_redirects** -> Vec get_work_redirects(ident) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - -### Return type - -[**Vec**](string.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work_releases** -> Vec get_work_releases(ident, optional) - - -Returns the set of release entities that are part of this work (aka, have `work_id` pointing to this work entity). - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ident** | **String**| | - **hide** | **String**| List of entity fields to elide in response. See `get_release`. | - -### Return type - -[**Vec**](release_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_work_revision** -> models::WorkEntity get_work_revision(rev_id, optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **rev_id** | **String**| UUID (lower-case, dash-separated, hex-encoded 128-bit) | - **expand** | **String**| List of sub-entities to expand in response. See `get_work`, though note that identifier-based expansions like `releases` will always be empty for revisions. | - **hide** | **String**| List of entity fields to elide in response. See `get_work`. | - -### Return type - -[**models::WorkEntity**](work_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **lookup_container** -> models::ContainerEntity lookup_container(optional) - - -Looks for an active entity with the given external identifier. If any such entity is found, returns a single complete entity. If multiple entities have the same external identifier, this is considered a soft catalog error, and the behavior of which entity is returned is undefined. One (and only one) external identifier should be specified per request. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **issnl** | **String**| | - **wikidata_qid** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. See `get_container`. | - **hide** | **String**| List of entity fields to elide in response. See `get_container`. | - -### Return type - -[**models::ContainerEntity**](container_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **lookup_creator** -> models::CreatorEntity lookup_creator(optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orcid** | **String**| ORCiD (https://orcid.org) identifier | - **wikidata_qid** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. See `get_creator`. | - **hide** | **String**| List of entity fields to elide in response. See `get_creator`. | - -### Return type - -[**models::CreatorEntity**](creator_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **lookup_file** -> models::FileEntity lookup_file(optional) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **md5** | **String**| MD5 hash of data, in hex encoding | - **sha1** | **String**| SHA-1 hash of data, in hex encoding | - **sha256** | **String**| SHA-256 hash of data, in hex encoding | - **expand** | **String**| List of sub-entities to expand in response. See `get_file`. | - **hide** | **String**| List of entity fields to elide in response. See `get_file`. | - -### Return type - -[**models::FileEntity**](file_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **lookup_release** -> models::ReleaseEntity lookup_release(optional) - - -Looks for an active entity with the given external identifier. If any such entity is found, returns a single complete entity. If multiple entities have the same external identifier, this is considered a soft catalog error, and the behavior of which entity is returned is undefined. One (and only one) external identifier should be specified per request. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **doi** | **String**| | - **wikidata_qid** | **String**| | - **isbn13** | **String**| | - **pmid** | **String**| | - **pmcid** | **String**| | - **core** | **String**| | - **arxiv** | **String**| | - **jstor** | **String**| | - **ark** | **String**| | - **mag** | **String**| | - **doaj** | **String**| | - **dblp** | **String**| | - **oai** | **String**| | - **expand** | **String**| List of sub-entities to expand in response. See `get_release`. | - **hide** | **String**| List of sub-entities to elide in response. See `get_release`. | - -### Return type - -[**models::ReleaseEntity**](release_entity.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_container** -> models::EntityEdit update_container(ctx, editgroup_id, ident, container_entity) - - -Updates an existing entity as part of a specific (existing) editgroup. The editgroup must be open for updates (aka, not accepted/merged), and the editor making the request must have permissions (aka, must have created the editgroup or have `admin` role). This method can also be used to update an existing entity edit as part of an editgroup. For example, if an entity was created in this editgroup, an editor could make changes to the new entity's metadata before merging. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **container_entity** | [**ContainerEntity**](ContainerEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_creator** -> models::EntityEdit update_creator(ctx, editgroup_id, ident, creator_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **creator_entity** | [**CreatorEntity**](CreatorEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_editgroup** -> models::Editgroup update_editgroup(ctx, editgroup_id, editgroup, optional) - - -Updates metadata for a single editgroup object. Note that only metadata fields such as the `description` or `extra` metadata can be changed with this method; it does not allow adding or removing edits to the editgroup (for that use the individual entity create/update/delete methods). - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| base32-encoded unique identifier | - **editgroup** | [**Editgroup**](Editgroup.md)| | - **optional** | **map[string]interface{}** | optional parameters | nil if no parameters - -### Optional Parameters -Optional parameters are passed through a map[string]interface{}. - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **editgroup_id** | **String**| base32-encoded unique identifier | - **editgroup** | [**Editgroup**](Editgroup.md)| | - **submit** | **bool**| | - -### Return type - -[**models::Editgroup**](editgroup.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_editor** -> models::Editor update_editor(ctx, editor_id, editor) - - -Allows metadata changes to some editor fields, such as the username. Changes require authentication and permissions. An editor can change their own username; changes to role flags require the `admin` role by the editor making the request. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editor_id** | **String**| | - **editor** | [**Editor**](Editor.md)| | - -### Return type - -[**models::Editor**](editor.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_file** -> models::EntityEdit update_file(ctx, editgroup_id, ident, file_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **file_entity** | [**FileEntity**](FileEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_fileset** -> models::EntityEdit update_fileset(ctx, editgroup_id, ident, fileset_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **fileset_entity** | [**FilesetEntity**](FilesetEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_release** -> models::EntityEdit update_release(ctx, editgroup_id, ident, release_entity) - - -Updates an existing entity as part of a specific (existing) editgroup. The editgroup must be open for updates (aka, not accepted/merged), and the editor making the requiest must have permissions (aka, must have created the editgroup or have `admin` role). This method can also be used to update an existing entity edit as part of an editgroup. For example, if an entity was created in this editgroup, an editor could make changes to the new entity's metadata before merging. - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **release_entity** | [**ReleaseEntity**](ReleaseEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_webcapture** -> models::EntityEdit update_webcapture(ctx, editgroup_id, ident, webcapture_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **webcapture_entity** | [**WebcaptureEntity**](WebcaptureEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_work** -> models::EntityEdit update_work(ctx, editgroup_id, ident, work_entity) - - -### Required Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **editgroup_id** | **String**| | - **ident** | **String**| | - **work_entity** | [**WorkEntity**](WorkEntity.md)| | - -### Return type - -[**models::EntityEdit**](entity_edit.md) - -### Authorization - -[Bearer](../README.md#Bearer) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/rust/fatcat-openapi/examples/ca.pem b/rust/fatcat-openapi/examples/ca.pem deleted file mode 100644 index d2317fb..0000000 --- a/rust/fatcat-openapi/examples/ca.pem +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICtjCCAZ4CCQDpKecRERZ0xDANBgkqhkiG9w0BAQsFADAdMQswCQYDVQQGEwJV -UzEOMAwGA1UEAxMFTXkgQ0EwHhcNMTcwNTIzMTYwMDIzWhcNMTcwNjIyMTYwMDIz -WjAdMQswCQYDVQQGEwJVUzEOMAwGA1UEAxMFTXkgQ0EwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQCt66py3x7sCSASRF2D05L5wkNDxAUjQKYx23W8Gbwv -GMGykk89BIdU5LX1JB1cKiUOkoIxfwAYuWc2V/wzTvVV7+11besnk3uX1c9KiqUF -LIX7kn/z5hzS4aelhKvH+MJlSZCSlp1ytpZbwo5GB5Pi2SGH56jDBiBoDRNBVdWL -z4wH7TdrQjqWwNxIZumD5OGMtcfJyuX08iPiEOaslOeoMqzObhvjc9aUgjVjhqyA -FkJGTXsi0oaD7oml+NE+mTNfEeZvEJQpLSjBY0OvQHzuHkyGBShBnfu/9x7/NRwd -WaqsLiF7/re9KDGYdJwP7Cu6uxYfKAyWarp6h2mG/GIdAgMBAAEwDQYJKoZIhvcN -AQELBQADggEBAGIl/VVIafeq/AJOQ9r7TzzB2ABJYr7NZa6bTu5O1jSp1Fonac15 -SZ8gvRxODgH22ZYSqghPG4xzq4J3hkytlQqm57ZEt2I2M3OqIp17Ndcc1xDYzpLl -tA0FrVn6crQTM8vQkTDtGesaCWX+7Fir5dK7HnYWzfpSmsOpST07PfbNisEXKOxG -Dj4lBL1OnhTjsJeymVS1pFvkKkrcEJO+IxFiHL3CDsWjcXB0Z+E1zBtPoYyYsNsO -rBrjUxcZewF4xqWZhpW90Mt61fY2nRgU0uUwHcvDQUqvmzKcsqYa4mPKzfBI5mxo -01Ta96cDD6pS5Y1hOflZ0g84f2g/7xBLLDA= ------END CERTIFICATE----- diff --git a/rust/fatcat-openapi/examples/client/main.rs b/rust/fatcat-openapi/examples/client/main.rs deleted file mode 100644 index 14a1bdf..0000000 --- a/rust/fatcat-openapi/examples/client/main.rs +++ /dev/null @@ -1,1148 +0,0 @@ -#![allow(missing_docs, unused_variables, trivial_casts)] - -use clap::{App, Arg}; -#[allow(unused_imports)] -use fatcat_openapi::{ - models, AcceptEditgroupResponse, Api, ApiNoContext, AuthCheckResponse, AuthOidcResponse, - Client, ContextWrapperExt, CreateAuthTokenResponse, CreateContainerAutoBatchResponse, - CreateContainerResponse, CreateCreatorAutoBatchResponse, CreateCreatorResponse, - CreateEditgroupAnnotationResponse, CreateEditgroupResponse, CreateFileAutoBatchResponse, - CreateFileResponse, CreateFilesetAutoBatchResponse, CreateFilesetResponse, - CreateReleaseAutoBatchResponse, CreateReleaseResponse, CreateWebcaptureAutoBatchResponse, - CreateWebcaptureResponse, CreateWorkAutoBatchResponse, CreateWorkResponse, - DeleteContainerEditResponse, DeleteContainerResponse, DeleteCreatorEditResponse, - DeleteCreatorResponse, DeleteFileEditResponse, DeleteFileResponse, DeleteFilesetEditResponse, - DeleteFilesetResponse, DeleteReleaseEditResponse, DeleteReleaseResponse, - DeleteWebcaptureEditResponse, DeleteWebcaptureResponse, DeleteWorkEditResponse, - DeleteWorkResponse, GetChangelogEntryResponse, GetChangelogResponse, GetContainerEditResponse, - GetContainerHistoryResponse, GetContainerRedirectsResponse, GetContainerResponse, - GetContainerRevisionResponse, GetCreatorEditResponse, GetCreatorHistoryResponse, - GetCreatorRedirectsResponse, GetCreatorReleasesResponse, GetCreatorResponse, - GetCreatorRevisionResponse, GetEditgroupAnnotationsResponse, GetEditgroupResponse, - GetEditgroupsReviewableResponse, GetEditorAnnotationsResponse, GetEditorEditgroupsResponse, - GetEditorResponse, GetFileEditResponse, GetFileHistoryResponse, GetFileRedirectsResponse, - GetFileResponse, GetFileRevisionResponse, GetFilesetEditResponse, GetFilesetHistoryResponse, - GetFilesetRedirectsResponse, GetFilesetResponse, GetFilesetRevisionResponse, - GetReleaseEditResponse, GetReleaseFilesResponse, GetReleaseFilesetsResponse, - GetReleaseHistoryResponse, GetReleaseRedirectsResponse, GetReleaseResponse, - GetReleaseRevisionResponse, GetReleaseWebcapturesResponse, GetWebcaptureEditResponse, - GetWebcaptureHistoryResponse, GetWebcaptureRedirectsResponse, GetWebcaptureResponse, - GetWebcaptureRevisionResponse, GetWorkEditResponse, GetWorkHistoryResponse, - GetWorkRedirectsResponse, GetWorkReleasesResponse, GetWorkResponse, GetWorkRevisionResponse, - LookupContainerResponse, LookupCreatorResponse, LookupFileResponse, LookupReleaseResponse, - UpdateContainerResponse, UpdateCreatorResponse, UpdateEditgroupResponse, UpdateEditorResponse, - UpdateFileResponse, UpdateFilesetResponse, UpdateReleaseResponse, UpdateWebcaptureResponse, - UpdateWorkResponse, -}; -#[allow(unused_imports)] -use futures::{future, stream, Stream}; - -#[allow(unused_imports)] -use log::info; - -// swagger::Has may be unused if there are no examples -#[allow(unused_imports)] -use swagger::{AuthData, ContextBuilder, EmptyContext, Has, Push, XSpanIdString}; - -type ClientContext = swagger::make_context_ty!( - ContextBuilder, - EmptyContext, - Option, - XSpanIdString -); - -// rt may be unused if there are no examples -#[allow(unused_mut)] -fn main() { - env_logger::init(); - - let matches = App::new("client") - .arg( - Arg::with_name("operation") - .help("Sets the operation to run") - .possible_values(&[ - "AcceptEditgroup", - "AuthCheck", - "CreateAuthToken", - "DeleteContainer", - "DeleteContainerEdit", - "DeleteCreator", - "DeleteCreatorEdit", - "DeleteFile", - "DeleteFileEdit", - "DeleteFileset", - "DeleteFilesetEdit", - "DeleteRelease", - "DeleteReleaseEdit", - "DeleteWebcapture", - "DeleteWebcaptureEdit", - "DeleteWork", - "DeleteWorkEdit", - "GetChangelog", - "GetChangelogEntry", - "GetContainer", - "GetContainerEdit", - "GetContainerHistory", - "GetContainerRedirects", - "GetContainerRevision", - "GetCreator", - "GetCreatorEdit", - "GetCreatorHistory", - "GetCreatorRedirects", - "GetCreatorReleases", - "GetCreatorRevision", - "GetEditgroup", - "GetEditgroupAnnotations", - "GetEditgroupsReviewable", - "GetEditor", - "GetEditorAnnotations", - "GetEditorEditgroups", - "GetFile", - "GetFileEdit", - "GetFileHistory", - "GetFileRedirects", - "GetFileRevision", - "GetFileset", - "GetFilesetEdit", - "GetFilesetHistory", - "GetFilesetRedirects", - "GetFilesetRevision", - "GetRelease", - "GetReleaseEdit", - "GetReleaseFiles", - "GetReleaseFilesets", - "GetReleaseHistory", - "GetReleaseRedirects", - "GetReleaseRevision", - "GetReleaseWebcaptures", - "GetWebcapture", - "GetWebcaptureEdit", - "GetWebcaptureHistory", - "GetWebcaptureRedirects", - "GetWebcaptureRevision", - "GetWork", - "GetWorkEdit", - "GetWorkHistory", - "GetWorkRedirects", - "GetWorkReleases", - "GetWorkRevision", - "LookupContainer", - "LookupCreator", - "LookupFile", - "LookupRelease", - ]) - .required(true) - .index(1), - ) - .arg( - Arg::with_name("https") - .long("https") - .help("Whether to use HTTPS or not"), - ) - .arg( - Arg::with_name("host") - .long("host") - .takes_value(true) - .default_value("api.fatcat.wiki") - .help("Hostname to contact"), - ) - .arg( - Arg::with_name("port") - .long("port") - .takes_value(true) - .default_value("8080") - .help("Port to contact"), - ) - .get_matches(); - - let is_https = matches.is_present("https"); - let base_url = format!( - "{}://{}:{}", - if is_https { "https" } else { "http" }, - matches.value_of("host").unwrap(), - matches.value_of("port").unwrap() - ); - - let context: ClientContext = swagger::make_context!( - ContextBuilder, - EmptyContext, - None as Option, - XSpanIdString::default() - ); - - let mut client: Box> = if matches.is_present("https") { - // Using Simple HTTPS - let client = - Box::new(Client::try_new_https(&base_url).expect("Failed to create HTTPS client")); - Box::new(client.with_context(context)) - } else { - // Using HTTP - let client = - Box::new(Client::try_new_http(&base_url).expect("Failed to create HTTP client")); - Box::new(client.with_context(context)) - }; - - let mut rt = tokio::runtime::Runtime::new().unwrap(); - - match matches.value_of("operation") { - Some("AcceptEditgroup") => { - let result = rt.block_on(client.accept_editgroup("editgroup_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("AuthCheck") => { - let result = rt.block_on(client.auth_check(Some("role_example".to_string()))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - /* Disabled because there's no example. - Some("AuthOidc") => { - let result = rt.block_on(client.auth_oidc( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - Some("CreateAuthToken") => { - let result = - rt.block_on(client.create_auth_token("editor_id_example".to_string(), Some(56))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - /* Disabled because there's no example. - Some("CreateContainer") => { - let result = rt.block_on(client.create_container( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateContainerAutoBatch") => { - let result = rt.block_on(client.create_container_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateCreator") => { - let result = rt.block_on(client.create_creator( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateCreatorAutoBatch") => { - let result = rt.block_on(client.create_creator_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateEditgroup") => { - let result = rt.block_on(client.create_editgroup( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateEditgroupAnnotation") => { - let result = rt.block_on(client.create_editgroup_annotation( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateFile") => { - let result = rt.block_on(client.create_file( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateFileAutoBatch") => { - let result = rt.block_on(client.create_file_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateFileset") => { - let result = rt.block_on(client.create_fileset( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateFilesetAutoBatch") => { - let result = rt.block_on(client.create_fileset_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateRelease") => { - let result = rt.block_on(client.create_release( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateReleaseAutoBatch") => { - let result = rt.block_on(client.create_release_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateWebcapture") => { - let result = rt.block_on(client.create_webcapture( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateWebcaptureAutoBatch") => { - let result = rt.block_on(client.create_webcapture_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateWork") => { - let result = rt.block_on(client.create_work( - "editgroup_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("CreateWorkAutoBatch") => { - let result = rt.block_on(client.create_work_auto_batch( - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - Some("DeleteContainer") => { - let result = rt.block_on(client.delete_container( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteContainerEdit") => { - let result = rt.block_on(client.delete_container_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteCreator") => { - let result = rt.block_on(client.delete_creator( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteCreatorEdit") => { - let result = rt.block_on(client.delete_creator_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteFile") => { - let result = rt.block_on(client.delete_file( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteFileEdit") => { - let result = rt.block_on(client.delete_file_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteFileset") => { - let result = rt.block_on(client.delete_fileset( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteFilesetEdit") => { - let result = rt.block_on(client.delete_fileset_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteRelease") => { - let result = rt.block_on(client.delete_release( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteReleaseEdit") => { - let result = rt.block_on(client.delete_release_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteWebcapture") => { - let result = rt.block_on(client.delete_webcapture( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteWebcaptureEdit") => { - let result = rt.block_on(client.delete_webcapture_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteWork") => { - let result = rt.block_on(client.delete_work( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("DeleteWorkEdit") => { - let result = rt.block_on(client.delete_work_edit( - "editgroup_id_example".to_string(), - "edit_id_example".to_string(), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetChangelog") => { - let result = rt.block_on(client.get_changelog(Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetChangelogEntry") => { - let result = rt.block_on(client.get_changelog_entry(789)); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetContainer") => { - let result = rt.block_on(client.get_container( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetContainerEdit") => { - let result = rt.block_on(client.get_container_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetContainerHistory") => { - let result = - rt.block_on(client.get_container_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetContainerRedirects") => { - let result = rt.block_on(client.get_container_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetContainerRevision") => { - let result = rt.block_on(client.get_container_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreator") => { - let result = rt.block_on(client.get_creator( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreatorEdit") => { - let result = rt.block_on(client.get_creator_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreatorHistory") => { - let result = - rt.block_on(client.get_creator_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreatorRedirects") => { - let result = rt.block_on(client.get_creator_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreatorReleases") => { - let result = rt.block_on(client.get_creator_releases( - "ident_example".to_string(), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetCreatorRevision") => { - let result = rt.block_on(client.get_creator_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditgroup") => { - let result = rt.block_on(client.get_editgroup("editgroup_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditgroupAnnotations") => { - let result = rt.block_on(client.get_editgroup_annotations( - "editgroup_id_example".to_string(), - Some("expand_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditgroupsReviewable") => { - let result = rt.block_on(client.get_editgroups_reviewable( - Some("expand_example".to_string()), - Some(789), - None, - None, - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditor") => { - let result = rt.block_on(client.get_editor("editor_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditorAnnotations") => { - let result = rt.block_on(client.get_editor_annotations( - "editor_id_example".to_string(), - Some(789), - None, - None, - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetEditorEditgroups") => { - let result = rt.block_on(client.get_editor_editgroups( - "editor_id_example".to_string(), - Some(789), - None, - None, - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFile") => { - let result = rt.block_on(client.get_file( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFileEdit") => { - let result = rt.block_on(client.get_file_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFileHistory") => { - let result = - rt.block_on(client.get_file_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFileRedirects") => { - let result = rt.block_on(client.get_file_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFileRevision") => { - let result = rt.block_on(client.get_file_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFileset") => { - let result = rt.block_on(client.get_fileset( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFilesetEdit") => { - let result = rt.block_on(client.get_fileset_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFilesetHistory") => { - let result = - rt.block_on(client.get_fileset_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFilesetRedirects") => { - let result = rt.block_on(client.get_fileset_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetFilesetRevision") => { - let result = rt.block_on(client.get_fileset_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetRelease") => { - let result = rt.block_on(client.get_release( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseEdit") => { - let result = rt.block_on(client.get_release_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseFiles") => { - let result = rt.block_on(client.get_release_files( - "ident_example".to_string(), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseFilesets") => { - let result = rt.block_on(client.get_release_filesets( - "ident_example".to_string(), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseHistory") => { - let result = - rt.block_on(client.get_release_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseRedirects") => { - let result = rt.block_on(client.get_release_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseRevision") => { - let result = rt.block_on(client.get_release_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetReleaseWebcaptures") => { - let result = rt.block_on(client.get_release_webcaptures( - "ident_example".to_string(), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWebcapture") => { - let result = rt.block_on(client.get_webcapture( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWebcaptureEdit") => { - let result = rt.block_on(client.get_webcapture_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWebcaptureHistory") => { - let result = - rt.block_on(client.get_webcapture_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWebcaptureRedirects") => { - let result = rt.block_on(client.get_webcapture_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWebcaptureRevision") => { - let result = rt.block_on(client.get_webcapture_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWork") => { - let result = rt.block_on(client.get_work( - "ident_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWorkEdit") => { - let result = rt.block_on(client.get_work_edit("edit_id_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWorkHistory") => { - let result = - rt.block_on(client.get_work_history("ident_example".to_string(), Some(789))); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWorkRedirects") => { - let result = rt.block_on(client.get_work_redirects("ident_example".to_string())); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWorkReleases") => { - let result = rt.block_on(client.get_work_releases( - "ident_example".to_string(), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("GetWorkRevision") => { - let result = rt.block_on(client.get_work_revision( - "rev_id_example".to_string(), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("LookupContainer") => { - let result = rt.block_on(client.lookup_container( - Some("issnl_example".to_string()), - Some("wikidata_qid_example".to_string()), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("LookupCreator") => { - let result = rt.block_on(client.lookup_creator( - Some("orcid_example".to_string()), - Some("wikidata_qid_example".to_string()), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("LookupFile") => { - let result = rt.block_on(client.lookup_file( - Some("md5_example".to_string()), - Some("sha1_example".to_string()), - Some("sha256_example".to_string()), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - Some("LookupRelease") => { - let result = rt.block_on(client.lookup_release( - Some("doi_example".to_string()), - Some("wikidata_qid_example".to_string()), - Some("isbn13_example".to_string()), - Some("pmid_example".to_string()), - Some("pmcid_example".to_string()), - Some("core_example".to_string()), - Some("arxiv_example".to_string()), - Some("jstor_example".to_string()), - Some("ark_example".to_string()), - Some("mag_example".to_string()), - Some("doaj_example".to_string()), - Some("dblp_example".to_string()), - Some("oai_example".to_string()), - Some("expand_example".to_string()), - Some("hide_example".to_string()), - )); - info!( - "{:?} (X-Span-ID: {:?})", - result, - (client.context() as &dyn Has).get().clone() - ); - } - /* Disabled because there's no example. - Some("UpdateContainer") => { - let result = rt.block_on(client.update_container( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateCreator") => { - let result = rt.block_on(client.update_creator( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateEditgroup") => { - let result = rt.block_on(client.update_editgroup( - "editgroup_id_example".to_string(), - ???, - Some(true) - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateEditor") => { - let result = rt.block_on(client.update_editor( - "editor_id_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateFile") => { - let result = rt.block_on(client.update_file( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateFileset") => { - let result = rt.block_on(client.update_fileset( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateRelease") => { - let result = rt.block_on(client.update_release( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateWebcapture") => { - let result = rt.block_on(client.update_webcapture( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - /* Disabled because there's no example. - Some("UpdateWork") => { - let result = rt.block_on(client.update_work( - "editgroup_id_example".to_string(), - "ident_example".to_string(), - ??? - )); - info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has).get().clone()); - }, - */ - _ => { - panic!("Invalid operation provided") - } - } -} diff --git a/rust/fatcat-openapi/examples/server-chain.pem b/rust/fatcat-openapi/examples/server-chain.pem deleted file mode 100644 index 47d7e20..0000000 --- a/rust/fatcat-openapi/examples/server-chain.pem +++ /dev/null @@ -1,66 +0,0 @@ -Certificate: - Data: - Version: 1 (0x0) - Serial Number: 4096 (0x1000) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, CN=My CA - Validity - Not Before: May 23 16:00:23 2017 GMT - Not After : Apr 29 16:00:23 2117 GMT - Subject: CN=localhost, C=US - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c9:d4:43:60:50:fc:d6:0f:38:4d:5d:5e:aa:7c: - c0:5e:a9:ec:d9:93:78:d3:93:72:28:41:f5:08:a5: - ea:ac:67:07:d7:1f:f7:7d:74:69:7e:46:89:20:4b: - 7a:2d:9b:02:08:e7:6f:0f:1d:0c:0f:c7:60:69:19: - 4b:df:7e:ca:75:94:0b:49:71:e3:6d:f2:e8:79:fd: - ed:0a:94:67:55:f3:ca:6b:61:ba:58:b7:2e:dd:7b: - ca:b9:02:9f:24:36:ac:26:8f:04:8f:81:c8:35:10: - f4:aa:33:b2:24:16:f8:f7:1e:ea:f7:16:fe:fa:34: - c3:dd:bb:2c:ba:7a:df:4d:e2:da:1e:e5:d2:28:44: - 6e:c8:96:e0:fd:09:0c:14:0c:31:dc:e0:ca:c1:a7: - 9b:bf:16:8c:f7:36:3f:1b:2e:dd:90:eb:45:78:51: - bf:59:22:1e:c6:8c:0a:69:88:e5:03:5e:73:b7:fc: - 93:7f:1b:46:1b:97:68:c5:c0:8b:35:1f:bb:1e:67: - 7f:55:b7:3b:55:3f:ea:f2:ca:db:cc:52:cd:16:89: - db:15:47:bd:f2:cd:6c:7a:d7:b4:1a:ac:c8:15:6c: - 6a:fb:77:c4:e9:f2:30:e0:14:24:66:65:6f:2a:e5: - 2d:cc:f6:81:ae:57:c8:d1:9b:38:90:dc:60:93:02: - 5e:cb - Exponent: 65537 (0x10001) - Signature Algorithm: sha256WithRSAEncryption - 1c:7c:39:e8:3d:49:b2:09:1e:68:5a:2f:74:18:f4:63:b5:8c: - f6:e6:a1:e3:4d:95:90:99:ef:32:5c:34:40:e8:55:13:0e:e0: - 1c:be:cd:ab:3f:64:38:99:5e:2b:c1:81:53:a0:18:a8:f6:ee: - 6a:33:73:6c:9a:73:9d:86:08:5d:c7:11:38:46:4c:cd:a0:47: - 37:8f:fe:a6:50:a9:02:21:99:42:86:5e:47:fe:65:56:60:1d: - 16:53:86:bd:e4:63:c5:69:cf:fa:30:51:ab:a1:c3:50:53:cc: - 66:1c:4c:ff:3f:2a:39:4d:a2:8f:9d:d1:a7:8b:22:e4:78:69: - 24:06:83:4d:cc:0a:c0:87:69:9b:bc:80:a9:d2:b7:a5:23:84: - 7e:a2:32:26:7c:78:0e:bd:db:cd:3b:69:18:33:b8:44:ef:96: - b4:99:86:ee:06:bd:51:1c:c7:a1:a4:0c:c4:4c:51:a0:df:ac: - 14:07:88:8e:d7:39:45:fe:52:e0:a3:4c:db:5d:7a:ab:4d:e4: - ca:06:e8:bd:74:6f:46:e7:93:4a:4f:1b:67:e7:a5:9f:ef:9c: - 02:49:d1:f2:d5:e9:53:ee:09:21:ac:08:c8:15:f7:af:35:b9: - 4f:11:0f:43:ae:46:8e:fd:5b:8d:a3:4e:a7:2c:b7:25:ed:e4: - e5:94:1d:e3 ------BEGIN CERTIFICATE----- -MIICtTCCAZ0CAhAAMA0GCSqGSIb3DQEBCwUAMB0xCzAJBgNVBAYTAlVTMQ4wDAYD -VQQDEwVNeSBDQTAgFw0xNzA1MjMxNjAwMjNaGA8yMTE3MDQyOTE2MDAyM1owITES -MBAGA1UEAxMJbG9jYWxob3N0MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAMnUQ2BQ/NYPOE1dXqp8wF6p7NmTeNOTcihB9Qil6qxn -B9cf9310aX5GiSBLei2bAgjnbw8dDA/HYGkZS99+ynWUC0lx423y6Hn97QqUZ1Xz -ymthuli3Lt17yrkCnyQ2rCaPBI+ByDUQ9KozsiQW+Pce6vcW/vo0w927LLp6303i -2h7l0ihEbsiW4P0JDBQMMdzgysGnm78WjPc2Pxsu3ZDrRXhRv1kiHsaMCmmI5QNe -c7f8k38bRhuXaMXAizUfux5nf1W3O1U/6vLK28xSzRaJ2xVHvfLNbHrXtBqsyBVs -avt3xOnyMOAUJGZlbyrlLcz2ga5XyNGbOJDcYJMCXssCAwEAATANBgkqhkiG9w0B -AQsFAAOCAQEAHHw56D1JsgkeaFovdBj0Y7WM9uah402VkJnvMlw0QOhVEw7gHL7N -qz9kOJleK8GBU6AYqPbuajNzbJpznYYIXccROEZMzaBHN4/+plCpAiGZQoZeR/5l -VmAdFlOGveRjxWnP+jBRq6HDUFPMZhxM/z8qOU2ij53Rp4si5HhpJAaDTcwKwIdp -m7yAqdK3pSOEfqIyJnx4Dr3bzTtpGDO4RO+WtJmG7ga9URzHoaQMxExRoN+sFAeI -jtc5Rf5S4KNM2116q03kygbovXRvRueTSk8bZ+eln++cAknR8tXpU+4JIawIyBX3 -rzW5TxEPQ65Gjv1bjaNOpyy3Je3k5ZQd4w== ------END CERTIFICATE----- diff --git a/rust/fatcat-openapi/examples/server-key.pem b/rust/fatcat-openapi/examples/server-key.pem deleted file mode 100644 index 29c0068..0000000 --- a/rust/fatcat-openapi/examples/server-key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ1ENgUPzWDzhN -XV6qfMBeqezZk3jTk3IoQfUIpeqsZwfXH/d9dGl+RokgS3otmwII528PHQwPx2Bp -GUvffsp1lAtJceNt8uh5/e0KlGdV88prYbpYty7de8q5Ap8kNqwmjwSPgcg1EPSq -M7IkFvj3Hur3Fv76NMPduyy6et9N4toe5dIoRG7IluD9CQwUDDHc4MrBp5u/Foz3 -Nj8bLt2Q60V4Ub9ZIh7GjAppiOUDXnO3/JN/G0Ybl2jFwIs1H7seZ39VtztVP+ry -ytvMUs0WidsVR73yzWx617QarMgVbGr7d8Tp8jDgFCRmZW8q5S3M9oGuV8jRmziQ -3GCTAl7LAgMBAAECggEBAKEd1q9j14KWYc64s6KLthGbutyxsinMMbxbct11fdIk -6YhdF3fJ35ETg9IJDr6rWEN9ZRX+jStncNpVfFEs6ThVd3Eo/nI+EEGaaIkikR93 -X2a7fEPn7/yVHu70XdBN6L1bPDvHUeiy4W2hmRrgT90OjGm1rNRWHOm7yugOwIZu -HclzbR9Ca7EInFnotUiDQm9sw9VKHbJHqWx6OORdZrxR2ytYs0Qkq0XpGMvti2HW -7WAmKTg5QM8myXW7+/4iqb/u68wVBR2BBalShKmIf7lim9O3W2a1RjDdsvm/wNe9 -I+D+Iq825vpqkKXcrxYlpVg7hYiaQaW/MNsEb7lQRjECgYEA/RJYby0POW+/k0Jn -jO8UmJVEMiuGa8WIUu/JJWMOmzRCukjSRNQOkt7niQrZPJYE8W6clM6RJTolWf9L -IL6mIb+mRaoudUk8SHGDq7ho1iMg9GK8lhYxvKh1Q6uv8EyVSkgLknAEY0NANKC1 -zNdU5Dhven9aRX2gq9vP4XwMz2MCgYEAzCogQ7IFk+gkp3k491dOZnrGRoRCfuzo -4CJtyKFgOSd7BjmpcKkj0IPfVBjw6GjMIxfQRMTQmxAjjWevH45vG8l0Iiwz/gSp -81b5nsDEX5uv2Olcmcz5zxRFy36jOZ9ihMWinxcIlT2oDbyCdbruDKZq9ieJ9S8g -4qGx0OkwE3kCgYEA7CmAiU89U9YqqttfEq/RQoqY91CSwmO10d+ej9seuEtOsdRf -FIfnibulycdr7hP5TOxyBpO1802NqayJiWcgVYIpQf2MGTtcnCYCP+95NcvWZvj1 -EAJqK6nwtFO1fcOZ1ZXh5qfOEGujsPkAbsXLnKXlsiTCMvMHSxl3pu5Cbg0CgYBf -JjbZNctRrjv+7Qj2hPLd4dQsIxGWc7ToWENP4J2mpVa5hQAJqFovoHXhjKohtk2F -AWEn243Y5oGbMjo0e74edhmwn2cvuF64MM2vBem/ISCn98IXT6cQskMA3qkVfsl8 -VVs/x41ReGWs2TD3y0GMFbb9t1mdMfSiincDhNnKCQKBgGfeT4jKyYeCoCw4OLI1 -G75Gd0METt/IkppwODPpNwj3Rp9I5jctWZFA/3wCX/zk0HgBeou5AFNS4nQZ/X/L -L9axbSdR7UJTGkT1r4gu3rLkPV4Tk+8XM03/JT2cofMlzQBuhvl1Pn4SgKowz7hl -lS76ECw4Av3T0S34VW9Z5oye ------END PRIVATE KEY----- diff --git a/rust/fatcat-openapi/examples/server/main.rs b/rust/fatcat-openapi/examples/server/main.rs deleted file mode 100644 index 5488dc6..0000000 --- a/rust/fatcat-openapi/examples/server/main.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Main binary entry point for fatcat_openapi implementation. - -#![allow(missing_docs)] - -use clap::{App, Arg}; - -mod server; - -/// Create custom server, wire it to the autogenerated router, -/// and pass it to the web server. -#[tokio::main] -async fn main() { - env_logger::init(); - - let matches = App::new("server") - .arg( - Arg::with_name("https") - .long("https") - .help("Whether to use HTTPS or not"), - ) - .get_matches(); - - let addr = "127.0.0.1:8080"; - - server::create(addr, matches.is_present("https")).await; -} diff --git a/rust/fatcat-openapi/examples/server/server.rs b/rust/fatcat-openapi/examples/server/server.rs deleted file mode 100644 index 981487e..0000000 --- a/rust/fatcat-openapi/examples/server/server.rs +++ /dev/null @@ -1,1687 +0,0 @@ -//! Main library entry point for fatcat_openapi implementation. - -#![allow(unused_imports)] - -use async_trait::async_trait; -use futures::{future, Stream, StreamExt, TryFutureExt, TryStreamExt}; -use hyper::server::conn::Http; -use hyper::service::Service; -use log::info; -#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] -use openssl::ssl::SslAcceptorBuilder; -use std::future::Future; -use std::marker::PhantomData; -use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll}; -use swagger::auth::MakeAllowAllAuthenticator; -use swagger::EmptyContext; -use swagger::{Has, XSpanIdString}; -use tokio::net::TcpListener; - -#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] -use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; - -use fatcat_openapi::models; - -/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names -pub async fn create(addr: &str, https: bool) { - let addr = addr.parse().expect("Failed to parse bind address"); - - let server = Server::new(); - - let service = MakeService::new(server); - - let service = MakeAllowAllAuthenticator::new(service, "cosmo"); - - let mut service = - fatcat_openapi::server::context::MakeAddContext::<_, EmptyContext>::new(service); - - if https { - #[cfg(any(target_os = "macos", target_os = "windows", target_os = "ios"))] - { - unimplemented!("SSL is not implemented for the examples on MacOS, Windows or iOS"); - } - - #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] - { - let mut ssl = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()) - .expect("Failed to create SSL Acceptor"); - - // Server authentication - ssl.set_private_key_file("examples/server-key.pem", SslFiletype::PEM) - .expect("Failed to set private key"); - ssl.set_certificate_chain_file("examples/server-chain.pem") - .expect("Failed to set cerificate chain"); - ssl.check_private_key() - .expect("Failed to check private key"); - - let tls_acceptor = Arc::new(ssl.build()); - let mut tcp_listener = TcpListener::bind(&addr).await.unwrap(); - let mut incoming = tcp_listener.incoming(); - - while let (Some(tcp), rest) = incoming.into_future().await { - if let Ok(tcp) = tcp { - let addr = tcp.peer_addr().expect("Unable to get remote address"); - let service = service.call(addr); - let tls_acceptor = Arc::clone(&tls_acceptor); - - tokio::spawn(async move { - let tls = tokio_openssl::accept(&*tls_acceptor, tcp) - .await - .map_err(|_| ())?; - - let service = service.await.map_err(|_| ())?; - - Http::new() - .serve_connection(tls, service) - .await - .map_err(|_| ()) - }); - } - - incoming = rest; - } - } - } else { - // Using HTTP - hyper::server::Server::bind(&addr) - .serve(service) - .await - .unwrap() - } -} - -#[derive(Copy, Clone)] -pub struct Server { - marker: PhantomData, -} - -impl Server { - pub fn new() -> Self { - Server { - marker: PhantomData, - } - } -} - -use fatcat_openapi::server::MakeService; -use fatcat_openapi::{ - AcceptEditgroupResponse, Api, AuthCheckResponse, AuthOidcResponse, CreateAuthTokenResponse, - CreateContainerAutoBatchResponse, CreateContainerResponse, CreateCreatorAutoBatchResponse, - CreateCreatorResponse, CreateEditgroupAnnotationResponse, CreateEditgroupResponse, - CreateFileAutoBatchResponse, CreateFileResponse, CreateFilesetAutoBatchResponse, - CreateFilesetResponse, CreateReleaseAutoBatchResponse, CreateReleaseResponse, - CreateWebcaptureAutoBatchResponse, CreateWebcaptureResponse, CreateWorkAutoBatchResponse, - CreateWorkResponse, DeleteContainerEditResponse, DeleteContainerResponse, - DeleteCreatorEditResponse, DeleteCreatorResponse, DeleteFileEditResponse, DeleteFileResponse, - DeleteFilesetEditResponse, DeleteFilesetResponse, DeleteReleaseEditResponse, - DeleteReleaseResponse, DeleteWebcaptureEditResponse, DeleteWebcaptureResponse, - DeleteWorkEditResponse, DeleteWorkResponse, GetChangelogEntryResponse, GetChangelogResponse, - GetContainerEditResponse, GetContainerHistoryResponse, GetContainerRedirectsResponse, - GetContainerResponse, GetContainerRevisionResponse, GetCreatorEditResponse, - GetCreatorHistoryResponse, GetCreatorRedirectsResponse, GetCreatorReleasesResponse, - GetCreatorResponse, GetCreatorRevisionResponse, GetEditgroupAnnotationsResponse, - GetEditgroupResponse, GetEditgroupsReviewableResponse, GetEditorAnnotationsResponse, - GetEditorEditgroupsResponse, GetEditorResponse, GetFileEditResponse, GetFileHistoryResponse, - GetFileRedirectsResponse, GetFileResponse, GetFileRevisionResponse, GetFilesetEditResponse, - GetFilesetHistoryResponse, GetFilesetRedirectsResponse, GetFilesetResponse, - GetFilesetRevisionResponse, GetReleaseEditResponse, GetReleaseFilesResponse, - GetReleaseFilesetsResponse, GetReleaseHistoryResponse, GetReleaseRedirectsResponse, - GetReleaseResponse, GetReleaseRevisionResponse, GetReleaseWebcapturesResponse, - GetWebcaptureEditResponse, GetWebcaptureHistoryResponse, GetWebcaptureRedirectsResponse, - GetWebcaptureResponse, GetWebcaptureRevisionResponse, GetWorkEditResponse, - GetWorkHistoryResponse, GetWorkRedirectsResponse, GetWorkReleasesResponse, GetWorkResponse, - GetWorkRevisionResponse, LookupContainerResponse, LookupCreatorResponse, LookupFileResponse, - LookupReleaseResponse, UpdateContainerResponse, UpdateCreatorResponse, UpdateEditgroupResponse, - UpdateEditorResponse, UpdateFileResponse, UpdateFilesetResponse, UpdateReleaseResponse, - UpdateWebcaptureResponse, UpdateWorkResponse, -}; -use std::error::Error; -use swagger::ApiError; - -#[async_trait] -impl Api for Server -where - C: Has + Send + Sync, -{ - async fn accept_editgroup( - &self, - editgroup_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "accept_editgroup(\"{}\") - X-Span-ID: {:?}", - editgroup_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn auth_check( - &self, - role: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "auth_check({:?}) - X-Span-ID: {:?}", - role, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn auth_oidc( - &self, - auth_oidc: models::AuthOidc, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "auth_oidc({:?}) - X-Span-ID: {:?}", - auth_oidc, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_auth_token( - &self, - editor_id: String, - duration_seconds: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_auth_token(\"{}\", {:?}) - X-Span-ID: {:?}", - editor_id, - duration_seconds, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_container( - &self, - editgroup_id: String, - container_entity: models::ContainerEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_container(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - container_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_container_auto_batch( - &self, - container_auto_batch: models::ContainerAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_container_auto_batch({:?}) - X-Span-ID: {:?}", - container_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_creator( - &self, - editgroup_id: String, - creator_entity: models::CreatorEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_creator(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - creator_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_creator_auto_batch( - &self, - creator_auto_batch: models::CreatorAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_creator_auto_batch({:?}) - X-Span-ID: {:?}", - creator_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_editgroup( - &self, - editgroup: models::Editgroup, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_editgroup({:?}) - X-Span-ID: {:?}", - editgroup, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_editgroup_annotation( - &self, - editgroup_id: String, - editgroup_annotation: models::EditgroupAnnotation, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_editgroup_annotation(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - editgroup_annotation, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_file( - &self, - editgroup_id: String, - file_entity: models::FileEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_file(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - file_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_file_auto_batch( - &self, - file_auto_batch: models::FileAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_file_auto_batch({:?}) - X-Span-ID: {:?}", - file_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_fileset( - &self, - editgroup_id: String, - fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_fileset(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - fileset_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_fileset_auto_batch( - &self, - fileset_auto_batch: models::FilesetAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_fileset_auto_batch({:?}) - X-Span-ID: {:?}", - fileset_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_release( - &self, - editgroup_id: String, - release_entity: models::ReleaseEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_release(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - release_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_release_auto_batch( - &self, - release_auto_batch: models::ReleaseAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_release_auto_batch({:?}) - X-Span-ID: {:?}", - release_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_webcapture( - &self, - editgroup_id: String, - webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_webcapture(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - webcapture_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_webcapture_auto_batch( - &self, - webcapture_auto_batch: models::WebcaptureAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_webcapture_auto_batch({:?}) - X-Span-ID: {:?}", - webcapture_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_work( - &self, - editgroup_id: String, - work_entity: models::WorkEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_work(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - work_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn create_work_auto_batch( - &self, - work_auto_batch: models::WorkAutoBatch, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "create_work_auto_batch({:?}) - X-Span-ID: {:?}", - work_auto_batch, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_container( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_container(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_container_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_container_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_creator( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_creator(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_creator_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_creator_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_file( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_file(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_file_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_file_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_fileset( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_fileset(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_fileset_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_fileset_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_release( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_release(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_release_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_release_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_webcapture( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_webcapture(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_webcapture_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_webcapture_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_work( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_work(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn delete_work_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "delete_work_edit(\"{}\", \"{}\") - X-Span-ID: {:?}", - editgroup_id, - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_changelog( - &self, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_changelog({:?}) - X-Span-ID: {:?}", - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_changelog_entry( - &self, - index: i64, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_changelog_entry({}) - X-Span-ID: {:?}", - index, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_container( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_container(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_container_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_container_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_container_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_container_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_container_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_container_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_container_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_container_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator_releases( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator_releases(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_creator_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_creator_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editgroup( - &self, - editgroup_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editgroup(\"{}\") - X-Span-ID: {:?}", - editgroup_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editgroup_annotations( - &self, - editgroup_id: String, - expand: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editgroup_annotations(\"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - expand, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editgroups_reviewable( - &self, - expand: Option, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editgroups_reviewable({:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - expand, - limit, - before, - since, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editor( - &self, - editor_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editor(\"{}\") - X-Span-ID: {:?}", - editor_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editor_annotations( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editor_annotations(\"{}\", {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - editor_id, - limit, - before, - since, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_editor_editgroups( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_editor_editgroups(\"{}\", {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - editor_id, - limit, - before, - since, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_file( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_file(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_file_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_file_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_file_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_file_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_file_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_file_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_file_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_file_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_fileset( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_fileset(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_fileset_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_fileset_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_fileset_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_fileset_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_fileset_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_fileset_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_fileset_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_fileset_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_files( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_files(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_filesets( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_filesets(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_release_webcaptures( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_release_webcaptures(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_webcapture( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_webcapture(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_webcapture_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_webcapture_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_webcapture_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_webcapture_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_webcapture_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_webcapture_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_webcapture_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_webcapture_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - ident, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work_edit( - &self, - edit_id: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work_edit(\"{}\") - X-Span-ID: {:?}", - edit_id, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work_history(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - limit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work_redirects( - &self, - ident: String, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work_redirects(\"{}\") - X-Span-ID: {:?}", - ident, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work_releases( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work_releases(\"{}\", {:?}) - X-Span-ID: {:?}", - ident, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn get_work_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "get_work_revision(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - rev_id, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn lookup_container( - &self, - issnl: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "lookup_container({:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - issnl, - wikidata_qid, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn lookup_creator( - &self, - orcid: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "lookup_creator({:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - orcid, - wikidata_qid, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn lookup_file( - &self, - md5: Option, - sha1: Option, - sha256: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "lookup_file({:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", - md5, - sha1, - sha256, - expand, - hide, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn lookup_release( - &self, - doi: Option, - wikidata_qid: Option, - isbn13: Option, - pmid: Option, - pmcid: Option, - core: Option, - arxiv: Option, - jstor: Option, - ark: Option, - mag: Option, - doaj: Option, - dblp: Option, - oai: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!("lookup_release({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", doi, wikidata_qid, isbn13, pmid, pmcid, core, arxiv, jstor, ark, mag, doaj, dblp, oai, expand, hide, context.get().0.clone()); - Err("Generic failuare".into()) - } - - async fn update_container( - &self, - editgroup_id: String, - ident: String, - container_entity: models::ContainerEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_container(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - container_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_creator( - &self, - editgroup_id: String, - ident: String, - creator_entity: models::CreatorEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_creator(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - creator_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_editgroup( - &self, - editgroup_id: String, - editgroup: models::Editgroup, - submit: Option, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_editgroup(\"{}\", {:?}, {:?}) - X-Span-ID: {:?}", - editgroup_id, - editgroup, - submit, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_editor( - &self, - editor_id: String, - editor: models::Editor, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_editor(\"{}\", {:?}) - X-Span-ID: {:?}", - editor_id, - editor, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_file( - &self, - editgroup_id: String, - ident: String, - file_entity: models::FileEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_file(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - file_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_fileset( - &self, - editgroup_id: String, - ident: String, - fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_fileset(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - fileset_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_release( - &self, - editgroup_id: String, - ident: String, - release_entity: models::ReleaseEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_release(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - release_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_webcapture( - &self, - editgroup_id: String, - ident: String, - webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_webcapture(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - webcapture_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } - - async fn update_work( - &self, - editgroup_id: String, - ident: String, - work_entity: models::WorkEntity, - context: &C, - ) -> Result { - let context = context.clone(); - info!( - "update_work(\"{}\", \"{}\", {:?}) - X-Span-ID: {:?}", - editgroup_id, - ident, - work_entity, - context.get().0.clone() - ); - Err("Generic failuare".into()) - } -} diff --git a/rust/fatcat-openapi/src/client/mod.rs b/rust/fatcat-openapi/src/client/mod.rs deleted file mode 100644 index bb1cee8..0000000 --- a/rust/fatcat-openapi/src/client/mod.rs +++ /dev/null @@ -1,16107 +0,0 @@ -use async_trait::async_trait; -use futures::{ - future, future::BoxFuture, future::FutureExt, future::TryFutureExt, stream, stream::StreamExt, - Stream, -}; -use hyper::header::{HeaderName, HeaderValue, CONTENT_TYPE}; -use hyper::{service::Service, Body, Request, Response, Uri}; -use percent_encoding::{utf8_percent_encode, AsciiSet}; -use std::borrow::Cow; -use std::convert::TryInto; -use std::error::Error; -use std::fmt; -use std::future::Future; -use std::io::{ErrorKind, Read}; -use std::marker::PhantomData; -use std::path::Path; -use std::str; -use std::str::FromStr; -use std::string::ToString; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll}; -use swagger::{ApiError, AuthData, BodyExt, Connector, DropContextService, Has, XSpanIdString}; -use url::form_urlencoded; - -use crate::header; -use crate::models; - -/// https://url.spec.whatwg.org/#fragment-percent-encode-set -#[allow(dead_code)] -const FRAGMENT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS - .add(b' ') - .add(b'"') - .add(b'<') - .add(b'>') - .add(b'`'); - -/// This encode set is used for object IDs -/// -/// Aside from the special characters defined in the `PATH_SEGMENT_ENCODE_SET`, -/// the vertical bar (|) is encoded. -#[allow(dead_code)] -const ID_ENCODE_SET: &AsciiSet = &FRAGMENT_ENCODE_SET.add(b'|'); - -use crate::{ - AcceptEditgroupResponse, Api, AuthCheckResponse, AuthOidcResponse, CreateAuthTokenResponse, - CreateContainerAutoBatchResponse, CreateContainerResponse, CreateCreatorAutoBatchResponse, - CreateCreatorResponse, CreateEditgroupAnnotationResponse, CreateEditgroupResponse, - CreateFileAutoBatchResponse, CreateFileResponse, CreateFilesetAutoBatchResponse, - CreateFilesetResponse, CreateReleaseAutoBatchResponse, CreateReleaseResponse, - CreateWebcaptureAutoBatchResponse, CreateWebcaptureResponse, CreateWorkAutoBatchResponse, - CreateWorkResponse, DeleteContainerEditResponse, DeleteContainerResponse, - DeleteCreatorEditResponse, DeleteCreatorResponse, DeleteFileEditResponse, DeleteFileResponse, - DeleteFilesetEditResponse, DeleteFilesetResponse, DeleteReleaseEditResponse, - DeleteReleaseResponse, DeleteWebcaptureEditResponse, DeleteWebcaptureResponse, - DeleteWorkEditResponse, DeleteWorkResponse, GetChangelogEntryResponse, GetChangelogResponse, - GetContainerEditResponse, GetContainerHistoryResponse, GetContainerRedirectsResponse, - GetContainerResponse, GetContainerRevisionResponse, GetCreatorEditResponse, - GetCreatorHistoryResponse, GetCreatorRedirectsResponse, GetCreatorReleasesResponse, - GetCreatorResponse, GetCreatorRevisionResponse, GetEditgroupAnnotationsResponse, - GetEditgroupResponse, GetEditgroupsReviewableResponse, GetEditorAnnotationsResponse, - GetEditorEditgroupsResponse, GetEditorResponse, GetFileEditResponse, GetFileHistoryResponse, - GetFileRedirectsResponse, GetFileResponse, GetFileRevisionResponse, GetFilesetEditResponse, - GetFilesetHistoryResponse, GetFilesetRedirectsResponse, GetFilesetResponse, - GetFilesetRevisionResponse, GetReleaseEditResponse, GetReleaseFilesResponse, - GetReleaseFilesetsResponse, GetReleaseHistoryResponse, GetReleaseRedirectsResponse, - GetReleaseResponse, GetReleaseRevisionResponse, GetReleaseWebcapturesResponse, - GetWebcaptureEditResponse, GetWebcaptureHistoryResponse, GetWebcaptureRedirectsResponse, - GetWebcaptureResponse, GetWebcaptureRevisionResponse, GetWorkEditResponse, - GetWorkHistoryResponse, GetWorkRedirectsResponse, GetWorkReleasesResponse, GetWorkResponse, - GetWorkRevisionResponse, LookupContainerResponse, LookupCreatorResponse, LookupFileResponse, - LookupReleaseResponse, UpdateContainerResponse, UpdateCreatorResponse, UpdateEditgroupResponse, - UpdateEditorResponse, UpdateFileResponse, UpdateFilesetResponse, UpdateReleaseResponse, - UpdateWebcaptureResponse, UpdateWorkResponse, -}; - -/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. -fn into_base_path( - input: impl TryInto, - correct_scheme: Option<&'static str>, -) -> Result { - // First convert to Uri, since a base path is a subset of Uri. - let uri = input.try_into()?; - - let scheme = uri.scheme_str().ok_or(ClientInitError::InvalidScheme)?; - - // Check the scheme if necessary - if let Some(correct_scheme) = correct_scheme { - if scheme != correct_scheme { - return Err(ClientInitError::InvalidScheme); - } - } - - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; - let port = uri - .port_u16() - .map(|x| format!(":{}", x)) - .unwrap_or_default(); - Ok(format!( - "{}://{}{}{}", - scheme, - host, - port, - uri.path().trim_end_matches('/') - )) -} - -/// A client that implements the API by making HTTP calls out to a server. -pub struct Client -where - S: Service<(Request, C), Response = Response> + Clone + Sync + Send + 'static, - S::Future: Send + 'static, - S::Error: Into + fmt::Display, - C: Clone + Send + Sync + 'static, -{ - /// Inner service - client_service: S, - - /// Base path of the API - base_path: String, - - /// Marker - marker: PhantomData, -} - -impl fmt::Debug for Client -where - S: Service<(Request, C), Response = Response> + Clone + Sync + Send + 'static, - S::Future: Send + 'static, - S::Error: Into + fmt::Display, - C: Clone + Send + Sync + 'static, -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Client {{ base_path: {} }}", self.base_path) - } -} - -impl Clone for Client -where - S: Service<(Request, C), Response = Response> + Clone + Sync + Send + 'static, - S::Future: Send + 'static, - S::Error: Into + fmt::Display, - C: Clone + Send + Sync + 'static, -{ - fn clone(&self) -> Self { - Self { - client_service: self.client_service.clone(), - base_path: self.base_path.clone(), - marker: PhantomData, - } - } -} - -impl Client, C>, C> -where - Connector: hyper::client::connect::Connect + Clone + Send + Sync + 'static, - C: Clone + Send + Sync + 'static, -{ - /// Create a client with a custom implementation of hyper::client::Connect. - /// - /// Intended for use with custom implementations of connect for e.g. protocol logging - /// or similar functionality which requires wrapping the transport layer. When wrapping a TCP connection, - /// this function should be used in conjunction with `swagger::Connector::builder()`. - /// - /// For ordinary tcp connections, prefer the use of `try_new_http`, `try_new_https` - /// and `try_new_https_mutual`, to avoid introducing a dependency on the underlying transport layer. - /// - /// # Arguments - /// - /// * `base_path` - base path of the client API, i.e. "http://www.my-api-implementation.com" - /// * `protocol` - Which protocol to use when constructing the request url, e.g. `Some("http")` - /// * `connector` - Implementation of `hyper::client::Connect` to use for the client - pub fn try_new_with_connector( - base_path: &str, - protocol: Option<&'static str>, - connector: Connector, - ) -> Result { - let client_service = hyper::client::Client::builder().build(connector); - let client_service = DropContextService::new(client_service); - - Ok(Self { - client_service, - base_path: into_base_path(base_path, protocol)?, - marker: PhantomData, - }) - } -} - -#[derive(Debug, Clone)] -pub enum HyperClient { - Http(hyper::client::Client), - Https(hyper::client::Client), -} - -impl Service> for HyperClient { - type Response = Response; - type Error = hyper::Error; - type Future = hyper::client::ResponseFuture; - - fn poll_ready(&mut self, cx: &mut Context) -> Poll> { - match self { - HyperClient::Http(client) => client.poll_ready(cx), - HyperClient::Https(client) => client.poll_ready(cx), - } - } - - fn call(&mut self, req: Request) -> Self::Future { - match self { - HyperClient::Http(client) => client.call(req), - HyperClient::Https(client) => client.call(req), - } - } -} - -impl Client, C> -where - C: Clone + Send + Sync + 'static, -{ - /// Create an HTTP client. - /// - /// # Arguments - /// * `base_path` - base path of the client API, i.e. "http://www.my-api-implementation.com" - pub fn try_new(base_path: &str) -> Result { - let uri = Uri::from_str(base_path)?; - - let scheme = uri.scheme_str().ok_or(ClientInitError::InvalidScheme)?; - let scheme = scheme.to_ascii_lowercase(); - - let connector = Connector::builder(); - - let client_service = match scheme.as_str() { - "http" => HyperClient::Http(hyper::client::Client::builder().build(connector.build())), - "https" => { - let connector = connector - .https() - .build() - .map_err(|e| ClientInitError::SslError(e))?; - HyperClient::Https(hyper::client::Client::builder().build(connector)) - } - _ => { - return Err(ClientInitError::InvalidScheme); - } - }; - - let client_service = DropContextService::new(client_service); - - Ok(Self { - client_service, - base_path: into_base_path(base_path, None)?, - marker: PhantomData, - }) - } -} - -impl Client, C>, C> -where - C: Clone + Send + Sync + 'static, -{ - /// Create an HTTP client. - /// - /// # Arguments - /// * `base_path` - base path of the client API, i.e. "http://www.my-api-implementation.com" - pub fn try_new_http(base_path: &str) -> Result { - let http_connector = Connector::builder().build(); - - Self::try_new_with_connector(base_path, Some("http"), http_connector) - } -} - -#[cfg(any(target_os = "macos", target_os = "windows", target_os = "ios"))] -type HttpsConnector = hyper_tls::HttpsConnector; - -#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] -type HttpsConnector = hyper_openssl::HttpsConnector; - -impl Client, C>, C> -where - C: Clone + Send + Sync + 'static, -{ - /// Create a client with a TLS connection to the server - /// - /// # Arguments - /// * `base_path` - base path of the client API, i.e. "https://www.my-api-implementation.com" - pub fn try_new_https(base_path: &str) -> Result { - let https_connector = Connector::builder() - .https() - .build() - .map_err(|e| ClientInitError::SslError(e))?; - Self::try_new_with_connector(base_path, Some("https"), https_connector) - } - - /// Create a client with a TLS connection to the server using a pinned certificate - /// - /// # Arguments - /// * `base_path` - base path of the client API, i.e. "https://www.my-api-implementation.com" - /// * `ca_certificate` - Path to CA certificate used to authenticate the server - #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] - pub fn try_new_https_pinned( - base_path: &str, - ca_certificate: CA, - ) -> Result - where - CA: AsRef, - { - let https_connector = Connector::builder() - .https() - .pin_server_certificate(ca_certificate) - .build() - .map_err(|e| ClientInitError::SslError(e))?; - Self::try_new_with_connector(base_path, Some("https"), https_connector) - } - - /// Create a client with a mutually authenticated TLS connection to the server. - /// - /// # Arguments - /// * `base_path` - base path of the client API, i.e. "https://www.my-api-implementation.com" - /// * `ca_certificate` - Path to CA certificate used to authenticate the server - /// * `client_key` - Path to the client private key - /// * `client_certificate` - Path to the client's public certificate associated with the private key - #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] - pub fn try_new_https_mutual( - base_path: &str, - ca_certificate: CA, - client_key: K, - client_certificate: D, - ) -> Result - where - CA: AsRef, - K: AsRef, - D: AsRef, - { - let https_connector = Connector::builder() - .https() - .pin_server_certificate(ca_certificate) - .client_authentication(client_key, client_certificate) - .build() - .map_err(|e| ClientInitError::SslError(e))?; - Self::try_new_with_connector(base_path, Some("https"), https_connector) - } -} - -impl Client -where - S: Service<(Request, C), Response = Response> + Clone + Sync + Send + 'static, - S::Future: Send + 'static, - S::Error: Into + fmt::Display, - C: Clone + Send + Sync + 'static, -{ - /// Constructor for creating a `Client` by passing in a pre-made `hyper::service::Service` / - /// `tower::Service` - /// - /// This allows adding custom wrappers around the underlying transport, for example for logging. - pub fn try_new_with_client_service( - client_service: S, - base_path: &str, - ) -> Result { - Ok(Self { - client_service, - base_path: into_base_path(base_path, None)?, - marker: PhantomData, - }) - } -} - -/// Error type failing to create a Client -#[derive(Debug)] -pub enum ClientInitError { - /// Invalid URL Scheme - InvalidScheme, - - /// Invalid URI - InvalidUri(hyper::http::uri::InvalidUri), - - /// Missing Hostname - MissingHost, - - /// SSL Connection Error - #[cfg(any(target_os = "macos", target_os = "windows", target_os = "ios"))] - SslError(native_tls::Error), - - /// SSL Connection Error - #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "ios")))] - SslError(openssl::error::ErrorStack), -} - -impl From for ClientInitError { - fn from(err: hyper::http::uri::InvalidUri) -> ClientInitError { - ClientInitError::InvalidUri(err) - } -} - -impl fmt::Display for ClientInitError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s: &dyn fmt::Debug = self; - s.fmt(f) - } -} - -impl Error for ClientInitError { - fn description(&self) -> &str { - "Failed to produce a hyper client." - } -} - -#[async_trait] -impl Api for Client -where - S: Service<(Request, C), Response = Response> + Clone + Sync + Send + 'static, - S::Future: Send + 'static, - S::Error: Into + fmt::Display, - C: Has + Has> + Clone + Send + Sync + 'static, -{ - fn poll_ready(&self, cx: &mut Context) -> Poll> { - match self.client_service.clone().poll_ready(cx) { - Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())), - Poll::Ready(Ok(o)) => Poll::Ready(Ok(o)), - Poll::Pending => Poll::Pending, - } - } - - async fn accept_editgroup( - &self, - param_editgroup_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/accept", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::MergedSuccessfully(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::NotFound(body)) - } - 409 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::EditConflict(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AcceptEditgroupResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn auth_check( - &self, - param_role: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/auth/check", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_role) = param_role { - query_string.append_pair("role", ¶m_role.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthCheckResponse::Success(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthCheckResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthCheckResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthCheckResponse::Forbidden(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthCheckResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn auth_oidc( - &self, - param_auth_oidc: models::AuthOidc, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/auth/oidc", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_auth_oidc).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::Found(body)) - } - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::Created(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::Forbidden(body)) - } - 409 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::Conflict(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(AuthOidcResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_auth_token( - &self, - param_editor_id: String, - param_duration_seconds: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/auth/token/{editor_id}", - self.base_path, - editor_id = utf8_percent_encode(¶m_editor_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_duration_seconds) = param_duration_seconds { - query_string.append_pair("duration_seconds", ¶m_duration_seconds.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateAuthTokenResponse::Success(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateAuthTokenResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateAuthTokenResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateAuthTokenResponse::Forbidden(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateAuthTokenResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_container( - &self, - param_editgroup_id: String, - param_container_entity: models::ContainerEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/container", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_container_entity) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_container_auto_batch( - &self, - param_container_auto_batch: models::ContainerAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/container/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_container_auto_batch) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateContainerAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_creator( - &self, - param_editgroup_id: String, - param_creator_entity: models::CreatorEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/creator", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_creator_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_creator_auto_batch( - &self, - param_creator_auto_batch: models::CreatorAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/creator/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_creator_auto_batch) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateCreatorAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_editgroup( - &self, - param_editgroup: models::Editgroup, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_editgroup).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::SuccessfullyCreated(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_editgroup_annotation( - &self, - param_editgroup_id: String, - param_editgroup_annotation: models::EditgroupAnnotation, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/annotation", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_editgroup_annotation) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::Created(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateEditgroupAnnotationResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_file( - &self, - param_editgroup_id: String, - param_file_entity: models::FileEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/file", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_file_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_file_auto_batch( - &self, - param_file_auto_batch: models::FileAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/file/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_file_auto_batch).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFileAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_fileset( - &self, - param_editgroup_id: String, - param_fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/fileset", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_fileset_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_fileset_auto_batch( - &self, - param_fileset_auto_batch: models::FilesetAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/fileset/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_fileset_auto_batch) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateFilesetAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_release( - &self, - param_editgroup_id: String, - param_release_entity: models::ReleaseEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/release", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_release_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_release_auto_batch( - &self, - param_release_auto_batch: models::ReleaseAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/release/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_release_auto_batch) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateReleaseAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_webcapture( - &self, - param_editgroup_id: String, - param_webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/webcapture", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_webcapture_entity) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_webcapture_auto_batch( - &self, - param_webcapture_auto_batch: models::WebcaptureAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/webcapture/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_webcapture_auto_batch) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWebcaptureAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_work( - &self, - param_editgroup_id: String, - param_work_entity: models::WorkEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/work", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_work_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::CreatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn create_work_auto_batch( - &self, - param_work_auto_batch: models::WorkAutoBatch, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/auto/work/batch", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("POST") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_work_auto_batch).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 201 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::CreatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(CreateWorkAutoBatchResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_container( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/container/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_container_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/container/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteContainerEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_creator( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/creator/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_creator_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/creator/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteCreatorEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_file( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/file/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_file_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/file/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFileEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_fileset( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/fileset/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_fileset_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/fileset/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteFilesetEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_release( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/release/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_release_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/release/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteReleaseEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_webcapture( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/webcapture/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_webcapture_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/webcapture/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWebcaptureEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_work( - &self, - param_editgroup_id: String, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/work/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::DeletedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn delete_work_edit( - &self, - param_editgroup_id: String, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/work/edit/{edit_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("DELETE") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::DeletedEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(DeleteWorkEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_changelog( - &self, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/changelog", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetChangelogResponse::Success(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogResponse::BadRequest(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_changelog_entry( - &self, - param_index: i64, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/changelog/{index}", - self.base_path, - index = utf8_percent_encode(¶m_index.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogEntryResponse::FoundChangelogEntry(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogEntryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogEntryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetChangelogEntryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_container( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/container/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_container_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/container/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_container_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/container/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetContainerHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_container_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/container/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetContainerRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_container_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/container/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetContainerRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetCreatorHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetCreatorRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator_releases( - &self, - param_ident: String, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/{ident}/releases", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetCreatorReleasesResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorReleasesResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorReleasesResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorReleasesResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_creator_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/creator/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetCreatorRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editgroup( - &self, - param_editgroup_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editgroup_annotations( - &self, - param_editgroup_id: String, - param_expand: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/annotations", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetEditgroupAnnotationsResponse::Success(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupAnnotationsResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupAnnotationsResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupAnnotationsResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupAnnotationsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupAnnotationsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editgroups_reviewable( - &self, - param_expand: Option, - param_limit: Option, - param_before: Option>, - param_since: Option>, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/editgroup/reviewable", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - if let Some(param_before) = param_before { - query_string.append_pair("before", ¶m_before.to_string()); - } - if let Some(param_since) = param_since { - query_string.append_pair("since", ¶m_since.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetEditgroupsReviewableResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupsReviewableResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupsReviewableResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditgroupsReviewableResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editor( - &self, - param_editor_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editor/{editor_id}", - self.base_path, - editor_id = utf8_percent_encode(¶m_editor_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editor_annotations( - &self, - param_editor_id: String, - param_limit: Option, - param_before: Option>, - param_since: Option>, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editor/{editor_id}/annotations", - self.base_path, - editor_id = utf8_percent_encode(¶m_editor_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - if let Some(param_before) = param_before { - query_string.append_pair("before", ¶m_before.to_string()); - } - if let Some(param_since) = param_since { - query_string.append_pair("since", ¶m_since.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetEditorAnnotationsResponse::Success(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorAnnotationsResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorAnnotationsResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorAnnotationsResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorAnnotationsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorAnnotationsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_editor_editgroups( - &self, - param_editor_id: String, - param_limit: Option, - param_before: Option>, - param_since: Option>, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editor/{editor_id}/editgroups", - self.base_path, - editor_id = utf8_percent_encode(¶m_editor_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - if let Some(param_before) = param_before { - query_string.append_pair("before", ¶m_before.to_string()); - } - if let Some(param_since) = param_since { - query_string.append_pair("since", ¶m_since.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetEditorEditgroupsResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorEditgroupsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorEditgroupsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetEditorEditgroupsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_file( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/file/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_file_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/file/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_file_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/file/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetFileHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_file_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/file/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetFileRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_file_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/file/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFileRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_fileset( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/fileset/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_fileset_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/fileset/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_fileset_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/fileset/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetFilesetHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_fileset_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/fileset/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetFilesetRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_fileset_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/fileset/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetFilesetRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_files( - &self, - param_ident: String, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}/files", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetReleaseFilesResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_filesets( - &self, - param_ident: String, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}/filesets", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetReleaseFilesetsResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesetsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesetsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseFilesetsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetReleaseHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetReleaseRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_release_webcaptures( - &self, - param_ident: String, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/release/{ident}/webcaptures", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetReleaseWebcapturesResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseWebcapturesResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseWebcapturesResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetReleaseWebcapturesResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_webcapture( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/webcapture/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_webcapture_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/webcapture/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_webcapture_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/webcapture/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetWebcaptureHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_webcapture_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/webcapture/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetWebcaptureRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_webcapture_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/webcapture/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWebcaptureRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work( - &self, - param_ident: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/{ident}", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work_edit( - &self, - param_edit_id: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/edit/{edit_id}", - self.base_path, - edit_id = utf8_percent_encode(¶m_edit_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkEditResponse::FoundEdit(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkEditResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkEditResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkEditResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work_history( - &self, - param_ident: String, - param_limit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/{ident}/history", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_limit) = param_limit { - query_string.append_pair("limit", ¶m_limit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetWorkHistoryResponse::FoundEntityHistory(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkHistoryResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkHistoryResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkHistoryResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work_redirects( - &self, - param_ident: String, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/{ident}/redirects", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetWorkRedirectsResponse::FoundEntityRedirects(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRedirectsResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRedirectsResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRedirectsResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work_releases( - &self, - param_ident: String, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/{ident}/releases", - self.base_path, - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::>(body)?; - Ok(GetWorkReleasesResponse::Found(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkReleasesResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkReleasesResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkReleasesResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn get_work_revision( - &self, - param_rev_id: String, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/work/rev/{rev_id}", - self.base_path, - rev_id = utf8_percent_encode(¶m_rev_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRevisionResponse::FoundEntityRevision(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRevisionResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRevisionResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(GetWorkRevisionResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn lookup_container( - &self, - param_issnl: Option, - param_wikidata_qid: Option, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/container/lookup", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_issnl) = param_issnl { - query_string.append_pair("issnl", ¶m_issnl.to_string()); - } - if let Some(param_wikidata_qid) = param_wikidata_qid { - query_string.append_pair("wikidata_qid", ¶m_wikidata_qid.to_string()); - } - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupContainerResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupContainerResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupContainerResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupContainerResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn lookup_creator( - &self, - param_orcid: Option, - param_wikidata_qid: Option, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/creator/lookup", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_orcid) = param_orcid { - query_string.append_pair("orcid", ¶m_orcid.to_string()); - } - if let Some(param_wikidata_qid) = param_wikidata_qid { - query_string.append_pair("wikidata_qid", ¶m_wikidata_qid.to_string()); - } - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupCreatorResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupCreatorResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupCreatorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupCreatorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn lookup_file( - &self, - param_md5: Option, - param_sha1: Option, - param_sha256: Option, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/file/lookup", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_md5) = param_md5 { - query_string.append_pair("md5", ¶m_md5.to_string()); - } - if let Some(param_sha1) = param_sha1 { - query_string.append_pair("sha1", ¶m_sha1.to_string()); - } - if let Some(param_sha256) = param_sha256 { - query_string.append_pair("sha256", ¶m_sha256.to_string()); - } - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupFileResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupFileResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupFileResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupFileResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn lookup_release( - &self, - param_doi: Option, - param_wikidata_qid: Option, - param_isbn13: Option, - param_pmid: Option, - param_pmcid: Option, - param_core: Option, - param_arxiv: Option, - param_jstor: Option, - param_ark: Option, - param_mag: Option, - param_doaj: Option, - param_dblp: Option, - param_oai: Option, - param_expand: Option, - param_hide: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!("{}/v0/release/lookup", self.base_path); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_doi) = param_doi { - query_string.append_pair("doi", ¶m_doi.to_string()); - } - if let Some(param_wikidata_qid) = param_wikidata_qid { - query_string.append_pair("wikidata_qid", ¶m_wikidata_qid.to_string()); - } - if let Some(param_isbn13) = param_isbn13 { - query_string.append_pair("isbn13", ¶m_isbn13.to_string()); - } - if let Some(param_pmid) = param_pmid { - query_string.append_pair("pmid", ¶m_pmid.to_string()); - } - if let Some(param_pmcid) = param_pmcid { - query_string.append_pair("pmcid", ¶m_pmcid.to_string()); - } - if let Some(param_core) = param_core { - query_string.append_pair("core", ¶m_core.to_string()); - } - if let Some(param_arxiv) = param_arxiv { - query_string.append_pair("arxiv", ¶m_arxiv.to_string()); - } - if let Some(param_jstor) = param_jstor { - query_string.append_pair("jstor", ¶m_jstor.to_string()); - } - if let Some(param_ark) = param_ark { - query_string.append_pair("ark", ¶m_ark.to_string()); - } - if let Some(param_mag) = param_mag { - query_string.append_pair("mag", ¶m_mag.to_string()); - } - if let Some(param_doaj) = param_doaj { - query_string.append_pair("doaj", ¶m_doaj.to_string()); - } - if let Some(param_dblp) = param_dblp { - query_string.append_pair("dblp", ¶m_dblp.to_string()); - } - if let Some(param_oai) = param_oai { - query_string.append_pair("oai", ¶m_oai.to_string()); - } - if let Some(param_expand) = param_expand { - query_string.append_pair("expand", ¶m_expand.to_string()); - } - if let Some(param_hide) = param_hide { - query_string.append_pair("hide", ¶m_hide.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupReleaseResponse::FoundEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupReleaseResponse::BadRequest(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupReleaseResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(LookupReleaseResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_container( - &self, - param_editgroup_id: String, - param_ident: String, - param_container_entity: models::ContainerEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/container/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_container_entity) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateContainerResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_creator( - &self, - param_editgroup_id: String, - param_ident: String, - param_creator_entity: models::CreatorEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/creator/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_creator_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateCreatorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_editgroup( - &self, - param_editgroup_id: String, - param_editgroup: models::Editgroup, - param_submit: Option, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(param_submit) = param_submit { - query_string.append_pair("submit", ¶m_submit.to_string()); - } - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_editgroup).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::UpdatedEditgroup(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditgroupResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_editor( - &self, - param_editor_id: String, - param_editor: models::Editor, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editor/{editor_id}", - self.base_path, - editor_id = utf8_percent_encode(¶m_editor_id.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_editor).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::UpdatedEditor(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateEditorResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_file( - &self, - param_editgroup_id: String, - param_ident: String, - param_file_entity: models::FileEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/file/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_file_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFileResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_fileset( - &self, - param_editgroup_id: String, - param_ident: String, - param_fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/fileset/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_fileset_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateFilesetResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_release( - &self, - param_editgroup_id: String, - param_ident: String, - param_release_entity: models::ReleaseEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/release/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_release_entity).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateReleaseResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_webcapture( - &self, - param_editgroup_id: String, - param_ident: String, - param_webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/webcapture/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = serde_json::to_string(¶m_webcapture_entity) - .expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWebcaptureResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } - - async fn update_work( - &self, - param_editgroup_id: String, - param_ident: String, - param_work_entity: models::WorkEntity, - context: &C, - ) -> Result { - let mut client_service = self.client_service.clone(); - let mut uri = format!( - "{}/v0/editgroup/{editgroup_id}/work/{ident}", - self.base_path, - editgroup_id = utf8_percent_encode(¶m_editgroup_id.to_string(), ID_ENCODE_SET), - ident = utf8_percent_encode(¶m_ident.to_string(), ID_ENCODE_SET) - ); - - // Query parameters - let query_string = { - let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - query_string.finish() - }; - if !query_string.is_empty() { - uri += "?"; - uri += &query_string; - } - - let uri = match Uri::from_str(&uri) { - Ok(uri) => uri, - Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))), - }; - - let mut request = match Request::builder() - .method("PUT") - .uri(uri) - .body(Body::empty()) - { - Ok(req) => req, - Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))), - }; - - let body = - serde_json::to_string(¶m_work_entity).expect("impossible to fail to serialize"); - - *request.body_mut() = Body::from(body); - - let header = "application/json"; - request.headers_mut().insert( - CONTENT_TYPE, - match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create header: {} - {}", - header, e - ))) - } - }, - ); - - let header = HeaderValue::from_str( - Has::::get(context) - .0 - .clone() - .to_string() - .as_str(), - ); - request.headers_mut().insert( - HeaderName::from_static("x-span-id"), - match header { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create X-Span ID header value: {}", - e - ))) - } - }, - ); - - if let Some(auth_data) = Has::>::get(context).as_ref() { - // Currently only authentication with Basic and Bearer are supported - match auth_data { - &AuthData::Bearer(ref bearer_header) => { - let auth = swagger::auth::Header(bearer_header.clone()); - let header = match HeaderValue::from_str(&format!("{}", auth)) { - Ok(h) => h, - Err(e) => { - return Err(ApiError(format!( - "Unable to create Authorization header: {}", - e - ))) - } - }; - request - .headers_mut() - .insert(hyper::header::AUTHORIZATION, header); - } - _ => {} - } - } - - let mut response = client_service - .call((request, context.clone())) - .map_err(|e| ApiError(format!("No response received: {}", e))) - .await?; - - match response.status().as_u16() { - 200 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::UpdatedEntity(body)) - } - 400 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::BadRequest(body)) - } - 401 => { - let response_www_authenticate = match response - .headers() - .get(HeaderName::from_static("www_authenticate")) - { - Some(response_www_authenticate) => { - let response_www_authenticate = response_www_authenticate.clone(); - let response_www_authenticate = match TryInto::< - header::IntoHeaderValue, - >::try_into( - response_www_authenticate - ) { - Ok(value) => value, - Err(e) => { - return Err(ApiError(format!("Invalid response header WWW_Authenticate for response 401 - {}", e))); - } - }; - let response_www_authenticate = response_www_authenticate.0; - Some(response_www_authenticate) - } - None => None, - }; - - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::NotAuthorized { - body: body, - www_authenticate: response_www_authenticate, - }) - } - 403 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::Forbidden(body)) - } - 404 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::NotFound(body)) - } - 500 => { - let body = response.into_body(); - let body = body - .to_raw() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .await?; - let body = str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body)?; - Ok(UpdateWorkResponse::GenericError(body)) - } - code => { - let headers = response.headers().clone(); - let body = response.into_body().take(100).to_raw().await; - Err(ApiError(format!( - "Unexpected response code {}:\n{:?}\n\n{}", - code, - headers, - match body { - Ok(body) => match String::from_utf8(body) { - Ok(body) => body, - Err(e) => format!("", e), - }, - Err(e) => format!("", e), - } - ))) - } - } - } -} diff --git a/rust/fatcat-openapi/src/context.rs b/rust/fatcat-openapi/src/context.rs deleted file mode 100644 index d782855..0000000 --- a/rust/fatcat-openapi/src/context.rs +++ /dev/null @@ -1,120 +0,0 @@ -use crate::Api; -use futures::future::BoxFuture; -use hyper::header::HeaderName; -use hyper::{service::Service, Error, Request, Response, StatusCode}; -use std::default::Default; -use std::io; -use std::marker::PhantomData; -use std::task::{Context, Poll}; -use swagger::auth::{AuthData, Authorization, Bearer, Scopes}; -use swagger::{EmptyContext, Has, Pop, Push, XSpanIdString}; -use url::form_urlencoded; - -pub struct MakeAddContext { - inner: T, - marker: PhantomData, -} - -impl MakeAddContext -where - A: Default + Push, - B: Push, Result = C>, - C: Push, Result = D>, -{ - pub fn new(inner: T) -> MakeAddContext { - MakeAddContext { - inner, - marker: PhantomData, - } - } -} - -// Make a service that adds context. -impl Service for MakeAddContext -where - Target: Send, - A: Default + Push + Send, - B: Push, Result = C>, - C: Push, Result = D>, - D: Send + 'static, - T: Service + Send, - T::Future: Send + 'static, -{ - type Error = T::Error; - type Response = AddContext; - type Future = BoxFuture<'static, Result>; - - fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { - self.inner.poll_ready(cx) - } - - fn call(&mut self, target: Target) -> Self::Future { - let service = self.inner.call(target); - - Box::pin(async move { Ok(AddContext::new(service.await?)) }) - } -} - -/// Middleware to add context data from the request -pub struct AddContext -where - A: Default + Push, - B: Push, Result = C>, - C: Push, Result = D>, -{ - inner: T, - marker: PhantomData, -} - -impl AddContext -where - A: Default + Push, - B: Push, Result = C>, - C: Push, Result = D>, -{ - pub fn new(inner: T) -> Self { - AddContext { - inner, - marker: PhantomData, - } - } -} - -impl Service> for AddContext -where - A: Default + Push, - B: Push, Result = C>, - C: Push, Result = D>, - D: Send + 'static, - T: Service<(Request, D)>, -{ - type Error = T::Error; - type Future = T::Future; - type Response = T::Response; - - fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { - self.inner.poll_ready(cx) - } - - fn call(&mut self, request: Request) -> Self::Future { - let context = A::default().push(XSpanIdString::get_or_generate(&request)); - let headers = request.headers(); - - { - use std::ops::Deref; - use swagger::auth::Basic; - if let Some(basic) = swagger::auth::from_headers::(&headers) { - let auth_data = AuthData::Basic(basic); - let context = context.push(Some(auth_data)); - let context = context.push(None::); - - return self.inner.call((request, context)); - } - } - - let context = context.push(None::); - let context = context.push(None::); - - self.inner.call((request, context)) - } -} diff --git a/rust/fatcat-openapi/src/header.rs b/rust/fatcat-openapi/src/header.rs deleted file mode 100644 index 7589ab0..0000000 --- a/rust/fatcat-openapi/src/header.rs +++ /dev/null @@ -1,197 +0,0 @@ -use chrono::{DateTime, Utc}; -use hyper::header::HeaderValue; -use std::convert::TryFrom; -use std::fmt; -use std::ops::Deref; - -/// A struct to allow homogeneous conversion into a HeaderValue. We can't -/// implement the From/Into trait on HeaderValue because we don't own -/// either of the types. -#[derive(Debug, Clone)] -pub(crate) struct IntoHeaderValue(pub T); - -// Generic implementations - -impl Deref for IntoHeaderValue { - type Target = T; - - fn deref(&self) -> &T { - &self.0 - } -} - -// Derive for each TryFrom in hyper::header::HeaderValue - -macro_rules! ihv_generate { - ($t:ident) => { - impl TryFrom for IntoHeaderValue<$t> { - type Error = String; - - fn try_from(hdr_value: HeaderValue) -> Result { - match hdr_value.to_str() { - Ok(hdr_value) => match hdr_value.parse::<$t>() { - Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), - Err(e) => Err(format!( - "Unable to parse {} as a string: {}", - stringify!($t), - e - )), - }, - Err(e) => Err(format!( - "Unable to parse header {:?} as a string - {}", - hdr_value, e - )), - } - } - } - - impl TryFrom> for HeaderValue { - type Error = String; - - fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { - Ok(hdr_value.0.into()) - } - } - }; -} - -ihv_generate!(u64); -ihv_generate!(i64); -ihv_generate!(i16); -ihv_generate!(u16); -ihv_generate!(u32); -ihv_generate!(usize); -ihv_generate!(isize); -ihv_generate!(i32); - -// Custom derivations - -// Vec - -impl TryFrom for IntoHeaderValue> { - type Error = String; - - fn try_from(hdr_value: HeaderValue) -> Result { - match hdr_value.to_str() { - Ok(hdr_value) => Ok(IntoHeaderValue( - hdr_value - .split(',') - .filter_map(|x| match x.trim() { - "" => None, - y => Some(y.to_string()), - }) - .collect(), - )), - Err(e) => Err(format!( - "Unable to parse header: {:?} as a string - {}", - hdr_value, e - )), - } - } -} - -impl TryFrom>> for HeaderValue { - type Error = String; - - fn try_from(hdr_value: IntoHeaderValue>) -> Result { - match HeaderValue::from_str(&hdr_value.0.join(", ")) { - Ok(hdr_value) => Ok(hdr_value), - Err(e) => Err(format!( - "Unable to convert {:?} into a header - {}", - hdr_value, e - )), - } - } -} - -// String - -impl TryFrom for IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: HeaderValue) -> Result { - match hdr_value.to_str() { - Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), - Err(e) => Err(format!("Unable to convert header {:?} to {}", hdr_value, e)), - } - } -} - -impl TryFrom> for HeaderValue { - type Error = String; - - fn try_from(hdr_value: IntoHeaderValue) -> Result { - match HeaderValue::from_str(&hdr_value.0) { - Ok(hdr_value) => Ok(hdr_value), - Err(e) => Err(format!( - "Unable to convert {:?} from a header {}", - hdr_value, e - )), - } - } -} - -// bool -impl TryFrom for IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: HeaderValue) -> Result { - match hdr_value.to_str() { - Ok(hdr_value) => match hdr_value.parse() { - Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), - Err(e) => Err(format!("Unable to parse bool from {} - {}", hdr_value, e)), - }, - Err(e) => Err(format!( - "Unable to convert {:?} from a header {}", - hdr_value, e - )), - } - } -} - -impl TryFrom> for HeaderValue { - type Error = String; - - fn try_from(hdr_value: IntoHeaderValue) -> Result { - match HeaderValue::from_str(&hdr_value.0.to_string()) { - Ok(hdr_value) => Ok(hdr_value), - Err(e) => Err(format!( - "Unable to convert: {:?} into a header: {}", - hdr_value, e - )), - } - } -} - -// DateTime - -impl TryFrom for IntoHeaderValue> { - type Error = String; - - fn try_from(hdr_value: HeaderValue) -> Result { - match hdr_value.to_str() { - Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { - Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), - Err(e) => Err(format!("Unable to parse: {} as date - {}", hdr_value, e)), - }, - Err(e) => Err(format!( - "Unable to convert header {:?} to string {}", - hdr_value, e - )), - } - } -} - -impl TryFrom>> for HeaderValue { - type Error = String; - - fn try_from(hdr_value: IntoHeaderValue>) -> Result { - match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { - Ok(hdr_value) => Ok(hdr_value), - Err(e) => Err(format!( - "Unable to convert {:?} to a header: {}", - hdr_value, e - )), - } - } -} diff --git a/rust/fatcat-openapi/src/lib.rs b/rust/fatcat-openapi/src/lib.rs deleted file mode 100644 index ba49f27..0000000 --- a/rust/fatcat-openapi/src/lib.rs +++ /dev/null @@ -1,3844 +0,0 @@ -#![allow( - missing_docs, - trivial_casts, - unused_variables, - unused_mut, - unused_imports, - unused_extern_crates, - non_camel_case_types -)] - -use async_trait::async_trait; -use futures::Stream; -use std::error::Error; -use std::task::{Context, Poll}; -use swagger::{ApiError, ContextWrapper}; - -type ServiceError = Box; - -pub const BASE_PATH: &'static str = "/v0"; -pub const API_VERSION: &'static str = "0.3.3"; - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum AcceptEditgroupResponse { - /// Merged Successfully - MergedSuccessfully(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Edit Conflict - EditConflict(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum AuthCheckResponse { - /// Success - Success(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum AuthOidcResponse { - /// Found - Found(models::AuthOidcResult), - /// Created - Created(models::AuthOidcResult), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Conflict - Conflict(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateAuthTokenResponse { - /// Success - Success(models::AuthTokenResult), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateContainerResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateContainerAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateCreatorResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateCreatorAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateEditgroupResponse { - /// Successfully Created - SuccessfullyCreated(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateEditgroupAnnotationResponse { - /// Created - Created(models::EditgroupAnnotation), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateFileResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateFileAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateFilesetResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateFilesetAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateReleaseResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateReleaseAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateWebcaptureResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateWebcaptureAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateWorkResponse { - /// Created Entity - CreatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum CreateWorkAutoBatchResponse { - /// Created Editgroup - CreatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteContainerResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteContainerEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteCreatorResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteCreatorEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteFileResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteFileEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteFilesetResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteFilesetEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteReleaseResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteReleaseEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteWebcaptureResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteWebcaptureEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteWorkResponse { - /// Deleted Entity - DeletedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum DeleteWorkEditResponse { - /// Deleted Edit - DeletedEdit(models::Success), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetChangelogResponse { - /// Success - Success(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetChangelogEntryResponse { - /// Found Changelog Entry - FoundChangelogEntry(models::ChangelogEntry), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetContainerResponse { - /// Found Entity - FoundEntity(models::ContainerEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetContainerEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetContainerHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetContainerRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetContainerRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::ContainerEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorResponse { - /// Found Entity - FoundEntity(models::CreatorEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorReleasesResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetCreatorRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::CreatorEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditgroupResponse { - /// Found - Found(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditgroupAnnotationsResponse { - /// Success - Success(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditgroupsReviewableResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditorResponse { - /// Found - Found(models::Editor), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditorAnnotationsResponse { - /// Success - Success(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetEditorEditgroupsResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFileResponse { - /// Found Entity - FoundEntity(models::FileEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFileEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFileHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFileRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFileRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::FileEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFilesetResponse { - /// Found Entity - FoundEntity(models::FilesetEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFilesetEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFilesetHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFilesetRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetFilesetRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::FilesetEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseResponse { - /// Found Entity - FoundEntity(models::ReleaseEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseFilesResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseFilesetsResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::ReleaseEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetReleaseWebcapturesResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWebcaptureResponse { - /// Found Entity - FoundEntity(models::WebcaptureEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWebcaptureEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWebcaptureHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWebcaptureRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWebcaptureRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::WebcaptureEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkResponse { - /// Found Entity - FoundEntity(models::WorkEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkEditResponse { - /// Found Edit - FoundEdit(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkHistoryResponse { - /// Found Entity History - FoundEntityHistory(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkRedirectsResponse { - /// Found Entity Redirects - FoundEntityRedirects(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkReleasesResponse { - /// Found - Found(Vec), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum GetWorkRevisionResponse { - /// Found Entity Revision - FoundEntityRevision(models::WorkEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum LookupContainerResponse { - /// Found Entity - FoundEntity(models::ContainerEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum LookupCreatorResponse { - /// Found Entity - FoundEntity(models::CreatorEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum LookupFileResponse { - /// Found Entity - FoundEntity(models::FileEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum LookupReleaseResponse { - /// Found Entity - FoundEntity(models::ReleaseEntity), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateContainerResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateCreatorResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateEditgroupResponse { - /// Updated Editgroup - UpdatedEditgroup(models::Editgroup), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateEditorResponse { - /// Updated Editor - UpdatedEditor(models::Editor), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateFileResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateFilesetResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateReleaseResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateWebcaptureResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -#[derive(Debug, PartialEq)] -#[must_use] -pub enum UpdateWorkResponse { - /// Updated Entity - UpdatedEntity(models::EntityEdit), - /// Bad Request - BadRequest(models::ErrorResponse), - /// Not Authorized - NotAuthorized { - body: models::ErrorResponse, - www_authenticate: Option, - }, - /// Forbidden - Forbidden(models::ErrorResponse), - /// Not Found - NotFound(models::ErrorResponse), - /// Generic Error - GenericError(models::ErrorResponse), -} - -/// API -#[async_trait] -pub trait Api { - fn poll_ready( - &self, - _cx: &mut Context, - ) -> Poll>> { - Poll::Ready(Ok(())) - } - - async fn accept_editgroup( - &self, - editgroup_id: String, - context: &C, - ) -> Result; - - async fn auth_check( - &self, - role: Option, - context: &C, - ) -> Result; - - async fn auth_oidc( - &self, - auth_oidc: models::AuthOidc, - context: &C, - ) -> Result; - - async fn create_auth_token( - &self, - editor_id: String, - duration_seconds: Option, - context: &C, - ) -> Result; - - async fn create_container( - &self, - editgroup_id: String, - container_entity: models::ContainerEntity, - context: &C, - ) -> Result; - - async fn create_container_auto_batch( - &self, - container_auto_batch: models::ContainerAutoBatch, - context: &C, - ) -> Result; - - async fn create_creator( - &self, - editgroup_id: String, - creator_entity: models::CreatorEntity, - context: &C, - ) -> Result; - - async fn create_creator_auto_batch( - &self, - creator_auto_batch: models::CreatorAutoBatch, - context: &C, - ) -> Result; - - async fn create_editgroup( - &self, - editgroup: models::Editgroup, - context: &C, - ) -> Result; - - async fn create_editgroup_annotation( - &self, - editgroup_id: String, - editgroup_annotation: models::EditgroupAnnotation, - context: &C, - ) -> Result; - - async fn create_file( - &self, - editgroup_id: String, - file_entity: models::FileEntity, - context: &C, - ) -> Result; - - async fn create_file_auto_batch( - &self, - file_auto_batch: models::FileAutoBatch, - context: &C, - ) -> Result; - - async fn create_fileset( - &self, - editgroup_id: String, - fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result; - - async fn create_fileset_auto_batch( - &self, - fileset_auto_batch: models::FilesetAutoBatch, - context: &C, - ) -> Result; - - async fn create_release( - &self, - editgroup_id: String, - release_entity: models::ReleaseEntity, - context: &C, - ) -> Result; - - async fn create_release_auto_batch( - &self, - release_auto_batch: models::ReleaseAutoBatch, - context: &C, - ) -> Result; - - async fn create_webcapture( - &self, - editgroup_id: String, - webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result; - - async fn create_webcapture_auto_batch( - &self, - webcapture_auto_batch: models::WebcaptureAutoBatch, - context: &C, - ) -> Result; - - async fn create_work( - &self, - editgroup_id: String, - work_entity: models::WorkEntity, - context: &C, - ) -> Result; - - async fn create_work_auto_batch( - &self, - work_auto_batch: models::WorkAutoBatch, - context: &C, - ) -> Result; - - async fn delete_container( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_container_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_creator( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_creator_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_file( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_file_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_fileset( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_fileset_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_release( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_release_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_webcapture( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_webcapture_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn delete_work( - &self, - editgroup_id: String, - ident: String, - context: &C, - ) -> Result; - - async fn delete_work_edit( - &self, - editgroup_id: String, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_changelog( - &self, - limit: Option, - context: &C, - ) -> Result; - - async fn get_changelog_entry( - &self, - index: i64, - context: &C, - ) -> Result; - - async fn get_container( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_container_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_container_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_container_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_container_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_creator( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_creator_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_creator_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_creator_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_creator_releases( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result; - - async fn get_creator_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_editgroup( - &self, - editgroup_id: String, - context: &C, - ) -> Result; - - async fn get_editgroup_annotations( - &self, - editgroup_id: String, - expand: Option, - context: &C, - ) -> Result; - - async fn get_editgroups_reviewable( - &self, - expand: Option, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result; - - async fn get_editor( - &self, - editor_id: String, - context: &C, - ) -> Result; - - async fn get_editor_annotations( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result; - - async fn get_editor_editgroups( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - context: &C, - ) -> Result; - - async fn get_file( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_file_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_file_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_file_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_file_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_fileset( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_fileset_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_fileset_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_fileset_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_fileset_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_release( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_release_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_release_files( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result; - - async fn get_release_filesets( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result; - - async fn get_release_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_release_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_release_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_release_webcaptures( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result; - - async fn get_webcapture( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_webcapture_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_webcapture_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_webcapture_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_webcapture_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_work( - &self, - ident: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn get_work_edit( - &self, - edit_id: String, - context: &C, - ) -> Result; - - async fn get_work_history( - &self, - ident: String, - limit: Option, - context: &C, - ) -> Result; - - async fn get_work_redirects( - &self, - ident: String, - context: &C, - ) -> Result; - - async fn get_work_releases( - &self, - ident: String, - hide: Option, - context: &C, - ) -> Result; - - async fn get_work_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn lookup_container( - &self, - issnl: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn lookup_creator( - &self, - orcid: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn lookup_file( - &self, - md5: Option, - sha1: Option, - sha256: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn lookup_release( - &self, - doi: Option, - wikidata_qid: Option, - isbn13: Option, - pmid: Option, - pmcid: Option, - core: Option, - arxiv: Option, - jstor: Option, - ark: Option, - mag: Option, - doaj: Option, - dblp: Option, - oai: Option, - expand: Option, - hide: Option, - context: &C, - ) -> Result; - - async fn update_container( - &self, - editgroup_id: String, - ident: String, - container_entity: models::ContainerEntity, - context: &C, - ) -> Result; - - async fn update_creator( - &self, - editgroup_id: String, - ident: String, - creator_entity: models::CreatorEntity, - context: &C, - ) -> Result; - - async fn update_editgroup( - &self, - editgroup_id: String, - editgroup: models::Editgroup, - submit: Option, - context: &C, - ) -> Result; - - async fn update_editor( - &self, - editor_id: String, - editor: models::Editor, - context: &C, - ) -> Result; - - async fn update_file( - &self, - editgroup_id: String, - ident: String, - file_entity: models::FileEntity, - context: &C, - ) -> Result; - - async fn update_fileset( - &self, - editgroup_id: String, - ident: String, - fileset_entity: models::FilesetEntity, - context: &C, - ) -> Result; - - async fn update_release( - &self, - editgroup_id: String, - ident: String, - release_entity: models::ReleaseEntity, - context: &C, - ) -> Result; - - async fn update_webcapture( - &self, - editgroup_id: String, - ident: String, - webcapture_entity: models::WebcaptureEntity, - context: &C, - ) -> Result; - - async fn update_work( - &self, - editgroup_id: String, - ident: String, - work_entity: models::WorkEntity, - context: &C, - ) -> Result; -} - -/// API where `Context` isn't passed on every API call -#[async_trait] -pub trait ApiNoContext { - fn poll_ready( - &self, - _cx: &mut Context, - ) -> Poll>>; - - fn context(&self) -> &C; - - async fn accept_editgroup( - &self, - editgroup_id: String, - ) -> Result; - - async fn auth_check(&self, role: Option) -> Result; - - async fn auth_oidc(&self, auth_oidc: models::AuthOidc) -> Result; - - async fn create_auth_token( - &self, - editor_id: String, - duration_seconds: Option, - ) -> Result; - - async fn create_container( - &self, - editgroup_id: String, - container_entity: models::ContainerEntity, - ) -> Result; - - async fn create_container_auto_batch( - &self, - container_auto_batch: models::ContainerAutoBatch, - ) -> Result; - - async fn create_creator( - &self, - editgroup_id: String, - creator_entity: models::CreatorEntity, - ) -> Result; - - async fn create_creator_auto_batch( - &self, - creator_auto_batch: models::CreatorAutoBatch, - ) -> Result; - - async fn create_editgroup( - &self, - editgroup: models::Editgroup, - ) -> Result; - - async fn create_editgroup_annotation( - &self, - editgroup_id: String, - editgroup_annotation: models::EditgroupAnnotation, - ) -> Result; - - async fn create_file( - &self, - editgroup_id: String, - file_entity: models::FileEntity, - ) -> Result; - - async fn create_file_auto_batch( - &self, - file_auto_batch: models::FileAutoBatch, - ) -> Result; - - async fn create_fileset( - &self, - editgroup_id: String, - fileset_entity: models::FilesetEntity, - ) -> Result; - - async fn create_fileset_auto_batch( - &self, - fileset_auto_batch: models::FilesetAutoBatch, - ) -> Result; - - async fn create_release( - &self, - editgroup_id: String, - release_entity: models::ReleaseEntity, - ) -> Result; - - async fn create_release_auto_batch( - &self, - release_auto_batch: models::ReleaseAutoBatch, - ) -> Result; - - async fn create_webcapture( - &self, - editgroup_id: String, - webcapture_entity: models::WebcaptureEntity, - ) -> Result; - - async fn create_webcapture_auto_batch( - &self, - webcapture_auto_batch: models::WebcaptureAutoBatch, - ) -> Result; - - async fn create_work( - &self, - editgroup_id: String, - work_entity: models::WorkEntity, - ) -> Result; - - async fn create_work_auto_batch( - &self, - work_auto_batch: models::WorkAutoBatch, - ) -> Result; - - async fn delete_container( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_container_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_creator( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_creator_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_file( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_file_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_fileset( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_fileset_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_release( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_release_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_webcapture( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_webcapture_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn delete_work( - &self, - editgroup_id: String, - ident: String, - ) -> Result; - - async fn delete_work_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result; - - async fn get_changelog(&self, limit: Option) -> Result; - - async fn get_changelog_entry(&self, index: i64) -> Result; - - async fn get_container( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_container_edit( - &self, - edit_id: String, - ) -> Result; - - async fn get_container_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_container_redirects( - &self, - ident: String, - ) -> Result; - - async fn get_container_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_creator( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_creator_edit(&self, edit_id: String) -> Result; - - async fn get_creator_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_creator_redirects( - &self, - ident: String, - ) -> Result; - - async fn get_creator_releases( - &self, - ident: String, - hide: Option, - ) -> Result; - - async fn get_creator_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_editgroup(&self, editgroup_id: String) -> Result; - - async fn get_editgroup_annotations( - &self, - editgroup_id: String, - expand: Option, - ) -> Result; - - async fn get_editgroups_reviewable( - &self, - expand: Option, - limit: Option, - before: Option>, - since: Option>, - ) -> Result; - - async fn get_editor(&self, editor_id: String) -> Result; - - async fn get_editor_annotations( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - ) -> Result; - - async fn get_editor_editgroups( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - ) -> Result; - - async fn get_file( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_file_edit(&self, edit_id: String) -> Result; - - async fn get_file_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_file_redirects(&self, ident: String) - -> Result; - - async fn get_file_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_fileset( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_fileset_edit(&self, edit_id: String) -> Result; - - async fn get_fileset_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_fileset_redirects( - &self, - ident: String, - ) -> Result; - - async fn get_fileset_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_release( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_release_edit(&self, edit_id: String) -> Result; - - async fn get_release_files( - &self, - ident: String, - hide: Option, - ) -> Result; - - async fn get_release_filesets( - &self, - ident: String, - hide: Option, - ) -> Result; - - async fn get_release_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_release_redirects( - &self, - ident: String, - ) -> Result; - - async fn get_release_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_release_webcaptures( - &self, - ident: String, - hide: Option, - ) -> Result; - - async fn get_webcapture( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_webcapture_edit( - &self, - edit_id: String, - ) -> Result; - - async fn get_webcapture_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_webcapture_redirects( - &self, - ident: String, - ) -> Result; - - async fn get_webcapture_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_work( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn get_work_edit(&self, edit_id: String) -> Result; - - async fn get_work_history( - &self, - ident: String, - limit: Option, - ) -> Result; - - async fn get_work_redirects(&self, ident: String) - -> Result; - - async fn get_work_releases( - &self, - ident: String, - hide: Option, - ) -> Result; - - async fn get_work_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result; - - async fn lookup_container( - &self, - issnl: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - ) -> Result; - - async fn lookup_creator( - &self, - orcid: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - ) -> Result; - - async fn lookup_file( - &self, - md5: Option, - sha1: Option, - sha256: Option, - expand: Option, - hide: Option, - ) -> Result; - - async fn lookup_release( - &self, - doi: Option, - wikidata_qid: Option, - isbn13: Option, - pmid: Option, - pmcid: Option, - core: Option, - arxiv: Option, - jstor: Option, - ark: Option, - mag: Option, - doaj: Option, - dblp: Option, - oai: Option, - expand: Option, - hide: Option, - ) -> Result; - - async fn update_container( - &self, - editgroup_id: String, - ident: String, - container_entity: models::ContainerEntity, - ) -> Result; - - async fn update_creator( - &self, - editgroup_id: String, - ident: String, - creator_entity: models::CreatorEntity, - ) -> Result; - - async fn update_editgroup( - &self, - editgroup_id: String, - editgroup: models::Editgroup, - submit: Option, - ) -> Result; - - async fn update_editor( - &self, - editor_id: String, - editor: models::Editor, - ) -> Result; - - async fn update_file( - &self, - editgroup_id: String, - ident: String, - file_entity: models::FileEntity, - ) -> Result; - - async fn update_fileset( - &self, - editgroup_id: String, - ident: String, - fileset_entity: models::FilesetEntity, - ) -> Result; - - async fn update_release( - &self, - editgroup_id: String, - ident: String, - release_entity: models::ReleaseEntity, - ) -> Result; - - async fn update_webcapture( - &self, - editgroup_id: String, - ident: String, - webcapture_entity: models::WebcaptureEntity, - ) -> Result; - - async fn update_work( - &self, - editgroup_id: String, - ident: String, - work_entity: models::WorkEntity, - ) -> Result; -} - -/// Trait to extend an API to make it easy to bind it to a context. -pub trait ContextWrapperExt -where - Self: Sized, -{ - /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; -} - -impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { - fn with_context(self: T, context: C) -> ContextWrapper { - ContextWrapper::::new(self, context) - } -} - -#[async_trait] -impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for ContextWrapper { - fn poll_ready(&self, cx: &mut Context) -> Poll> { - self.api().poll_ready(cx) - } - - fn context(&self) -> &C { - ContextWrapper::context(self) - } - - async fn accept_editgroup( - &self, - editgroup_id: String, - ) -> Result { - let context = self.context().clone(); - self.api().accept_editgroup(editgroup_id, &context).await - } - - async fn auth_check(&self, role: Option) -> Result { - let context = self.context().clone(); - self.api().auth_check(role, &context).await - } - - async fn auth_oidc(&self, auth_oidc: models::AuthOidc) -> Result { - let context = self.context().clone(); - self.api().auth_oidc(auth_oidc, &context).await - } - - async fn create_auth_token( - &self, - editor_id: String, - duration_seconds: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_auth_token(editor_id, duration_seconds, &context) - .await - } - - async fn create_container( - &self, - editgroup_id: String, - container_entity: models::ContainerEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_container(editgroup_id, container_entity, &context) - .await - } - - async fn create_container_auto_batch( - &self, - container_auto_batch: models::ContainerAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_container_auto_batch(container_auto_batch, &context) - .await - } - - async fn create_creator( - &self, - editgroup_id: String, - creator_entity: models::CreatorEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_creator(editgroup_id, creator_entity, &context) - .await - } - - async fn create_creator_auto_batch( - &self, - creator_auto_batch: models::CreatorAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_creator_auto_batch(creator_auto_batch, &context) - .await - } - - async fn create_editgroup( - &self, - editgroup: models::Editgroup, - ) -> Result { - let context = self.context().clone(); - self.api().create_editgroup(editgroup, &context).await - } - - async fn create_editgroup_annotation( - &self, - editgroup_id: String, - editgroup_annotation: models::EditgroupAnnotation, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_editgroup_annotation(editgroup_id, editgroup_annotation, &context) - .await - } - - async fn create_file( - &self, - editgroup_id: String, - file_entity: models::FileEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_file(editgroup_id, file_entity, &context) - .await - } - - async fn create_file_auto_batch( - &self, - file_auto_batch: models::FileAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_file_auto_batch(file_auto_batch, &context) - .await - } - - async fn create_fileset( - &self, - editgroup_id: String, - fileset_entity: models::FilesetEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_fileset(editgroup_id, fileset_entity, &context) - .await - } - - async fn create_fileset_auto_batch( - &self, - fileset_auto_batch: models::FilesetAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_fileset_auto_batch(fileset_auto_batch, &context) - .await - } - - async fn create_release( - &self, - editgroup_id: String, - release_entity: models::ReleaseEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_release(editgroup_id, release_entity, &context) - .await - } - - async fn create_release_auto_batch( - &self, - release_auto_batch: models::ReleaseAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_release_auto_batch(release_auto_batch, &context) - .await - } - - async fn create_webcapture( - &self, - editgroup_id: String, - webcapture_entity: models::WebcaptureEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_webcapture(editgroup_id, webcapture_entity, &context) - .await - } - - async fn create_webcapture_auto_batch( - &self, - webcapture_auto_batch: models::WebcaptureAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_webcapture_auto_batch(webcapture_auto_batch, &context) - .await - } - - async fn create_work( - &self, - editgroup_id: String, - work_entity: models::WorkEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_work(editgroup_id, work_entity, &context) - .await - } - - async fn create_work_auto_batch( - &self, - work_auto_batch: models::WorkAutoBatch, - ) -> Result { - let context = self.context().clone(); - self.api() - .create_work_auto_batch(work_auto_batch, &context) - .await - } - - async fn delete_container( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_container(editgroup_id, ident, &context) - .await - } - - async fn delete_container_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_container_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_creator( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_creator(editgroup_id, ident, &context) - .await - } - - async fn delete_creator_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_creator_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_file( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().delete_file(editgroup_id, ident, &context).await - } - - async fn delete_file_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_file_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_fileset( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_fileset(editgroup_id, ident, &context) - .await - } - - async fn delete_fileset_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_fileset_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_release( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_release(editgroup_id, ident, &context) - .await - } - - async fn delete_release_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_release_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_webcapture( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_webcapture(editgroup_id, ident, &context) - .await - } - - async fn delete_webcapture_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_webcapture_edit(editgroup_id, edit_id, &context) - .await - } - - async fn delete_work( - &self, - editgroup_id: String, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().delete_work(editgroup_id, ident, &context).await - } - - async fn delete_work_edit( - &self, - editgroup_id: String, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api() - .delete_work_edit(editgroup_id, edit_id, &context) - .await - } - - async fn get_changelog(&self, limit: Option) -> Result { - let context = self.context().clone(); - self.api().get_changelog(limit, &context).await - } - - async fn get_changelog_entry(&self, index: i64) -> Result { - let context = self.context().clone(); - self.api().get_changelog_entry(index, &context).await - } - - async fn get_container( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_container(ident, expand, hide, &context) - .await - } - - async fn get_container_edit( - &self, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_container_edit(edit_id, &context).await - } - - async fn get_container_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_container_history(ident, limit, &context) - .await - } - - async fn get_container_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_container_redirects(ident, &context).await - } - - async fn get_container_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_container_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_creator( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_creator(ident, expand, hide, &context).await - } - - async fn get_creator_edit(&self, edit_id: String) -> Result { - let context = self.context().clone(); - self.api().get_creator_edit(edit_id, &context).await - } - - async fn get_creator_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_creator_history(ident, limit, &context).await - } - - async fn get_creator_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_creator_redirects(ident, &context).await - } - - async fn get_creator_releases( - &self, - ident: String, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_creator_releases(ident, hide, &context).await - } - - async fn get_creator_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_creator_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_editgroup(&self, editgroup_id: String) -> Result { - let context = self.context().clone(); - self.api().get_editgroup(editgroup_id, &context).await - } - - async fn get_editgroup_annotations( - &self, - editgroup_id: String, - expand: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_editgroup_annotations(editgroup_id, expand, &context) - .await - } - - async fn get_editgroups_reviewable( - &self, - expand: Option, - limit: Option, - before: Option>, - since: Option>, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_editgroups_reviewable(expand, limit, before, since, &context) - .await - } - - async fn get_editor(&self, editor_id: String) -> Result { - let context = self.context().clone(); - self.api().get_editor(editor_id, &context).await - } - - async fn get_editor_annotations( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_editor_annotations(editor_id, limit, before, since, &context) - .await - } - - async fn get_editor_editgroups( - &self, - editor_id: String, - limit: Option, - before: Option>, - since: Option>, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_editor_editgroups(editor_id, limit, before, since, &context) - .await - } - - async fn get_file( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_file(ident, expand, hide, &context).await - } - - async fn get_file_edit(&self, edit_id: String) -> Result { - let context = self.context().clone(); - self.api().get_file_edit(edit_id, &context).await - } - - async fn get_file_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_file_history(ident, limit, &context).await - } - - async fn get_file_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_file_redirects(ident, &context).await - } - - async fn get_file_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_file_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_fileset( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_fileset(ident, expand, hide, &context).await - } - - async fn get_fileset_edit(&self, edit_id: String) -> Result { - let context = self.context().clone(); - self.api().get_fileset_edit(edit_id, &context).await - } - - async fn get_fileset_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_fileset_history(ident, limit, &context).await - } - - async fn get_fileset_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_fileset_redirects(ident, &context).await - } - - async fn get_fileset_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_fileset_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_release( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_release(ident, expand, hide, &context).await - } - - async fn get_release_edit(&self, edit_id: String) -> Result { - let context = self.context().clone(); - self.api().get_release_edit(edit_id, &context).await - } - - async fn get_release_files( - &self, - ident: String, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_release_files(ident, hide, &context).await - } - - async fn get_release_filesets( - &self, - ident: String, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_release_filesets(ident, hide, &context).await - } - - async fn get_release_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_release_history(ident, limit, &context).await - } - - async fn get_release_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_release_redirects(ident, &context).await - } - - async fn get_release_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_release_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_release_webcaptures( - &self, - ident: String, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_release_webcaptures(ident, hide, &context) - .await - } - - async fn get_webcapture( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_webcapture(ident, expand, hide, &context) - .await - } - - async fn get_webcapture_edit( - &self, - edit_id: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_webcapture_edit(edit_id, &context).await - } - - async fn get_webcapture_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_webcapture_history(ident, limit, &context) - .await - } - - async fn get_webcapture_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_webcapture_redirects(ident, &context).await - } - - async fn get_webcapture_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_webcapture_revision(rev_id, expand, hide, &context) - .await - } - - async fn get_work( - &self, - ident: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_work(ident, expand, hide, &context).await - } - - async fn get_work_edit(&self, edit_id: String) -> Result { - let context = self.context().clone(); - self.api().get_work_edit(edit_id, &context).await - } - - async fn get_work_history( - &self, - ident: String, - limit: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_work_history(ident, limit, &context).await - } - - async fn get_work_redirects( - &self, - ident: String, - ) -> Result { - let context = self.context().clone(); - self.api().get_work_redirects(ident, &context).await - } - - async fn get_work_releases( - &self, - ident: String, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api().get_work_releases(ident, hide, &context).await - } - - async fn get_work_revision( - &self, - rev_id: String, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .get_work_revision(rev_id, expand, hide, &context) - .await - } - - async fn lookup_container( - &self, - issnl: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .lookup_container(issnl, wikidata_qid, expand, hide, &context) - .await - } - - async fn lookup_creator( - &self, - orcid: Option, - wikidata_qid: Option, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .lookup_creator(orcid, wikidata_qid, expand, hide, &context) - .await - } - - async fn lookup_file( - &self, - md5: Option, - sha1: Option, - sha256: Option, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .lookup_file(md5, sha1, sha256, expand, hide, &context) - .await - } - - async fn lookup_release( - &self, - doi: Option, - wikidata_qid: Option, - isbn13: Option, - pmid: Option, - pmcid: Option, - core: Option, - arxiv: Option, - jstor: Option, - ark: Option, - mag: Option, - doaj: Option, - dblp: Option, - oai: Option, - expand: Option, - hide: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .lookup_release( - doi, - wikidata_qid, - isbn13, - pmid, - pmcid, - core, - arxiv, - jstor, - ark, - mag, - doaj, - dblp, - oai, - expand, - hide, - &context, - ) - .await - } - - async fn update_container( - &self, - editgroup_id: String, - ident: String, - container_entity: models::ContainerEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_container(editgroup_id, ident, container_entity, &context) - .await - } - - async fn update_creator( - &self, - editgroup_id: String, - ident: String, - creator_entity: models::CreatorEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_creator(editgroup_id, ident, creator_entity, &context) - .await - } - - async fn update_editgroup( - &self, - editgroup_id: String, - editgroup: models::Editgroup, - submit: Option, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_editgroup(editgroup_id, editgroup, submit, &context) - .await - } - - async fn update_editor( - &self, - editor_id: String, - editor: models::Editor, - ) -> Result { - let context = self.context().clone(); - self.api().update_editor(editor_id, editor, &context).await - } - - async fn update_file( - &self, - editgroup_id: String, - ident: String, - file_entity: models::FileEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_file(editgroup_id, ident, file_entity, &context) - .await - } - - async fn update_fileset( - &self, - editgroup_id: String, - ident: String, - fileset_entity: models::FilesetEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_fileset(editgroup_id, ident, fileset_entity, &context) - .await - } - - async fn update_release( - &self, - editgroup_id: String, - ident: String, - release_entity: models::ReleaseEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_release(editgroup_id, ident, release_entity, &context) - .await - } - - async fn update_webcapture( - &self, - editgroup_id: String, - ident: String, - webcapture_entity: models::WebcaptureEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_webcapture(editgroup_id, ident, webcapture_entity, &context) - .await - } - - async fn update_work( - &self, - editgroup_id: String, - ident: String, - work_entity: models::WorkEntity, - ) -> Result { - let context = self.context().clone(); - self.api() - .update_work(editgroup_id, ident, work_entity, &context) - .await - } -} - -#[cfg(feature = "client")] -pub mod client; - -// Re-export Client as a top-level name -#[cfg(feature = "client")] -pub use client::Client; - -#[cfg(feature = "server")] -pub mod server; - -// Re-export router() as a top-level name -#[cfg(feature = "server")] -pub use self::server::Service; - -#[cfg(feature = "server")] -pub mod context; - -pub mod models; - -#[cfg(any(feature = "client", feature = "server"))] -pub(crate) mod header; diff --git a/rust/fatcat-openapi/src/models.rs b/rust/fatcat-openapi/src/models.rs deleted file mode 100644 index d642c62..0000000 --- a/rust/fatcat-openapi/src/models.rs +++ /dev/null @@ -1,7621 +0,0 @@ -#![allow(unused_qualifications)] - -#[cfg(any(feature = "client", feature = "server"))] -use crate::header; -use crate::models; - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for AuthOidc - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into AuthOidc - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct AuthOidc { - /// Fatcat-specific short name (slug) for remote service being used for authentication. - #[serde(rename = "provider")] - pub provider: String, - - /// `SUB` from OIDC protocol. Usually a URL. - #[serde(rename = "sub")] - pub sub: String, - - /// `ISS` from OIDC protocol. Usually a stable account username, number, or identifier. - #[serde(rename = "iss")] - pub iss: String, - - /// What it sounds like; returned by OIDC, and used as a hint when creating new editor accounts. Fatcat usernames are usually this string with the `provider` slug as a suffix, though some munging may occur. - #[serde(rename = "preferred_username")] - pub preferred_username: String, -} - -impl AuthOidc { - pub fn new(provider: String, sub: String, iss: String, preferred_username: String) -> AuthOidc { - AuthOidc { - provider: provider, - sub: sub, - iss: iss, - preferred_username: preferred_username, - } - } -} - -/// Converts the AuthOidc value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for AuthOidc { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("provider".to_string()); - params.push(self.provider.to_string()); - - params.push("sub".to_string()); - params.push(self.sub.to_string()); - - params.push("iss".to_string()); - params.push(self.iss.to_string()); - - params.push("preferred_username".to_string()); - params.push(self.preferred_username.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a AuthOidc value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for AuthOidc { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub provider: Vec, - pub sub: Vec, - pub iss: Vec, - pub preferred_username: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing AuthOidc".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "provider" => intermediate_rep - .provider - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sub" => intermediate_rep - .sub - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "iss" => intermediate_rep - .iss - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "preferred_username" => intermediate_rep - .preferred_username - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing AuthOidc".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(AuthOidc { - provider: intermediate_rep - .provider - .into_iter() - .next() - .ok_or("provider missing in AuthOidc".to_string())?, - sub: intermediate_rep - .sub - .into_iter() - .next() - .ok_or("sub missing in AuthOidc".to_string())?, - iss: intermediate_rep - .iss - .into_iter() - .next() - .ok_or("iss missing in AuthOidc".to_string())?, - preferred_username: intermediate_rep - .preferred_username - .into_iter() - .next() - .ok_or("preferred_username missing in AuthOidc".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for AuthOidcResult - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into AuthOidcResult - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct AuthOidcResult { - #[serde(rename = "editor")] - pub editor: models::Editor, - - #[serde(rename = "token")] - pub token: String, -} - -impl AuthOidcResult { - pub fn new(editor: models::Editor, token: String) -> AuthOidcResult { - AuthOidcResult { - editor: editor, - token: token, - } - } -} - -/// Converts the AuthOidcResult value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for AuthOidcResult { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editor in query parameter serialization - - params.push("token".to_string()); - params.push(self.token.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a AuthOidcResult value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for AuthOidcResult { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editor: Vec, - pub token: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing AuthOidcResult".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editor" => intermediate_rep - .editor - .push(models::Editor::from_str(val).map_err(|x| format!("{}", x))?), - "token" => intermediate_rep - .token - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing AuthOidcResult".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(AuthOidcResult { - editor: intermediate_rep - .editor - .into_iter() - .next() - .ok_or("editor missing in AuthOidcResult".to_string())?, - token: intermediate_rep - .token - .into_iter() - .next() - .ok_or("token missing in AuthOidcResult".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for AuthTokenResult - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into AuthTokenResult - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct AuthTokenResult { - #[serde(rename = "token")] - pub token: String, -} - -impl AuthTokenResult { - pub fn new(token: String) -> AuthTokenResult { - AuthTokenResult { token: token } - } -} - -/// Converts the AuthTokenResult value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for AuthTokenResult { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("token".to_string()); - params.push(self.token.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a AuthTokenResult value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for AuthTokenResult { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub token: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing AuthTokenResult".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "token" => intermediate_rep - .token - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing AuthTokenResult".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(AuthTokenResult { - token: intermediate_rep - .token - .into_iter() - .next() - .ok_or("token missing in AuthTokenResult".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ChangelogEntry - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ChangelogEntry - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ChangelogEntry { - /// Monotonically increasing sequence number of this changelog entry. - #[serde(rename = "index")] - pub index: i64, - - /// Identifier of editgroup accepted/merged in this changelog entry. - #[serde(rename = "editgroup_id")] - pub editgroup_id: String, - - /// Date and time when the editgroup was accpeted. - #[serde(rename = "timestamp")] - pub timestamp: chrono::DateTime, - - #[serde(rename = "editgroup")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editgroup: Option, -} - -impl ChangelogEntry { - pub fn new( - index: i64, - editgroup_id: String, - timestamp: chrono::DateTime, - ) -> ChangelogEntry { - ChangelogEntry { - index: index, - editgroup_id: editgroup_id, - timestamp: timestamp, - editgroup: None, - } - } -} - -/// Converts the ChangelogEntry value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ChangelogEntry { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("index".to_string()); - params.push(self.index.to_string()); - - params.push("editgroup_id".to_string()); - params.push(self.editgroup_id.to_string()); - - // Skipping timestamp in query parameter serialization - - // Skipping editgroup in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ChangelogEntry value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ChangelogEntry { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub index: Vec, - pub editgroup_id: Vec, - pub timestamp: Vec>, - pub editgroup: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ChangelogEntry".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "index" => intermediate_rep - .index - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "editgroup_id" => intermediate_rep - .editgroup_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "timestamp" => intermediate_rep.timestamp.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ChangelogEntry".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ChangelogEntry { - index: intermediate_rep - .index - .into_iter() - .next() - .ok_or("index missing in ChangelogEntry".to_string())?, - editgroup_id: intermediate_rep - .editgroup_id - .into_iter() - .next() - .ok_or("editgroup_id missing in ChangelogEntry".to_string())?, - timestamp: intermediate_rep - .timestamp - .into_iter() - .next() - .ok_or("timestamp missing in ChangelogEntry".to_string())?, - editgroup: intermediate_rep.editgroup.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ContainerAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ContainerAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ContainerAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl ContainerAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> ContainerAutoBatch { - ContainerAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the ContainerAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ContainerAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ContainerAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ContainerAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ContainerAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => return std::result::Result::Err( - "Parsing a container in this style is not supported in ContainerAutoBatch" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ContainerAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ContainerAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in ContainerAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in ContainerAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ContainerEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ContainerEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ContainerEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - /// Name of the container (eg, Journal title). Required for entity creation. - #[serde(rename = "name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Type of container, eg 'journal' or 'proceedings'. See Guide for list of valid types. - #[serde(rename = "container_type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub container_type: Option, - - /// Name of the organization or entity responsible for publication. Not the complete imprint/brand. - #[serde(rename = "publisher")] - #[serde(skip_serializing_if = "Option::is_none")] - pub publisher: Option, - - /// Linking ISSN number (ISSN-L). Should be valid and registered with issn.org - #[serde(rename = "issnl")] - #[serde(skip_serializing_if = "Option::is_none")] - pub issnl: Option, - - #[serde(rename = "wikidata_qid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub wikidata_qid: Option, -} - -impl ContainerEntity { - pub fn new() -> ContainerEntity { - ContainerEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - name: None, - container_type: None, - publisher: None, - issnl: None, - wikidata_qid: None, - } - } -} - -/// Converts the ContainerEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ContainerEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - if let Some(ref name) = self.name { - params.push("name".to_string()); - params.push(name.to_string()); - } - - if let Some(ref container_type) = self.container_type { - params.push("container_type".to_string()); - params.push(container_type.to_string()); - } - - if let Some(ref publisher) = self.publisher { - params.push("publisher".to_string()); - params.push(publisher.to_string()); - } - - if let Some(ref issnl) = self.issnl { - params.push("issnl".to_string()); - params.push(issnl.to_string()); - } - - if let Some(ref wikidata_qid) = self.wikidata_qid { - params.push("wikidata_qid".to_string()); - params.push(wikidata_qid.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ContainerEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ContainerEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub name: Vec, - pub container_type: Vec, - pub publisher: Vec, - pub issnl: Vec, - pub wikidata_qid: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ContainerEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ContainerEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ContainerEntity" - .to_string(), - ) - } - "name" => intermediate_rep - .name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "container_type" => intermediate_rep - .container_type - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "publisher" => intermediate_rep - .publisher - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "issnl" => intermediate_rep - .issnl - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "wikidata_qid" => intermediate_rep - .wikidata_qid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ContainerEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ContainerEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - name: intermediate_rep.name.into_iter().next(), - container_type: intermediate_rep.container_type.into_iter().next(), - publisher: intermediate_rep.publisher.into_iter().next(), - issnl: intermediate_rep.issnl.into_iter().next(), - wikidata_qid: intermediate_rep.wikidata_qid.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for CreatorAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into CreatorAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct CreatorAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl CreatorAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> CreatorAutoBatch { - CreatorAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the CreatorAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for CreatorAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a CreatorAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for CreatorAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing CreatorAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => return std::result::Result::Err( - "Parsing a container in this style is not supported in CreatorAutoBatch" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing CreatorAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(CreatorAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in CreatorAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in CreatorAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for CreatorEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into CreatorEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct CreatorEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - /// Name as should be displayed in web interface or in author lists (not index/sorted). Required for valid entities. - #[serde(rename = "display_name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub display_name: Option, - - /// In English commonly the first name, but ordering is context and culture specific. - #[serde(rename = "given_name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub given_name: Option, - - /// In English commonly the last, or family name, but ordering is context and culture specific. - #[serde(rename = "surname")] - #[serde(skip_serializing_if = "Option::is_none")] - pub surname: Option, - - /// ORCiD (https://orcid.org) identifier - #[serde(rename = "orcid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub orcid: Option, - - /// Wikidata entity QID - #[serde(rename = "wikidata_qid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub wikidata_qid: Option, -} - -impl CreatorEntity { - pub fn new() -> CreatorEntity { - CreatorEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - display_name: None, - given_name: None, - surname: None, - orcid: None, - wikidata_qid: None, - } - } -} - -/// Converts the CreatorEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for CreatorEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - if let Some(ref display_name) = self.display_name { - params.push("display_name".to_string()); - params.push(display_name.to_string()); - } - - if let Some(ref given_name) = self.given_name { - params.push("given_name".to_string()); - params.push(given_name.to_string()); - } - - if let Some(ref surname) = self.surname { - params.push("surname".to_string()); - params.push(surname.to_string()); - } - - if let Some(ref orcid) = self.orcid { - params.push("orcid".to_string()); - params.push(orcid.to_string()); - } - - if let Some(ref wikidata_qid) = self.wikidata_qid { - params.push("wikidata_qid".to_string()); - params.push(wikidata_qid.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a CreatorEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for CreatorEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub display_name: Vec, - pub given_name: Vec, - pub surname: Vec, - pub orcid: Vec, - pub wikidata_qid: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing CreatorEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in CreatorEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in CreatorEntity" - .to_string(), - ) - } - "display_name" => intermediate_rep - .display_name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "given_name" => intermediate_rep - .given_name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "surname" => intermediate_rep - .surname - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "orcid" => intermediate_rep - .orcid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "wikidata_qid" => intermediate_rep - .wikidata_qid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing CreatorEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(CreatorEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - display_name: intermediate_rep.display_name.into_iter().next(), - given_name: intermediate_rep.given_name.into_iter().next(), - surname: intermediate_rep.surname.into_iter().next(), - orcid: intermediate_rep.orcid.into_iter().next(), - wikidata_qid: intermediate_rep.wikidata_qid.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for Editgroup - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into Editgroup - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct Editgroup { - /// Fatcat identifier for this editgroup. Assigned on creation. - #[serde(rename = "editgroup_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editgroup_id: Option, - - /// Fatcat identifer of editor that created this editgroup. - #[serde(rename = "editor_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editor_id: Option, - - #[serde(rename = "editor")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editor: Option, - - /// For accepted/merged editgroups, the changelog index that the accept occured at. WARNING: not populated in all contexts that an editgroup could be included in a response. - #[serde(rename = "changelog_index")] - #[serde(skip_serializing_if = "Option::is_none")] - pub changelog_index: Option, - - /// Timestamp when this editgroup was first created. - #[serde(rename = "created")] - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Timestamp when this editgroup was most recently submitted for review. If withdrawn, or never submitted, will be `null`. - #[serde(rename = "submitted")] - #[serde(skip_serializing_if = "Option::is_none")] - pub submitted: Option>, - - /// Comment describing the changes in this editgroup. Can be updated with PUT request. - #[serde(rename = "description")] - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Free-form JSON metadata attached to this editgroup. Eg, metadata provenance, or script user-agent details. See guide for (unenforced) schema norms. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Only included in GET responses, and not in all contexts. Do not include this field in PUT or POST requests. - #[serde(rename = "annotations")] - #[serde(skip_serializing_if = "Option::is_none")] - pub annotations: Option>, - - #[serde(rename = "edits")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edits: Option, -} - -impl Editgroup { - pub fn new() -> Editgroup { - Editgroup { - editgroup_id: None, - editor_id: None, - editor: None, - changelog_index: None, - created: None, - submitted: None, - description: None, - extra: None, - annotations: None, - edits: None, - } - } -} - -/// Converts the Editgroup value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for Editgroup { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref editgroup_id) = self.editgroup_id { - params.push("editgroup_id".to_string()); - params.push(editgroup_id.to_string()); - } - - if let Some(ref editor_id) = self.editor_id { - params.push("editor_id".to_string()); - params.push(editor_id.to_string()); - } - - // Skipping editor in query parameter serialization - - if let Some(ref changelog_index) = self.changelog_index { - params.push("changelog_index".to_string()); - params.push(changelog_index.to_string()); - } - - // Skipping created in query parameter serialization - - // Skipping submitted in query parameter serialization - - if let Some(ref description) = self.description { - params.push("description".to_string()); - params.push(description.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping annotations in query parameter serialization - - // Skipping edits in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a Editgroup value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for Editgroup { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup_id: Vec, - pub editor_id: Vec, - pub editor: Vec, - pub changelog_index: Vec, - pub created: Vec>, - pub submitted: Vec>, - pub description: Vec, - pub extra: Vec>, - pub annotations: Vec>, - pub edits: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing Editgroup".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup_id" => intermediate_rep - .editgroup_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editor_id" => intermediate_rep - .editor_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editor" => intermediate_rep - .editor - .push(models::Editor::from_str(val).map_err(|x| format!("{}", x))?), - "changelog_index" => intermediate_rep - .changelog_index - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "created" => intermediate_rep.created.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "submitted" => intermediate_rep.submitted.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "description" => intermediate_rep - .description - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in Editgroup" - .to_string(), - ) - } - "annotations" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in Editgroup" - .to_string(), - ) - } - "edits" => intermediate_rep - .edits - .push(models::EditgroupEdits::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing Editgroup".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(Editgroup { - editgroup_id: intermediate_rep.editgroup_id.into_iter().next(), - editor_id: intermediate_rep.editor_id.into_iter().next(), - editor: intermediate_rep.editor.into_iter().next(), - changelog_index: intermediate_rep.changelog_index.into_iter().next(), - created: intermediate_rep.created.into_iter().next(), - submitted: intermediate_rep.submitted.into_iter().next(), - description: intermediate_rep.description.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - annotations: intermediate_rep.annotations.into_iter().next(), - edits: intermediate_rep.edits.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for EditgroupAnnotation - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into EditgroupAnnotation - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct EditgroupAnnotation { - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "annotation_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub annotation_id: Option, - - /// Editgroup that this annotation applies to. Set automatically in creations based on URL parameter. - #[serde(rename = "editgroup_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editgroup_id: Option, - - /// Defaults to editor created the annotation via POST request. - #[serde(rename = "editor_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editor_id: Option, - - #[serde(rename = "editor")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editor: Option, - - /// Timestamp when annotation was first created. - #[serde(rename = "created")] - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - #[serde(rename = "comment_markdown")] - #[serde(skip_serializing_if = "Option::is_none")] - pub comment_markdown: Option, - - /// Additional free-form JSON metadata that can be included as part of the annotation (or even as the primary annotation itself). See guide for details. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, -} - -impl EditgroupAnnotation { - pub fn new() -> EditgroupAnnotation { - EditgroupAnnotation { - annotation_id: None, - editgroup_id: None, - editor_id: None, - editor: None, - created: None, - comment_markdown: None, - extra: None, - } - } -} - -/// Converts the EditgroupAnnotation value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for EditgroupAnnotation { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref annotation_id) = self.annotation_id { - params.push("annotation_id".to_string()); - params.push(annotation_id.to_string()); - } - - if let Some(ref editgroup_id) = self.editgroup_id { - params.push("editgroup_id".to_string()); - params.push(editgroup_id.to_string()); - } - - if let Some(ref editor_id) = self.editor_id { - params.push("editor_id".to_string()); - params.push(editor_id.to_string()); - } - - // Skipping editor in query parameter serialization - - // Skipping created in query parameter serialization - - if let Some(ref comment_markdown) = self.comment_markdown { - params.push("comment_markdown".to_string()); - params.push(comment_markdown.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a EditgroupAnnotation value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for EditgroupAnnotation { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub annotation_id: Vec, - pub editgroup_id: Vec, - pub editor_id: Vec, - pub editor: Vec, - pub created: Vec>, - pub comment_markdown: Vec, - pub extra: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing EditgroupAnnotation".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "annotation_id" => intermediate_rep - .annotation_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editgroup_id" => intermediate_rep - .editgroup_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editor_id" => intermediate_rep - .editor_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editor" => intermediate_rep - .editor - .push(models::Editor::from_str(val).map_err(|x| format!("{}", x))?), - "created" => intermediate_rep.created.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "comment_markdown" => intermediate_rep - .comment_markdown - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupAnnotation" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing EditgroupAnnotation".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(EditgroupAnnotation { - annotation_id: intermediate_rep.annotation_id.into_iter().next(), - editgroup_id: intermediate_rep.editgroup_id.into_iter().next(), - editor_id: intermediate_rep.editor_id.into_iter().next(), - editor: intermediate_rep.editor.into_iter().next(), - created: intermediate_rep.created.into_iter().next(), - comment_markdown: intermediate_rep.comment_markdown.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - }) - } -} - -/// Only included in GET responses, and not in all contexts. Do not include this field in PUT or POST requests. -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for EditgroupEdits - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into EditgroupEdits - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct EditgroupEdits { - #[serde(rename = "containers")] - #[serde(skip_serializing_if = "Option::is_none")] - pub containers: Option>, - - #[serde(rename = "creators")] - #[serde(skip_serializing_if = "Option::is_none")] - pub creators: Option>, - - #[serde(rename = "files")] - #[serde(skip_serializing_if = "Option::is_none")] - pub files: Option>, - - #[serde(rename = "filesets")] - #[serde(skip_serializing_if = "Option::is_none")] - pub filesets: Option>, - - #[serde(rename = "webcaptures")] - #[serde(skip_serializing_if = "Option::is_none")] - pub webcaptures: Option>, - - #[serde(rename = "releases")] - #[serde(skip_serializing_if = "Option::is_none")] - pub releases: Option>, - - #[serde(rename = "works")] - #[serde(skip_serializing_if = "Option::is_none")] - pub works: Option>, -} - -impl EditgroupEdits { - pub fn new() -> EditgroupEdits { - EditgroupEdits { - containers: None, - creators: None, - files: None, - filesets: None, - webcaptures: None, - releases: None, - works: None, - } - } -} - -/// Converts the EditgroupEdits value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for EditgroupEdits { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping containers in query parameter serialization - - // Skipping creators in query parameter serialization - - // Skipping files in query parameter serialization - - // Skipping filesets in query parameter serialization - - // Skipping webcaptures in query parameter serialization - - // Skipping releases in query parameter serialization - - // Skipping works in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a EditgroupEdits value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for EditgroupEdits { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub containers: Vec>, - pub creators: Vec>, - pub files: Vec>, - pub filesets: Vec>, - pub webcaptures: Vec>, - pub releases: Vec>, - pub works: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing EditgroupEdits".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "containers" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "creators" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "files" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "filesets" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "webcaptures" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "releases" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - "works" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EditgroupEdits" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing EditgroupEdits".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(EditgroupEdits { - containers: intermediate_rep.containers.into_iter().next(), - creators: intermediate_rep.creators.into_iter().next(), - files: intermediate_rep.files.into_iter().next(), - filesets: intermediate_rep.filesets.into_iter().next(), - webcaptures: intermediate_rep.webcaptures.into_iter().next(), - releases: intermediate_rep.releases.into_iter().next(), - works: intermediate_rep.works.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for Editor - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into Editor - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct Editor { - /// Fatcat identifier for the editor. Can not be changed. - #[serde(rename = "editor_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub editor_id: Option, - - /// Username/handle (short slug-like string) to identify this editor. May be changed at any time by the editor; use the `editor_id` as a persistend identifer. - #[serde(rename = "username")] - pub username: String, - - /// Whether this editor has the `admin` role. - #[serde(rename = "is_admin")] - #[serde(skip_serializing_if = "Option::is_none")] - pub is_admin: Option, - - /// Whether this editor is a bot (as opposed to a human making manual edits) - #[serde(rename = "is_bot")] - #[serde(skip_serializing_if = "Option::is_none")] - pub is_bot: Option, - - /// Whether this editor's account is enabled (if not API tokens and web logins will not work). - #[serde(rename = "is_active")] - #[serde(skip_serializing_if = "Option::is_none")] - pub is_active: Option, -} - -impl Editor { - pub fn new(username: String) -> Editor { - Editor { - editor_id: None, - username: username, - is_admin: None, - is_bot: None, - is_active: None, - } - } -} - -/// Converts the Editor value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for Editor { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref editor_id) = self.editor_id { - params.push("editor_id".to_string()); - params.push(editor_id.to_string()); - } - - params.push("username".to_string()); - params.push(self.username.to_string()); - - if let Some(ref is_admin) = self.is_admin { - params.push("is_admin".to_string()); - params.push(is_admin.to_string()); - } - - if let Some(ref is_bot) = self.is_bot { - params.push("is_bot".to_string()); - params.push(is_bot.to_string()); - } - - if let Some(ref is_active) = self.is_active { - params.push("is_active".to_string()); - params.push(is_active.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a Editor value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for Editor { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editor_id: Vec, - pub username: Vec, - pub is_admin: Vec, - pub is_bot: Vec, - pub is_active: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing Editor".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editor_id" => intermediate_rep - .editor_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "username" => intermediate_rep - .username - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "is_admin" => intermediate_rep - .is_admin - .push(bool::from_str(val).map_err(|x| format!("{}", x))?), - "is_bot" => intermediate_rep - .is_bot - .push(bool::from_str(val).map_err(|x| format!("{}", x))?), - "is_active" => intermediate_rep - .is_active - .push(bool::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing Editor".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(Editor { - editor_id: intermediate_rep.editor_id.into_iter().next(), - username: intermediate_rep - .username - .into_iter() - .next() - .ok_or("username missing in Editor".to_string())?, - is_admin: intermediate_rep.is_admin.into_iter().next(), - is_bot: intermediate_rep.is_bot.into_iter().next(), - is_active: intermediate_rep.is_active.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for EntityEdit - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into EntityEdit - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct EntityEdit { - /// Unique UUID for this specific edit object. - #[serde(rename = "edit_id")] - pub edit_id: String, - - /// Fatcat identifier of the entity this edit is mutating. - #[serde(rename = "ident")] - pub ident: String, - - /// Entity revision that this edit will set the entity to. May be `null` in the case of deletions. - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// Revision of entity just before this edit. May be used in the future to prevent edit race conditions. - #[serde(rename = "prev_revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub prev_revision: Option, - - /// When an edit is to merge entities (redirect one to another), this is the entity fatcat identifier for the target entity. - #[serde(rename = "redirect_ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect_ident: Option, - - /// Editgroup identifier that this edit is part of. - #[serde(rename = "editgroup_id")] - pub editgroup_id: String, - - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, -} - -impl EntityEdit { - pub fn new(edit_id: String, ident: String, editgroup_id: String) -> EntityEdit { - EntityEdit { - edit_id: edit_id, - ident: ident, - revision: None, - prev_revision: None, - redirect_ident: None, - editgroup_id: editgroup_id, - extra: None, - } - } -} - -/// Converts the EntityEdit value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for EntityEdit { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("edit_id".to_string()); - params.push(self.edit_id.to_string()); - - params.push("ident".to_string()); - params.push(self.ident.to_string()); - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref prev_revision) = self.prev_revision { - params.push("prev_revision".to_string()); - params.push(prev_revision.to_string()); - } - - if let Some(ref redirect_ident) = self.redirect_ident { - params.push("redirect_ident".to_string()); - params.push(redirect_ident.to_string()); - } - - params.push("editgroup_id".to_string()); - params.push(self.editgroup_id.to_string()); - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a EntityEdit value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for EntityEdit { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub edit_id: Vec, - pub ident: Vec, - pub revision: Vec, - pub prev_revision: Vec, - pub redirect_ident: Vec, - pub editgroup_id: Vec, - pub extra: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing EntityEdit".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "edit_id" => intermediate_rep - .edit_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "prev_revision" => intermediate_rep - .prev_revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect_ident" => intermediate_rep - .redirect_ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "editgroup_id" => intermediate_rep - .editgroup_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in EntityEdit" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing EntityEdit".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(EntityEdit { - edit_id: intermediate_rep - .edit_id - .into_iter() - .next() - .ok_or("edit_id missing in EntityEdit".to_string())?, - ident: intermediate_rep - .ident - .into_iter() - .next() - .ok_or("ident missing in EntityEdit".to_string())?, - revision: intermediate_rep.revision.into_iter().next(), - prev_revision: intermediate_rep.prev_revision.into_iter().next(), - redirect_ident: intermediate_rep.redirect_ident.into_iter().next(), - editgroup_id: intermediate_rep - .editgroup_id - .into_iter() - .next() - .ok_or("editgroup_id missing in EntityEdit".to_string())?, - extra: intermediate_rep.extra.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for EntityHistoryEntry - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into EntityHistoryEntry - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct EntityHistoryEntry { - #[serde(rename = "edit")] - pub edit: models::EntityEdit, - - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "changelog_entry")] - pub changelog_entry: models::ChangelogEntry, -} - -impl EntityHistoryEntry { - pub fn new( - edit: models::EntityEdit, - editgroup: models::Editgroup, - changelog_entry: models::ChangelogEntry, - ) -> EntityHistoryEntry { - EntityHistoryEntry { - edit: edit, - editgroup: editgroup, - changelog_entry: changelog_entry, - } - } -} - -/// Converts the EntityHistoryEntry value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for EntityHistoryEntry { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping edit in query parameter serialization - - // Skipping editgroup in query parameter serialization - - // Skipping changelog_entry in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a EntityHistoryEntry value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for EntityHistoryEntry { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub edit: Vec, - pub editgroup: Vec, - pub changelog_entry: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing EntityHistoryEntry".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "edit" => intermediate_rep - .edit - .push(models::EntityEdit::from_str(val).map_err(|x| format!("{}", x))?), - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "changelog_entry" => intermediate_rep - .changelog_entry - .push(models::ChangelogEntry::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing EntityHistoryEntry".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(EntityHistoryEntry { - edit: intermediate_rep - .edit - .into_iter() - .next() - .ok_or("edit missing in EntityHistoryEntry".to_string())?, - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in EntityHistoryEntry".to_string())?, - changelog_entry: intermediate_rep - .changelog_entry - .into_iter() - .next() - .ok_or("changelog_entry missing in EntityHistoryEntry".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ErrorResponse - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ErrorResponse - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ErrorResponse { - #[serde(rename = "success")] - pub success: bool, - - #[serde(rename = "error")] - pub error: String, - - #[serde(rename = "message")] - pub message: String, -} - -impl ErrorResponse { - pub fn new(success: bool, error: String, message: String) -> ErrorResponse { - ErrorResponse { - success: success, - error: error, - message: message, - } - } -} - -/// Converts the ErrorResponse value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ErrorResponse { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("success".to_string()); - params.push(self.success.to_string()); - - params.push("error".to_string()); - params.push(self.error.to_string()); - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ErrorResponse value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ErrorResponse { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub success: Vec, - pub error: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ErrorResponse".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "success" => intermediate_rep - .success - .push(bool::from_str(val).map_err(|x| format!("{}", x))?), - "error" => intermediate_rep - .error - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep - .message - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ErrorResponse".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ErrorResponse { - success: intermediate_rep - .success - .into_iter() - .next() - .ok_or("success missing in ErrorResponse".to_string())?, - error: intermediate_rep - .error - .into_iter() - .next() - .ok_or("error missing in ErrorResponse".to_string())?, - message: intermediate_rep - .message - .into_iter() - .next() - .ok_or("message missing in ErrorResponse".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FileAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FileAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FileAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl FileAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> FileAutoBatch { - FileAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the FileAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FileAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FileAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FileAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FileAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileAutoBatch" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FileAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FileAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in FileAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in FileAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FileEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FileEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FileEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - /// Size of file in bytes. Non-zero. - #[serde(rename = "size")] - #[serde(skip_serializing_if = "Option::is_none")] - pub size: Option, - - /// MD5 hash of data, in hex encoding - #[serde(rename = "md5")] - #[serde(skip_serializing_if = "Option::is_none")] - pub md5: Option, - - /// SHA-1 hash of data, in hex encoding - #[serde(rename = "sha1")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha1: Option, - - /// SHA-256 hash of data, in hex encoding - #[serde(rename = "sha256")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha256: Option, - - #[serde(rename = "urls")] - #[serde(skip_serializing_if = "Option::is_none")] - pub urls: Option>, - - #[serde(rename = "mimetype")] - #[serde(skip_serializing_if = "Option::is_none")] - pub mimetype: Option, - - /// Set of identifier of release entities this file represents a full manifestation of. Usually a single release, but some files contain content of multiple full releases (eg, an issue of a journal). - #[serde(rename = "release_ids")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_ids: Option>, - - /// Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. - #[serde(rename = "releases")] - #[serde(skip_serializing_if = "Option::is_none")] - pub releases: Option>, -} - -impl FileEntity { - pub fn new() -> FileEntity { - FileEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - size: None, - md5: None, - sha1: None, - sha256: None, - urls: None, - mimetype: None, - release_ids: None, - releases: None, - } - } -} - -/// Converts the FileEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FileEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - if let Some(ref size) = self.size { - params.push("size".to_string()); - params.push(size.to_string()); - } - - if let Some(ref md5) = self.md5 { - params.push("md5".to_string()); - params.push(md5.to_string()); - } - - if let Some(ref sha1) = self.sha1 { - params.push("sha1".to_string()); - params.push(sha1.to_string()); - } - - if let Some(ref sha256) = self.sha256 { - params.push("sha256".to_string()); - params.push(sha256.to_string()); - } - - // Skipping urls in query parameter serialization - - if let Some(ref mimetype) = self.mimetype { - params.push("mimetype".to_string()); - params.push(mimetype.to_string()); - } - - if let Some(ref release_ids) = self.release_ids { - params.push("release_ids".to_string()); - params.push( - release_ids - .iter() - .map(|x| x.to_string()) - .collect::>() - .join(",") - .to_string(), - ); - } - - // Skipping releases in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FileEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FileEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub size: Vec, - pub md5: Vec, - pub sha1: Vec, - pub sha256: Vec, - pub urls: Vec>, - pub mimetype: Vec, - pub release_ids: Vec>, - pub releases: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FileEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileEntity" - .to_string(), - ) - } - "size" => intermediate_rep - .size - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "md5" => intermediate_rep - .md5 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sha1" => intermediate_rep - .sha1 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sha256" => intermediate_rep - .sha256 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "urls" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileEntity" - .to_string(), - ) - } - "mimetype" => intermediate_rep - .mimetype - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "release_ids" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileEntity" - .to_string(), - ) - } - "releases" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FileEntity" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FileEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FileEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - size: intermediate_rep.size.into_iter().next(), - md5: intermediate_rep.md5.into_iter().next(), - sha1: intermediate_rep.sha1.into_iter().next(), - sha256: intermediate_rep.sha256.into_iter().next(), - urls: intermediate_rep.urls.into_iter().next(), - mimetype: intermediate_rep.mimetype.into_iter().next(), - release_ids: intermediate_rep.release_ids.into_iter().next(), - releases: intermediate_rep.releases.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FileUrl - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FileUrl - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FileUrl { - /// URL/URI pointing directly to a machine retrievable copy of this exact file. - #[serde(rename = "url")] - pub url: String, - - /// Indicates type of host this URL points to. Eg, \"publisher\", \"repository\", \"webarchive\". See guide for list of acceptable values. - #[serde(rename = "rel")] - pub rel: String, -} - -impl FileUrl { - pub fn new(url: String, rel: String) -> FileUrl { - FileUrl { url: url, rel: rel } - } -} - -/// Converts the FileUrl value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FileUrl { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("url".to_string()); - params.push(self.url.to_string()); - - params.push("rel".to_string()); - params.push(self.rel.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FileUrl value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FileUrl { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub url: Vec, - pub rel: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FileUrl".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "url" => intermediate_rep - .url - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "rel" => intermediate_rep - .rel - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FileUrl".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FileUrl { - url: intermediate_rep - .url - .into_iter() - .next() - .ok_or("url missing in FileUrl".to_string())?, - rel: intermediate_rep - .rel - .into_iter() - .next() - .ok_or("rel missing in FileUrl".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FilesetAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FilesetAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FilesetAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl FilesetAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> FilesetAutoBatch { - FilesetAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the FilesetAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FilesetAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FilesetAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FilesetAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FilesetAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetAutoBatch" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FilesetAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FilesetAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in FilesetAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in FilesetAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FilesetEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FilesetEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FilesetEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - #[serde(rename = "manifest")] - #[serde(skip_serializing_if = "Option::is_none")] - pub manifest: Option>, - - #[serde(rename = "urls")] - #[serde(skip_serializing_if = "Option::is_none")] - pub urls: Option>, - - /// Set of identifier of release entities this fileset represents a full manifestation of. Usually a single release. - #[serde(rename = "release_ids")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_ids: Option>, - - /// Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. - #[serde(rename = "releases")] - #[serde(skip_serializing_if = "Option::is_none")] - pub releases: Option>, -} - -impl FilesetEntity { - pub fn new() -> FilesetEntity { - FilesetEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - manifest: None, - urls: None, - release_ids: None, - releases: None, - } - } -} - -/// Converts the FilesetEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FilesetEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - // Skipping manifest in query parameter serialization - - // Skipping urls in query parameter serialization - - if let Some(ref release_ids) = self.release_ids { - params.push("release_ids".to_string()); - params.push( - release_ids - .iter() - .map(|x| x.to_string()) - .collect::>() - .join(",") - .to_string(), - ); - } - - // Skipping releases in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FilesetEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FilesetEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub manifest: Vec>, - pub urls: Vec>, - pub release_ids: Vec>, - pub releases: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FilesetEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - "manifest" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - "urls" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - "release_ids" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - "releases" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetEntity" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FilesetEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FilesetEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - manifest: intermediate_rep.manifest.into_iter().next(), - urls: intermediate_rep.urls.into_iter().next(), - release_ids: intermediate_rep.release_ids.into_iter().next(), - releases: intermediate_rep.releases.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FilesetFile - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FilesetFile - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FilesetFile { - /// Path name of file within this fileset (eg, directory) - #[serde(rename = "path")] - pub path: String, - - /// File size in bytes - #[serde(rename = "size")] - pub size: i64, - - /// MD5 hash of data, in hex encoding - #[serde(rename = "md5")] - #[serde(skip_serializing_if = "Option::is_none")] - pub md5: Option, - - /// SHA-1 hash of data, in hex encoding - #[serde(rename = "sha1")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha1: Option, - - /// SHA-256 hash of data, in hex encoding - #[serde(rename = "sha256")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha256: Option, - - /// Free-form additional metadata about this specific file in the set. Eg, `mimetype`. See guide for nomative (but unenforced) schema fields. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, -} - -impl FilesetFile { - pub fn new(path: String, size: i64) -> FilesetFile { - FilesetFile { - path: path, - size: size, - md5: None, - sha1: None, - sha256: None, - extra: None, - } - } -} - -/// Converts the FilesetFile value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FilesetFile { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("path".to_string()); - params.push(self.path.to_string()); - - params.push("size".to_string()); - params.push(self.size.to_string()); - - if let Some(ref md5) = self.md5 { - params.push("md5".to_string()); - params.push(md5.to_string()); - } - - if let Some(ref sha1) = self.sha1 { - params.push("sha1".to_string()); - params.push(sha1.to_string()); - } - - if let Some(ref sha256) = self.sha256 { - params.push("sha256".to_string()); - params.push(sha256.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FilesetFile value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FilesetFile { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub path: Vec, - pub size: Vec, - pub md5: Vec, - pub sha1: Vec, - pub sha256: Vec, - pub extra: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FilesetFile".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "path" => intermediate_rep - .path - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "size" => intermediate_rep - .size - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "md5" => intermediate_rep - .md5 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sha1" => intermediate_rep - .sha1 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sha256" => intermediate_rep - .sha256 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in FilesetFile" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FilesetFile".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FilesetFile { - path: intermediate_rep - .path - .into_iter() - .next() - .ok_or("path missing in FilesetFile".to_string())?, - size: intermediate_rep - .size - .into_iter() - .next() - .ok_or("size missing in FilesetFile".to_string())?, - md5: intermediate_rep.md5.into_iter().next(), - sha1: intermediate_rep.sha1.into_iter().next(), - sha256: intermediate_rep.sha256.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for FilesetUrl - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into FilesetUrl - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FilesetUrl { - #[serde(rename = "url")] - pub url: String, - - /// Indicates type of host this URL points to. See guide for list of acceptable values. - #[serde(rename = "rel")] - pub rel: String, -} - -impl FilesetUrl { - pub fn new(url: String, rel: String) -> FilesetUrl { - FilesetUrl { url: url, rel: rel } - } -} - -/// Converts the FilesetUrl value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for FilesetUrl { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("url".to_string()); - params.push(self.url.to_string()); - - params.push("rel".to_string()); - params.push(self.rel.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a FilesetUrl value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for FilesetUrl { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub url: Vec, - pub rel: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing FilesetUrl".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "url" => intermediate_rep - .url - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "rel" => intermediate_rep - .rel - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing FilesetUrl".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(FilesetUrl { - url: intermediate_rep - .url - .into_iter() - .next() - .ok_or("url missing in FilesetUrl".to_string())?, - rel: intermediate_rep - .rel - .into_iter() - .next() - .ok_or("rel missing in FilesetUrl".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseAbstract - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseAbstract - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseAbstract { - /// SHA-1 hash of data, in hex encoding - #[serde(rename = "sha1")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha1: Option, - - /// Abstract content. May be encoded, as per `mimetype` field, but only string/text content may be included. - #[serde(rename = "content")] - #[serde(skip_serializing_if = "Option::is_none")] - pub content: Option, - - /// Mimetype of abstract contents. `text/plain` is the default if content isn't encoded. - #[serde(rename = "mimetype")] - #[serde(skip_serializing_if = "Option::is_none")] - pub mimetype: Option, - - /// ISO language code of the abstract. Same semantics as release `language` field. - #[serde(rename = "lang")] - #[serde(skip_serializing_if = "Option::is_none")] - pub lang: Option, -} - -impl ReleaseAbstract { - pub fn new() -> ReleaseAbstract { - ReleaseAbstract { - sha1: None, - content: None, - mimetype: None, - lang: None, - } - } -} - -/// Converts the ReleaseAbstract value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseAbstract { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref sha1) = self.sha1 { - params.push("sha1".to_string()); - params.push(sha1.to_string()); - } - - if let Some(ref content) = self.content { - params.push("content".to_string()); - params.push(content.to_string()); - } - - if let Some(ref mimetype) = self.mimetype { - params.push("mimetype".to_string()); - params.push(mimetype.to_string()); - } - - if let Some(ref lang) = self.lang { - params.push("lang".to_string()); - params.push(lang.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseAbstract value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseAbstract { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub sha1: Vec, - pub content: Vec, - pub mimetype: Vec, - pub lang: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseAbstract".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "sha1" => intermediate_rep - .sha1 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "content" => intermediate_rep - .content - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "mimetype" => intermediate_rep - .mimetype - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "lang" => intermediate_rep - .lang - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseAbstract".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseAbstract { - sha1: intermediate_rep.sha1.into_iter().next(), - content: intermediate_rep.content.into_iter().next(), - mimetype: intermediate_rep.mimetype.into_iter().next(), - lang: intermediate_rep.lang.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl ReleaseAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> ReleaseAutoBatch { - ReleaseAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the ReleaseAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseAutoBatch" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in ReleaseAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in ReleaseAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseContrib - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseContrib - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseContrib { - /// Internally assigned zero-indexed sequence number of contribution. Authors should come first; this encodes the order of attriubtion. - #[serde(rename = "index")] - #[serde(skip_serializing_if = "Option::is_none")] - pub index: Option, - - /// If known, indicates the creator entity this contribution was made by. - #[serde(rename = "creator_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub creator_id: Option, - - #[serde(rename = "creator")] - #[serde(skip_serializing_if = "Option::is_none")] - pub creator: Option, - - /// Full name of the contributor as typeset in the release. - #[serde(rename = "raw_name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub raw_name: Option, - - /// In English commonly the first name, but ordering is context and culture specific. - #[serde(rename = "given_name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub given_name: Option, - - /// In English commonly the last, or family name, but ordering is context and culture specific. - #[serde(rename = "surname")] - #[serde(skip_serializing_if = "Option::is_none")] - pub surname: Option, - - /// Short string (slug) indicating type of contribution (eg, \"author\", \"translator\"). See guide for list of accpeted values. - #[serde(rename = "role")] - #[serde(skip_serializing_if = "Option::is_none")] - pub role: Option, - - /// Raw affiliation string as displayed in text - #[serde(rename = "raw_affiliation")] - #[serde(skip_serializing_if = "Option::is_none")] - pub raw_affiliation: Option, - - /// Additional free-form JSON metadata about this contributor/contribution. See guide for normative schema. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, -} - -impl ReleaseContrib { - pub fn new() -> ReleaseContrib { - ReleaseContrib { - index: None, - creator_id: None, - creator: None, - raw_name: None, - given_name: None, - surname: None, - role: None, - raw_affiliation: None, - extra: None, - } - } -} - -/// Converts the ReleaseContrib value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseContrib { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref index) = self.index { - params.push("index".to_string()); - params.push(index.to_string()); - } - - if let Some(ref creator_id) = self.creator_id { - params.push("creator_id".to_string()); - params.push(creator_id.to_string()); - } - - // Skipping creator in query parameter serialization - - if let Some(ref raw_name) = self.raw_name { - params.push("raw_name".to_string()); - params.push(raw_name.to_string()); - } - - if let Some(ref given_name) = self.given_name { - params.push("given_name".to_string()); - params.push(given_name.to_string()); - } - - if let Some(ref surname) = self.surname { - params.push("surname".to_string()); - params.push(surname.to_string()); - } - - if let Some(ref role) = self.role { - params.push("role".to_string()); - params.push(role.to_string()); - } - - if let Some(ref raw_affiliation) = self.raw_affiliation { - params.push("raw_affiliation".to_string()); - params.push(raw_affiliation.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseContrib value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseContrib { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub index: Vec, - pub creator_id: Vec, - pub creator: Vec, - pub raw_name: Vec, - pub given_name: Vec, - pub surname: Vec, - pub role: Vec, - pub raw_affiliation: Vec, - pub extra: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseContrib".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "index" => intermediate_rep - .index - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "creator_id" => intermediate_rep - .creator_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "creator" => intermediate_rep - .creator - .push(models::CreatorEntity::from_str(val).map_err(|x| format!("{}", x))?), - "raw_name" => intermediate_rep - .raw_name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "given_name" => intermediate_rep - .given_name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "surname" => intermediate_rep - .surname - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "role" => intermediate_rep - .role - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "raw_affiliation" => intermediate_rep - .raw_affiliation - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseContrib" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseContrib".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseContrib { - index: intermediate_rep.index.into_iter().next(), - creator_id: intermediate_rep.creator_id.into_iter().next(), - creator: intermediate_rep.creator.into_iter().next(), - raw_name: intermediate_rep.raw_name.into_iter().next(), - given_name: intermediate_rep.given_name.into_iter().next(), - surname: intermediate_rep.surname.into_iter().next(), - role: intermediate_rep.role.into_iter().next(), - raw_affiliation: intermediate_rep.raw_affiliation.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - /// Required for valid entities. The title used in citations and for display. Sometimes the English translation of title e even if release content is not English. - #[serde(rename = "title")] - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - - /// Subtitle of release. In many cases, better to merge with title than include as separate field (unless combined title would be very long). See guide for details. - #[serde(rename = "subtitle")] - #[serde(skip_serializing_if = "Option::is_none")] - pub subtitle: Option, - - /// Title in original language if `title` field has been translated. See guide for details. - #[serde(rename = "original_title")] - #[serde(skip_serializing_if = "Option::is_none")] - pub original_title: Option, - - /// Identifier of work this release is part of. In creation (POST) requests, a work entity will be created automatically if this field is not set. - #[serde(rename = "work_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub work_id: Option, - - #[serde(rename = "container")] - #[serde(skip_serializing_if = "Option::is_none")] - pub container: Option, - - /// Complete file entities identified by `file_ids` field. Only included in GET responses when `files` included in `expand` parameter; ignored in PUT or POST requests. - #[serde(rename = "files")] - #[serde(skip_serializing_if = "Option::is_none")] - pub files: Option>, - - /// Complete file entities identified by `filesets_ids` field. Only included in GET responses when `filesets` included in `expand` parameter; ignored in PUT or POST requests. - #[serde(rename = "filesets")] - #[serde(skip_serializing_if = "Option::is_none")] - pub filesets: Option>, - - /// Complete webcapture entities identified by `webcapture_ids` field. Only included in GET responses when `webcaptures` included in `expand` parameter; ignored in PUT or POST requests. - #[serde(rename = "webcaptures")] - #[serde(skip_serializing_if = "Option::is_none")] - pub webcaptures: Option>, - - /// Used to link this release to a container entity that the release was published as part of. - #[serde(rename = "container_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub container_id: Option, - - /// \"Type\" or \"medium\" that this release is published as. See guide for valid values. - #[serde(rename = "release_type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_type: Option, - - /// The stage of publication of this specific release. See guide for valid values and semantics. - #[serde(rename = "release_stage")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_stage: Option, - - /// Full date when this release was formally published. ISO format, like `2019-03-05`. See guide for semantics. - #[serde(rename = "release_date")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_date: Option, - - /// Year when this release was formally published. Must match `release_date` if that field is set; this field exists because sometimes only the year is known. - #[serde(rename = "release_year")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_year: Option, - - /// Type of withdrawl or retraction of this release, if applicable. If release has not been withdrawn, should be `null` (aka, not set, not the string \"null\" or an empty string). - #[serde(rename = "withdrawn_status")] - #[serde(skip_serializing_if = "Option::is_none")] - pub withdrawn_status: Option, - - /// Full date when this release was formally withdrawn (if applicable). ISO format, like `release_date`. - #[serde(rename = "withdrawn_date")] - #[serde(skip_serializing_if = "Option::is_none")] - pub withdrawn_date: Option, - - /// Year corresponding with `withdrawn_date` like `release_year`/`release_date`. - #[serde(rename = "withdrawn_year")] - #[serde(skip_serializing_if = "Option::is_none")] - pub withdrawn_year: Option, - - #[serde(rename = "ext_ids")] - pub ext_ids: models::ReleaseExtIds, - - /// Volume number of container that this release was published in. Often corresponds to the \"Nth\" year of publication, but can be any string. See guide. - #[serde(rename = "volume")] - #[serde(skip_serializing_if = "Option::is_none")] - pub volume: Option, - - /// Issue number of volume/container that this release was published in. Sometimes coresponds to a month number in the year, but can be any string. See guide. - #[serde(rename = "issue")] - #[serde(skip_serializing_if = "Option::is_none")] - pub issue: Option, - - /// Either a single page number (\"first page\") or a range of pages separated by a dash (\"-\"). See guide for details. - #[serde(rename = "pages")] - #[serde(skip_serializing_if = "Option::is_none")] - pub pages: Option, - - /// For, eg, technical reports, which are published in series or assigned some other institutional or container-specific identifier. - #[serde(rename = "number")] - #[serde(skip_serializing_if = "Option::is_none")] - pub number: Option, - - /// For, eg, updated technical reports or software packages, where the version string may be the only field disambiguating between releases. - #[serde(rename = "version")] - #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, - - /// Name, usually English, of the entity or institution responsible for publication of this release. Not necessarily the imprint/brand. See guide. - #[serde(rename = "publisher")] - #[serde(skip_serializing_if = "Option::is_none")] - pub publisher: Option, - - /// Primary language of the content of the full release. Two-letter RFC1766/ISO639-1 language code, with some custom extensions/additions. See guide. - #[serde(rename = "language")] - #[serde(skip_serializing_if = "Option::is_none")] - pub language: Option, - - /// Short string (slug) name of license under which release is openly published (if applicable). - #[serde(rename = "license_slug")] - #[serde(skip_serializing_if = "Option::is_none")] - pub license_slug: Option, - - #[serde(rename = "contribs")] - #[serde(skip_serializing_if = "Option::is_none")] - pub contribs: Option>, - - #[serde(rename = "refs")] - #[serde(skip_serializing_if = "Option::is_none")] - pub refs: Option>, - - #[serde(rename = "abstracts")] - #[serde(skip_serializing_if = "Option::is_none")] - pub abstracts: Option>, -} - -impl ReleaseEntity { - pub fn new(ext_ids: models::ReleaseExtIds) -> ReleaseEntity { - ReleaseEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - title: None, - subtitle: None, - original_title: None, - work_id: None, - container: None, - files: None, - filesets: None, - webcaptures: None, - container_id: None, - release_type: None, - release_stage: None, - release_date: None, - release_year: None, - withdrawn_status: None, - withdrawn_date: None, - withdrawn_year: None, - ext_ids: ext_ids, - volume: None, - issue: None, - pages: None, - number: None, - version: None, - publisher: None, - language: None, - license_slug: None, - contribs: None, - refs: None, - abstracts: None, - } - } -} - -/// Converts the ReleaseEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - if let Some(ref title) = self.title { - params.push("title".to_string()); - params.push(title.to_string()); - } - - if let Some(ref subtitle) = self.subtitle { - params.push("subtitle".to_string()); - params.push(subtitle.to_string()); - } - - if let Some(ref original_title) = self.original_title { - params.push("original_title".to_string()); - params.push(original_title.to_string()); - } - - if let Some(ref work_id) = self.work_id { - params.push("work_id".to_string()); - params.push(work_id.to_string()); - } - - // Skipping container in query parameter serialization - - // Skipping files in query parameter serialization - - // Skipping filesets in query parameter serialization - - // Skipping webcaptures in query parameter serialization - - if let Some(ref container_id) = self.container_id { - params.push("container_id".to_string()); - params.push(container_id.to_string()); - } - - if let Some(ref release_type) = self.release_type { - params.push("release_type".to_string()); - params.push(release_type.to_string()); - } - - if let Some(ref release_stage) = self.release_stage { - params.push("release_stage".to_string()); - params.push(release_stage.to_string()); - } - - // Skipping release_date in query parameter serialization - - if let Some(ref release_year) = self.release_year { - params.push("release_year".to_string()); - params.push(release_year.to_string()); - } - - if let Some(ref withdrawn_status) = self.withdrawn_status { - params.push("withdrawn_status".to_string()); - params.push(withdrawn_status.to_string()); - } - - // Skipping withdrawn_date in query parameter serialization - - if let Some(ref withdrawn_year) = self.withdrawn_year { - params.push("withdrawn_year".to_string()); - params.push(withdrawn_year.to_string()); - } - - // Skipping ext_ids in query parameter serialization - - if let Some(ref volume) = self.volume { - params.push("volume".to_string()); - params.push(volume.to_string()); - } - - if let Some(ref issue) = self.issue { - params.push("issue".to_string()); - params.push(issue.to_string()); - } - - if let Some(ref pages) = self.pages { - params.push("pages".to_string()); - params.push(pages.to_string()); - } - - if let Some(ref number) = self.number { - params.push("number".to_string()); - params.push(number.to_string()); - } - - if let Some(ref version) = self.version { - params.push("version".to_string()); - params.push(version.to_string()); - } - - if let Some(ref publisher) = self.publisher { - params.push("publisher".to_string()); - params.push(publisher.to_string()); - } - - if let Some(ref language) = self.language { - params.push("language".to_string()); - params.push(language.to_string()); - } - - if let Some(ref license_slug) = self.license_slug { - params.push("license_slug".to_string()); - params.push(license_slug.to_string()); - } - - // Skipping contribs in query parameter serialization - - // Skipping refs in query parameter serialization - - // Skipping abstracts in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub title: Vec, - pub subtitle: Vec, - pub original_title: Vec, - pub work_id: Vec, - pub container: Vec, - pub files: Vec>, - pub filesets: Vec>, - pub webcaptures: Vec>, - pub container_id: Vec, - pub release_type: Vec, - pub release_stage: Vec, - pub release_date: Vec, - pub release_year: Vec, - pub withdrawn_status: Vec, - pub withdrawn_date: Vec, - pub withdrawn_year: Vec, - pub ext_ids: Vec, - pub volume: Vec, - pub issue: Vec, - pub pages: Vec, - pub number: Vec, - pub version: Vec, - pub publisher: Vec, - pub language: Vec, - pub license_slug: Vec, - pub contribs: Vec>, - pub refs: Vec>, - pub abstracts: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "title" => intermediate_rep - .title - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "subtitle" => intermediate_rep - .subtitle - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "original_title" => intermediate_rep - .original_title - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "work_id" => intermediate_rep - .work_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "container" => intermediate_rep.container.push( - models::ContainerEntity::from_str(val).map_err(|x| format!("{}", x))?, - ), - "files" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "filesets" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "webcaptures" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "container_id" => intermediate_rep - .container_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "release_type" => intermediate_rep - .release_type - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "release_stage" => intermediate_rep - .release_stage - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "release_date" => intermediate_rep - .release_date - .push(chrono::NaiveDate::from_str(val).map_err(|x| format!("{}", x))?), - "release_year" => intermediate_rep - .release_year - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "withdrawn_status" => intermediate_rep - .withdrawn_status - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "withdrawn_date" => intermediate_rep - .withdrawn_date - .push(chrono::NaiveDate::from_str(val).map_err(|x| format!("{}", x))?), - "withdrawn_year" => intermediate_rep - .withdrawn_year - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "ext_ids" => intermediate_rep - .ext_ids - .push(models::ReleaseExtIds::from_str(val).map_err(|x| format!("{}", x))?), - "volume" => intermediate_rep - .volume - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "issue" => intermediate_rep - .issue - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "pages" => intermediate_rep - .pages - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "number" => intermediate_rep - .number - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "version" => intermediate_rep - .version - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "publisher" => intermediate_rep - .publisher - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "language" => intermediate_rep - .language - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "license_slug" => intermediate_rep - .license_slug - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "contribs" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "refs" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - "abstracts" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseEntity" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - title: intermediate_rep.title.into_iter().next(), - subtitle: intermediate_rep.subtitle.into_iter().next(), - original_title: intermediate_rep.original_title.into_iter().next(), - work_id: intermediate_rep.work_id.into_iter().next(), - container: intermediate_rep.container.into_iter().next(), - files: intermediate_rep.files.into_iter().next(), - filesets: intermediate_rep.filesets.into_iter().next(), - webcaptures: intermediate_rep.webcaptures.into_iter().next(), - container_id: intermediate_rep.container_id.into_iter().next(), - release_type: intermediate_rep.release_type.into_iter().next(), - release_stage: intermediate_rep.release_stage.into_iter().next(), - release_date: intermediate_rep.release_date.into_iter().next(), - release_year: intermediate_rep.release_year.into_iter().next(), - withdrawn_status: intermediate_rep.withdrawn_status.into_iter().next(), - withdrawn_date: intermediate_rep.withdrawn_date.into_iter().next(), - withdrawn_year: intermediate_rep.withdrawn_year.into_iter().next(), - ext_ids: intermediate_rep - .ext_ids - .into_iter() - .next() - .ok_or("ext_ids missing in ReleaseEntity".to_string())?, - volume: intermediate_rep.volume.into_iter().next(), - issue: intermediate_rep.issue.into_iter().next(), - pages: intermediate_rep.pages.into_iter().next(), - number: intermediate_rep.number.into_iter().next(), - version: intermediate_rep.version.into_iter().next(), - publisher: intermediate_rep.publisher.into_iter().next(), - language: intermediate_rep.language.into_iter().next(), - license_slug: intermediate_rep.license_slug.into_iter().next(), - contribs: intermediate_rep.contribs.into_iter().next(), - refs: intermediate_rep.refs.into_iter().next(), - abstracts: intermediate_rep.abstracts.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseExtIds - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseExtIds - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseExtIds { - /// Digital Object Identifier (DOI), mostly for published papers and datasets. Should be registered and resolvable via https://doi.org/ - #[serde(rename = "doi")] - #[serde(skip_serializing_if = "Option::is_none")] - pub doi: Option, - - /// Wikidata entity QID - #[serde(rename = "wikidata_qid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub wikidata_qid: Option, - - /// ISBN-13, for books. Usually not set for chapters. ISBN-10 should be converted to ISBN-13. - #[serde(rename = "isbn13")] - #[serde(skip_serializing_if = "Option::is_none")] - pub isbn13: Option, - - /// PubMed Identifier - #[serde(rename = "pmid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub pmid: Option, - - /// PubMed Central Identifier - #[serde(rename = "pmcid")] - #[serde(skip_serializing_if = "Option::is_none")] - pub pmcid: Option, - - /// CORE (https://core.ac.uk) identifier - #[serde(rename = "core")] - #[serde(skip_serializing_if = "Option::is_none")] - pub core: Option, - - /// arXiv (https://arxiv.org) identifier; must include version - #[serde(rename = "arxiv")] - #[serde(skip_serializing_if = "Option::is_none")] - pub arxiv: Option, - - /// JSTOR work identifier - #[serde(rename = "jstor")] - #[serde(skip_serializing_if = "Option::is_none")] - pub jstor: Option, - - /// ARK identifier - #[serde(rename = "ark")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ark: Option, - - /// Microsoft Academic Graph identifier - #[serde(rename = "mag")] - #[serde(skip_serializing_if = "Option::is_none")] - pub mag: Option, - - /// DOAJ article-level identifier - #[serde(rename = "doaj")] - #[serde(skip_serializing_if = "Option::is_none")] - pub doaj: Option, - - /// dblp (https://dblp.uni-trier.de/) paper identifier; eg for conference proceedings - #[serde(rename = "dblp")] - #[serde(skip_serializing_if = "Option::is_none")] - pub dblp: Option, - - /// OAI-PMH identifier; only used when an OAI-PMH record is the only authoritative metadata (eg, journal OAI-PMH feeds w/o DOIs) - #[serde(rename = "oai")] - #[serde(skip_serializing_if = "Option::is_none")] - pub oai: Option, -} - -impl ReleaseExtIds { - pub fn new() -> ReleaseExtIds { - ReleaseExtIds { - doi: None, - wikidata_qid: None, - isbn13: None, - pmid: None, - pmcid: None, - core: None, - arxiv: None, - jstor: None, - ark: None, - mag: None, - doaj: None, - dblp: None, - oai: None, - } - } -} - -/// Converts the ReleaseExtIds value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseExtIds { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref doi) = self.doi { - params.push("doi".to_string()); - params.push(doi.to_string()); - } - - if let Some(ref wikidata_qid) = self.wikidata_qid { - params.push("wikidata_qid".to_string()); - params.push(wikidata_qid.to_string()); - } - - if let Some(ref isbn13) = self.isbn13 { - params.push("isbn13".to_string()); - params.push(isbn13.to_string()); - } - - if let Some(ref pmid) = self.pmid { - params.push("pmid".to_string()); - params.push(pmid.to_string()); - } - - if let Some(ref pmcid) = self.pmcid { - params.push("pmcid".to_string()); - params.push(pmcid.to_string()); - } - - if let Some(ref core) = self.core { - params.push("core".to_string()); - params.push(core.to_string()); - } - - if let Some(ref arxiv) = self.arxiv { - params.push("arxiv".to_string()); - params.push(arxiv.to_string()); - } - - if let Some(ref jstor) = self.jstor { - params.push("jstor".to_string()); - params.push(jstor.to_string()); - } - - if let Some(ref ark) = self.ark { - params.push("ark".to_string()); - params.push(ark.to_string()); - } - - if let Some(ref mag) = self.mag { - params.push("mag".to_string()); - params.push(mag.to_string()); - } - - if let Some(ref doaj) = self.doaj { - params.push("doaj".to_string()); - params.push(doaj.to_string()); - } - - if let Some(ref dblp) = self.dblp { - params.push("dblp".to_string()); - params.push(dblp.to_string()); - } - - if let Some(ref oai) = self.oai { - params.push("oai".to_string()); - params.push(oai.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseExtIds value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseExtIds { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub doi: Vec, - pub wikidata_qid: Vec, - pub isbn13: Vec, - pub pmid: Vec, - pub pmcid: Vec, - pub core: Vec, - pub arxiv: Vec, - pub jstor: Vec, - pub ark: Vec, - pub mag: Vec, - pub doaj: Vec, - pub dblp: Vec, - pub oai: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseExtIds".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "doi" => intermediate_rep - .doi - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "wikidata_qid" => intermediate_rep - .wikidata_qid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "isbn13" => intermediate_rep - .isbn13 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "pmid" => intermediate_rep - .pmid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "pmcid" => intermediate_rep - .pmcid - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "core" => intermediate_rep - .core - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "arxiv" => intermediate_rep - .arxiv - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "jstor" => intermediate_rep - .jstor - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ark" => intermediate_rep - .ark - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "mag" => intermediate_rep - .mag - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "doaj" => intermediate_rep - .doaj - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "dblp" => intermediate_rep - .dblp - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "oai" => intermediate_rep - .oai - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseExtIds".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseExtIds { - doi: intermediate_rep.doi.into_iter().next(), - wikidata_qid: intermediate_rep.wikidata_qid.into_iter().next(), - isbn13: intermediate_rep.isbn13.into_iter().next(), - pmid: intermediate_rep.pmid.into_iter().next(), - pmcid: intermediate_rep.pmcid.into_iter().next(), - core: intermediate_rep.core.into_iter().next(), - arxiv: intermediate_rep.arxiv.into_iter().next(), - jstor: intermediate_rep.jstor.into_iter().next(), - ark: intermediate_rep.ark.into_iter().next(), - mag: intermediate_rep.mag.into_iter().next(), - doaj: intermediate_rep.doaj.into_iter().next(), - dblp: intermediate_rep.dblp.into_iter().next(), - oai: intermediate_rep.oai.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for ReleaseRef - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into ReleaseRef - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ReleaseRef { - /// Zero-indexed sequence number of this reference in the list of references. Assigned automatically and used internally; don't confuse with `key`. - #[serde(rename = "index")] - #[serde(skip_serializing_if = "Option::is_none")] - pub index: Option, - - /// Optional, fatcat identifier of release entity that this reference is citing. - #[serde(rename = "target_release_id")] - #[serde(skip_serializing_if = "Option::is_none")] - pub target_release_id: Option, - - /// Additional free-form JSON metadata about this citation. Generally follows Citation Style Language (CSL) JSON schema. See guide for details. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Short string used to indicate this reference from within the release text; or numbering of references as typeset in the release itself. Optional; don't confuse with `index` field. - #[serde(rename = "key")] - #[serde(skip_serializing_if = "Option::is_none")] - pub key: Option, - - /// Year that the cited work was published in. - #[serde(rename = "year")] - #[serde(skip_serializing_if = "Option::is_none")] - pub year: Option, - - /// Name of the container (eg, journal) that the citation work was published as part of. May be an acronym or full name. - #[serde(rename = "container_name")] - #[serde(skip_serializing_if = "Option::is_none")] - pub container_name: Option, - - /// Name of the work being cited. - #[serde(rename = "title")] - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - - /// Page number or other indicator of the specific subset of a work being cited. Not to be confused with the first page (or page range) of an entire paper or chapter being cited. - #[serde(rename = "locator")] - #[serde(skip_serializing_if = "Option::is_none")] - pub locator: Option, -} - -impl ReleaseRef { - pub fn new() -> ReleaseRef { - ReleaseRef { - index: None, - target_release_id: None, - extra: None, - key: None, - year: None, - container_name: None, - title: None, - locator: None, - } - } -} - -/// Converts the ReleaseRef value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ReleaseRef { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref index) = self.index { - params.push("index".to_string()); - params.push(index.to_string()); - } - - if let Some(ref target_release_id) = self.target_release_id { - params.push("target_release_id".to_string()); - params.push(target_release_id.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - if let Some(ref key) = self.key { - params.push("key".to_string()); - params.push(key.to_string()); - } - - if let Some(ref year) = self.year { - params.push("year".to_string()); - params.push(year.to_string()); - } - - if let Some(ref container_name) = self.container_name { - params.push("container_name".to_string()); - params.push(container_name.to_string()); - } - - if let Some(ref title) = self.title { - params.push("title".to_string()); - params.push(title.to_string()); - } - - if let Some(ref locator) = self.locator { - params.push("locator".to_string()); - params.push(locator.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ReleaseRef value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ReleaseRef { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub index: Vec, - pub target_release_id: Vec, - pub extra: Vec>, - pub key: Vec, - pub year: Vec, - pub container_name: Vec, - pub title: Vec, - pub locator: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing ReleaseRef".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "index" => intermediate_rep - .index - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "target_release_id" => intermediate_rep - .target_release_id - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in ReleaseRef" - .to_string(), - ) - } - "key" => intermediate_rep - .key - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "year" => intermediate_rep - .year - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "container_name" => intermediate_rep - .container_name - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "title" => intermediate_rep - .title - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "locator" => intermediate_rep - .locator - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing ReleaseRef".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ReleaseRef { - index: intermediate_rep.index.into_iter().next(), - target_release_id: intermediate_rep.target_release_id.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - key: intermediate_rep.key.into_iter().next(), - year: intermediate_rep.year.into_iter().next(), - container_name: intermediate_rep.container_name.into_iter().next(), - title: intermediate_rep.title.into_iter().next(), - locator: intermediate_rep.locator.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for Success - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into Success - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct Success { - #[serde(rename = "success")] - pub success: bool, - - #[serde(rename = "message")] - pub message: String, -} - -impl Success { - pub fn new(success: bool, message: String) -> Success { - Success { - success: success, - message: message, - } - } -} - -/// Converts the Success value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for Success { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("success".to_string()); - params.push(self.success.to_string()); - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a Success value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for Success { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub success: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing Success".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "success" => intermediate_rep - .success - .push(bool::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep - .message - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing Success".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(Success { - success: intermediate_rep - .success - .into_iter() - .next() - .ok_or("success missing in Success".to_string())?, - message: intermediate_rep - .message - .into_iter() - .next() - .ok_or("message missing in Success".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WebcaptureAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WebcaptureAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WebcaptureAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl WebcaptureAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> WebcaptureAutoBatch { - WebcaptureAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the WebcaptureAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WebcaptureAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WebcaptureAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WebcaptureAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WebcaptureAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureAutoBatch" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WebcaptureAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WebcaptureAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in WebcaptureAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in WebcaptureAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WebcaptureCdxLine - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WebcaptureCdxLine - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WebcaptureCdxLine { - /// \"Sortable URL\" format. See guide for details. - #[serde(rename = "surt")] - pub surt: String, - - /// Date and time of capture, in ISO format. UTC, 'Z'-terminated, second (or better) precision. - #[serde(rename = "timestamp")] - pub timestamp: chrono::DateTime, - - /// Full URL/URI of resource captured. - #[serde(rename = "url")] - pub url: String, - - /// Mimetype of the resource at this URL. May be the Content-Type header, or the actually sniffed file type. - #[serde(rename = "mimetype")] - #[serde(skip_serializing_if = "Option::is_none")] - pub mimetype: Option, - - /// HTTP status code. Should generally be 200, especially for the primary resource, but may be 3xx (redirect) or even error codes if embedded resources can not be fetched successfully. - #[serde(rename = "status_code")] - #[serde(skip_serializing_if = "Option::is_none")] - pub status_code: Option, - - /// Resource (file) size in bytes - #[serde(rename = "size")] - #[serde(skip_serializing_if = "Option::is_none")] - pub size: Option, - - /// SHA-1 hash of data, in hex encoding - #[serde(rename = "sha1")] - pub sha1: String, - - /// SHA-256 hash of data, in hex encoding - #[serde(rename = "sha256")] - #[serde(skip_serializing_if = "Option::is_none")] - pub sha256: Option, -} - -impl WebcaptureCdxLine { - pub fn new( - surt: String, - timestamp: chrono::DateTime, - url: String, - sha1: String, - ) -> WebcaptureCdxLine { - WebcaptureCdxLine { - surt: surt, - timestamp: timestamp, - url: url, - mimetype: None, - status_code: None, - size: None, - sha1: sha1, - sha256: None, - } - } -} - -/// Converts the WebcaptureCdxLine value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WebcaptureCdxLine { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("surt".to_string()); - params.push(self.surt.to_string()); - - // Skipping timestamp in query parameter serialization - - params.push("url".to_string()); - params.push(self.url.to_string()); - - if let Some(ref mimetype) = self.mimetype { - params.push("mimetype".to_string()); - params.push(mimetype.to_string()); - } - - if let Some(ref status_code) = self.status_code { - params.push("status_code".to_string()); - params.push(status_code.to_string()); - } - - if let Some(ref size) = self.size { - params.push("size".to_string()); - params.push(size.to_string()); - } - - params.push("sha1".to_string()); - params.push(self.sha1.to_string()); - - if let Some(ref sha256) = self.sha256 { - params.push("sha256".to_string()); - params.push(sha256.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WebcaptureCdxLine value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WebcaptureCdxLine { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub surt: Vec, - pub timestamp: Vec>, - pub url: Vec, - pub mimetype: Vec, - pub status_code: Vec, - pub size: Vec, - pub sha1: Vec, - pub sha256: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WebcaptureCdxLine".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "surt" => intermediate_rep - .surt - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "timestamp" => intermediate_rep.timestamp.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "url" => intermediate_rep - .url - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "mimetype" => intermediate_rep - .mimetype - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "status_code" => intermediate_rep - .status_code - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "size" => intermediate_rep - .size - .push(i64::from_str(val).map_err(|x| format!("{}", x))?), - "sha1" => intermediate_rep - .sha1 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "sha256" => intermediate_rep - .sha256 - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WebcaptureCdxLine".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WebcaptureCdxLine { - surt: intermediate_rep - .surt - .into_iter() - .next() - .ok_or("surt missing in WebcaptureCdxLine".to_string())?, - timestamp: intermediate_rep - .timestamp - .into_iter() - .next() - .ok_or("timestamp missing in WebcaptureCdxLine".to_string())?, - url: intermediate_rep - .url - .into_iter() - .next() - .ok_or("url missing in WebcaptureCdxLine".to_string())?, - mimetype: intermediate_rep.mimetype.into_iter().next(), - status_code: intermediate_rep.status_code.into_iter().next(), - size: intermediate_rep.size.into_iter().next(), - sha1: intermediate_rep - .sha1 - .into_iter() - .next() - .ok_or("sha1 missing in WebcaptureCdxLine".to_string())?, - sha256: intermediate_rep.sha256.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> - for hyper::header::HeaderValue -{ - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WebcaptureEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom - for header::IntoHeaderValue -{ - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WebcaptureEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WebcaptureEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, - - #[serde(rename = "cdx")] - #[serde(skip_serializing_if = "Option::is_none")] - pub cdx: Option>, - - #[serde(rename = "archive_urls")] - #[serde(skip_serializing_if = "Option::is_none")] - pub archive_urls: Option>, - - /// Base URL of the primary resource this is a capture of - #[serde(rename = "original_url")] - #[serde(skip_serializing_if = "Option::is_none")] - pub original_url: Option, - - /// Same format as CDX line timestamp (UTC, etc). Corresponds to the overall capture timestamp. Should generally be the timestamp of capture of the primary resource URL. - #[serde(rename = "timestamp")] - #[serde(skip_serializing_if = "Option::is_none")] - pub timestamp: Option>, - - /// Set of identifier of release entities this fileset represents a full manifestation of. Usually a single release. - #[serde(rename = "release_ids")] - #[serde(skip_serializing_if = "Option::is_none")] - pub release_ids: Option>, - - /// Full release entities, included in GET responses when `releases` included in `expand` parameter. Ignored if included in PUT or POST requests. - #[serde(rename = "releases")] - #[serde(skip_serializing_if = "Option::is_none")] - pub releases: Option>, -} - -impl WebcaptureEntity { - pub fn new() -> WebcaptureEntity { - WebcaptureEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - cdx: None, - archive_urls: None, - original_url: None, - timestamp: None, - release_ids: None, - releases: None, - } - } -} - -/// Converts the WebcaptureEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WebcaptureEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - // Skipping cdx in query parameter serialization - - // Skipping archive_urls in query parameter serialization - - if let Some(ref original_url) = self.original_url { - params.push("original_url".to_string()); - params.push(original_url.to_string()); - } - - // Skipping timestamp in query parameter serialization - - if let Some(ref release_ids) = self.release_ids { - params.push("release_ids".to_string()); - params.push( - release_ids - .iter() - .map(|x| x.to_string()) - .collect::>() - .join(",") - .to_string(), - ); - } - - // Skipping releases in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WebcaptureEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WebcaptureEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - pub cdx: Vec>, - pub archive_urls: Vec>, - pub original_url: Vec, - pub timestamp: Vec>, - pub release_ids: Vec>, - pub releases: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WebcaptureEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - "edit_extra" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - "cdx" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - "archive_urls" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - "original_url" => intermediate_rep - .original_url - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "timestamp" => intermediate_rep.timestamp.push( - chrono::DateTime::::from_str(val) - .map_err(|x| format!("{}", x))?, - ), - "release_ids" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - "releases" => return std::result::Result::Err( - "Parsing a container in this style is not supported in WebcaptureEntity" - .to_string(), - ), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WebcaptureEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WebcaptureEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - cdx: intermediate_rep.cdx.into_iter().next(), - archive_urls: intermediate_rep.archive_urls.into_iter().next(), - original_url: intermediate_rep.original_url.into_iter().next(), - timestamp: intermediate_rep.timestamp.into_iter().next(), - release_ids: intermediate_rep.release_ids.into_iter().next(), - releases: intermediate_rep.releases.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WebcaptureUrl - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WebcaptureUrl - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WebcaptureUrl { - /// URL/URI pointing to archive of this web resource. - #[serde(rename = "url")] - pub url: String, - - /// Type of archive endpoint. Usually `wayback` (WBM replay of primary resource), or `warc` (direct URL to a WARC file containing all resources of the capture). See guide for full list. - #[serde(rename = "rel")] - pub rel: String, -} - -impl WebcaptureUrl { - pub fn new(url: String, rel: String) -> WebcaptureUrl { - WebcaptureUrl { url: url, rel: rel } - } -} - -/// Converts the WebcaptureUrl value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WebcaptureUrl { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("url".to_string()); - params.push(self.url.to_string()); - - params.push("rel".to_string()); - params.push(self.rel.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WebcaptureUrl value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WebcaptureUrl { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub url: Vec, - pub rel: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WebcaptureUrl".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "url" => intermediate_rep - .url - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "rel" => intermediate_rep - .rel - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WebcaptureUrl".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WebcaptureUrl { - url: intermediate_rep - .url - .into_iter() - .next() - .ok_or("url missing in WebcaptureUrl".to_string())?, - rel: intermediate_rep - .rel - .into_iter() - .next() - .ok_or("rel missing in WebcaptureUrl".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WorkAutoBatch - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WorkAutoBatch - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WorkAutoBatch { - #[serde(rename = "editgroup")] - pub editgroup: models::Editgroup, - - #[serde(rename = "entity_list")] - pub entity_list: Vec, -} - -impl WorkAutoBatch { - pub fn new( - editgroup: models::Editgroup, - entity_list: Vec, - ) -> WorkAutoBatch { - WorkAutoBatch { - editgroup: editgroup, - entity_list: entity_list, - } - } -} - -/// Converts the WorkAutoBatch value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WorkAutoBatch { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping editgroup in query parameter serialization - - // Skipping entity_list in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WorkAutoBatch value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WorkAutoBatch { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub editgroup: Vec, - pub entity_list: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WorkAutoBatch".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "editgroup" => intermediate_rep - .editgroup - .push(models::Editgroup::from_str(val).map_err(|x| format!("{}", x))?), - "entity_list" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in WorkAutoBatch" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WorkAutoBatch".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WorkAutoBatch { - editgroup: intermediate_rep - .editgroup - .into_iter() - .next() - .ok_or("editgroup missing in WorkAutoBatch".to_string())?, - entity_list: intermediate_rep - .entity_list - .into_iter() - .next() - .ok_or("entity_list missing in WorkAutoBatch".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from( - hdr_value: header::IntoHeaderValue, - ) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Invalid header value for WorkEntity - value: {} is invalid {}", - hdr_value, e - )), - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => { - std::result::Result::Ok(header::IntoHeaderValue(value)) - } - std::result::Result::Err(err) => std::result::Result::Err(format!( - "Unable to convert header value '{}' into WorkEntity - {}", - value, err - )), - } - } - std::result::Result::Err(e) => std::result::Result::Err(format!( - "Unable to convert header: {:?} to string: {}", - hdr_value, e - )), - } - } -} - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct WorkEntity { - // Note: inline enums are not fully supported by openapi-generator - #[serde(rename = "state")] - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// base32-encoded unique identifier - #[serde(rename = "ident")] - #[serde(skip_serializing_if = "Option::is_none")] - pub ident: Option, - - /// UUID (lower-case, dash-separated, hex-encoded 128-bit) - #[serde(rename = "revision")] - #[serde(skip_serializing_if = "Option::is_none")] - pub revision: Option, - - /// base32-encoded unique identifier - #[serde(rename = "redirect")] - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Free-form JSON metadata that will be stored with the other entity metadata. See guide for (unenforced) schema conventions. - #[serde(rename = "extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option>, - - /// Free-form JSON metadata that will be stored with specific entity edits (eg, creation/update/delete). - #[serde(rename = "edit_extra")] - #[serde(skip_serializing_if = "Option::is_none")] - pub edit_extra: Option>, -} - -impl WorkEntity { - pub fn new() -> WorkEntity { - WorkEntity { - state: None, - ident: None, - revision: None, - redirect: None, - extra: None, - edit_extra: None, - } - } -} - -/// Converts the WorkEntity value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for WorkEntity { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref state) = self.state { - params.push("state".to_string()); - params.push(state.to_string()); - } - - if let Some(ref ident) = self.ident { - params.push("ident".to_string()); - params.push(ident.to_string()); - } - - if let Some(ref revision) = self.revision { - params.push("revision".to_string()); - params.push(revision.to_string()); - } - - if let Some(ref redirect) = self.redirect { - params.push("redirect".to_string()); - params.push(redirect.to_string()); - } - - // Skipping extra in query parameter serialization - // Skipping extra in query parameter serialization - - // Skipping edit_extra in query parameter serialization - // Skipping edit_extra in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a WorkEntity value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for WorkEntity { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub state: Vec, - pub ident: Vec, - pub revision: Vec, - pub redirect: Vec, - pub extra: Vec>, - pub edit_extra: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => { - return std::result::Result::Err( - "Missing value while parsing WorkEntity".to_string(), - ) - } - }; - - if let Some(key) = key_result { - match key { - "state" => intermediate_rep - .state - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "ident" => intermediate_rep - .ident - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "revision" => intermediate_rep - .revision - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "redirect" => intermediate_rep - .redirect - .push(String::from_str(val).map_err(|x| format!("{}", x))?), - "extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in WorkEntity" - .to_string(), - ) - } - "edit_extra" => { - return std::result::Result::Err( - "Parsing a container in this style is not supported in WorkEntity" - .to_string(), - ) - } - _ => { - return std::result::Result::Err( - "Unexpected key while parsing WorkEntity".to_string(), - ) - } - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(WorkEntity { - state: intermediate_rep.state.into_iter().next(), - ident: intermediate_rep.ident.into_iter().next(), - revision: intermediate_rep.revision.into_iter().next(), - redirect: intermediate_rep.redirect.into_iter().next(), - extra: intermediate_rep.extra.into_iter().next(), - edit_extra: intermediate_rep.edit_extra.into_iter().next(), - }) - } -} diff --git a/rust/fatcat-openapi/src/server/mod.rs b/rust/fatcat-openapi/src/server/mod.rs deleted file mode 100644 index ac07c6e..0000000 --- a/rust/fatcat-openapi/src/server/mod.rs +++ /dev/null @@ -1,15856 +0,0 @@ -use futures::{future, future::BoxFuture, future::FutureExt, stream, stream::TryStreamExt, Stream}; -use hyper::header::{HeaderName, HeaderValue, CONTENT_TYPE}; -use hyper::{Body, HeaderMap, Request, Response, StatusCode}; -use log::warn; -#[allow(unused_imports)] -use std::convert::{TryFrom, TryInto}; -use std::error::Error; -use std::future::Future; -use std::marker::PhantomData; -use std::task::{Context, Poll}; -pub use swagger::auth::Authorization; -use swagger::auth::Scopes; -use swagger::{ApiError, BodyExt, Has, RequestParser, XSpanIdString}; -use url::form_urlencoded; - -use crate::header; -#[allow(unused_imports)] -use crate::models; - -pub use crate::context; - -type ServiceFuture = BoxFuture<'static, Result, crate::ServiceError>>; - -use crate::{ - AcceptEditgroupResponse, Api, AuthCheckResponse, AuthOidcResponse, CreateAuthTokenResponse, - CreateContainerAutoBatchResponse, CreateContainerResponse, CreateCreatorAutoBatchResponse, - CreateCreatorResponse, CreateEditgroupAnnotationResponse, CreateEditgroupResponse, - CreateFileAutoBatchResponse, CreateFileResponse, CreateFilesetAutoBatchResponse, - CreateFilesetResponse, CreateReleaseAutoBatchResponse, CreateReleaseResponse, - CreateWebcaptureAutoBatchResponse, CreateWebcaptureResponse, CreateWorkAutoBatchResponse, - CreateWorkResponse, DeleteContainerEditResponse, DeleteContainerResponse, - DeleteCreatorEditResponse, DeleteCreatorResponse, DeleteFileEditResponse, DeleteFileResponse, - DeleteFilesetEditResponse, DeleteFilesetResponse, DeleteReleaseEditResponse, - DeleteReleaseResponse, DeleteWebcaptureEditResponse, DeleteWebcaptureResponse, - DeleteWorkEditResponse, DeleteWorkResponse, GetChangelogEntryResponse, GetChangelogResponse, - GetContainerEditResponse, GetContainerHistoryResponse, GetContainerRedirectsResponse, - GetContainerResponse, GetContainerRevisionResponse, GetCreatorEditResponse, - GetCreatorHistoryResponse, GetCreatorRedirectsResponse, GetCreatorReleasesResponse, - GetCreatorResponse, GetCreatorRevisionResponse, GetEditgroupAnnotationsResponse, - GetEditgroupResponse, GetEditgroupsReviewableResponse, GetEditorAnnotationsResponse, - GetEditorEditgroupsResponse, GetEditorResponse, GetFileEditResponse, GetFileHistoryResponse, - GetFileRedirectsResponse, GetFileResponse, GetFileRevisionResponse, GetFilesetEditResponse, - GetFilesetHistoryResponse, GetFilesetRedirectsResponse, GetFilesetResponse, - GetFilesetRevisionResponse, GetReleaseEditResponse, GetReleaseFilesResponse, - GetReleaseFilesetsResponse, GetReleaseHistoryResponse, GetReleaseRedirectsResponse, - GetReleaseResponse, GetReleaseRevisionResponse, GetReleaseWebcapturesResponse, - GetWebcaptureEditResponse, GetWebcaptureHistoryResponse, GetWebcaptureRedirectsResponse, - GetWebcaptureResponse, GetWebcaptureRevisionResponse, GetWorkEditResponse, - GetWorkHistoryResponse, GetWorkRedirectsResponse, GetWorkReleasesResponse, GetWorkResponse, - GetWorkRevisionResponse, LookupContainerResponse, LookupCreatorResponse, LookupFileResponse, - LookupReleaseResponse, UpdateContainerResponse, UpdateCreatorResponse, UpdateEditgroupResponse, - UpdateEditorResponse, UpdateFileResponse, UpdateFilesetResponse, UpdateReleaseResponse, - UpdateWebcaptureResponse, UpdateWorkResponse, -}; - -mod paths { - use lazy_static::lazy_static; - - lazy_static! { - pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![ - r"^/v0/auth/check$", - r"^/v0/auth/oidc$", - r"^/v0/auth/token/(?P[^/?#]*)$", - r"^/v0/changelog$", - r"^/v0/changelog/(?P[^/?#]*)$", - r"^/v0/container/edit/(?P[^/?#]*)$", - r"^/v0/container/lookup$", - r"^/v0/container/rev/(?P[^/?#]*)$", - r"^/v0/container/(?P[^/?#]*)$", - r"^/v0/container/(?P[^/?#]*)/history$", - r"^/v0/container/(?P[^/?#]*)/redirects$", - r"^/v0/creator/edit/(?P[^/?#]*)$", - r"^/v0/creator/lookup$", - r"^/v0/creator/rev/(?P[^/?#]*)$", - r"^/v0/creator/(?P[^/?#]*)$", - r"^/v0/creator/(?P[^/?#]*)/history$", - r"^/v0/creator/(?P[^/?#]*)/redirects$", - r"^/v0/creator/(?P[^/?#]*)/releases$", - r"^/v0/editgroup$", - r"^/v0/editgroup/auto/container/batch$", - r"^/v0/editgroup/auto/creator/batch$", - r"^/v0/editgroup/auto/file/batch$", - r"^/v0/editgroup/auto/fileset/batch$", - r"^/v0/editgroup/auto/release/batch$", - r"^/v0/editgroup/auto/webcapture/batch$", - r"^/v0/editgroup/auto/work/batch$", - r"^/v0/editgroup/reviewable$", - r"^/v0/editgroup/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/accept$", - r"^/v0/editgroup/(?P[^/?#]*)/annotation$", - r"^/v0/editgroup/(?P[^/?#]*)/annotations$", - r"^/v0/editgroup/(?P[^/?#]*)/container$", - r"^/v0/editgroup/(?P[^/?#]*)/container/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/container/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/creator$", - r"^/v0/editgroup/(?P[^/?#]*)/creator/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/creator/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/file$", - r"^/v0/editgroup/(?P[^/?#]*)/file/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/file/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/fileset$", - r"^/v0/editgroup/(?P[^/?#]*)/fileset/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/fileset/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/release$", - r"^/v0/editgroup/(?P[^/?#]*)/release/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/release/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/webcapture$", - r"^/v0/editgroup/(?P[^/?#]*)/webcapture/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/webcapture/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/work$", - r"^/v0/editgroup/(?P[^/?#]*)/work/edit/(?P[^/?#]*)$", - r"^/v0/editgroup/(?P[^/?#]*)/work/(?P[^/?#]*)$", - r"^/v0/editor/(?P[^/?#]*)$", - r"^/v0/editor/(?P[^/?#]*)/annotations$", - r"^/v0/editor/(?P[^/?#]*)/editgroups$", - r"^/v0/file/edit/(?P[^/?#]*)$", - r"^/v0/file/lookup$", - r"^/v0/file/rev/(?P[^/?#]*)$", - r"^/v0/file/(?P[^/?#]*)$", - r"^/v0/file/(?P[^/?#]*)/history$", - r"^/v0/file/(?P[^/?#]*)/redirects$", - r"^/v0/fileset/edit/(?P[^/?#]*)$", - r"^/v0/fileset/rev/(?P[^/?#]*)$", - r"^/v0/fileset/(?P[^/?#]*)$", - r"^/v0/fileset/(?P[^/?#]*)/history$", - r"^/v0/fileset/(?P[^/?#]*)/redirects$", - r"^/v0/release/edit/(?P[^/?#]*)$", - r"^/v0/release/lookup$", - r"^/v0/release/rev/(?P[^/?#]*)$", - r"^/v0/release/(?P[^/?#]*)$", - r"^/v0/release/(?P[^/?#]*)/files$", - r"^/v0/release/(?P[^/?#]*)/filesets$", - r"^/v0/release/(?P[^/?#]*)/history$", - r"^/v0/release/(?P[^/?#]*)/redirects$", - r"^/v0/release/(?P[^/?#]*)/webcaptures$", - r"^/v0/webcapture/edit/(?P[^/?#]*)$", - r"^/v0/webcapture/rev/(?P[^/?#]*)$", - r"^/v0/webcapture/(?P[^/?#]*)$", - r"^/v0/webcapture/(?P[^/?#]*)/history$", - r"^/v0/webcapture/(?P[^/?#]*)/redirects$", - r"^/v0/work/edit/(?P[^/?#]*)$", - r"^/v0/work/rev/(?P[^/?#]*)$", - r"^/v0/work/(?P[^/?#]*)$", - r"^/v0/work/(?P[^/?#]*)/history$", - r"^/v0/work/(?P[^/?#]*)/redirects$", - r"^/v0/work/(?P[^/?#]*)/releases$" - ]) - .expect("Unable to create global regex set"); - } - pub(crate) static ID_AUTH_CHECK: usize = 0; - pub(crate) static ID_AUTH_OIDC: usize = 1; - pub(crate) static ID_AUTH_TOKEN_EDITOR_ID: usize = 2; - lazy_static! { - pub static ref REGEX_AUTH_TOKEN_EDITOR_ID: regex::Regex = - regex::Regex::new(r"^/v0/auth/token/(?P[^/?#]*)$") - .expect("Unable to create regex for AUTH_TOKEN_EDITOR_ID"); - } - pub(crate) static ID_CHANGELOG: usize = 3; - pub(crate) static ID_CHANGELOG_INDEX: usize = 4; - lazy_static! { - pub static ref REGEX_CHANGELOG_INDEX: regex::Regex = - regex::Regex::new(r"^/v0/changelog/(?P[^/?#]*)$") - .expect("Unable to create regex for CHANGELOG_INDEX"); - } - pub(crate) static ID_CONTAINER_EDIT_EDIT_ID: usize = 5; - lazy_static! { - pub static ref REGEX_CONTAINER_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/container/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for CONTAINER_EDIT_EDIT_ID"); - } - pub(crate) static ID_CONTAINER_LOOKUP: usize = 6; - pub(crate) static ID_CONTAINER_REV_REV_ID: usize = 7; - lazy_static! { - pub static ref REGEX_CONTAINER_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/container/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for CONTAINER_REV_REV_ID"); - } - pub(crate) static ID_CONTAINER_IDENT: usize = 8; - lazy_static! { - pub static ref REGEX_CONTAINER_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/container/(?P[^/?#]*)$") - .expect("Unable to create regex for CONTAINER_IDENT"); - } - pub(crate) static ID_CONTAINER_IDENT_HISTORY: usize = 9; - lazy_static! { - pub static ref REGEX_CONTAINER_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/container/(?P[^/?#]*)/history$") - .expect("Unable to create regex for CONTAINER_IDENT_HISTORY"); - } - pub(crate) static ID_CONTAINER_IDENT_REDIRECTS: usize = 10; - lazy_static! { - pub static ref REGEX_CONTAINER_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/container/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for CONTAINER_IDENT_REDIRECTS"); - } - pub(crate) static ID_CREATOR_EDIT_EDIT_ID: usize = 11; - lazy_static! { - pub static ref REGEX_CREATOR_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/creator/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for CREATOR_EDIT_EDIT_ID"); - } - pub(crate) static ID_CREATOR_LOOKUP: usize = 12; - pub(crate) static ID_CREATOR_REV_REV_ID: usize = 13; - lazy_static! { - pub static ref REGEX_CREATOR_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/creator/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for CREATOR_REV_REV_ID"); - } - pub(crate) static ID_CREATOR_IDENT: usize = 14; - lazy_static! { - pub static ref REGEX_CREATOR_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/creator/(?P[^/?#]*)$") - .expect("Unable to create regex for CREATOR_IDENT"); - } - pub(crate) static ID_CREATOR_IDENT_HISTORY: usize = 15; - lazy_static! { - pub static ref REGEX_CREATOR_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/creator/(?P[^/?#]*)/history$") - .expect("Unable to create regex for CREATOR_IDENT_HISTORY"); - } - pub(crate) static ID_CREATOR_IDENT_REDIRECTS: usize = 16; - lazy_static! { - pub static ref REGEX_CREATOR_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/creator/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for CREATOR_IDENT_REDIRECTS"); - } - pub(crate) static ID_CREATOR_IDENT_RELEASES: usize = 17; - lazy_static! { - pub static ref REGEX_CREATOR_IDENT_RELEASES: regex::Regex = - regex::Regex::new(r"^/v0/creator/(?P[^/?#]*)/releases$") - .expect("Unable to create regex for CREATOR_IDENT_RELEASES"); - } - pub(crate) static ID_EDITGROUP: usize = 18; - pub(crate) static ID_EDITGROUP_AUTO_CONTAINER_BATCH: usize = 19; - pub(crate) static ID_EDITGROUP_AUTO_CREATOR_BATCH: usize = 20; - pub(crate) static ID_EDITGROUP_AUTO_FILE_BATCH: usize = 21; - pub(crate) static ID_EDITGROUP_AUTO_FILESET_BATCH: usize = 22; - pub(crate) static ID_EDITGROUP_AUTO_RELEASE_BATCH: usize = 23; - pub(crate) static ID_EDITGROUP_AUTO_WEBCAPTURE_BATCH: usize = 24; - pub(crate) static ID_EDITGROUP_AUTO_WORK_BATCH: usize = 25; - pub(crate) static ID_EDITGROUP_REVIEWABLE: usize = 26; - pub(crate) static ID_EDITGROUP_EDITGROUP_ID: usize = 27; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_ACCEPT: usize = 28; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_ACCEPT: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/accept$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_ACCEPT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_ANNOTATION: usize = 29; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATION: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/annotation$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_ANNOTATION"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_ANNOTATIONS: usize = 30; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATIONS: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/annotations$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_ANNOTATIONS"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CONTAINER: usize = 31; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/container$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CONTAINER"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID: usize = 32; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/container/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT: usize = 33; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/container/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CREATOR: usize = 34; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CREATOR: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/creator$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CREATOR"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID: usize = 35; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/creator/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT: usize = 36; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/creator/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_CREATOR_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILE: usize = 37; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILE: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/file$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILE"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID: usize = 38; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/file/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT: usize = 39; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILE_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/file/(?P[^/?#]*)$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILE_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILESET: usize = 40; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILESET: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/fileset$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILESET"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID: usize = 41; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/fileset/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT: usize = 42; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_FILESET_IDENT: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/fileset/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_FILESET_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_RELEASE: usize = 43; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_RELEASE: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/release$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_RELEASE"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID: usize = 44; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/release/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT: usize = 45; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/release/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_RELEASE_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE: usize = 46; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/webcapture$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WEBCAPTURE"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID: usize = 47; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/webcapture/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT: usize = 48; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/webcapture/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WORK: usize = 49; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WORK: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/work$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WORK"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID: usize = 50; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new( - r"^/v0/editgroup/(?P[^/?#]*)/work/edit/(?P[^/?#]*)$" - ) - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID"); - } - pub(crate) static ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT: usize = 51; - lazy_static! { - pub static ref REGEX_EDITGROUP_EDITGROUP_ID_WORK_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/editgroup/(?P[^/?#]*)/work/(?P[^/?#]*)$") - .expect("Unable to create regex for EDITGROUP_EDITGROUP_ID_WORK_IDENT"); - } - pub(crate) static ID_EDITOR_EDITOR_ID: usize = 52; - lazy_static! { - pub static ref REGEX_EDITOR_EDITOR_ID: regex::Regex = - regex::Regex::new(r"^/v0/editor/(?P[^/?#]*)$") - .expect("Unable to create regex for EDITOR_EDITOR_ID"); - } - pub(crate) static ID_EDITOR_EDITOR_ID_ANNOTATIONS: usize = 53; - lazy_static! { - pub static ref REGEX_EDITOR_EDITOR_ID_ANNOTATIONS: regex::Regex = - regex::Regex::new(r"^/v0/editor/(?P[^/?#]*)/annotations$") - .expect("Unable to create regex for EDITOR_EDITOR_ID_ANNOTATIONS"); - } - pub(crate) static ID_EDITOR_EDITOR_ID_EDITGROUPS: usize = 54; - lazy_static! { - pub static ref REGEX_EDITOR_EDITOR_ID_EDITGROUPS: regex::Regex = - regex::Regex::new(r"^/v0/editor/(?P[^/?#]*)/editgroups$") - .expect("Unable to create regex for EDITOR_EDITOR_ID_EDITGROUPS"); - } - pub(crate) static ID_FILE_EDIT_EDIT_ID: usize = 55; - lazy_static! { - pub static ref REGEX_FILE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/file/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for FILE_EDIT_EDIT_ID"); - } - pub(crate) static ID_FILE_LOOKUP: usize = 56; - pub(crate) static ID_FILE_REV_REV_ID: usize = 57; - lazy_static! { - pub static ref REGEX_FILE_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/file/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for FILE_REV_REV_ID"); - } - pub(crate) static ID_FILE_IDENT: usize = 58; - lazy_static! { - pub static ref REGEX_FILE_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/file/(?P[^/?#]*)$") - .expect("Unable to create regex for FILE_IDENT"); - } - pub(crate) static ID_FILE_IDENT_HISTORY: usize = 59; - lazy_static! { - pub static ref REGEX_FILE_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/file/(?P[^/?#]*)/history$") - .expect("Unable to create regex for FILE_IDENT_HISTORY"); - } - pub(crate) static ID_FILE_IDENT_REDIRECTS: usize = 60; - lazy_static! { - pub static ref REGEX_FILE_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/file/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for FILE_IDENT_REDIRECTS"); - } - pub(crate) static ID_FILESET_EDIT_EDIT_ID: usize = 61; - lazy_static! { - pub static ref REGEX_FILESET_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/fileset/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for FILESET_EDIT_EDIT_ID"); - } - pub(crate) static ID_FILESET_REV_REV_ID: usize = 62; - lazy_static! { - pub static ref REGEX_FILESET_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/fileset/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for FILESET_REV_REV_ID"); - } - pub(crate) static ID_FILESET_IDENT: usize = 63; - lazy_static! { - pub static ref REGEX_FILESET_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/fileset/(?P[^/?#]*)$") - .expect("Unable to create regex for FILESET_IDENT"); - } - pub(crate) static ID_FILESET_IDENT_HISTORY: usize = 64; - lazy_static! { - pub static ref REGEX_FILESET_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/fileset/(?P[^/?#]*)/history$") - .expect("Unable to create regex for FILESET_IDENT_HISTORY"); - } - pub(crate) static ID_FILESET_IDENT_REDIRECTS: usize = 65; - lazy_static! { - pub static ref REGEX_FILESET_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/fileset/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for FILESET_IDENT_REDIRECTS"); - } - pub(crate) static ID_RELEASE_EDIT_EDIT_ID: usize = 66; - lazy_static! { - pub static ref REGEX_RELEASE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/release/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for RELEASE_EDIT_EDIT_ID"); - } - pub(crate) static ID_RELEASE_LOOKUP: usize = 67; - pub(crate) static ID_RELEASE_REV_REV_ID: usize = 68; - lazy_static! { - pub static ref REGEX_RELEASE_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/release/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for RELEASE_REV_REV_ID"); - } - pub(crate) static ID_RELEASE_IDENT: usize = 69; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)$") - .expect("Unable to create regex for RELEASE_IDENT"); - } - pub(crate) static ID_RELEASE_IDENT_FILES: usize = 70; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT_FILES: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)/files$") - .expect("Unable to create regex for RELEASE_IDENT_FILES"); - } - pub(crate) static ID_RELEASE_IDENT_FILESETS: usize = 71; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT_FILESETS: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)/filesets$") - .expect("Unable to create regex for RELEASE_IDENT_FILESETS"); - } - pub(crate) static ID_RELEASE_IDENT_HISTORY: usize = 72; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)/history$") - .expect("Unable to create regex for RELEASE_IDENT_HISTORY"); - } - pub(crate) static ID_RELEASE_IDENT_REDIRECTS: usize = 73; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for RELEASE_IDENT_REDIRECTS"); - } - pub(crate) static ID_RELEASE_IDENT_WEBCAPTURES: usize = 74; - lazy_static! { - pub static ref REGEX_RELEASE_IDENT_WEBCAPTURES: regex::Regex = - regex::Regex::new(r"^/v0/release/(?P[^/?#]*)/webcaptures$") - .expect("Unable to create regex for RELEASE_IDENT_WEBCAPTURES"); - } - pub(crate) static ID_WEBCAPTURE_EDIT_EDIT_ID: usize = 75; - lazy_static! { - pub static ref REGEX_WEBCAPTURE_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/webcapture/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for WEBCAPTURE_EDIT_EDIT_ID"); - } - pub(crate) static ID_WEBCAPTURE_REV_REV_ID: usize = 76; - lazy_static! { - pub static ref REGEX_WEBCAPTURE_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/webcapture/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for WEBCAPTURE_REV_REV_ID"); - } - pub(crate) static ID_WEBCAPTURE_IDENT: usize = 77; - lazy_static! { - pub static ref REGEX_WEBCAPTURE_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/webcapture/(?P[^/?#]*)$") - .expect("Unable to create regex for WEBCAPTURE_IDENT"); - } - pub(crate) static ID_WEBCAPTURE_IDENT_HISTORY: usize = 78; - lazy_static! { - pub static ref REGEX_WEBCAPTURE_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/webcapture/(?P[^/?#]*)/history$") - .expect("Unable to create regex for WEBCAPTURE_IDENT_HISTORY"); - } - pub(crate) static ID_WEBCAPTURE_IDENT_REDIRECTS: usize = 79; - lazy_static! { - pub static ref REGEX_WEBCAPTURE_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/webcapture/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for WEBCAPTURE_IDENT_REDIRECTS"); - } - pub(crate) static ID_WORK_EDIT_EDIT_ID: usize = 80; - lazy_static! { - pub static ref REGEX_WORK_EDIT_EDIT_ID: regex::Regex = - regex::Regex::new(r"^/v0/work/edit/(?P[^/?#]*)$") - .expect("Unable to create regex for WORK_EDIT_EDIT_ID"); - } - pub(crate) static ID_WORK_REV_REV_ID: usize = 81; - lazy_static! { - pub static ref REGEX_WORK_REV_REV_ID: regex::Regex = - regex::Regex::new(r"^/v0/work/rev/(?P[^/?#]*)$") - .expect("Unable to create regex for WORK_REV_REV_ID"); - } - pub(crate) static ID_WORK_IDENT: usize = 82; - lazy_static! { - pub static ref REGEX_WORK_IDENT: regex::Regex = - regex::Regex::new(r"^/v0/work/(?P[^/?#]*)$") - .expect("Unable to create regex for WORK_IDENT"); - } - pub(crate) static ID_WORK_IDENT_HISTORY: usize = 83; - lazy_static! { - pub static ref REGEX_WORK_IDENT_HISTORY: regex::Regex = - regex::Regex::new(r"^/v0/work/(?P[^/?#]*)/history$") - .expect("Unable to create regex for WORK_IDENT_HISTORY"); - } - pub(crate) static ID_WORK_IDENT_REDIRECTS: usize = 84; - lazy_static! { - pub static ref REGEX_WORK_IDENT_REDIRECTS: regex::Regex = - regex::Regex::new(r"^/v0/work/(?P[^/?#]*)/redirects$") - .expect("Unable to create regex for WORK_IDENT_REDIRECTS"); - } - pub(crate) static ID_WORK_IDENT_RELEASES: usize = 85; - lazy_static! { - pub static ref REGEX_WORK_IDENT_RELEASES: regex::Regex = - regex::Regex::new(r"^/v0/work/(?P[^/?#]*)/releases$") - .expect("Unable to create regex for WORK_IDENT_RELEASES"); - } -} - -pub struct MakeService -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - api_impl: T, - marker: PhantomData, -} - -impl MakeService -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - pub fn new(api_impl: T) -> Self { - MakeService { - api_impl, - marker: PhantomData, - } - } -} - -impl hyper::service::Service for MakeService -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - type Response = Service; - type Error = crate::ServiceError; - type Future = future::Ready>; - - fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { - Poll::Ready(Ok(())) - } - - fn call(&mut self, target: Target) -> Self::Future { - futures::future::ok(Service::new(self.api_impl.clone())) - } -} - -fn method_not_allowed() -> Result, crate::ServiceError> { - Ok(Response::builder() - .status(StatusCode::METHOD_NOT_ALLOWED) - .body(Body::empty()) - .expect("Unable to create Method Not Allowed response")) -} - -pub struct Service -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - api_impl: T, - marker: PhantomData, -} - -impl Service -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - pub fn new(api_impl: T) -> Self { - Service { - api_impl: api_impl, - marker: PhantomData, - } - } -} - -impl Clone for Service -where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - fn clone(&self) -> Self { - Service { - api_impl: self.api_impl.clone(), - marker: self.marker.clone(), - } - } -} - -impl hyper::service::Service<(Request, C)> for Service -where - T: Api + Clone + Send + Sync + 'static, - C: Has + Has> + Send + Sync + 'static, -{ - type Response = Response; - type Error = crate::ServiceError; - type Future = ServiceFuture; - - fn poll_ready(&mut self, cx: &mut Context) -> Poll> { - self.api_impl.poll_ready(cx) - } - - fn call(&mut self, req: (Request, C)) -> Self::Future { - async fn run( - mut api_impl: T, - req: (Request, C), - ) -> Result, crate::ServiceError> - where - T: Api + Clone + Send + 'static, - C: Has + Has> + Send + Sync + 'static, - { - let (request, context) = req; - let (parts, body) = request.into_parts(); - let (method, uri, headers) = (parts.method, parts.uri, parts.headers); - let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - - match &method { - // AcceptEditgroup - POST /editgroup/{editgroup_id}/accept - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ACCEPT) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_ACCEPT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_ACCEPT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_ACCEPT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .accept_editgroup(param_editgroup_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - AcceptEditgroupResponse::MergedSuccessfully(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_MERGED_SUCCESSFULLY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::EditConflict(body) => { - *response.status_mut() = StatusCode::from_u16(409) - .expect("Unable to turn 409 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_EDIT_CONFLICT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AcceptEditgroupResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for ACCEPT_EDITGROUP_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // AuthCheck - GET /auth/check - &hyper::Method::GET if path.matched(paths::ID_AUTH_CHECK) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_role = query_params - .iter() - .filter(|e| e.0 == "role") - .map(|e| e.1.to_owned()) - .nth(0); - let param_role = match param_role { - Some(param_role) => { - let param_role = ::from_str(¶m_role); - match param_role { - Ok(param_role) => Some(param_role), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter role - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter role")), - } - } - None => None, - }; - - let result = api_impl.auth_check(param_role, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - AuthCheckResponse::Success(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_CHECK_SUCCESS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AuthCheckResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_CHECK_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AuthCheckResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_CHECK_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AuthCheckResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_CHECK_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - AuthCheckResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_CHECK_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // AuthOidc - POST /auth/oidc - &hyper::Method::POST if path.matched(paths::ID_AUTH_OIDC) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_auth_oidc: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_auth_oidc) => param_auth_oidc, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter AuthOidc - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter AuthOidc due to schema")), - } - } else { - None - }; - let param_auth_oidc = match param_auth_oidc { - Some(param_auth_oidc) => param_auth_oidc, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter AuthOidc")) - .expect("Unable to create Bad Request response for missing body parameter AuthOidc")), - }; - - let result = api_impl.auth_oidc( - param_auth_oidc, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - AuthOidcResponse::Found - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::Created - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_CREATED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::Conflict - (body) - => { - *response.status_mut() = StatusCode::from_u16(409).expect("Unable to turn 409 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_CONFLICT")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - AuthOidcResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for AUTH_OIDC_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter AuthOidc: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter AuthOidc")), - } - } - - // CreateAuthToken - POST /auth/token/{editor_id} - &hyper::Method::POST if path.matched(paths::ID_AUTH_TOKEN_EDITOR_ID) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_AUTH_TOKEN_EDITOR_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE AUTH_TOKEN_EDITOR_ID in set but failed match against \"{}\"", path, paths::REGEX_AUTH_TOKEN_EDITOR_ID.as_str()) - ); - - let param_editor_id = match percent_encoding::percent_decode(path_params["editor_id"].as_bytes()).decode_utf8() { - Ok(param_editor_id) => match param_editor_id.parse::() { - Ok(param_editor_id) => param_editor_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editor_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editor_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_duration_seconds = query_params - .iter() - .filter(|e| e.0 == "duration_seconds") - .map(|e| e.1.to_owned()) - .nth(0); - let param_duration_seconds = match param_duration_seconds { - Some(param_duration_seconds) => { - let param_duration_seconds = - ::from_str(¶m_duration_seconds); - match param_duration_seconds { - Ok(param_duration_seconds) => Some(param_duration_seconds), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter duration_seconds - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter duration_seconds")), - } - } - None => None, - }; - - let result = api_impl - .create_auth_token(param_editor_id, param_duration_seconds, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - CreateAuthTokenResponse::Success(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_AUTH_TOKEN_SUCCESS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - CreateAuthTokenResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_AUTH_TOKEN_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - CreateAuthTokenResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_AUTH_TOKEN_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - CreateAuthTokenResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_AUTH_TOKEN_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - CreateAuthTokenResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_AUTH_TOKEN_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // CreateContainer - POST /editgroup/{editgroup_id}/container - &hyper::Method::POST - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CONTAINER in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_container_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_container_entity) => param_container_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ContainerEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ContainerEntity due to schema")), - } - } else { - None - }; - let param_container_entity = match param_container_entity { - Some(param_container_entity) => param_container_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ContainerEntity")) - .expect("Unable to create Bad Request response for missing body parameter ContainerEntity")), - }; - - let result = api_impl.create_container( - param_editgroup_id, - param_container_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateContainerResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ContainerEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ContainerEntity")), - } - } - - // CreateContainerAutoBatch - POST /editgroup/auto/container/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_CONTAINER_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_container_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_container_auto_batch) => param_container_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ContainerAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ContainerAutoBatch due to schema")), - } - } else { - None - }; - let param_container_auto_batch = match param_container_auto_batch { - Some(param_container_auto_batch) => param_container_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ContainerAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter ContainerAutoBatch")), - }; - - let result = api_impl.create_container_auto_batch( - param_container_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateContainerAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateContainerAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CONTAINER_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ContainerAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ContainerAutoBatch")), - } - } - - // CreateCreator - POST /editgroup/{editgroup_id}/creator - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CREATOR in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_creator_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_creator_entity) => param_creator_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter CreatorEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter CreatorEntity due to schema")), - } - } else { - None - }; - let param_creator_entity = match param_creator_entity { - Some(param_creator_entity) => param_creator_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter CreatorEntity")) - .expect("Unable to create Bad Request response for missing body parameter CreatorEntity")), - }; - - let result = api_impl.create_creator( - param_editgroup_id, - param_creator_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateCreatorResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter CreatorEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter CreatorEntity")), - } - } - - // CreateCreatorAutoBatch - POST /editgroup/auto/creator/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_CREATOR_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_creator_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_creator_auto_batch) => param_creator_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter CreatorAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter CreatorAutoBatch due to schema")), - } - } else { - None - }; - let param_creator_auto_batch = match param_creator_auto_batch { - Some(param_creator_auto_batch) => param_creator_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter CreatorAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter CreatorAutoBatch")), - }; - - let result = api_impl.create_creator_auto_batch( - param_creator_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateCreatorAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateCreatorAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_CREATOR_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter CreatorAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter CreatorAutoBatch")), - } - } - - // CreateEditgroup - POST /editgroup - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_editgroup: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_editgroup) => param_editgroup, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter Editgroup - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter Editgroup due to schema")), - } - } else { - None - }; - let param_editgroup = match param_editgroup { - Some(param_editgroup) => param_editgroup, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter Editgroup")) - .expect("Unable to create Bad Request response for missing body parameter Editgroup")), - }; - - let result = api_impl.create_editgroup( - param_editgroup, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateEditgroupResponse::SuccessfullyCreated - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_SUCCESSFULLY_CREATED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter Editgroup: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter Editgroup")), - } - } - - // CreateEditgroupAnnotation - POST /editgroup/{editgroup_id}/annotation - &hyper::Method::POST - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATION) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATION - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_ANNOTATION in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATION.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_editgroup_annotation: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_editgroup_annotation) => param_editgroup_annotation, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter EditgroupAnnotation - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter EditgroupAnnotation due to schema")), - } - } else { - None - }; - let param_editgroup_annotation = match param_editgroup_annotation { - Some(param_editgroup_annotation) => param_editgroup_annotation, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter EditgroupAnnotation")) - .expect("Unable to create Bad Request response for missing body parameter EditgroupAnnotation")), - }; - - let result = api_impl.create_editgroup_annotation( - param_editgroup_id, - param_editgroup_annotation, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateEditgroupAnnotationResponse::Created - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_CREATED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupAnnotationResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupAnnotationResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupAnnotationResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupAnnotationResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateEditgroupAnnotationResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_EDITGROUP_ANNOTATION_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter EditgroupAnnotation: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter EditgroupAnnotation")), - } - } - - // CreateFile - POST /editgroup/{editgroup_id}/file - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILE in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_file_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_file_entity) => param_file_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FileEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FileEntity due to schema")), - } - } else { - None - }; - let param_file_entity = match param_file_entity { - Some(param_file_entity) => param_file_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FileEntity")) - .expect("Unable to create Bad Request response for missing body parameter FileEntity")), - }; - - let result = api_impl.create_file( - param_editgroup_id, - param_file_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateFileResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FileEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FileEntity")), - } - } - - // CreateFileAutoBatch - POST /editgroup/auto/file/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_FILE_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_file_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_file_auto_batch) => param_file_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FileAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FileAutoBatch due to schema")), - } - } else { - None - }; - let param_file_auto_batch = match param_file_auto_batch { - Some(param_file_auto_batch) => param_file_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FileAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter FileAutoBatch")), - }; - - let result = api_impl.create_file_auto_batch( - param_file_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateFileAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFileAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILE_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FileAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FileAutoBatch")), - } - } - - // CreateFileset - POST /editgroup/{editgroup_id}/fileset - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILESET in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_fileset_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_fileset_entity) => param_fileset_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FilesetEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FilesetEntity due to schema")), - } - } else { - None - }; - let param_fileset_entity = match param_fileset_entity { - Some(param_fileset_entity) => param_fileset_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FilesetEntity")) - .expect("Unable to create Bad Request response for missing body parameter FilesetEntity")), - }; - - let result = api_impl.create_fileset( - param_editgroup_id, - param_fileset_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateFilesetResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FilesetEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FilesetEntity")), - } - } - - // CreateFilesetAutoBatch - POST /editgroup/auto/fileset/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_FILESET_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_fileset_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_fileset_auto_batch) => param_fileset_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FilesetAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FilesetAutoBatch due to schema")), - } - } else { - None - }; - let param_fileset_auto_batch = match param_fileset_auto_batch { - Some(param_fileset_auto_batch) => param_fileset_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FilesetAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter FilesetAutoBatch")), - }; - - let result = api_impl.create_fileset_auto_batch( - param_fileset_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateFilesetAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateFilesetAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_FILESET_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FilesetAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FilesetAutoBatch")), - } - } - - // CreateRelease - POST /editgroup/{editgroup_id}/release - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_RELEASE in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_release_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_release_entity) => param_release_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ReleaseEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ReleaseEntity due to schema")), - } - } else { - None - }; - let param_release_entity = match param_release_entity { - Some(param_release_entity) => param_release_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ReleaseEntity")) - .expect("Unable to create Bad Request response for missing body parameter ReleaseEntity")), - }; - - let result = api_impl.create_release( - param_editgroup_id, - param_release_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateReleaseResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ReleaseEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ReleaseEntity")), - } - } - - // CreateReleaseAutoBatch - POST /editgroup/auto/release/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_RELEASE_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_release_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_release_auto_batch) => param_release_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ReleaseAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ReleaseAutoBatch due to schema")), - } - } else { - None - }; - let param_release_auto_batch = match param_release_auto_batch { - Some(param_release_auto_batch) => param_release_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ReleaseAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter ReleaseAutoBatch")), - }; - - let result = api_impl.create_release_auto_batch( - param_release_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateReleaseAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateReleaseAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_RELEASE_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ReleaseAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ReleaseAutoBatch")), - } - } - - // CreateWebcapture - POST /editgroup/{editgroup_id}/webcapture - &hyper::Method::POST - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WEBCAPTURE in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_webcapture_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_webcapture_entity) => param_webcapture_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WebcaptureEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WebcaptureEntity due to schema")), - } - } else { - None - }; - let param_webcapture_entity = match param_webcapture_entity { - Some(param_webcapture_entity) => param_webcapture_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WebcaptureEntity")) - .expect("Unable to create Bad Request response for missing body parameter WebcaptureEntity")), - }; - - let result = api_impl.create_webcapture( - param_editgroup_id, - param_webcapture_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateWebcaptureResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WebcaptureEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WebcaptureEntity")), - } - } - - // CreateWebcaptureAutoBatch - POST /editgroup/auto/webcapture/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_WEBCAPTURE_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_webcapture_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_webcapture_auto_batch) => param_webcapture_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WebcaptureAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WebcaptureAutoBatch due to schema")), - } - } else { - None - }; - let param_webcapture_auto_batch = match param_webcapture_auto_batch { - Some(param_webcapture_auto_batch) => param_webcapture_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WebcaptureAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter WebcaptureAutoBatch")), - }; - - let result = api_impl.create_webcapture_auto_batch( - param_webcapture_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateWebcaptureAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWebcaptureAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WEBCAPTURE_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WebcaptureAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WebcaptureAutoBatch")), - } - } - - // CreateWork - POST /editgroup/{editgroup_id}/work - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WORK in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_work_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_work_entity) => param_work_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WorkEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WorkEntity due to schema")), - } - } else { - None - }; - let param_work_entity = match param_work_entity { - Some(param_work_entity) => param_work_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WorkEntity")) - .expect("Unable to create Bad Request response for missing body parameter WorkEntity")), - }; - - let result = api_impl.create_work( - param_editgroup_id, - param_work_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateWorkResponse::CreatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_CREATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WorkEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WorkEntity")), - } - } - - // CreateWorkAutoBatch - POST /editgroup/auto/work/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_WORK_BATCH) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_work_auto_batch: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_work_auto_batch) => param_work_auto_batch, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WorkAutoBatch - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WorkAutoBatch due to schema")), - } - } else { - None - }; - let param_work_auto_batch = match param_work_auto_batch { - Some(param_work_auto_batch) => param_work_auto_batch, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WorkAutoBatch")) - .expect("Unable to create Bad Request response for missing body parameter WorkAutoBatch")), - }; - - let result = api_impl.create_work_auto_batch( - param_work_auto_batch, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - CreateWorkAutoBatchResponse::CreatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_CREATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkAutoBatchResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkAutoBatchResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkAutoBatchResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkAutoBatchResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - CreateWorkAutoBatchResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for CREATE_WORK_AUTO_BATCH_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WorkAutoBatch: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WorkAutoBatch")), - } - } - - // DeleteContainer - DELETE /editgroup/{editgroup_id}/container/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_container(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteContainerResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteContainerEdit - DELETE /editgroup/{editgroup_id}/container/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_container_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteContainerEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteContainerEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CONTAINER_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteCreator - DELETE /editgroup/{editgroup_id}/creator/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CREATOR_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_creator(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteCreatorResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteCreatorEdit - DELETE /editgroup/{editgroup_id}/creator/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_creator_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteCreatorEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteCreatorEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_CREATOR_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteFile - DELETE /editgroup/{editgroup_id}/file/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_file(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteFileResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteFileEdit - DELETE /editgroup/{editgroup_id}/file/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_file_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteFileEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFileEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteFileset - DELETE /editgroup/{editgroup_id}/fileset/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILESET_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_fileset(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteFilesetResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteFilesetEdit - DELETE /editgroup/{editgroup_id}/fileset/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_fileset_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteFilesetEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteFilesetEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_FILESET_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteRelease - DELETE /editgroup/{editgroup_id}/release/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_RELEASE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_release(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteReleaseResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteReleaseEdit - DELETE /editgroup/{editgroup_id}/release/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_release_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteReleaseEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteReleaseEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_RELEASE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteWebcapture - DELETE /editgroup/{editgroup_id}/webcapture/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_webcapture(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteWebcaptureResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteWebcaptureEdit - DELETE /editgroup/{editgroup_id}/webcapture/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_webcapture_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteWebcaptureEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWebcaptureEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WEBCAPTURE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteWork - DELETE /editgroup/{editgroup_id}/work/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WORK_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_work(param_editgroup_id, param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteWorkResponse::DeletedEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_DELETED_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // DeleteWorkEdit - DELETE /editgroup/{editgroup_id}/work/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .delete_work_edit(param_editgroup_id, param_edit_id, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - DeleteWorkEditResponse::DeletedEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_DELETED_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkEditResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkEditResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - DeleteWorkEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for DELETE_WORK_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetChangelog - GET /changelog - &hyper::Method::GET if path.matched(paths::ID_CHANGELOG) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl.get_changelog(param_limit, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetChangelogResponse::Success(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_SUCCESS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetChangelogResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetChangelogResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetChangelogEntry - GET /changelog/{index} - &hyper::Method::GET if path.matched(paths::ID_CHANGELOG_INDEX) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CHANGELOG_INDEX - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CHANGELOG_INDEX in set but failed match against \"{}\"", path, paths::REGEX_CHANGELOG_INDEX.as_str()) - ); - - let param_index = match percent_encoding::percent_decode(path_params["index"].as_bytes()).decode_utf8() { - Ok(param_index) => match param_index.parse::() { - Ok(param_index) => param_index, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter index: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["index"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_changelog_entry(param_index, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetChangelogEntryResponse::FoundChangelogEntry(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_ENTRY_FOUND_CHANGELOG_ENTRY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetChangelogEntryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_ENTRY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetChangelogEntryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_ENTRY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetChangelogEntryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CHANGELOG_ENTRY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetContainer - GET /container/{ident} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CONTAINER_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CONTAINER_IDENT in set but failed match against \"{}\"", path, paths::REGEX_CONTAINER_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_container(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetContainerResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetContainerEdit - GET /container/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CONTAINER_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CONTAINER_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_CONTAINER_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_container_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetContainerEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetContainerHistory - GET /container/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CONTAINER_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CONTAINER_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_CONTAINER_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_container_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetContainerHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetContainerRedirects - GET /container/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CONTAINER_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CONTAINER_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_CONTAINER_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .get_container_redirects(param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetContainerRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetContainerRevision - GET /container/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CONTAINER_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CONTAINER_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_CONTAINER_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_container_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetContainerRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetContainerRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CONTAINER_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreator - GET /creator/{ident} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_IDENT in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_creator(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreatorEdit - GET /creator/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_creator_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreatorHistory - GET /creator/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_creator_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreatorRedirects - GET /creator/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_creator_redirects(param_ident, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreatorReleases - GET /creator/{ident}/releases - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_RELEASES) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_IDENT_RELEASES - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_IDENT_RELEASES in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_IDENT_RELEASES.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_creator_releases(param_ident, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorReleasesResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_RELEASES_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorReleasesResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_RELEASES_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorReleasesResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_RELEASES_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorReleasesResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_RELEASES_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetCreatorRevision - GET /creator/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_CREATOR_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE CREATOR_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_CREATOR_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_creator_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetCreatorRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetCreatorRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_CREATOR_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditgroup - GET /editgroup/{editgroup_id} - &hyper::Method::GET if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_editgroup(param_editgroup_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetEditgroupResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditgroupAnnotations - GET /editgroup/{editgroup_id}/annotations - &hyper::Method::GET - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATIONS) => - { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATIONS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_ANNOTATIONS in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_ANNOTATIONS.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - - let result = api_impl - .get_editgroup_annotations(param_editgroup_id, param_expand, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetEditgroupAnnotationsResponse::Success(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_SUCCESS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupAnnotationsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupAnnotationsResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupAnnotationsResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupAnnotationsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupAnnotationsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUP_ANNOTATIONS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditgroupsReviewable - GET /editgroup/reviewable - &hyper::Method::GET if path.matched(paths::ID_EDITGROUP_REVIEWABLE) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - let param_before = query_params - .iter() - .filter(|e| e.0 == "before") - .map(|e| e.1.to_owned()) - .nth(0); - let param_before = match param_before { - Some(param_before) => { - let param_before = - as std::str::FromStr>::from_str( - ¶m_before, - ); - match param_before { - Ok(param_before) => Some(param_before), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter before - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter before")), - } - } - None => None, - }; - let param_since = query_params - .iter() - .filter(|e| e.0 == "since") - .map(|e| e.1.to_owned()) - .nth(0); - let param_since = match param_since { - Some(param_since) => { - let param_since = - as std::str::FromStr>::from_str( - ¶m_since, - ); - match param_since { - Ok(param_since) => Some(param_since), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter since - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter since")), - } - } - None => None, - }; - - let result = api_impl - .get_editgroups_reviewable( - param_expand, - param_limit, - param_before, - param_since, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetEditgroupsReviewableResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUPS_REVIEWABLE_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupsReviewableResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUPS_REVIEWABLE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupsReviewableResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUPS_REVIEWABLE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditgroupsReviewableResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITGROUPS_REVIEWABLE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditor - GET /editor/{editor_id} - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITOR_EDITOR_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITOR_EDITOR_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITOR_EDITOR_ID.as_str()) - ); - - let param_editor_id = match percent_encoding::percent_decode(path_params["editor_id"].as_bytes()).decode_utf8() { - Ok(param_editor_id) => match param_editor_id.parse::() { - Ok(param_editor_id) => param_editor_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editor_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editor_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_editor(param_editor_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => { - match rsp { - GetEditorResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - } - } - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditorAnnotations - GET /editor/{editor_id}/annotations - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID_ANNOTATIONS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITOR_EDITOR_ID_ANNOTATIONS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITOR_EDITOR_ID_ANNOTATIONS in set but failed match against \"{}\"", path, paths::REGEX_EDITOR_EDITOR_ID_ANNOTATIONS.as_str()) - ); - - let param_editor_id = match percent_encoding::percent_decode(path_params["editor_id"].as_bytes()).decode_utf8() { - Ok(param_editor_id) => match param_editor_id.parse::() { - Ok(param_editor_id) => param_editor_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editor_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editor_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - let param_before = query_params - .iter() - .filter(|e| e.0 == "before") - .map(|e| e.1.to_owned()) - .nth(0); - let param_before = match param_before { - Some(param_before) => { - let param_before = - as std::str::FromStr>::from_str( - ¶m_before, - ); - match param_before { - Ok(param_before) => Some(param_before), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter before - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter before")), - } - } - None => None, - }; - let param_since = query_params - .iter() - .filter(|e| e.0 == "since") - .map(|e| e.1.to_owned()) - .nth(0); - let param_since = match param_since { - Some(param_since) => { - let param_since = - as std::str::FromStr>::from_str( - ¶m_since, - ); - match param_since { - Ok(param_since) => Some(param_since), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter since - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter since")), - } - } - None => None, - }; - - let result = api_impl - .get_editor_annotations( - param_editor_id, - param_limit, - param_before, - param_since, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetEditorAnnotationsResponse::Success(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_SUCCESS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorAnnotationsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorAnnotationsResponse::NotAuthorized { - body, - www_authenticate, - } => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate, - ); - } - *response.status_mut() = StatusCode::from_u16(401) - .expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorAnnotationsResponse::Forbidden(body) => { - *response.status_mut() = StatusCode::from_u16(403) - .expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_FORBIDDEN")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorAnnotationsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorAnnotationsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_ANNOTATIONS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetEditorEditgroups - GET /editor/{editor_id}/editgroups - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID_EDITGROUPS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITOR_EDITOR_ID_EDITGROUPS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITOR_EDITOR_ID_EDITGROUPS in set but failed match against \"{}\"", path, paths::REGEX_EDITOR_EDITOR_ID_EDITGROUPS.as_str()) - ); - - let param_editor_id = match percent_encoding::percent_decode(path_params["editor_id"].as_bytes()).decode_utf8() { - Ok(param_editor_id) => match param_editor_id.parse::() { - Ok(param_editor_id) => param_editor_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editor_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editor_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - let param_before = query_params - .iter() - .filter(|e| e.0 == "before") - .map(|e| e.1.to_owned()) - .nth(0); - let param_before = match param_before { - Some(param_before) => { - let param_before = - as std::str::FromStr>::from_str( - ¶m_before, - ); - match param_before { - Ok(param_before) => Some(param_before), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter before - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter before")), - } - } - None => None, - }; - let param_since = query_params - .iter() - .filter(|e| e.0 == "since") - .map(|e| e.1.to_owned()) - .nth(0); - let param_since = match param_since { - Some(param_since) => { - let param_since = - as std::str::FromStr>::from_str( - ¶m_since, - ); - match param_since { - Ok(param_since) => Some(param_since), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter since - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter since")), - } - } - None => None, - }; - - let result = api_impl - .get_editor_editgroups( - param_editor_id, - param_limit, - param_before, - param_since, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetEditorEditgroupsResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_EDITGROUPS_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorEditgroupsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_EDITGROUPS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorEditgroupsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_EDITGROUPS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetEditorEditgroupsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_EDITOR_EDITGROUPS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFile - GET /file/{ident} - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_FILE_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_file(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFileResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFileEdit - GET /file/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_FILE_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_FILE_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_file_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFileEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFileHistory - GET /file/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILE_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILE_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_FILE_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_file_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFileHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFileRedirects - GET /file/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILE_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILE_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_FILE_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_file_redirects(param_ident, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFileRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFileRevision - GET /file/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_FILE_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILE_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILE_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_FILE_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_file_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFileRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFileRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILE_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFileset - GET /fileset/{ident} - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILESET_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILESET_IDENT in set but failed match against \"{}\"", path, paths::REGEX_FILESET_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_fileset(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFilesetResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFilesetEdit - GET /fileset/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_FILESET_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILESET_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILESET_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_FILESET_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_fileset_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFilesetEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFilesetHistory - GET /fileset/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILESET_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILESET_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_FILESET_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_fileset_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFilesetHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFilesetRedirects - GET /fileset/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILESET_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILESET_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_FILESET_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_fileset_redirects(param_ident, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFilesetRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetFilesetRevision - GET /fileset/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_FILESET_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_FILESET_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE FILESET_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_FILESET_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_fileset_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetFilesetRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetFilesetRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_FILESET_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetRelease - GET /release/{ident} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_release(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseEdit - GET /release/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_release_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseFiles - GET /release/{ident}/files - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_FILES) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT_FILES - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT_FILES in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT_FILES.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_release_files(param_ident, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseFilesResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILES_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILES_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILES_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILES_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseFilesets - GET /release/{ident}/filesets - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_FILESETS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT_FILESETS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT_FILESETS in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT_FILESETS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_release_filesets(param_ident, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseFilesetsResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILESETS_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesetsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILESETS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesetsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILESETS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseFilesetsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_FILESETS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseHistory - GET /release/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_release_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseRedirects - GET /release/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_release_redirects(param_ident, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseRevision - GET /release/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_release_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetReleaseWebcaptures - GET /release/{ident}/webcaptures - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_WEBCAPTURES) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_RELEASE_IDENT_WEBCAPTURES - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE RELEASE_IDENT_WEBCAPTURES in set but failed match against \"{}\"", path, paths::REGEX_RELEASE_IDENT_WEBCAPTURES.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_release_webcaptures(param_ident, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetReleaseWebcapturesResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_WEBCAPTURES_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseWebcapturesResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_WEBCAPTURES_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseWebcapturesResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_WEBCAPTURES_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetReleaseWebcapturesResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_RELEASE_WEBCAPTURES_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWebcapture - GET /webcapture/{ident} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WEBCAPTURE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WEBCAPTURE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_WEBCAPTURE_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_webcapture(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWebcaptureResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWebcaptureEdit - GET /webcapture/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WEBCAPTURE_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WEBCAPTURE_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_WEBCAPTURE_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_webcapture_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWebcaptureEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWebcaptureHistory - GET /webcapture/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WEBCAPTURE_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WEBCAPTURE_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_WEBCAPTURE_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_webcapture_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWebcaptureHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWebcaptureRedirects - GET /webcapture/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WEBCAPTURE_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WEBCAPTURE_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_WEBCAPTURE_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl - .get_webcapture_redirects(param_ident, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWebcaptureRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWebcaptureRevision - GET /webcapture/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WEBCAPTURE_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WEBCAPTURE_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_WEBCAPTURE_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_webcapture_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWebcaptureRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWebcaptureRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WEBCAPTURE_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWork - GET /work/{ident} - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_IDENT in set but failed match against \"{}\"", path, paths::REGEX_WORK_IDENT.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_work(param_ident, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWorkEdit - GET /work/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_WORK_EDIT_EDIT_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_EDIT_EDIT_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_EDIT_EDIT_ID in set but failed match against \"{}\"", path, paths::REGEX_WORK_EDIT_EDIT_ID.as_str()) - ); - - let param_edit_id = match percent_encoding::percent_decode(path_params["edit_id"].as_bytes()).decode_utf8() { - Ok(param_edit_id) => match param_edit_id.parse::() { - Ok(param_edit_id) => param_edit_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter edit_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["edit_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_work_edit(param_edit_id, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkEditResponse::FoundEdit(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_EDIT_FOUND_EDIT")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkEditResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_EDIT_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkEditResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_EDIT_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkEditResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_EDIT_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWorkHistory - GET /work/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_HISTORY) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_IDENT_HISTORY - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_IDENT_HISTORY in set but failed match against \"{}\"", path, paths::REGEX_WORK_IDENT_HISTORY.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_limit = query_params - .iter() - .filter(|e| e.0 == "limit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_limit = match param_limit { - Some(param_limit) => { - let param_limit = ::from_str(¶m_limit); - match param_limit { - Ok(param_limit) => Some(param_limit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter limit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter limit")), - } - } - None => None, - }; - - let result = api_impl - .get_work_history(param_ident, param_limit, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkHistoryResponse::FoundEntityHistory(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_HISTORY_FOUND_ENTITY_HISTORY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkHistoryResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_HISTORY_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkHistoryResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_HISTORY_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkHistoryResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_HISTORY_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWorkRedirects - GET /work/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_REDIRECTS) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_IDENT_REDIRECTS - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_IDENT_REDIRECTS in set but failed match against \"{}\"", path, paths::REGEX_WORK_IDENT_REDIRECTS.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let result = api_impl.get_work_redirects(param_ident, &context).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkRedirectsResponse::FoundEntityRedirects(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REDIRECTS_FOUND_ENTITY_REDIRECTS")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRedirectsResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REDIRECTS_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRedirectsResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REDIRECTS_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRedirectsResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REDIRECTS_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWorkReleases - GET /work/{ident}/releases - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_RELEASES) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_IDENT_RELEASES - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_IDENT_RELEASES in set but failed match against \"{}\"", path, paths::REGEX_WORK_IDENT_RELEASES.as_str()) - ); - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_work_releases(param_ident, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkReleasesResponse::Found(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_RELEASES_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkReleasesResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_RELEASES_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkReleasesResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_RELEASES_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkReleasesResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_RELEASES_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // GetWorkRevision - GET /work/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_WORK_REV_REV_ID) => { - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_WORK_REV_REV_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE WORK_REV_REV_ID in set but failed match against \"{}\"", path, paths::REGEX_WORK_REV_REV_ID.as_str()) - ); - - let param_rev_id = match percent_encoding::percent_decode(path_params["rev_id"].as_bytes()).decode_utf8() { - Ok(param_rev_id) => match param_rev_id.parse::() { - Ok(param_rev_id) => param_rev_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter rev_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["rev_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .get_work_revision(param_rev_id, param_expand, param_hide, &context) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - GetWorkRevisionResponse::FoundEntityRevision(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REVISION_FOUND_ENTITY_REVISION")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRevisionResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REVISION_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRevisionResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REVISION_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - GetWorkRevisionResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for GET_WORK_REVISION_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // LookupContainer - GET /container/lookup - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_LOOKUP) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_issnl = query_params - .iter() - .filter(|e| e.0 == "issnl") - .map(|e| e.1.to_owned()) - .nth(0); - let param_issnl = match param_issnl { - Some(param_issnl) => { - let param_issnl = ::from_str(¶m_issnl); - match param_issnl { - Ok(param_issnl) => Some(param_issnl), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter issnl - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter issnl")), - } - } - None => None, - }; - let param_wikidata_qid = query_params - .iter() - .filter(|e| e.0 == "wikidata_qid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_wikidata_qid = match param_wikidata_qid { - Some(param_wikidata_qid) => { - let param_wikidata_qid = - ::from_str(¶m_wikidata_qid); - match param_wikidata_qid { - Ok(param_wikidata_qid) => Some(param_wikidata_qid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter wikidata_qid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter wikidata_qid")), - } - } - None => None, - }; - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .lookup_container( - param_issnl, - param_wikidata_qid, - param_expand, - param_hide, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - LookupContainerResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CONTAINER_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupContainerResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CONTAINER_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupContainerResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CONTAINER_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupContainerResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CONTAINER_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // LookupCreator - GET /creator/lookup - &hyper::Method::GET if path.matched(paths::ID_CREATOR_LOOKUP) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_orcid = query_params - .iter() - .filter(|e| e.0 == "orcid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_orcid = match param_orcid { - Some(param_orcid) => { - let param_orcid = ::from_str(¶m_orcid); - match param_orcid { - Ok(param_orcid) => Some(param_orcid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter orcid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter orcid")), - } - } - None => None, - }; - let param_wikidata_qid = query_params - .iter() - .filter(|e| e.0 == "wikidata_qid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_wikidata_qid = match param_wikidata_qid { - Some(param_wikidata_qid) => { - let param_wikidata_qid = - ::from_str(¶m_wikidata_qid); - match param_wikidata_qid { - Ok(param_wikidata_qid) => Some(param_wikidata_qid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter wikidata_qid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter wikidata_qid")), - } - } - None => None, - }; - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .lookup_creator( - param_orcid, - param_wikidata_qid, - param_expand, - param_hide, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - LookupCreatorResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CREATOR_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupCreatorResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CREATOR_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupCreatorResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CREATOR_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupCreatorResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_CREATOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // LookupFile - GET /file/lookup - &hyper::Method::GET if path.matched(paths::ID_FILE_LOOKUP) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_md5 = query_params - .iter() - .filter(|e| e.0 == "md5") - .map(|e| e.1.to_owned()) - .nth(0); - let param_md5 = match param_md5 { - Some(param_md5) => { - let param_md5 = ::from_str(¶m_md5); - match param_md5 { - Ok(param_md5) => Some(param_md5), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter md5 - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter md5")), - } - } - None => None, - }; - let param_sha1 = query_params - .iter() - .filter(|e| e.0 == "sha1") - .map(|e| e.1.to_owned()) - .nth(0); - let param_sha1 = match param_sha1 { - Some(param_sha1) => { - let param_sha1 = ::from_str(¶m_sha1); - match param_sha1 { - Ok(param_sha1) => Some(param_sha1), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter sha1 - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter sha1")), - } - } - None => None, - }; - let param_sha256 = query_params - .iter() - .filter(|e| e.0 == "sha256") - .map(|e| e.1.to_owned()) - .nth(0); - let param_sha256 = match param_sha256 { - Some(param_sha256) => { - let param_sha256 = - ::from_str(¶m_sha256); - match param_sha256 { - Ok(param_sha256) => Some(param_sha256), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter sha256 - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter sha256")), - } - } - None => None, - }; - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .lookup_file( - param_md5, - param_sha1, - param_sha256, - param_expand, - param_hide, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - LookupFileResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_FILE_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupFileResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_FILE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupFileResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_FILE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupFileResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_FILE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // LookupRelease - GET /release/lookup - &hyper::Method::GET if path.matched(paths::ID_RELEASE_LOOKUP) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_doi = query_params - .iter() - .filter(|e| e.0 == "doi") - .map(|e| e.1.to_owned()) - .nth(0); - let param_doi = match param_doi { - Some(param_doi) => { - let param_doi = ::from_str(¶m_doi); - match param_doi { - Ok(param_doi) => Some(param_doi), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter doi - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter doi")), - } - } - None => None, - }; - let param_wikidata_qid = query_params - .iter() - .filter(|e| e.0 == "wikidata_qid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_wikidata_qid = match param_wikidata_qid { - Some(param_wikidata_qid) => { - let param_wikidata_qid = - ::from_str(¶m_wikidata_qid); - match param_wikidata_qid { - Ok(param_wikidata_qid) => Some(param_wikidata_qid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter wikidata_qid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter wikidata_qid")), - } - } - None => None, - }; - let param_isbn13 = query_params - .iter() - .filter(|e| e.0 == "isbn13") - .map(|e| e.1.to_owned()) - .nth(0); - let param_isbn13 = match param_isbn13 { - Some(param_isbn13) => { - let param_isbn13 = - ::from_str(¶m_isbn13); - match param_isbn13 { - Ok(param_isbn13) => Some(param_isbn13), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter isbn13 - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter isbn13")), - } - } - None => None, - }; - let param_pmid = query_params - .iter() - .filter(|e| e.0 == "pmid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_pmid = match param_pmid { - Some(param_pmid) => { - let param_pmid = ::from_str(¶m_pmid); - match param_pmid { - Ok(param_pmid) => Some(param_pmid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter pmid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter pmid")), - } - } - None => None, - }; - let param_pmcid = query_params - .iter() - .filter(|e| e.0 == "pmcid") - .map(|e| e.1.to_owned()) - .nth(0); - let param_pmcid = match param_pmcid { - Some(param_pmcid) => { - let param_pmcid = ::from_str(¶m_pmcid); - match param_pmcid { - Ok(param_pmcid) => Some(param_pmcid), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter pmcid - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter pmcid")), - } - } - None => None, - }; - let param_core = query_params - .iter() - .filter(|e| e.0 == "core") - .map(|e| e.1.to_owned()) - .nth(0); - let param_core = match param_core { - Some(param_core) => { - let param_core = ::from_str(¶m_core); - match param_core { - Ok(param_core) => Some(param_core), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter core - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter core")), - } - } - None => None, - }; - let param_arxiv = query_params - .iter() - .filter(|e| e.0 == "arxiv") - .map(|e| e.1.to_owned()) - .nth(0); - let param_arxiv = match param_arxiv { - Some(param_arxiv) => { - let param_arxiv = ::from_str(¶m_arxiv); - match param_arxiv { - Ok(param_arxiv) => Some(param_arxiv), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter arxiv - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter arxiv")), - } - } - None => None, - }; - let param_jstor = query_params - .iter() - .filter(|e| e.0 == "jstor") - .map(|e| e.1.to_owned()) - .nth(0); - let param_jstor = match param_jstor { - Some(param_jstor) => { - let param_jstor = ::from_str(¶m_jstor); - match param_jstor { - Ok(param_jstor) => Some(param_jstor), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter jstor - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter jstor")), - } - } - None => None, - }; - let param_ark = query_params - .iter() - .filter(|e| e.0 == "ark") - .map(|e| e.1.to_owned()) - .nth(0); - let param_ark = match param_ark { - Some(param_ark) => { - let param_ark = ::from_str(¶m_ark); - match param_ark { - Ok(param_ark) => Some(param_ark), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter ark - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter ark")), - } - } - None => None, - }; - let param_mag = query_params - .iter() - .filter(|e| e.0 == "mag") - .map(|e| e.1.to_owned()) - .nth(0); - let param_mag = match param_mag { - Some(param_mag) => { - let param_mag = ::from_str(¶m_mag); - match param_mag { - Ok(param_mag) => Some(param_mag), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter mag - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter mag")), - } - } - None => None, - }; - let param_doaj = query_params - .iter() - .filter(|e| e.0 == "doaj") - .map(|e| e.1.to_owned()) - .nth(0); - let param_doaj = match param_doaj { - Some(param_doaj) => { - let param_doaj = ::from_str(¶m_doaj); - match param_doaj { - Ok(param_doaj) => Some(param_doaj), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter doaj - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter doaj")), - } - } - None => None, - }; - let param_dblp = query_params - .iter() - .filter(|e| e.0 == "dblp") - .map(|e| e.1.to_owned()) - .nth(0); - let param_dblp = match param_dblp { - Some(param_dblp) => { - let param_dblp = ::from_str(¶m_dblp); - match param_dblp { - Ok(param_dblp) => Some(param_dblp), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter dblp - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter dblp")), - } - } - None => None, - }; - let param_oai = query_params - .iter() - .filter(|e| e.0 == "oai") - .map(|e| e.1.to_owned()) - .nth(0); - let param_oai = match param_oai { - Some(param_oai) => { - let param_oai = ::from_str(¶m_oai); - match param_oai { - Ok(param_oai) => Some(param_oai), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter oai - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter oai")), - } - } - None => None, - }; - let param_expand = query_params - .iter() - .filter(|e| e.0 == "expand") - .map(|e| e.1.to_owned()) - .nth(0); - let param_expand = match param_expand { - Some(param_expand) => { - let param_expand = - ::from_str(¶m_expand); - match param_expand { - Ok(param_expand) => Some(param_expand), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter expand - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter expand")), - } - } - None => None, - }; - let param_hide = query_params - .iter() - .filter(|e| e.0 == "hide") - .map(|e| e.1.to_owned()) - .nth(0); - let param_hide = match param_hide { - Some(param_hide) => { - let param_hide = ::from_str(¶m_hide); - match param_hide { - Ok(param_hide) => Some(param_hide), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter hide - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter hide")), - } - } - None => None, - }; - - let result = api_impl - .lookup_release( - param_doi, - param_wikidata_qid, - param_isbn13, - param_pmid, - param_pmcid, - param_core, - param_arxiv, - param_jstor, - param_ark, - param_mag, - param_doaj, - param_dblp, - param_oai, - param_expand, - param_hide, - &context, - ) - .await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str( - (&context as &dyn Has) - .get() - .0 - .clone() - .to_string() - .as_str(), - ) - .expect("Unable to create X-Span-ID header value"), - ); - - match result { - Ok(rsp) => match rsp { - LookupReleaseResponse::FoundEntity(body) => { - *response.status_mut() = StatusCode::from_u16(200) - .expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_RELEASE_FOUND_ENTITY")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupReleaseResponse::BadRequest(body) => { - *response.status_mut() = StatusCode::from_u16(400) - .expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_RELEASE_BAD_REQUEST")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupReleaseResponse::NotFound(body) => { - *response.status_mut() = StatusCode::from_u16(404) - .expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_RELEASE_NOT_FOUND")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - LookupReleaseResponse::GenericError(body) => { - *response.status_mut() = StatusCode::from_u16(500) - .expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for LOOKUP_RELEASE_GENERIC_ERROR")); - let body = serde_json::to_string(&body) - .expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - } - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - } - } - - Ok(response) - } - - // UpdateContainer - PUT /editgroup/{editgroup_id}/container/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_container_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_container_entity) => param_container_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ContainerEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ContainerEntity due to schema")), - } - } else { - None - }; - let param_container_entity = match param_container_entity { - Some(param_container_entity) => param_container_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ContainerEntity")) - .expect("Unable to create Bad Request response for missing body parameter ContainerEntity")), - }; - - let result = api_impl.update_container( - param_editgroup_id, - param_ident, - param_container_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateContainerResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateContainerResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateContainerResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateContainerResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateContainerResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateContainerResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CONTAINER_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ContainerEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ContainerEntity")), - } - } - - // UpdateCreator - PUT /editgroup/{editgroup_id}/creator/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_CREATOR_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_creator_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_creator_entity) => param_creator_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter CreatorEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter CreatorEntity due to schema")), - } - } else { - None - }; - let param_creator_entity = match param_creator_entity { - Some(param_creator_entity) => param_creator_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter CreatorEntity")) - .expect("Unable to create Bad Request response for missing body parameter CreatorEntity")), - }; - - let result = api_impl.update_creator( - param_editgroup_id, - param_ident, - param_creator_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateCreatorResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateCreatorResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateCreatorResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateCreatorResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateCreatorResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateCreatorResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_CREATOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter CreatorEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter CreatorEntity")), - } - } - - // UpdateEditgroup - PUT /editgroup/{editgroup_id} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = - form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) - .collect::>(); - let param_submit = query_params - .iter() - .filter(|e| e.0 == "submit") - .map(|e| e.1.to_owned()) - .nth(0); - let param_submit = match param_submit { - Some(param_submit) => { - let param_submit = ::from_str(¶m_submit); - match param_submit { - Ok(param_submit) => Some(param_submit), - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse query parameter submit - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid query parameter submit")), - } - } - None => None, - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_editgroup: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_editgroup) => param_editgroup, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter Editgroup - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter Editgroup due to schema")), - } - } else { - None - }; - let param_editgroup = match param_editgroup { - Some(param_editgroup) => param_editgroup, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter Editgroup")) - .expect("Unable to create Bad Request response for missing body parameter Editgroup")), - }; - - let result = api_impl.update_editgroup( - param_editgroup_id, - param_editgroup, - param_submit, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateEditgroupResponse::UpdatedEditgroup - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_UPDATED_EDITGROUP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditgroupResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditgroupResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditgroupResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditgroupResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditgroupResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITGROUP_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter Editgroup: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter Editgroup")), - } - } - - // UpdateEditor - PUT /editor/{editor_id} - &hyper::Method::PUT if path.matched(paths::ID_EDITOR_EDITOR_ID) => { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITOR_EDITOR_ID - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITOR_EDITOR_ID in set but failed match against \"{}\"", path, paths::REGEX_EDITOR_EDITOR_ID.as_str()) - ); - - let param_editor_id = match percent_encoding::percent_decode(path_params["editor_id"].as_bytes()).decode_utf8() { - Ok(param_editor_id) => match param_editor_id.parse::() { - Ok(param_editor_id) => param_editor_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editor_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editor_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_editor: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_editor) => param_editor, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter Editor - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter Editor due to schema")), - } - } else { - None - }; - let param_editor = match param_editor { - Some(param_editor) => param_editor, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter Editor")) - .expect("Unable to create Bad Request response for missing body parameter Editor")), - }; - - let result = api_impl.update_editor( - param_editor_id, - param_editor, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateEditorResponse::UpdatedEditor - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_UPDATED_EDITOR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditorResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditorResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditorResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditorResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateEditorResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_EDITOR_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter Editor: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter Editor")), - } - } - - // UpdateFile - PUT /editgroup/{editgroup_id}/file/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_file_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_file_entity) => param_file_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FileEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FileEntity due to schema")), - } - } else { - None - }; - let param_file_entity = match param_file_entity { - Some(param_file_entity) => param_file_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FileEntity")) - .expect("Unable to create Bad Request response for missing body parameter FileEntity")), - }; - - let result = api_impl.update_file( - param_editgroup_id, - param_ident, - param_file_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateFileResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFileResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFileResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFileResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFileResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFileResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FileEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FileEntity")), - } - } - - // UpdateFileset - PUT /editgroup/{editgroup_id}/fileset/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_FILESET_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_FILESET_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_fileset_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_fileset_entity) => param_fileset_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter FilesetEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter FilesetEntity due to schema")), - } - } else { - None - }; - let param_fileset_entity = match param_fileset_entity { - Some(param_fileset_entity) => param_fileset_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter FilesetEntity")) - .expect("Unable to create Bad Request response for missing body parameter FilesetEntity")), - }; - - let result = api_impl.update_fileset( - param_editgroup_id, - param_ident, - param_fileset_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateFilesetResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFilesetResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFilesetResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFilesetResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFilesetResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateFilesetResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_FILESET_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter FilesetEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter FilesetEntity")), - } - } - - // UpdateRelease - PUT /editgroup/{editgroup_id}/release/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_RELEASE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_release_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_release_entity) => param_release_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter ReleaseEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter ReleaseEntity due to schema")), - } - } else { - None - }; - let param_release_entity = match param_release_entity { - Some(param_release_entity) => param_release_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter ReleaseEntity")) - .expect("Unable to create Bad Request response for missing body parameter ReleaseEntity")), - }; - - let result = api_impl.update_release( - param_editgroup_id, - param_ident, - param_release_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateReleaseResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateReleaseResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateReleaseResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateReleaseResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateReleaseResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateReleaseResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_RELEASE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter ReleaseEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter ReleaseEntity")), - } - } - - // UpdateWebcapture - PUT /editgroup/{editgroup_id}/webcapture/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_webcapture_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_webcapture_entity) => param_webcapture_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WebcaptureEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WebcaptureEntity due to schema")), - } - } else { - None - }; - let param_webcapture_entity = match param_webcapture_entity { - Some(param_webcapture_entity) => param_webcapture_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WebcaptureEntity")) - .expect("Unable to create Bad Request response for missing body parameter WebcaptureEntity")), - }; - - let result = api_impl.update_webcapture( - param_editgroup_id, - param_ident, - param_webcapture_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateWebcaptureResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWebcaptureResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWebcaptureResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWebcaptureResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWebcaptureResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWebcaptureResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WEBCAPTURE_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WebcaptureEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WebcaptureEntity")), - } - } - - // UpdateWork - PUT /editgroup/{editgroup_id}/work/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT) => - { - { - let authorization = match (&context as &dyn Has>) - .get() - { - &Some(ref authorization) => authorization, - &None => { - return Ok(Response::builder() - .status(StatusCode::FORBIDDEN) - .body(Body::from("Unauthenticated")) - .expect("Unable to create Authentication Forbidden response")) - } - }; - } - - // Path parameters - let path: &str = &uri.path().to_string(); - let path_params = - paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_IDENT - .captures(&path) - .unwrap_or_else(|| - panic!("Path {} matched RE EDITGROUP_EDITGROUP_ID_WORK_IDENT in set but failed match against \"{}\"", path, paths::REGEX_EDITGROUP_EDITGROUP_ID_WORK_IDENT.as_str()) - ); - - let param_editgroup_id = match percent_encoding::percent_decode(path_params["editgroup_id"].as_bytes()).decode_utf8() { - Ok(param_editgroup_id) => match param_editgroup_id.parse::() { - Ok(param_editgroup_id) => param_editgroup_id, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter editgroup_id: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["editgroup_id"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - let param_ident = match percent_encoding::percent_decode(path_params["ident"].as_bytes()).decode_utf8() { - Ok(param_ident) => match param_ident.parse::() { - Ok(param_ident) => param_ident, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse path parameter ident: {}", e))) - .expect("Unable to create Bad Request response for invalid path parameter")), - }, - Err(_) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["ident"]))) - .expect("Unable to create Bad Request response for invalid percent decode")) - }; - - // Body parameters (note that non-required body parameters will ignore garbage - // values, rather than causing a 400 response). Produce warning header and logs for - // any unused fields. - let result = body.to_raw().await; - match result { - Ok(body) => { - let mut unused_elements = Vec::new(); - let param_work_entity: Option = if !body.is_empty() { - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); - match serde_ignored::deserialize(deserializer, |path| { - warn!("Ignoring unknown field in body: {}", path); - unused_elements.push(path.to_string()); - }) { - Ok(param_work_entity) => param_work_entity, - Err(e) => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't parse body parameter WorkEntity - doesn't match schema: {}", e))) - .expect("Unable to create Bad Request response for invalid body parameter WorkEntity due to schema")), - } - } else { - None - }; - let param_work_entity = match param_work_entity { - Some(param_work_entity) => param_work_entity, - None => return Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from("Missing required body parameter WorkEntity")) - .expect("Unable to create Bad Request response for missing body parameter WorkEntity")), - }; - - let result = api_impl.update_work( - param_editgroup_id, - param_ident, - param_work_entity, - &context - ).await; - let mut response = Response::new(Body::empty()); - response.headers_mut().insert( - HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) - .expect("Unable to create X-Span-ID header value")); - - if !unused_elements.is_empty() { - response.headers_mut().insert( - HeaderName::from_static("warning"), - HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) - .expect("Unable to create Warning header value")); - } - - match result { - Ok(rsp) => match rsp { - UpdateWorkResponse::UpdatedEntity - (body) - => { - *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_UPDATED_ENTITY")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWorkResponse::BadRequest - (body) - => { - *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_BAD_REQUEST")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWorkResponse::NotAuthorized - { - body, - www_authenticate - } - => { - if let Some(www_authenticate) = www_authenticate { - let www_authenticate = match header::IntoHeaderValue(www_authenticate).try_into() { - Ok(val) => val, - Err(e) => { - return Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("An internal server error occurred handling www_authenticate header - {}", e))) - .expect("Unable to create Internal Server Error for invalid response header")) - } - }; - - response.headers_mut().insert( - HeaderName::from_static("www_authenticate"), - www_authenticate - ); - } - *response.status_mut() = StatusCode::from_u16(401).expect("Unable to turn 401 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_NOT_AUTHORIZED")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWorkResponse::Forbidden - (body) - => { - *response.status_mut() = StatusCode::from_u16(403).expect("Unable to turn 403 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_FORBIDDEN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWorkResponse::NotFound - (body) - => { - *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - UpdateWorkResponse::GenericError - (body) - => { - *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); - response.headers_mut().insert( - CONTENT_TYPE, - HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for UPDATE_WORK_GENERIC_ERROR")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); - }, - }, - Err(_) => { - // Application code returned an error. This should not happen, as the implementation should - // return a valid response. - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - *response.body_mut() = Body::from("An internal error occurred"); - }, - } - - Ok(response) - }, - Err(e) => Ok(Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read body parameter WorkEntity: {}", e))) - .expect("Unable to create Bad Request response due to unable to read body parameter WorkEntity")), - } - } - - _ if path.matched(paths::ID_AUTH_CHECK) => method_not_allowed(), - _ if path.matched(paths::ID_AUTH_OIDC) => method_not_allowed(), - _ if path.matched(paths::ID_AUTH_TOKEN_EDITOR_ID) => method_not_allowed(), - _ if path.matched(paths::ID_CHANGELOG) => method_not_allowed(), - _ if path.matched(paths::ID_CHANGELOG_INDEX) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_LOOKUP) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_CONTAINER_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_LOOKUP) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_CREATOR_IDENT_RELEASES) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_CONTAINER_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_CREATOR_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_FILE_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_FILESET_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_RELEASE_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_AUTO_WEBCAPTURE_BATCH) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_AUTO_WORK_BATCH) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_REVIEWABLE) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ACCEPT) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATION) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATIONS) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK) => method_not_allowed(), - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT) => { - method_not_allowed() - } - _ if path.matched(paths::ID_EDITOR_EDITOR_ID) => method_not_allowed(), - _ if path.matched(paths::ID_EDITOR_EDITOR_ID_ANNOTATIONS) => method_not_allowed(), - _ if path.matched(paths::ID_EDITOR_EDITOR_ID_EDITGROUPS) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_LOOKUP) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_FILE_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_FILESET_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_FILESET_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_FILESET_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_FILESET_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_FILESET_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_LOOKUP) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT_FILES) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT_FILESETS) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_RELEASE_IDENT_WEBCAPTURES) => method_not_allowed(), - _ if path.matched(paths::ID_WEBCAPTURE_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_WEBCAPTURE_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_WEBCAPTURE_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_WEBCAPTURE_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_WEBCAPTURE_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_EDIT_EDIT_ID) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_REV_REV_ID) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_IDENT) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_IDENT_HISTORY) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_IDENT_REDIRECTS) => method_not_allowed(), - _ if path.matched(paths::ID_WORK_IDENT_RELEASES) => method_not_allowed(), - _ => Ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::empty()) - .expect("Unable to create Not Found response")), - } - } - Box::pin(run(self.api_impl.clone(), req)) - } -} - -/// Request parser for `Api`. -pub struct ApiRequestParser; -impl RequestParser for ApiRequestParser { - fn parse_operation_id(request: &Request) -> Result<&'static str, ()> { - let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { - // AcceptEditgroup - POST /editgroup/{editgroup_id}/accept - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ACCEPT) => { - Ok("AcceptEditgroup") - } - // AuthCheck - GET /auth/check - &hyper::Method::GET if path.matched(paths::ID_AUTH_CHECK) => Ok("AuthCheck"), - // AuthOidc - POST /auth/oidc - &hyper::Method::POST if path.matched(paths::ID_AUTH_OIDC) => Ok("AuthOidc"), - // CreateAuthToken - POST /auth/token/{editor_id} - &hyper::Method::POST if path.matched(paths::ID_AUTH_TOKEN_EDITOR_ID) => { - Ok("CreateAuthToken") - } - // CreateContainer - POST /editgroup/{editgroup_id}/container - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER) => { - Ok("CreateContainer") - } - // CreateContainerAutoBatch - POST /editgroup/auto/container/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_CONTAINER_BATCH) => { - Ok("CreateContainerAutoBatch") - } - // CreateCreator - POST /editgroup/{editgroup_id}/creator - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR) => { - Ok("CreateCreator") - } - // CreateCreatorAutoBatch - POST /editgroup/auto/creator/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_CREATOR_BATCH) => { - Ok("CreateCreatorAutoBatch") - } - // CreateEditgroup - POST /editgroup - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP) => Ok("CreateEditgroup"), - // CreateEditgroupAnnotation - POST /editgroup/{editgroup_id}/annotation - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATION) => { - Ok("CreateEditgroupAnnotation") - } - // CreateFile - POST /editgroup/{editgroup_id}/file - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE) => { - Ok("CreateFile") - } - // CreateFileAutoBatch - POST /editgroup/auto/file/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_FILE_BATCH) => { - Ok("CreateFileAutoBatch") - } - // CreateFileset - POST /editgroup/{editgroup_id}/fileset - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET) => { - Ok("CreateFileset") - } - // CreateFilesetAutoBatch - POST /editgroup/auto/fileset/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_FILESET_BATCH) => { - Ok("CreateFilesetAutoBatch") - } - // CreateRelease - POST /editgroup/{editgroup_id}/release - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE) => { - Ok("CreateRelease") - } - // CreateReleaseAutoBatch - POST /editgroup/auto/release/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_RELEASE_BATCH) => { - Ok("CreateReleaseAutoBatch") - } - // CreateWebcapture - POST /editgroup/{editgroup_id}/webcapture - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE) => { - Ok("CreateWebcapture") - } - // CreateWebcaptureAutoBatch - POST /editgroup/auto/webcapture/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_WEBCAPTURE_BATCH) => { - Ok("CreateWebcaptureAutoBatch") - } - // CreateWork - POST /editgroup/{editgroup_id}/work - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK) => { - Ok("CreateWork") - } - // CreateWorkAutoBatch - POST /editgroup/auto/work/batch - &hyper::Method::POST if path.matched(paths::ID_EDITGROUP_AUTO_WORK_BATCH) => { - Ok("CreateWorkAutoBatch") - } - // DeleteContainer - DELETE /editgroup/{editgroup_id}/container/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT) => - { - Ok("DeleteContainer") - } - // DeleteContainerEdit - DELETE /editgroup/{editgroup_id}/container/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_EDIT_EDIT_ID) => - { - Ok("DeleteContainerEdit") - } - // DeleteCreator - DELETE /editgroup/{editgroup_id}/creator/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT) => - { - Ok("DeleteCreator") - } - // DeleteCreatorEdit - DELETE /editgroup/{editgroup_id}/creator/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_EDIT_EDIT_ID) => - { - Ok("DeleteCreatorEdit") - } - // DeleteFile - DELETE /editgroup/{editgroup_id}/file/{ident} - &hyper::Method::DELETE if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT) => { - Ok("DeleteFile") - } - // DeleteFileEdit - DELETE /editgroup/{editgroup_id}/file/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_EDIT_EDIT_ID) => - { - Ok("DeleteFileEdit") - } - // DeleteFileset - DELETE /editgroup/{editgroup_id}/fileset/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT) => - { - Ok("DeleteFileset") - } - // DeleteFilesetEdit - DELETE /editgroup/{editgroup_id}/fileset/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_EDIT_EDIT_ID) => - { - Ok("DeleteFilesetEdit") - } - // DeleteRelease - DELETE /editgroup/{editgroup_id}/release/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT) => - { - Ok("DeleteRelease") - } - // DeleteReleaseEdit - DELETE /editgroup/{editgroup_id}/release/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_EDIT_EDIT_ID) => - { - Ok("DeleteReleaseEdit") - } - // DeleteWebcapture - DELETE /editgroup/{editgroup_id}/webcapture/{ident} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT) => - { - Ok("DeleteWebcapture") - } - // DeleteWebcaptureEdit - DELETE /editgroup/{editgroup_id}/webcapture/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_EDIT_EDIT_ID) => - { - Ok("DeleteWebcaptureEdit") - } - // DeleteWork - DELETE /editgroup/{editgroup_id}/work/{ident} - &hyper::Method::DELETE if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT) => { - Ok("DeleteWork") - } - // DeleteWorkEdit - DELETE /editgroup/{editgroup_id}/work/edit/{edit_id} - &hyper::Method::DELETE - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_EDIT_EDIT_ID) => - { - Ok("DeleteWorkEdit") - } - // GetChangelog - GET /changelog - &hyper::Method::GET if path.matched(paths::ID_CHANGELOG) => Ok("GetChangelog"), - // GetChangelogEntry - GET /changelog/{index} - &hyper::Method::GET if path.matched(paths::ID_CHANGELOG_INDEX) => { - Ok("GetChangelogEntry") - } - // GetContainer - GET /container/{ident} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT) => Ok("GetContainer"), - // GetContainerEdit - GET /container/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_EDIT_EDIT_ID) => { - Ok("GetContainerEdit") - } - // GetContainerHistory - GET /container/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT_HISTORY) => { - Ok("GetContainerHistory") - } - // GetContainerRedirects - GET /container/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_IDENT_REDIRECTS) => { - Ok("GetContainerRedirects") - } - // GetContainerRevision - GET /container/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_REV_REV_ID) => { - Ok("GetContainerRevision") - } - // GetCreator - GET /creator/{ident} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT) => Ok("GetCreator"), - // GetCreatorEdit - GET /creator/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_EDIT_EDIT_ID) => { - Ok("GetCreatorEdit") - } - // GetCreatorHistory - GET /creator/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_HISTORY) => { - Ok("GetCreatorHistory") - } - // GetCreatorRedirects - GET /creator/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_REDIRECTS) => { - Ok("GetCreatorRedirects") - } - // GetCreatorReleases - GET /creator/{ident}/releases - &hyper::Method::GET if path.matched(paths::ID_CREATOR_IDENT_RELEASES) => { - Ok("GetCreatorReleases") - } - // GetCreatorRevision - GET /creator/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_CREATOR_REV_REV_ID) => { - Ok("GetCreatorRevision") - } - // GetEditgroup - GET /editgroup/{editgroup_id} - &hyper::Method::GET if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID) => { - Ok("GetEditgroup") - } - // GetEditgroupAnnotations - GET /editgroup/{editgroup_id}/annotations - &hyper::Method::GET if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_ANNOTATIONS) => { - Ok("GetEditgroupAnnotations") - } - // GetEditgroupsReviewable - GET /editgroup/reviewable - &hyper::Method::GET if path.matched(paths::ID_EDITGROUP_REVIEWABLE) => { - Ok("GetEditgroupsReviewable") - } - // GetEditor - GET /editor/{editor_id} - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID) => Ok("GetEditor"), - // GetEditorAnnotations - GET /editor/{editor_id}/annotations - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID_ANNOTATIONS) => { - Ok("GetEditorAnnotations") - } - // GetEditorEditgroups - GET /editor/{editor_id}/editgroups - &hyper::Method::GET if path.matched(paths::ID_EDITOR_EDITOR_ID_EDITGROUPS) => { - Ok("GetEditorEditgroups") - } - // GetFile - GET /file/{ident} - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT) => Ok("GetFile"), - // GetFileEdit - GET /file/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_FILE_EDIT_EDIT_ID) => Ok("GetFileEdit"), - // GetFileHistory - GET /file/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT_HISTORY) => { - Ok("GetFileHistory") - } - // GetFileRedirects - GET /file/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_FILE_IDENT_REDIRECTS) => { - Ok("GetFileRedirects") - } - // GetFileRevision - GET /file/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_FILE_REV_REV_ID) => Ok("GetFileRevision"), - // GetFileset - GET /fileset/{ident} - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT) => Ok("GetFileset"), - // GetFilesetEdit - GET /fileset/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_FILESET_EDIT_EDIT_ID) => { - Ok("GetFilesetEdit") - } - // GetFilesetHistory - GET /fileset/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT_HISTORY) => { - Ok("GetFilesetHistory") - } - // GetFilesetRedirects - GET /fileset/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_FILESET_IDENT_REDIRECTS) => { - Ok("GetFilesetRedirects") - } - // GetFilesetRevision - GET /fileset/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_FILESET_REV_REV_ID) => { - Ok("GetFilesetRevision") - } - // GetRelease - GET /release/{ident} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT) => Ok("GetRelease"), - // GetReleaseEdit - GET /release/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_EDIT_EDIT_ID) => { - Ok("GetReleaseEdit") - } - // GetReleaseFiles - GET /release/{ident}/files - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_FILES) => { - Ok("GetReleaseFiles") - } - // GetReleaseFilesets - GET /release/{ident}/filesets - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_FILESETS) => { - Ok("GetReleaseFilesets") - } - // GetReleaseHistory - GET /release/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_HISTORY) => { - Ok("GetReleaseHistory") - } - // GetReleaseRedirects - GET /release/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_REDIRECTS) => { - Ok("GetReleaseRedirects") - } - // GetReleaseRevision - GET /release/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_RELEASE_REV_REV_ID) => { - Ok("GetReleaseRevision") - } - // GetReleaseWebcaptures - GET /release/{ident}/webcaptures - &hyper::Method::GET if path.matched(paths::ID_RELEASE_IDENT_WEBCAPTURES) => { - Ok("GetReleaseWebcaptures") - } - // GetWebcapture - GET /webcapture/{ident} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT) => Ok("GetWebcapture"), - // GetWebcaptureEdit - GET /webcapture/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_EDIT_EDIT_ID) => { - Ok("GetWebcaptureEdit") - } - // GetWebcaptureHistory - GET /webcapture/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT_HISTORY) => { - Ok("GetWebcaptureHistory") - } - // GetWebcaptureRedirects - GET /webcapture/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_IDENT_REDIRECTS) => { - Ok("GetWebcaptureRedirects") - } - // GetWebcaptureRevision - GET /webcapture/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_WEBCAPTURE_REV_REV_ID) => { - Ok("GetWebcaptureRevision") - } - // GetWork - GET /work/{ident} - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT) => Ok("GetWork"), - // GetWorkEdit - GET /work/edit/{edit_id} - &hyper::Method::GET if path.matched(paths::ID_WORK_EDIT_EDIT_ID) => Ok("GetWorkEdit"), - // GetWorkHistory - GET /work/{ident}/history - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_HISTORY) => { - Ok("GetWorkHistory") - } - // GetWorkRedirects - GET /work/{ident}/redirects - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_REDIRECTS) => { - Ok("GetWorkRedirects") - } - // GetWorkReleases - GET /work/{ident}/releases - &hyper::Method::GET if path.matched(paths::ID_WORK_IDENT_RELEASES) => { - Ok("GetWorkReleases") - } - // GetWorkRevision - GET /work/rev/{rev_id} - &hyper::Method::GET if path.matched(paths::ID_WORK_REV_REV_ID) => Ok("GetWorkRevision"), - // LookupContainer - GET /container/lookup - &hyper::Method::GET if path.matched(paths::ID_CONTAINER_LOOKUP) => { - Ok("LookupContainer") - } - // LookupCreator - GET /creator/lookup - &hyper::Method::GET if path.matched(paths::ID_CREATOR_LOOKUP) => Ok("LookupCreator"), - // LookupFile - GET /file/lookup - &hyper::Method::GET if path.matched(paths::ID_FILE_LOOKUP) => Ok("LookupFile"), - // LookupRelease - GET /release/lookup - &hyper::Method::GET if path.matched(paths::ID_RELEASE_LOOKUP) => Ok("LookupRelease"), - // UpdateContainer - PUT /editgroup/{editgroup_id}/container/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CONTAINER_IDENT) => - { - Ok("UpdateContainer") - } - // UpdateCreator - PUT /editgroup/{editgroup_id}/creator/{ident} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_CREATOR_IDENT) => { - Ok("UpdateCreator") - } - // UpdateEditgroup - PUT /editgroup/{editgroup_id} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID) => { - Ok("UpdateEditgroup") - } - // UpdateEditor - PUT /editor/{editor_id} - &hyper::Method::PUT if path.matched(paths::ID_EDITOR_EDITOR_ID) => Ok("UpdateEditor"), - // UpdateFile - PUT /editgroup/{editgroup_id}/file/{ident} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILE_IDENT) => { - Ok("UpdateFile") - } - // UpdateFileset - PUT /editgroup/{editgroup_id}/fileset/{ident} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_FILESET_IDENT) => { - Ok("UpdateFileset") - } - // UpdateRelease - PUT /editgroup/{editgroup_id}/release/{ident} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_RELEASE_IDENT) => { - Ok("UpdateRelease") - } - // UpdateWebcapture - PUT /editgroup/{editgroup_id}/webcapture/{ident} - &hyper::Method::PUT - if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WEBCAPTURE_IDENT) => - { - Ok("UpdateWebcapture") - } - // UpdateWork - PUT /editgroup/{editgroup_id}/work/{ident} - &hyper::Method::PUT if path.matched(paths::ID_EDITGROUP_EDITGROUP_ID_WORK_IDENT) => { - Ok("UpdateWork") - } - _ => Err(()), - } - } -} -- cgit v1.2.3